3 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
5 var fs$3 = _interopDefault(require('fs'));
6 var path$2 = _interopDefault(require('path'));
7 var os$1 = _interopDefault(require('os'));
8 var tty$1 = _interopDefault(require('tty'));
9 var assert$1 = _interopDefault(require('assert'));
10 var util$3 = _interopDefault(require('util'));
11 var stream$6 = _interopDefault(require('stream'));
12 var events$1 = _interopDefault(require('events'));
14 var name = "prettier";
15 var version = "2.0.5";
16 var description = "Prettier is an opinionated code formatter";
17 var bin = "./bin/prettier.js";
18 var repository = "prettier/prettier";
19 var homepage = "https://prettier.io";
20 var author = "James Long";
22 var main = "./index.js";
27 "@angular/compiler": "9.0.5",
28 "@babel/code-frame": "7.8.0",
29 "@babel/parser": "7.9.4",
30 "@glimmer/syntax": "0.50.0",
31 "@iarna/toml": "2.2.3",
32 "@typescript-eslint/typescript-estree": "2.26.0",
33 "angular-estree-parser": "1.3.0",
34 "angular-html-parser": "1.4.0",
37 "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
43 editorconfig: "0.15.3",
44 "editorconfig-to-prettier": "0.1.1",
45 "escape-string-regexp": "2.0.0",
48 "find-parent-dir": "0.3.0",
49 "find-project-root": "1.1.1",
50 "flow-parser": "0.122.0",
51 "get-stream": "5.1.0",
54 "html-element-attributes": "2.2.1",
55 "html-styles": "1.0.0",
56 "html-tag-names": "1.1.5",
58 "jest-docblock": "25.2.6",
59 "json-stable-stringify": "1.0.1",
61 "lines-and-columns": "1.1.6",
62 "linguist-languages": "7.9.0",
67 "n-readlines": "1.0.0",
68 "please-upgrade-node": "3.2.0",
69 "postcss-less": "3.1.4",
70 "postcss-media-query-parser": "0.2.3",
71 "postcss-scss": "2.0.0",
72 "postcss-selector-parser": "2.2.3",
73 "postcss-values-parser": "2.0.1",
74 "regexp-util": "1.2.2",
75 "remark-math": "1.0.6",
76 "remark-parse": "5.0.0",
80 "string-width": "4.2.0",
82 "unicode-regex": "3.0.0",
85 "yaml-unist-parser": "1.1.1"
87 var devDependencies = {
88 "@babel/core": "7.9.0",
89 "@babel/preset-env": "7.9.0",
90 "@rollup/plugin-alias": "3.0.1",
91 "@rollup/plugin-commonjs": "11.0.2",
92 "@rollup/plugin-json": "4.0.2",
93 "@rollup/plugin-node-resolve": "7.1.1",
94 "@rollup/plugin-replace": "2.3.1",
95 "babel-loader": "8.1.0",
97 "builtin-modules": "3.1.0",
102 "eslint-config-prettier": "6.10.1",
103 "eslint-formatter-friendly": "7.0.0",
104 "eslint-plugin-import": "2.20.2",
105 "eslint-plugin-prettier": "3.1.2",
106 "eslint-plugin-react": "7.19.0",
107 "eslint-plugin-unicorn": "18.0.1",
110 "jest-snapshot-serializer-ansi": "1.0.0",
111 "jest-snapshot-serializer-raw": "1.1.0",
112 "jest-watch-typeahead": "0.5.0",
116 "rollup-plugin-babel": "4.4.0",
117 "rollup-plugin-node-globals": "1.4.0",
118 "rollup-plugin-terser": "5.3.0",
120 "snapshot-diff": "0.7.0",
121 "strip-ansi": "6.0.0",
122 "synchronous-promise": "2.0.10",
124 "terser-webpack-plugin": "2.3.5",
128 prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
129 "prepare-release": "yarn && yarn build && yarn test:dist",
131 "test:dist": "cross-env NODE_ENV=production jest",
132 "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest tests/",
133 "test:integration": "jest tests_integration",
134 "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
135 "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
136 "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
137 "lint:typecheck": "tsc",
138 "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
139 "lint:changelog": "node ./scripts/lint-changelog.js",
140 "lint:prettier": "prettier \"**/*.{md,json,yml,html,css}\" --check",
141 "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"",
142 "lint:spellcheck": "cspell {bin,scripts,src,website}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md",
143 "lint:deps": "node ./scripts/check-deps.js",
144 build: "node --max-old-space-size=3072 ./scripts/build/build.js",
145 "build-docs": "node ./scripts/build-docs.js"
150 description: description,
152 repository: repository,
158 dependencies: dependencies,
159 devDependencies: devDependencies,
163 var _package$1 = /*#__PURE__*/Object.freeze({
167 description: description,
169 repository: repository,
175 dependencies: dependencies,
176 devDependencies: devDependencies,
184 diff: function diff(oldString, newString) {
185 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
186 var callback = options.callback;
188 if (typeof options === 'function') {
193 this.options = options;
196 function done(value) {
198 setTimeout(function () {
199 callback(undefined, value);
205 } // Allow subclasses to massage the input prior to running
208 oldString = this.castInput(oldString);
209 newString = this.castInput(newString);
210 oldString = this.removeEmpty(this.tokenize(oldString));
211 newString = this.removeEmpty(this.tokenize(newString));
212 var newLen = newString.length,
213 oldLen = oldString.length;
215 var maxEditLength = newLen + oldLen;
219 }]; // Seed editLength = 0, i.e. the content starts with the same values
221 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
223 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
224 // Identity per the equality and tokenizer
226 value: this.join(newString),
227 count: newString.length
229 } // Main worker method. checks all permutations of a given edit length for acceptance.
232 function execEditLength() {
233 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
234 var basePath = void 0;
236 var addPath = bestPath[diagonalPath - 1],
237 removePath = bestPath[diagonalPath + 1],
238 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
241 // No one else is going to attempt to use this value, clear it
242 bestPath[diagonalPath - 1] = undefined;
245 var canAdd = addPath && addPath.newPos + 1 < newLen,
246 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
248 if (!canAdd && !canRemove) {
249 // If this path is a terminal then prune
250 bestPath[diagonalPath] = undefined;
252 } // Select the diagonal that we want to branch from. We select the prior
253 // path whose position in the new string is the farthest from the origin
254 // and does not pass the bounds of the diff graph
257 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
258 basePath = clonePath(removePath);
259 self.pushComponent(basePath.components, undefined, true);
261 basePath = addPath; // No need to clone, we've pulled it from the list
264 self.pushComponent(basePath.components, true, undefined);
267 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
269 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
270 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
272 // Otherwise track this path as a potential candidate and continue.
273 bestPath[diagonalPath] = basePath;
278 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
279 // sync and async mode which is never fun. Loops over execEditLength until a value
285 setTimeout(function () {
286 // This should not happen, but we want to be safe.
288 /* istanbul ignore next */
289 if (editLength > maxEditLength) {
293 if (!execEditLength()) {
299 while (editLength <= maxEditLength) {
300 var ret = execEditLength();
308 pushComponent: function pushComponent(components, added, removed) {
309 var last = components[components.length - 1];
311 if (last && last.added === added && last.removed === removed) {
312 // We need to clone here as the component clone operation is just
313 // as shallow array clone
314 components[components.length - 1] = {
315 count: last.count + 1,
327 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
328 var newLen = newString.length,
329 oldLen = oldString.length,
330 newPos = basePath.newPos,
331 oldPos = newPos - diagonalPath,
334 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
341 basePath.components.push({
346 basePath.newPos = newPos;
349 equals: function equals(left, right) {
350 if (this.options.comparator) {
351 return this.options.comparator(left, right);
353 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
356 removeEmpty: function removeEmpty(array) {
359 for (var i = 0; i < array.length; i++) {
367 castInput: function castInput(value) {
370 tokenize: function tokenize(value) {
371 return value.split('');
373 join: function join(chars) {
374 return chars.join('');
378 function buildValues(diff, components, newString, oldString, useLongestToken) {
379 var componentPos = 0,
380 componentLen = components.length,
384 for (; componentPos < componentLen; componentPos++) {
385 var component = components[componentPos];
387 if (!component.removed) {
388 if (!component.added && useLongestToken) {
389 var value = newString.slice(newPos, newPos + component.count);
390 value = value.map(function (value, i) {
391 var oldValue = oldString[oldPos + i];
392 return oldValue.length > value.length ? oldValue : value;
394 component.value = diff.join(value);
396 component.value = diff.join(newString.slice(newPos, newPos + component.count));
399 newPos += component.count; // Common case
401 if (!component.added) {
402 oldPos += component.count;
405 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
406 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
407 // The diffing algorithm is tied to add then remove output and this is the simplest
408 // route to get the desired output with minimal overhead.
410 if (componentPos && components[componentPos - 1].added) {
411 var tmp = components[componentPos - 1];
412 components[componentPos - 1] = components[componentPos];
413 components[componentPos] = tmp;
416 } // Special case handle for when one terminal is ignored (i.e. whitespace).
417 // For this case we merge the terminal into the prior string and drop the change.
418 // This is only available for string mode.
421 var lastComponent = components[componentLen - 1];
423 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
424 components[componentLen - 2].value += lastComponent.value;
431 function clonePath(path) {
434 components: path.components.slice(0)
438 var characterDiff = new Diff();
440 function diffChars(oldStr, newStr, options) {
441 return characterDiff.diff(oldStr, newStr, options);
444 function generateOptions(options, defaults) {
445 if (typeof options === 'function') {
446 defaults.callback = options;
447 } else if (options) {
448 for (var name in options) {
449 /* istanbul ignore else */
450 if (options.hasOwnProperty(name)) {
451 defaults[name] = options[name];
458 // Ranges and exceptions:
459 // Latin-1 Supplement, 0080–00FF
460 // - U+00D7 × Multiplication sign
461 // - U+00F7 ÷ Division sign
462 // Latin Extended-A, 0100–017F
463 // Latin Extended-B, 0180–024F
464 // IPA Extensions, 0250–02AF
465 // Spacing Modifier Letters, 02B0–02FF
466 // - U+02C7 ˇ ˇ Caron
467 // - U+02D8 ˘ ˘ Breve
468 // - U+02D9 ˙ ˙ Dot Above
469 // - U+02DA ˚ ˚ Ring Above
470 // - U+02DB ˛ ˛ Ogonek
471 // - U+02DC ˜ ˜ Small Tilde
472 // - U+02DD ˝ ˝ Double Acute Accent
473 // Latin Extended Additional, 1E00–1EFF
476 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
477 var reWhitespace = /\S/;
478 var wordDiff = new Diff();
480 wordDiff.equals = function (left, right) {
481 if (this.options.ignoreCase) {
482 left = left.toLowerCase();
483 right = right.toLowerCase();
486 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
489 wordDiff.tokenize = function (value) {
490 var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
492 for (var i = 0; i < tokens.length - 1; i++) {
493 // If we have an empty string in the next field and we have only word chars before and after, merge
494 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
495 tokens[i] += tokens[i + 2];
496 tokens.splice(i + 1, 2);
504 function diffWords(oldStr, newStr, options) {
505 options = generateOptions(options, {
506 ignoreWhitespace: true
508 return wordDiff.diff(oldStr, newStr, options);
511 function diffWordsWithSpace(oldStr, newStr, options) {
512 return wordDiff.diff(oldStr, newStr, options);
515 var lineDiff = new Diff();
517 lineDiff.tokenize = function (value) {
519 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
521 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
522 linesAndNewlines.pop();
523 } // Merge the content and line separators into single tokens
526 for (var i = 0; i < linesAndNewlines.length; i++) {
527 var line = linesAndNewlines[i];
529 if (i % 2 && !this.options.newlineIsToken) {
530 retLines[retLines.length - 1] += line;
532 if (this.options.ignoreWhitespace) {
543 function diffLines(oldStr, newStr, callback) {
544 return lineDiff.diff(oldStr, newStr, callback);
547 function diffTrimmedLines(oldStr, newStr, callback) {
548 var options = generateOptions(callback, {
549 ignoreWhitespace: true
551 return lineDiff.diff(oldStr, newStr, options);
554 var sentenceDiff = new Diff();
556 sentenceDiff.tokenize = function (value) {
557 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
560 function diffSentences(oldStr, newStr, callback) {
561 return sentenceDiff.diff(oldStr, newStr, callback);
564 var cssDiff = new Diff();
566 cssDiff.tokenize = function (value) {
567 return value.split(/([{}:;,]|\s+)/);
570 function diffCss(oldStr, newStr, callback) {
571 return cssDiff.diff(oldStr, newStr, callback);
574 function _typeof(obj) {
575 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
576 _typeof = function (obj) {
580 _typeof = function (obj) {
581 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
588 function _toConsumableArray(arr) {
589 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
592 function _arrayWithoutHoles(arr) {
593 if (Array.isArray(arr)) {
594 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
600 function _iterableToArray(iter) {
601 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
604 function _nonIterableSpread() {
605 throw new TypeError("Invalid attempt to spread non-iterable instance");
608 var objectPrototypeToString = Object.prototype.toString;
609 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
610 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
612 jsonDiff.useLongestToken = true;
613 jsonDiff.tokenize = lineDiff.tokenize;
615 jsonDiff.castInput = function (value) {
616 var _this$options = this.options,
617 undefinedReplacement = _this$options.undefinedReplacement,
618 _this$options$stringi = _this$options.stringifyReplacer,
619 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
620 return typeof v === 'undefined' ? undefinedReplacement : v;
621 } : _this$options$stringi;
622 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
625 jsonDiff.equals = function (left, right) {
626 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
629 function diffJson(oldObj, newObj, options) {
630 return jsonDiff.diff(oldObj, newObj, options);
631 } // This function handles the presence of circular references by bailing out when encountering an
632 // object that is already on the "stack" of items being processed. Accepts an optional replacer
635 function canonicalize(obj, stack, replacementStack, replacer, key) {
637 replacementStack = replacementStack || [];
640 obj = replacer(key, obj);
645 for (i = 0; i < stack.length; i += 1) {
646 if (stack[i] === obj) {
647 return replacementStack[i];
651 var canonicalizedObj;
653 if ('[object Array]' === objectPrototypeToString.call(obj)) {
655 canonicalizedObj = new Array(obj.length);
656 replacementStack.push(canonicalizedObj);
658 for (i = 0; i < obj.length; i += 1) {
659 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
663 replacementStack.pop();
664 return canonicalizedObj;
667 if (obj && obj.toJSON) {
671 if (_typeof(obj) === 'object' && obj !== null) {
673 canonicalizedObj = {};
674 replacementStack.push(canonicalizedObj);
680 /* istanbul ignore else */
681 if (obj.hasOwnProperty(_key)) {
682 sortedKeys.push(_key);
688 for (i = 0; i < sortedKeys.length; i += 1) {
689 _key = sortedKeys[i];
690 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
694 replacementStack.pop();
696 canonicalizedObj = obj;
699 return canonicalizedObj;
702 var arrayDiff = new Diff();
704 arrayDiff.tokenize = function (value) {
705 return value.slice();
708 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
712 function diffArrays(oldArr, newArr, callback) {
713 return arrayDiff.diff(oldArr, newArr, callback);
716 function parsePatch(uniDiff) {
717 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
718 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
719 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
723 function parseIndex() {
725 list.push(index); // Parse diff metadata
727 while (i < diffstr.length) {
728 var line = diffstr[i]; // File header found, end parsing diff metadata
730 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
735 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
738 index.index = header[1];
742 } // Parse file headers if they are defined. Unified diff requires them, but
743 // there's no technical issues to have an isolated hunk without file header
746 parseFileHeader(index);
747 parseFileHeader(index); // Parse hunks
751 while (i < diffstr.length) {
752 var _line = diffstr[i];
754 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
756 } else if (/^@@/.test(_line)) {
757 index.hunks.push(parseHunk());
758 } else if (_line && options.strict) {
759 // Ignore unexpected content unless in strict mode
760 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
765 } // Parses the --- and +++ headers, if none are found, no lines
769 function parseFileHeader(index) {
770 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
773 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
774 var data = fileHeader[2].split('\t', 2);
775 var fileName = data[0].replace(/\\\\/g, '\\');
777 if (/^".*"$/.test(fileName)) {
778 fileName = fileName.substr(1, fileName.length - 2);
781 index[keyPrefix + 'FileName'] = fileName;
782 index[keyPrefix + 'Header'] = (data[1] || '').trim();
786 // This assumes that we are at the start of a hunk.
789 function parseHunk() {
790 var chunkHeaderIndex = i,
791 chunkHeaderLine = diffstr[i++],
792 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
794 oldStart: +chunkHeader[1],
795 oldLines: +chunkHeader[2] || 1,
796 newStart: +chunkHeader[3],
797 newLines: +chunkHeader[4] || 1,
804 for (; i < diffstr.length; i++) {
805 // Lines starting with '---' could be mistaken for the "remove line" operation
806 // But they could be the header for the next file. Therefore prune such cases out.
807 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
811 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
813 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
814 hunk.lines.push(diffstr[i]);
815 hunk.linedelimiters.push(delimiters[i] || '\n');
817 if (operation === '+') {
819 } else if (operation === '-') {
821 } else if (operation === ' ') {
828 } // Handle the empty block count case
831 if (!addCount && hunk.newLines === 1) {
835 if (!removeCount && hunk.oldLines === 1) {
837 } // Perform optional sanity checking
840 if (options.strict) {
841 if (addCount !== hunk.newLines) {
842 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
845 if (removeCount !== hunk.oldLines) {
846 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
853 while (i < diffstr.length) {
858 } // Iterator that traverses in the range of [min, max], stepping
859 // by distance from a given start position. I.e. for [0, 4], with
860 // start of 2, this will iterate 2, 3, 1, 4, 0.
863 function distanceIterator(start, minLine, maxLine) {
864 var wantForward = true,
865 backwardExhausted = false,
866 forwardExhausted = false,
868 return function iterator() {
869 if (wantForward && !forwardExhausted) {
870 if (backwardExhausted) {
874 } // Check if trying to fit beyond text length, and if not, check it fits
875 // after offset location (or desired location on first iteration)
878 if (start + localOffset <= maxLine) {
882 forwardExhausted = true;
885 if (!backwardExhausted) {
886 if (!forwardExhausted) {
888 } // Check if trying to fit before text beginning, and if not, check it fits
889 // before offset location
892 if (minLine <= start - localOffset) {
893 return -localOffset++;
896 backwardExhausted = true;
898 } // We tried to fit hunk before text beginning and beyond text length, then
899 // hunk can't fit on the text. Return undefined
904 function applyPatch(source, uniDiff) {
905 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
907 if (typeof uniDiff === 'string') {
908 uniDiff = parsePatch(uniDiff);
911 if (Array.isArray(uniDiff)) {
912 if (uniDiff.length > 1) {
913 throw new Error('applyPatch only works with a single input.');
916 uniDiff = uniDiff[0];
917 } // Apply the diff to the input
920 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
921 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
922 hunks = uniDiff.hunks,
923 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
924 return line === patchContent;
927 fuzzFactor = options.fuzzFactor || 0,
933 * Checks if the hunk exactly fits on the provided location
937 function hunkFits(hunk, toPos) {
938 for (var j = 0; j < hunk.lines.length; j++) {
939 var line = hunk.lines[j],
940 operation = line.length > 0 ? line[0] : ' ',
941 content = line.length > 0 ? line.substr(1) : line;
943 if (operation === ' ' || operation === '-') {
944 // Context sanity check
945 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
948 if (errorCount > fuzzFactor) {
958 } // Search best fit offsets for each hunk based on the previous ones
961 for (var i = 0; i < hunks.length; i++) {
963 maxLine = lines.length - hunk.oldLines,
965 toPos = offset + hunk.oldStart - 1;
966 var iterator = distanceIterator(toPos, minLine, maxLine);
968 for (; localOffset !== undefined; localOffset = iterator()) {
969 if (hunkFits(hunk, toPos + localOffset)) {
970 hunk.offset = offset += localOffset;
975 if (localOffset === undefined) {
977 } // Set lower text limit to end of the current hunk, so next ones don't try
978 // to fit over already patched text
981 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
982 } // Apply patch hunks
987 for (var _i = 0; _i < hunks.length; _i++) {
988 var _hunk = hunks[_i],
989 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
991 diffOffset += _hunk.newLines - _hunk.oldLines;
994 // Creating a new file
998 for (var j = 0; j < _hunk.lines.length; j++) {
999 var line = _hunk.lines[j],
1000 operation = line.length > 0 ? line[0] : ' ',
1001 content = line.length > 0 ? line.substr(1) : line,
1002 delimiter = _hunk.linedelimiters[j];
1004 if (operation === ' ') {
1006 } else if (operation === '-') {
1007 lines.splice(_toPos, 1);
1008 delimiters.splice(_toPos, 1);
1009 /* istanbul ignore else */
1010 } else if (operation === '+') {
1011 lines.splice(_toPos, 0, content);
1012 delimiters.splice(_toPos, 0, delimiter);
1014 } else if (operation === '\\') {
1015 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
1017 if (previousOperation === '+') {
1019 } else if (previousOperation === '-') {
1024 } // Handle EOFNL insertion/removal
1028 while (!lines[lines.length - 1]) {
1032 } else if (addEOFNL) {
1034 delimiters.push('\n');
1037 for (var _k = 0; _k < lines.length - 1; _k++) {
1038 lines[_k] = lines[_k] + delimiters[_k];
1041 return lines.join('');
1042 } // Wrapper that supports multiple file patches via callbacks.
1045 function applyPatches(uniDiff, options) {
1046 if (typeof uniDiff === 'string') {
1047 uniDiff = parsePatch(uniDiff);
1050 var currentIndex = 0;
1052 function processIndex() {
1053 var index = uniDiff[currentIndex++];
1056 return options.complete();
1059 options.loadFile(index, function (err, data) {
1061 return options.complete(err);
1064 var updatedContent = applyPatch(data, index, options);
1065 options.patched(index, updatedContent, function (err) {
1067 return options.complete(err);
1078 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1083 if (typeof options.context === 'undefined') {
1084 options.context = 4;
1087 var diff = diffLines(oldStr, newStr, options);
1091 }); // Append an empty value to make cleanup easier
1093 function contextLines(lines) {
1094 return lines.map(function (entry) {
1100 var oldRangeStart = 0,
1106 var _loop = function _loop(i) {
1107 var current = diff[i],
1108 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
1109 current.lines = lines;
1111 if (current.added || current.removed) {
1112 var _curRange; // If we have previous context, start with that
1115 if (!oldRangeStart) {
1116 var prev = diff[i - 1];
1117 oldRangeStart = oldLine;
1118 newRangeStart = newLine;
1121 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
1122 oldRangeStart -= curRange.length;
1123 newRangeStart -= curRange.length;
1125 } // Output our changes
1128 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
1129 return (current.added ? '+' : '-') + entry;
1130 }))); // Track the updated file position
1133 if (current.added) {
1134 newLine += lines.length;
1136 oldLine += lines.length;
1139 // Identical context lines. Track line changes
1140 if (oldRangeStart) {
1141 // Close out any changes that have been output (or join overlapping)
1142 if (lines.length <= options.context * 2 && i < diff.length - 2) {
1143 var _curRange2; // Overlapping
1146 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
1148 var _curRange3; // end the range and output
1151 var contextSize = Math.min(lines.length, options.context);
1153 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
1156 oldStart: oldRangeStart,
1157 oldLines: oldLine - oldRangeStart + contextSize,
1158 newStart: newRangeStart,
1159 newLines: newLine - newRangeStart + contextSize,
1163 if (i >= diff.length - 2 && lines.length <= options.context) {
1164 // EOF is inside this hunk
1165 var oldEOFNewline = /\n$/.test(oldStr);
1166 var newEOFNewline = /\n$/.test(newStr);
1167 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
1169 if (!oldEOFNewline && noNlBeforeAdds) {
1170 // special case: old has no eol and no trailing context; no-nl can end up before adds
1171 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
1174 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
1175 curRange.push('\\ No newline at end of file');
1186 oldLine += lines.length;
1187 newLine += lines.length;
1191 for (var i = 0; i < diff.length; i++) {
1196 oldFileName: oldFileName,
1197 newFileName: newFileName,
1198 oldHeader: oldHeader,
1199 newHeader: newHeader,
1204 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1205 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
1208 if (oldFileName == newFileName) {
1209 ret.push('Index: ' + oldFileName);
1212 ret.push('===================================================================');
1213 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
1214 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
1216 for (var i = 0; i < diff.hunks.length; i++) {
1217 var hunk = diff.hunks[i];
1218 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
1219 ret.push.apply(ret, hunk.lines);
1222 return ret.join('\n') + '\n';
1225 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1226 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1229 function arrayEqual(a, b) {
1230 if (a.length !== b.length) {
1234 return arrayStartsWith(a, b);
1237 function arrayStartsWith(array, start) {
1238 if (start.length > array.length) {
1242 for (var i = 0; i < start.length; i++) {
1243 if (start[i] !== array[i]) {
1251 function calcLineCount(hunk) {
1252 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
1253 oldLines = _calcOldNewLineCount.oldLines,
1254 newLines = _calcOldNewLineCount.newLines;
1256 if (oldLines !== undefined) {
1257 hunk.oldLines = oldLines;
1259 delete hunk.oldLines;
1262 if (newLines !== undefined) {
1263 hunk.newLines = newLines;
1265 delete hunk.newLines;
1269 function merge(mine, theirs, base) {
1270 mine = loadPatch(mine, base);
1271 theirs = loadPatch(theirs, base);
1272 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
1273 // Leaving sanity checks on this to the API consumer that may know more about the
1274 // meaning in their own context.
1276 if (mine.index || theirs.index) {
1277 ret.index = mine.index || theirs.index;
1280 if (mine.newFileName || theirs.newFileName) {
1281 if (!fileNameChanged(mine)) {
1282 // No header or no change in ours, use theirs (and ours if theirs does not exist)
1283 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
1284 ret.newFileName = theirs.newFileName || mine.newFileName;
1285 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
1286 ret.newHeader = theirs.newHeader || mine.newHeader;
1287 } else if (!fileNameChanged(theirs)) {
1288 // No header or no change in theirs, use ours
1289 ret.oldFileName = mine.oldFileName;
1290 ret.newFileName = mine.newFileName;
1291 ret.oldHeader = mine.oldHeader;
1292 ret.newHeader = mine.newHeader;
1294 // Both changed... figure it out
1295 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
1296 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
1297 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
1298 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
1308 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
1309 var mineCurrent = mine.hunks[mineIndex] || {
1312 theirsCurrent = theirs.hunks[theirsIndex] || {
1316 if (hunkBefore(mineCurrent, theirsCurrent)) {
1317 // This patch does not overlap with any of the others, yay.
1318 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
1320 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
1321 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
1322 // This patch does not overlap with any of the others, yay.
1323 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
1325 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
1327 // Overlap, merge as best we can
1329 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
1331 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
1335 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
1338 ret.hunks.push(mergedHunk);
1345 function loadPatch(param, base) {
1346 if (typeof param === 'string') {
1347 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
1348 return parsePatch(param)[0];
1352 throw new Error('Must provide a base reference or pass in a patch');
1355 return structuredPatch(undefined, undefined, base, param);
1361 function fileNameChanged(patch) {
1362 return patch.newFileName && patch.newFileName !== patch.oldFileName;
1365 function selectField(index, mine, theirs) {
1366 if (mine === theirs) {
1369 index.conflict = true;
1377 function hunkBefore(test, check) {
1378 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
1381 function cloneHunk(hunk, offset) {
1383 oldStart: hunk.oldStart,
1384 oldLines: hunk.oldLines,
1385 newStart: hunk.newStart + offset,
1386 newLines: hunk.newLines,
1391 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
1392 // This will generally result in a conflicted hunk, but there are cases where the context
1393 // is the only overlap where we can successfully merge the content here.
1400 offset: theirOffset,
1403 }; // Handle any leading content
1405 insertLeading(hunk, mine, their);
1406 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
1408 while (mine.index < mine.lines.length && their.index < their.lines.length) {
1409 var mineCurrent = mine.lines[mine.index],
1410 theirCurrent = their.lines[their.index];
1412 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
1413 // Both modified ...
1414 mutualChange(hunk, mine, their);
1415 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
1416 var _hunk$lines; // Mine inserted
1419 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
1420 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
1421 var _hunk$lines2; // Theirs inserted
1424 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
1425 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
1426 // Mine removed or edited
1427 removal(hunk, mine, their);
1428 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
1429 // Their removed or edited
1430 removal(hunk, their, mine, true);
1431 } else if (mineCurrent === theirCurrent) {
1433 hunk.lines.push(mineCurrent);
1438 conflict(hunk, collectChange(mine), collectChange(their));
1440 } // Now push anything that may be remaining
1443 insertTrailing(hunk, mine);
1444 insertTrailing(hunk, their);
1445 calcLineCount(hunk);
1448 function mutualChange(hunk, mine, their) {
1449 var myChanges = collectChange(mine),
1450 theirChanges = collectChange(their);
1452 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
1453 // Special case for remove changes that are supersets of one another
1454 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
1457 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
1460 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
1463 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
1467 } else if (arrayEqual(myChanges, theirChanges)) {
1470 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
1475 conflict(hunk, myChanges, theirChanges);
1478 function removal(hunk, mine, their, swap) {
1479 var myChanges = collectChange(mine),
1480 theirChanges = collectContext(their, myChanges);
1482 if (theirChanges.merged) {
1485 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
1487 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
1491 function conflict(hunk, mine, their) {
1492 hunk.conflict = true;
1500 function insertLeading(hunk, insert, their) {
1501 while (insert.offset < their.offset && insert.index < insert.lines.length) {
1502 var line = insert.lines[insert.index++];
1503 hunk.lines.push(line);
1508 function insertTrailing(hunk, insert) {
1509 while (insert.index < insert.lines.length) {
1510 var line = insert.lines[insert.index++];
1511 hunk.lines.push(line);
1515 function collectChange(state) {
1517 operation = state.lines[state.index][0];
1519 while (state.index < state.lines.length) {
1520 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
1522 if (operation === '-' && line[0] === '+') {
1526 if (operation === line[0]) {
1537 function collectContext(state, matchChanges) {
1541 contextChanges = false,
1544 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
1545 var change = state.lines[state.index],
1546 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
1548 if (match[0] === '+') {
1552 contextChanges = contextChanges || change[0] !== ' ';
1554 matchIndex++; // Consume any additions in the other block as a conflict to attempt
1555 // to pull in the remaining context after this
1557 if (change[0] === '+') {
1560 while (change[0] === '+') {
1561 changes.push(change);
1562 change = state.lines[++state.index];
1566 if (match.substr(1) === change.substr(1)) {
1567 changes.push(change);
1574 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
1582 while (matchIndex < matchChanges.length) {
1583 merged.push(matchChanges[matchIndex++]);
1592 function allRemoves(changes) {
1593 return changes.reduce(function (prev, change) {
1594 return prev && change[0] === '-';
1598 function skipRemoveSuperset(state, removeChanges, delta) {
1599 for (var i = 0; i < delta; i++) {
1600 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
1602 if (state.lines[state.index + i] !== ' ' + changeContent) {
1607 state.index += delta;
1611 function calcOldNewLineCount(lines) {
1614 lines.forEach(function (line) {
1615 if (typeof line !== 'string') {
1616 var myCount = calcOldNewLineCount(line.mine);
1617 var theirCount = calcOldNewLineCount(line.theirs);
1619 if (oldLines !== undefined) {
1620 if (myCount.oldLines === theirCount.oldLines) {
1621 oldLines += myCount.oldLines;
1623 oldLines = undefined;
1627 if (newLines !== undefined) {
1628 if (myCount.newLines === theirCount.newLines) {
1629 newLines += myCount.newLines;
1631 newLines = undefined;
1635 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
1639 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
1648 } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
1651 function convertChangesToDMP(changes) {
1656 for (var i = 0; i < changes.length; i++) {
1657 change = changes[i];
1661 } else if (change.removed) {
1667 ret.push([operation, change.value]);
1673 function convertChangesToXML(changes) {
1676 for (var i = 0; i < changes.length; i++) {
1677 var change = changes[i];
1681 } else if (change.removed) {
1685 ret.push(escapeHTML(change.value));
1689 } else if (change.removed) {
1694 return ret.join('');
1697 function escapeHTML(s) {
1699 n = n.replace(/&/g, '&');
1700 n = n.replace(/</g, '<');
1701 n = n.replace(/>/g, '>');
1702 n = n.replace(/"/g, '"');
1706 var index_es6 = /*#__PURE__*/Object.freeze({
1709 diffChars: diffChars,
1710 diffWords: diffWords,
1711 diffWordsWithSpace: diffWordsWithSpace,
1712 diffLines: diffLines,
1713 diffTrimmedLines: diffTrimmedLines,
1714 diffSentences: diffSentences,
1717 diffArrays: diffArrays,
1718 structuredPatch: structuredPatch,
1719 createTwoFilesPatch: createTwoFilesPatch,
1720 createPatch: createPatch,
1721 applyPatch: applyPatch,
1722 applyPatches: applyPatches,
1723 parsePatch: parsePatch,
1725 convertChangesToDMP: convertChangesToDMP,
1726 convertChangesToXML: convertChangesToXML,
1727 canonicalize: canonicalize
1736 constructor(file, options) {
1737 options = options || {};
1738 if (!options.readChunk) options.readChunk = 1024;
1740 if (!options.newLineCharacter) {
1741 options.newLineCharacter = 0x0a; //linux line ending
1743 options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
1746 if (typeof file === 'number') {
1749 this.fd = fs$3.openSync(file, 'r');
1752 this.options = options;
1753 this.newLineCharacter = options.newLineCharacter;
1757 _searchInBuffer(buffer, hexNeedle) {
1760 for (let i = 0; i <= buffer.length; i++) {
1761 let b_byte = buffer[i];
1763 if (b_byte === hexNeedle) {
1773 this.eofReached = false;
1774 this.linesCache = [];
1775 this.fdPosition = 0;
1779 fs$3.closeSync(this.fd);
1783 _extractLines(buffer) {
1786 let bufferPosition = 0;
1787 let lastNewLineBufferPosition = 0;
1790 let bufferPositionValue = buffer[bufferPosition++];
1792 if (bufferPositionValue === this.newLineCharacter) {
1793 line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
1795 lastNewLineBufferPosition = bufferPosition;
1796 } else if (!bufferPositionValue) {
1801 let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
1803 if (leftovers.length) {
1804 lines.push(leftovers);
1810 _readChunk(lineLeftovers) {
1811 let totalBytesRead = 0;
1816 const readBuffer = new Buffer(this.options.readChunk);
1817 bytesRead = fs$3.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
1818 totalBytesRead = totalBytesRead + bytesRead;
1819 this.fdPosition = this.fdPosition + bytesRead;
1820 buffers.push(readBuffer);
1821 } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
1823 let bufferData = Buffer.concat(buffers);
1825 if (bytesRead < this.options.readChunk) {
1826 this.eofReached = true;
1827 bufferData = bufferData.slice(0, totalBytesRead);
1830 if (totalBytesRead) {
1831 this.linesCache = this._extractLines(bufferData);
1833 if (lineLeftovers) {
1834 this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
1838 return totalBytesRead;
1842 if (!this.fd) return false;
1845 if (this.eofReached && this.linesCache.length === 0) {
1851 if (!this.linesCache.length) {
1852 bytesRead = this._readChunk();
1855 if (this.linesCache.length) {
1856 line = this.linesCache.shift();
1857 const lastLineCharacter = line[line.length - 1];
1859 if (lastLineCharacter !== 0x0a) {
1860 bytesRead = this._readChunk(line);
1863 line = this.linesCache.shift();
1868 if (this.eofReached && this.linesCache.length === 0) {
1872 if (line && line[line.length - 1] === this.newLineCharacter) {
1873 line = line.slice(0, line.length - 1);
1881 var readlines = LineByLine;
1884 * The inverse of `_.toPairs`; this method returns an object composed
1885 * from key-value `pairs`.
1891 * @param {Array} pairs The key-value pairs.
1892 * @returns {Object} Returns the new object.
1895 * _.fromPairs([['a', 1], ['b', 2]]);
1896 * // => { 'a': 1, 'b': 2 }
1898 function fromPairs(pairs) {
1900 length = pairs == null ? 0 : pairs.length,
1903 while (++index < length) {
1904 var pair = pairs[index];
1905 result[pair[0]] = pair[1];
1911 var fromPairs_1 = fromPairs;
1913 class ConfigError extends Error {}
1915 class DebugError extends Error {}
1917 class UndefinedParserError extends Error {}
1922 UndefinedParserError
1925 function _objectWithoutPropertiesLoose(source, excluded) {
1926 if (source == null) return {};
1928 var sourceKeys = Object.keys(source);
1931 for (i = 0; i < sourceKeys.length; i++) {
1932 key = sourceKeys[i];
1933 if (excluded.indexOf(key) >= 0) continue;
1934 target[key] = source[key];
1940 const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {};
1941 var debug_1 = debug;
1943 // Note: this is the semver.org version of the spec that it implements
1944 // Not necessarily the package version of this code.
1945 const SEMVER_SPEC_VERSION = '2.0.0';
1946 const MAX_LENGTH = 256;
1947 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
1948 /* istanbul ignore next */
1949 9007199254740991; // Max safe segment length for coercion.
1951 const MAX_SAFE_COMPONENT_LENGTH = 16;
1953 SEMVER_SPEC_VERSION,
1956 MAX_SAFE_COMPONENT_LENGTH
1959 function unwrapExports (x) {
1960 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1963 function createCommonjsModule(fn, module) {
1964 return module = { exports: {} }, fn(module, module.exports), module.exports;
1967 function getCjsExportFromNamespace (n) {
1968 return n && n['default'] || n;
1971 var re_1 = createCommonjsModule(function (module, exports) {
1973 MAX_SAFE_COMPONENT_LENGTH
1975 exports = module.exports = {}; // The actual regexps go on exports.re
1977 const re = exports.re = [];
1978 const src = exports.src = [];
1979 const t = exports.t = {};
1982 const createToken = (name, value, isGlobal) => {
1984 debug_1(index, value);
1987 re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
1988 }; // The following Regular Expressions can be used for tokenizing,
1989 // validating, and parsing SemVer version strings.
1990 // ## Numeric Identifier
1991 // A single `0`, or a non-zero digit followed by zero or more digits.
1994 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
1995 createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier
1996 // Zero or more digits, followed by a letter or hyphen, and then zero or
1997 // more letters, digits, or hyphens.
1999 createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version
2000 // Three dot-separated numeric identifiers.
2002 createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
2003 createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); // ## Pre-release Version Identifier
2004 // A numeric identifier, or a non-numeric identifier.
2006 createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
2007 createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); // ## Pre-release Version
2008 // Hyphen, followed by one or more dot-separated pre-release version
2011 createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
2012 createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); // ## Build Metadata Identifier
2013 // Any combination of digits, letters, or hyphens.
2015 createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata
2016 // Plus sign, followed by one or more period-separated build metadata
2019 createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); // ## Full Version String
2020 // A main version, followed optionally by a pre-release version and
2022 // Note that the only major, minor, patch, and pre-release sections of
2023 // the version string are capturing groups. The build metadata is not a
2024 // capturing group, because it should not ever be used in version
2027 createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
2028 createToken('FULL', `^${src[t.FULLPLAIN]}$`); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
2029 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
2030 // common in the npm registry.
2032 createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
2033 createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
2034 createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x".
2035 // Note that "x.x" is a valid xRange identifer, meaning "any version"
2036 // Only the first item is strictly required.
2038 createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
2039 createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
2040 createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
2041 createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
2042 createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
2043 createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); // Coercion.
2044 // Extract anything that could conceivably be a part of a valid semver
2046 createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`);
2047 createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges.
2048 // Meaning is "reasonably at or greater than"
2050 createToken('LONETILDE', '(?:~>?)');
2051 createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
2052 exports.tildeTrimReplace = '$1~';
2053 createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
2054 createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); // Caret ranges.
2055 // Meaning is "at least and backwards compatible with"
2057 createToken('LONECARET', '(?:\\^)');
2058 createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
2059 exports.caretTrimReplace = '$1^';
2060 createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
2061 createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); // A simple gt/lt/eq thing, or just "" to indicate "any version"
2063 createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
2064 createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); // An expression to strip any whitespace between the gtlt and the thing
2065 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
2067 createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
2068 exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
2069 // Note that these all use the loose form, because they'll be
2070 // checked against either the strict or loose comparator form
2073 createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
2074 createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); // Star ranges basically just allow anything at all.
2076 createToken('STAR', '(<|>)?=?\\s*\\*');
2079 var re_3 = re_1.src;
2081 var re_5 = re_1.tildeTrimReplace;
2082 var re_6 = re_1.caretTrimReplace;
2083 var re_7 = re_1.comparatorTrimReplace;
2085 const numeric = /^[0-9]+$/;
2087 const compareIdentifiers = (a, b) => {
2088 const anum = numeric.test(a);
2089 const bnum = numeric.test(b);
2096 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
2099 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
2107 MAX_LENGTH: MAX_LENGTH$1,
2108 MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1
2115 compareIdentifiers: compareIdentifiers$1
2119 constructor(version, options) {
2120 if (!options || typeof options !== 'object') {
2123 includePrerelease: false
2127 if (version instanceof SemVer) {
2128 if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
2131 version = version.version;
2133 } else if (typeof version !== 'string') {
2134 throw new TypeError(`Invalid Version: ${version}`);
2137 if (version.length > MAX_LENGTH$1) {
2138 throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`);
2141 debug_1('SemVer', version, options);
2142 this.options = options;
2143 this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we
2144 // don't run into trouble passing this.options around.
2146 this.includePrerelease = !!options.includePrerelease;
2147 const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
2150 throw new TypeError(`Invalid Version: ${version}`);
2153 this.raw = version; // these are actually numbers
2159 if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) {
2160 throw new TypeError('Invalid major version');
2163 if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) {
2164 throw new TypeError('Invalid minor version');
2167 if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) {
2168 throw new TypeError('Invalid patch version');
2169 } // numberify any prerelease numeric ids
2173 this.prerelease = [];
2175 this.prerelease = m[4].split('.').map(id => {
2176 if (/^[0-9]+$/.test(id)) {
2179 if (num >= 0 && num < MAX_SAFE_INTEGER$1) {
2188 this.build = m[5] ? m[5].split('.') : [];
2193 this.version = `${this.major}.${this.minor}.${this.patch}`;
2195 if (this.prerelease.length) {
2196 this.version += `-${this.prerelease.join('.')}`;
2199 return this.version;
2203 return this.version;
2207 debug_1('SemVer.compare', this.version, this.options, other);
2209 if (!(other instanceof SemVer)) {
2210 if (typeof other === 'string' && other === this.version) {
2214 other = new SemVer(other, this.options);
2217 if (other.version === this.version) {
2221 return this.compareMain(other) || this.comparePre(other);
2224 compareMain(other) {
2225 if (!(other instanceof SemVer)) {
2226 other = new SemVer(other, this.options);
2229 return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch);
2233 if (!(other instanceof SemVer)) {
2234 other = new SemVer(other, this.options);
2235 } // NOT having a prerelease is > having one
2238 if (this.prerelease.length && !other.prerelease.length) {
2240 } else if (!this.prerelease.length && other.prerelease.length) {
2242 } else if (!this.prerelease.length && !other.prerelease.length) {
2249 const a = this.prerelease[i];
2250 const b = other.prerelease[i];
2251 debug_1('prerelease compare', i, a, b);
2253 if (a === undefined && b === undefined) {
2255 } else if (b === undefined) {
2257 } else if (a === undefined) {
2259 } else if (a === b) {
2262 return compareIdentifiers$1(a, b);
2267 compareBuild(other) {
2268 if (!(other instanceof SemVer)) {
2269 other = new SemVer(other, this.options);
2275 const a = this.build[i];
2276 const b = other.build[i];
2277 debug_1('prerelease compare', i, a, b);
2279 if (a === undefined && b === undefined) {
2281 } else if (b === undefined) {
2283 } else if (a === undefined) {
2285 } else if (a === b) {
2288 return compareIdentifiers$1(a, b);
2291 } // preminor will bump the version up to the next minor release, and immediately
2292 // down to pre-release. premajor and prepatch work the same way.
2295 inc(release, identifier) {
2298 this.prerelease.length = 0;
2302 this.inc('pre', identifier);
2306 this.prerelease.length = 0;
2309 this.inc('pre', identifier);
2313 // If this is already a prerelease, it will bump to the next version
2314 // drop any prereleases that might already exist, since they are not
2315 // relevant at this point.
2316 this.prerelease.length = 0;
2317 this.inc('patch', identifier);
2318 this.inc('pre', identifier);
2320 // If the input is a non-prerelease version, this acts the same as
2324 if (this.prerelease.length === 0) {
2325 this.inc('patch', identifier);
2328 this.inc('pre', identifier);
2332 // If this is a pre-major version, bump up to the same major version.
2333 // Otherwise increment major.
2334 // 1.0.0-5 bumps to 1.0.0
2335 // 1.1.0 bumps to 2.0.0
2336 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
2342 this.prerelease = [];
2346 // If this is a pre-minor version, bump up to the same minor version.
2347 // Otherwise increment minor.
2348 // 1.2.0-5 bumps to 1.2.0
2349 // 1.2.1 bumps to 1.3.0
2350 if (this.patch !== 0 || this.prerelease.length === 0) {
2355 this.prerelease = [];
2359 // If this is not a pre-release version, it will increment the patch.
2360 // If it is a pre-release it will bump up to the same patch version.
2361 // 1.2.0-5 patches to 1.2.0
2362 // 1.2.0 patches to 1.2.1
2363 if (this.prerelease.length === 0) {
2367 this.prerelease = [];
2369 // This probably shouldn't be used publicly.
2370 // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
2373 if (this.prerelease.length === 0) {
2374 this.prerelease = [0];
2376 let i = this.prerelease.length;
2379 if (typeof this.prerelease[i] === 'number') {
2380 this.prerelease[i]++;
2386 // didn't increment anything
2387 this.prerelease.push(0);
2392 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
2393 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
2394 if (this.prerelease[0] === identifier) {
2395 if (isNaN(this.prerelease[1])) {
2396 this.prerelease = [identifier, 0];
2399 this.prerelease = [identifier, 0];
2406 throw new Error(`invalid increment argument: ${release}`);
2410 this.raw = this.version;
2416 var semver = SemVer;
2418 const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose));
2420 var compare_1 = compare;
2422 const lt = (a, b, loose) => compare_1(a, b, loose) < 0;
2426 const gte = (a, b, loose) => compare_1(a, b, loose) >= 0;
2430 var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({
2434 var dedent_1 = createCommonjsModule(function (module) {
2436 function dedent(strings) {
2439 if (typeof strings === "string") {
2440 // dedent can be used as a plain function
2444 } // first, perform interpolation
2449 for (var i = 0; i < raw.length; i++) {
2450 result += raw[i]. // join lines when there is a suppressed newline
2451 replace(/\\\n[ \t]*/g, ""). // handle escaped backticks
2452 replace(/\\`/g, "`");
2454 if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
2455 result += arguments.length <= i + 1 ? undefined : arguments[i + 1];
2457 } // now strip indentation
2460 var lines = result.split("\n");
2462 lines.forEach(function (l) {
2463 var m = l.match(/^(\s+)\S+/);
2466 var indent = m[1].length;
2469 // this is the first indented line
2472 mindent = Math.min(mindent, indent);
2477 if (mindent !== null) {
2478 result = lines.map(function (l) {
2479 return l[0] === " " ? l.slice(mindent) : l;
2481 } // dedent eats leading and trailing whitespace too
2484 result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too
2486 return result.replace(/\\n/g, "\n");
2490 module.exports = dedent;
2494 const CATEGORY_CONFIG = "Config";
2495 const CATEGORY_EDITOR = "Editor";
2496 const CATEGORY_FORMAT = "Format";
2497 const CATEGORY_OTHER = "Other";
2498 const CATEGORY_OUTPUT = "Output";
2499 const CATEGORY_GLOBAL = "Global";
2500 const CATEGORY_SPECIAL = "Special";
2502 * @typedef {Object} OptionInfo
2503 * @property {string} [since] - available since version
2504 * @property {string} category
2505 * @property {'int' | 'boolean' | 'choice' | 'path'} type
2506 * @property {boolean} [array] - indicate it's an array of the specified type
2507 * @property {OptionValueInfo} [default]
2508 * @property {OptionRangeInfo} [range] - for type int
2509 * @property {string} description
2510 * @property {string} [deprecated] - deprecated since version
2511 * @property {OptionRedirectInfo} [redirect] - redirect deprecated option
2512 * @property {(value: any) => boolean} [exception]
2513 * @property {OptionChoiceInfo[]} [choices] - for type choice
2514 * @property {string} [cliName]
2515 * @property {string} [cliCategory]
2516 * @property {string} [cliDescription]
2518 * @typedef {number | boolean | string} OptionValue
2519 * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
2521 * @typedef {Object} OptionRedirectInfo
2522 * @property {string} option
2523 * @property {OptionValue} value
2525 * @typedef {Object} OptionRangeInfo
2526 * @property {number} start - recommended range start
2527 * @property {number} end - recommended range end
2528 * @property {number} step - recommended range step
2530 * @typedef {Object} OptionChoiceInfo
2531 * @property {boolean | string} value - boolean for the option that is originally boolean type
2532 * @property {string} description
2533 * @property {string} [since] - undefined if available since the first version of the option
2534 * @property {string} [deprecated] - deprecated since version
2535 * @property {OptionValueInfo} [redirect] - redirect deprecated value
2538 /** @type {{ [name: string]: OptionInfo }} */
2543 category: CATEGORY_SPECIAL,
2551 description: dedent_1`
2552 Print (to stderr) where a cursor at the given position would move to after formatting.
2553 This option cannot be used with --range-start and --range-end.
2555 cliCategory: CATEGORY_EDITOR
2559 category: CATEGORY_GLOBAL,
2568 description: "Which end of line characters to apply.",
2571 description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
2574 description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
2577 description: "Carriage Return character only (\\r), used very rarely"
2580 description: dedent_1`
2582 (mixed values within one file are normalised by looking at what's used after the first line)
2588 category: CATEGORY_SPECIAL,
2590 description: "Specify the input filepath. This will be used to do parser inference.",
2591 cliName: "stdin-filepath",
2592 cliCategory: CATEGORY_OTHER,
2593 cliDescription: "Path to the file to pretend that stdin comes from."
2597 category: CATEGORY_SPECIAL,
2600 description: "Insert @format pragma into file's first docblock comment.",
2601 cliCategory: CATEGORY_OTHER
2605 category: CATEGORY_GLOBAL,
2614 description: "Which parser to use.",
2615 exception: value => typeof value === "string" || typeof value === "function",
2622 description: "JavaScript"
2624 value: "babel-flow",
2630 description: "TypeScript"
2632 value: "typescript",
2634 description: "TypeScript"
2654 description: "JSON5"
2656 value: "json-stringify",
2658 description: "JSON.stringify"
2662 description: "GraphQL"
2666 description: "Markdown"
2682 description: "Handlebars"
2690 description: "Angular"
2694 description: "Lightning Web Components"
2704 category: CATEGORY_GLOBAL,
2705 description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
2706 exception: value => typeof value === "string" || typeof value === "object",
2708 cliCategory: CATEGORY_CONFIG
2717 category: CATEGORY_GLOBAL,
2718 description: dedent_1`
2719 Custom directory that contains prettier plugins in node_modules subdirectory.
2720 Overrides default behavior when plugins are searched relatively to the location of Prettier.
2721 Multiple values are accepted.
2723 exception: value => typeof value === "string" || typeof value === "object",
2724 cliName: "plugin-search-dir",
2725 cliCategory: CATEGORY_CONFIG
2729 category: CATEGORY_GLOBAL,
2732 description: "The line length where Prettier will try wrap.",
2741 category: CATEGORY_SPECIAL,
2749 description: dedent_1`
2750 Format code ending at a given character offset (exclusive).
2751 The range will extend forwards to the end of the selected statement.
2752 This option cannot be used with --cursor-offset.
2754 cliCategory: CATEGORY_EDITOR
2758 category: CATEGORY_SPECIAL,
2766 description: dedent_1`
2767 Format code starting at a given character offset.
2768 The range will extend backwards to the start of the first line containing the selected statement.
2769 This option cannot be used with --cursor-offset.
2771 cliCategory: CATEGORY_EDITOR
2775 category: CATEGORY_SPECIAL,
2778 description: dedent_1`
2779 Require either '@prettier' or '@format' to be present in the file's first docblock comment
2780 in order for it to be formatted.
2782 cliCategory: CATEGORY_OTHER
2786 category: CATEGORY_GLOBAL,
2788 description: "Number of spaces per indentation level.",
2797 category: CATEGORY_GLOBAL,
2800 description: "Indent with tabs instead of spaces."
2814 var require$$0 = getCjsExportFromNamespace(_package$1);
2821 const currentVersion = require$$0.version;
2822 const coreOptions$1 = coreOptions.options;
2824 * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version
2825 * of this function created by `withPlugins`. Don't pass them here directly.
2826 * @param {object} param0
2827 * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`.
2828 * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`.
2829 * @param {boolean=} param0.showUnreleased
2830 * @param {boolean=} param0.showDeprecated
2831 * @param {boolean=} param0.showInternal
2834 function getSupportInfo({
2836 showUnreleased = false,
2837 showDeprecated = false,
2838 showInternal = false
2840 // pre-release version is smaller than the normal version in semver,
2841 // we need to treat it as the normal one so as to test new features.
2842 const version = currentVersion.split("-", 1)[0];
2843 const options = arrayify(Object.assign({}, ...plugins.map(({
2845 }) => options), coreOptions$1), "name").filter(option => filterSince(option) && filterDeprecated(option)).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1).map(mapInternal).map(option => {
2846 option = Object.assign({}, option);
2848 if (Array.isArray(option.default)) {
2849 option.default = option.default.length === 1 ? option.default[0].value : option.default.filter(filterSince).sort((info1, info2) => semver$1.compare(info2.since, info1.since))[0].value;
2852 if (Array.isArray(option.choices)) {
2853 option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option));
2856 const filteredPlugins = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined);
2857 const pluginDefaults = filteredPlugins.reduce((reduced, plugin) => {
2858 reduced[plugin.name] = plugin.defaultOptions[option.name];
2861 return Object.assign({}, option, {
2865 const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince);
2871 function filterSince(object) {
2872 return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since);
2875 function filterDeprecated(object) {
2876 return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated);
2879 function mapInternal(object) {
2884 const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]);
2894 /*! *****************************************************************************
\r
2895 Copyright (c) Microsoft Corporation. All rights reserved.
\r
2896 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
\r
2897 this file except in compliance with the License. You may obtain a copy of the
\r
2898 License at http://www.apache.org/licenses/LICENSE-2.0
\r
2900 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
\r
2901 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
\r
2902 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
\r
2903 MERCHANTABLITY OR NON-INFRINGEMENT.
\r
2905 See the Apache Version 2.0 License for specific language governing permissions
\r
2906 and limitations under the License.
\r
2907 ***************************************************************************** */
2909 /* global Reflect, Promise */
2910 var extendStatics = function (d, b) {
2911 extendStatics = Object.setPrototypeOf || {
2913 } instanceof Array && function (d, b) {
2915 } || function (d, b) {
2916 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
2919 return extendStatics(d, b);
2922 function __extends(d, b) {
2923 extendStatics(d, b);
2926 this.constructor = d;
2929 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2931 var __assign = function () {
2932 __assign = Object.assign || function __assign(t) {
2933 for (var s, i = 1, n = arguments.length; i < n; i++) {
2936 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
2942 return __assign.apply(this, arguments);
2944 function __rest(s, e) {
2947 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
2949 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2950 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
2954 function __decorate(decorators, target, key, desc) {
2955 var c = arguments.length,
2956 r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
2958 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2959 return c > 3 && r && Object.defineProperty(target, key, r), r;
2961 function __param(paramIndex, decorator) {
2962 return function (target, key) {
2963 decorator(target, key, paramIndex);
2966 function __metadata(metadataKey, metadataValue) {
2967 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
2969 function __awaiter(thisArg, _arguments, P, generator) {
2970 return new (P || (P = Promise))(function (resolve, reject) {
2971 function fulfilled(value) {
2973 step(generator.next(value));
2979 function rejected(value) {
2981 step(generator["throw"](value));
2987 function step(result) {
2988 result.done ? resolve(result.value) : new P(function (resolve) {
2989 resolve(result.value);
2990 }).then(fulfilled, rejected);
2993 step((generator = generator.apply(thisArg, _arguments || [])).next());
2996 function __generator(thisArg, body) {
3000 if (t[0] & 1) throw t[1];
3014 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
3019 return function (v) {
3020 return step([n, v]);
3025 if (f) throw new TypeError("Generator is already executing.");
3028 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
3029 if (y = 0, t) op = [op[0] & 2, t.value];
3058 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
3063 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
3068 if (op[0] === 6 && _.label < t[1]) {
3074 if (t && _.label < t[2]) {
3082 if (t[2]) _.ops.pop();
3089 op = body.call(thisArg, _);
3097 if (op[0] & 5) throw op[1];
3099 value: op[0] ? op[1] : void 0,
3104 function __exportStar(m, exports) {
3105 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
3107 function __values(o) {
3108 var m = typeof Symbol === "function" && o[Symbol.iterator],
3110 if (m) return m.call(o);
3113 if (o && i >= o.length) o = void 0;
3121 function __read(o, n) {
3122 var m = typeof Symbol === "function" && o[Symbol.iterator];
3130 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
3137 if (r && !r.done && (m = i["return"])) m.call(i);
3139 if (e) throw e.error;
3145 function __spread() {
3146 for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
3150 function __spreadArrays() {
3151 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
3153 for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
3157 function __await(v) {
3158 return this instanceof __await ? (this.v = v, this) : new __await(v);
3160 function __asyncGenerator(thisArg, _arguments, generator) {
3161 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3162 var g = generator.apply(thisArg, _arguments || []),
3165 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
3170 if (g[n]) i[n] = function (v) {
3171 return new Promise(function (a, b) {
3172 q.push([n, v, a, b]) > 1 || resume(n, v);
3177 function resume(n, v) {
3186 r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
3189 function fulfill(value) {
3190 resume("next", value);
3193 function reject(value) {
3194 resume("throw", value);
3197 function settle(f, v) {
3198 if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
3201 function __asyncDelegator(o) {
3203 return i = {}, verb("next"), verb("throw", function (e) {
3205 }), verb("return"), i[Symbol.iterator] = function () {
3209 function verb(n, f) {
3210 i[n] = o[n] ? function (v) {
3212 value: __await(o[n](v)),
3213 done: n === "return"
3218 function __asyncValues(o) {
3219 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3220 var m = o[Symbol.asyncIterator],
3222 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
3227 i[n] = o[n] && function (v) {
3228 return new Promise(function (resolve, reject) {
3229 v = o[n](v), settle(resolve, reject, v.done, v.value);
3234 function settle(resolve, reject, d, v) {
3235 Promise.resolve(v).then(function (v) {
3243 function __makeTemplateObject(cooked, raw) {
3244 if (Object.defineProperty) {
3245 Object.defineProperty(cooked, "raw", {
3254 function __importStar(mod) {
3255 if (mod && mod.__esModule) return mod;
3257 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
3258 result.default = mod;
3261 function __importDefault(mod) {
3262 return mod && mod.__esModule ? mod : {
3267 var tslib_es6 = /*#__PURE__*/Object.freeze({
3269 __extends: __extends,
3270 get __assign () { return __assign; },
3272 __decorate: __decorate,
3274 __metadata: __metadata,
3275 __awaiter: __awaiter,
3276 __generator: __generator,
3277 __exportStar: __exportStar,
3281 __spreadArrays: __spreadArrays,
3283 __asyncGenerator: __asyncGenerator,
3284 __asyncDelegator: __asyncDelegator,
3285 __asyncValues: __asyncValues,
3286 __makeTemplateObject: __makeTemplateObject,
3287 __importStar: __importStar,
3288 __importDefault: __importDefault
3291 var api = createCommonjsModule(function (module, exports) {
3293 Object.defineProperty(exports, "__esModule", {
3296 exports.apiDescriptor = {
3297 key: key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(key) ? key : JSON.stringify(key),
3300 if (value === null || typeof value !== 'object') {
3301 return JSON.stringify(value);
3304 if (Array.isArray(value)) {
3305 return `[${value.map(subValue => exports.apiDescriptor.value(subValue)).join(', ')}]`;
3308 const keys = Object.keys(value);
3309 return keys.length === 0 ? '{}' : `{ ${keys.map(key => `${exports.apiDescriptor.key(key)}: ${exports.apiDescriptor.value(value[key])}`).join(', ')} }`;
3315 }) => exports.apiDescriptor.value({
3321 var api_1 = api.apiDescriptor;
3323 var descriptors = createCommonjsModule(function (module, exports) {
3325 Object.defineProperty(exports, "__esModule", {
3329 tslib_es6.__exportStar(api, exports);
3331 unwrapExports(descriptors);
3333 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
3335 var escapeStringRegexp = function (str) {
3336 if (typeof str !== 'string') {
3337 throw new TypeError('Expected a string');
3340 return str.replace(matchOperatorsRe, '\\$&');
3344 "aliceblue": [240, 248, 255],
3345 "antiquewhite": [250, 235, 215],
3346 "aqua": [0, 255, 255],
3347 "aquamarine": [127, 255, 212],
3348 "azure": [240, 255, 255],
3349 "beige": [245, 245, 220],
3350 "bisque": [255, 228, 196],
3352 "blanchedalmond": [255, 235, 205],
3353 "blue": [0, 0, 255],
3354 "blueviolet": [138, 43, 226],
3355 "brown": [165, 42, 42],
3356 "burlywood": [222, 184, 135],
3357 "cadetblue": [95, 158, 160],
3358 "chartreuse": [127, 255, 0],
3359 "chocolate": [210, 105, 30],
3360 "coral": [255, 127, 80],
3361 "cornflowerblue": [100, 149, 237],
3362 "cornsilk": [255, 248, 220],
3363 "crimson": [220, 20, 60],
3364 "cyan": [0, 255, 255],
3365 "darkblue": [0, 0, 139],
3366 "darkcyan": [0, 139, 139],
3367 "darkgoldenrod": [184, 134, 11],
3368 "darkgray": [169, 169, 169],
3369 "darkgreen": [0, 100, 0],
3370 "darkgrey": [169, 169, 169],
3371 "darkkhaki": [189, 183, 107],
3372 "darkmagenta": [139, 0, 139],
3373 "darkolivegreen": [85, 107, 47],
3374 "darkorange": [255, 140, 0],
3375 "darkorchid": [153, 50, 204],
3376 "darkred": [139, 0, 0],
3377 "darksalmon": [233, 150, 122],
3378 "darkseagreen": [143, 188, 143],
3379 "darkslateblue": [72, 61, 139],
3380 "darkslategray": [47, 79, 79],
3381 "darkslategrey": [47, 79, 79],
3382 "darkturquoise": [0, 206, 209],
3383 "darkviolet": [148, 0, 211],
3384 "deeppink": [255, 20, 147],
3385 "deepskyblue": [0, 191, 255],
3386 "dimgray": [105, 105, 105],
3387 "dimgrey": [105, 105, 105],
3388 "dodgerblue": [30, 144, 255],
3389 "firebrick": [178, 34, 34],
3390 "floralwhite": [255, 250, 240],
3391 "forestgreen": [34, 139, 34],
3392 "fuchsia": [255, 0, 255],
3393 "gainsboro": [220, 220, 220],
3394 "ghostwhite": [248, 248, 255],
3395 "gold": [255, 215, 0],
3396 "goldenrod": [218, 165, 32],
3397 "gray": [128, 128, 128],
3398 "green": [0, 128, 0],
3399 "greenyellow": [173, 255, 47],
3400 "grey": [128, 128, 128],
3401 "honeydew": [240, 255, 240],
3402 "hotpink": [255, 105, 180],
3403 "indianred": [205, 92, 92],
3404 "indigo": [75, 0, 130],
3405 "ivory": [255, 255, 240],
3406 "khaki": [240, 230, 140],
3407 "lavender": [230, 230, 250],
3408 "lavenderblush": [255, 240, 245],
3409 "lawngreen": [124, 252, 0],
3410 "lemonchiffon": [255, 250, 205],
3411 "lightblue": [173, 216, 230],
3412 "lightcoral": [240, 128, 128],
3413 "lightcyan": [224, 255, 255],
3414 "lightgoldenrodyellow": [250, 250, 210],
3415 "lightgray": [211, 211, 211],
3416 "lightgreen": [144, 238, 144],
3417 "lightgrey": [211, 211, 211],
3418 "lightpink": [255, 182, 193],
3419 "lightsalmon": [255, 160, 122],
3420 "lightseagreen": [32, 178, 170],
3421 "lightskyblue": [135, 206, 250],
3422 "lightslategray": [119, 136, 153],
3423 "lightslategrey": [119, 136, 153],
3424 "lightsteelblue": [176, 196, 222],
3425 "lightyellow": [255, 255, 224],
3426 "lime": [0, 255, 0],
3427 "limegreen": [50, 205, 50],
3428 "linen": [250, 240, 230],
3429 "magenta": [255, 0, 255],
3430 "maroon": [128, 0, 0],
3431 "mediumaquamarine": [102, 205, 170],
3432 "mediumblue": [0, 0, 205],
3433 "mediumorchid": [186, 85, 211],
3434 "mediumpurple": [147, 112, 219],
3435 "mediumseagreen": [60, 179, 113],
3436 "mediumslateblue": [123, 104, 238],
3437 "mediumspringgreen": [0, 250, 154],
3438 "mediumturquoise": [72, 209, 204],
3439 "mediumvioletred": [199, 21, 133],
3440 "midnightblue": [25, 25, 112],
3441 "mintcream": [245, 255, 250],
3442 "mistyrose": [255, 228, 225],
3443 "moccasin": [255, 228, 181],
3444 "navajowhite": [255, 222, 173],
3445 "navy": [0, 0, 128],
3446 "oldlace": [253, 245, 230],
3447 "olive": [128, 128, 0],
3448 "olivedrab": [107, 142, 35],
3449 "orange": [255, 165, 0],
3450 "orangered": [255, 69, 0],
3451 "orchid": [218, 112, 214],
3452 "palegoldenrod": [238, 232, 170],
3453 "palegreen": [152, 251, 152],
3454 "paleturquoise": [175, 238, 238],
3455 "palevioletred": [219, 112, 147],
3456 "papayawhip": [255, 239, 213],
3457 "peachpuff": [255, 218, 185],
3458 "peru": [205, 133, 63],
3459 "pink": [255, 192, 203],
3460 "plum": [221, 160, 221],
3461 "powderblue": [176, 224, 230],
3462 "purple": [128, 0, 128],
3463 "rebeccapurple": [102, 51, 153],
3465 "rosybrown": [188, 143, 143],
3466 "royalblue": [65, 105, 225],
3467 "saddlebrown": [139, 69, 19],
3468 "salmon": [250, 128, 114],
3469 "sandybrown": [244, 164, 96],
3470 "seagreen": [46, 139, 87],
3471 "seashell": [255, 245, 238],
3472 "sienna": [160, 82, 45],
3473 "silver": [192, 192, 192],
3474 "skyblue": [135, 206, 235],
3475 "slateblue": [106, 90, 205],
3476 "slategray": [112, 128, 144],
3477 "slategrey": [112, 128, 144],
3478 "snow": [255, 250, 250],
3479 "springgreen": [0, 255, 127],
3480 "steelblue": [70, 130, 180],
3481 "tan": [210, 180, 140],
3482 "teal": [0, 128, 128],
3483 "thistle": [216, 191, 216],
3484 "tomato": [255, 99, 71],
3485 "turquoise": [64, 224, 208],
3486 "violet": [238, 130, 238],
3487 "wheat": [245, 222, 179],
3488 "white": [255, 255, 255],
3489 "whitesmoke": [245, 245, 245],
3490 "yellow": [255, 255, 0],
3491 "yellowgreen": [154, 205, 50]
3494 var conversions = createCommonjsModule(function (module) {
3496 // NOTE: conversions should only return primitive values (i.e. arrays, or
3497 // values that give correct `typeof` results).
3498 // do not use box values types (i.e. Number(), String(), etc.)
3499 var reverseKeywords = {};
3501 for (var key in colorName) {
3502 if (colorName.hasOwnProperty(key)) {
3503 reverseKeywords[colorName[key]] = key;
3507 var convert = module.exports = {
3558 labels: ['h', 'c', 'g']
3562 labels: ['r16', 'g16', 'b16']
3568 }; // hide .channels and .labels properties
3570 for (var model in convert) {
3571 if (convert.hasOwnProperty(model)) {
3572 if (!('channels' in convert[model])) {
3573 throw new Error('missing channels property: ' + model);
3576 if (!('labels' in convert[model])) {
3577 throw new Error('missing channel labels property: ' + model);
3580 if (convert[model].labels.length !== convert[model].channels) {
3581 throw new Error('channel and label counts mismatch: ' + model);
3584 var channels = convert[model].channels;
3585 var labels = convert[model].labels;
3586 delete convert[model].channels;
3587 delete convert[model].labels;
3588 Object.defineProperty(convert[model], 'channels', {
3591 Object.defineProperty(convert[model], 'labels', {
3597 convert.rgb.hsl = function (rgb) {
3598 var r = rgb[0] / 255;
3599 var g = rgb[1] / 255;
3600 var b = rgb[2] / 255;
3601 var min = Math.min(r, g, b);
3602 var max = Math.max(r, g, b);
3603 var delta = max - min;
3610 } else if (r === max) {
3611 h = (g - b) / delta;
3612 } else if (g === max) {
3613 h = 2 + (b - r) / delta;
3614 } else if (b === max) {
3615 h = 4 + (r - g) / delta;
3618 h = Math.min(h * 60, 360);
3624 l = (min + max) / 2;
3628 } else if (l <= 0.5) {
3629 s = delta / (max + min);
3631 s = delta / (2 - max - min);
3634 return [h, s * 100, l * 100];
3637 convert.rgb.hsv = function (rgb) {
3643 var r = rgb[0] / 255;
3644 var g = rgb[1] / 255;
3645 var b = rgb[2] / 255;
3646 var v = Math.max(r, g, b);
3647 var diff = v - Math.min(r, g, b);
3649 var diffc = function (c) {
3650 return (v - c) / 6 / diff + 1 / 2;
3663 } else if (g === v) {
3664 h = 1 / 3 + rdif - bdif;
3665 } else if (b === v) {
3666 h = 2 / 3 + gdif - rdif;
3676 return [h * 360, s * 100, v * 100];
3679 convert.rgb.hwb = function (rgb) {
3683 var h = convert.rgb.hsl(rgb)[0];
3684 var w = 1 / 255 * Math.min(r, Math.min(g, b));
3685 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
3686 return [h, w * 100, b * 100];
3689 convert.rgb.cmyk = function (rgb) {
3690 var r = rgb[0] / 255;
3691 var g = rgb[1] / 255;
3692 var b = rgb[2] / 255;
3697 k = Math.min(1 - r, 1 - g, 1 - b);
3698 c = (1 - r - k) / (1 - k) || 0;
3699 m = (1 - g - k) / (1 - k) || 0;
3700 y = (1 - b - k) / (1 - k) || 0;
3701 return [c * 100, m * 100, y * 100, k * 100];
3704 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
3708 function comparativeDistance(x, y) {
3709 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
3712 convert.rgb.keyword = function (rgb) {
3713 var reversed = reverseKeywords[rgb];
3719 var currentClosestDistance = Infinity;
3720 var currentClosestKeyword;
3722 for (var keyword in colorName) {
3723 if (colorName.hasOwnProperty(keyword)) {
3724 var value = colorName[keyword]; // Compute comparative distance
3726 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
3728 if (distance < currentClosestDistance) {
3729 currentClosestDistance = distance;
3730 currentClosestKeyword = keyword;
3735 return currentClosestKeyword;
3738 convert.keyword.rgb = function (keyword) {
3739 return colorName[keyword];
3742 convert.rgb.xyz = function (rgb) {
3743 var r = rgb[0] / 255;
3744 var g = rgb[1] / 255;
3745 var b = rgb[2] / 255; // assume sRGB
3747 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
3748 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
3749 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
3750 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
3751 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
3752 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
3753 return [x * 100, y * 100, z * 100];
3756 convert.rgb.lab = function (rgb) {
3757 var xyz = convert.rgb.xyz(rgb);
3767 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
3768 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
3769 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
3776 convert.hsl.rgb = function (hsl) {
3777 var h = hsl[0] / 360;
3778 var s = hsl[1] / 100;
3779 var l = hsl[2] / 100;
3788 return [val, val, val];
3800 for (var i = 0; i < 3; i++) {
3801 t3 = h + 1 / 3 * -(i - 1);
3812 val = t1 + (t2 - t1) * 6 * t3;
3813 } else if (2 * t3 < 1) {
3815 } else if (3 * t3 < 2) {
3816 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
3827 convert.hsl.hsv = function (hsl) {
3829 var s = hsl[1] / 100;
3830 var l = hsl[2] / 100;
3832 var lmin = Math.max(l, 0.01);
3836 s *= l <= 1 ? l : 2 - l;
3837 smin *= lmin <= 1 ? lmin : 2 - lmin;
3839 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
3840 return [h, sv * 100, v * 100];
3843 convert.hsv.rgb = function (hsv) {
3844 var h = hsv[0] / 60;
3845 var s = hsv[1] / 100;
3846 var v = hsv[2] / 100;
3847 var hi = Math.floor(h) % 6;
3848 var f = h - Math.floor(h);
3849 var p = 255 * v * (1 - s);
3850 var q = 255 * v * (1 - s * f);
3851 var t = 255 * v * (1 - s * (1 - f));
3875 convert.hsv.hsl = function (hsv) {
3877 var s = hsv[1] / 100;
3878 var v = hsv[2] / 100;
3879 var vmin = Math.max(v, 0.01);
3884 lmin = (2 - s) * vmin;
3886 sl /= lmin <= 1 ? lmin : 2 - lmin;
3889 return [h, sl * 100, l * 100];
3890 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
3893 convert.hwb.rgb = function (hwb) {
3894 var h = hwb[0] / 360;
3895 var wh = hwb[1] / 100;
3896 var bl = hwb[2] / 100;
3897 var ratio = wh + bl;
3901 var n; // wh + bl cant be > 1
3908 i = Math.floor(6 * h);
3912 if ((i & 0x01) !== 0) {
3916 n = wh + f * (v - wh); // linear interpolation
3962 return [r * 255, g * 255, b * 255];
3965 convert.cmyk.rgb = function (cmyk) {
3966 var c = cmyk[0] / 100;
3967 var m = cmyk[1] / 100;
3968 var y = cmyk[2] / 100;
3969 var k = cmyk[3] / 100;
3973 r = 1 - Math.min(1, c * (1 - k) + k);
3974 g = 1 - Math.min(1, m * (1 - k) + k);
3975 b = 1 - Math.min(1, y * (1 - k) + k);
3976 return [r * 255, g * 255, b * 255];
3979 convert.xyz.rgb = function (xyz) {
3980 var x = xyz[0] / 100;
3981 var y = xyz[1] / 100;
3982 var z = xyz[2] / 100;
3986 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
3987 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
3988 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
3990 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
3991 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
3992 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
3993 r = Math.min(Math.max(0, r), 1);
3994 g = Math.min(Math.max(0, g), 1);
3995 b = Math.min(Math.max(0, b), 1);
3996 return [r * 255, g * 255, b * 255];
3999 convert.xyz.lab = function (xyz) {
4009 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
4010 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
4011 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
4018 convert.lab.xyz = function (lab) {
4028 var y2 = Math.pow(y, 3);
4029 var x2 = Math.pow(x, 3);
4030 var z2 = Math.pow(z, 3);
4031 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
4032 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
4033 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
4040 convert.lab.lch = function (lab) {
4047 hr = Math.atan2(b, a);
4048 h = hr * 360 / 2 / Math.PI;
4054 c = Math.sqrt(a * a + b * b);
4058 convert.lch.lab = function (lch) {
4065 hr = h / 360 * 2 * Math.PI;
4066 a = c * Math.cos(hr);
4067 b = c * Math.sin(hr);
4071 convert.rgb.ansi16 = function (args) {
4075 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
4077 value = Math.round(value / 50);
4083 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
4092 convert.hsv.ansi16 = function (args) {
4093 // optimization here; we already know the value and don't need to get
4094 // it converted for us.
4095 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
4098 convert.rgb.ansi256 = function (args) {
4101 var b = args[2]; // we use the extended greyscale palette here, with the exception of
4102 // black and white. normal palette only has 4 greyscale shades.
4104 if (r === g && g === b) {
4113 return Math.round((r - 8) / 247 * 24) + 232;
4116 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
4120 convert.ansi16.rgb = function (args) {
4121 var color = args % 10; // handle greyscale
4123 if (color === 0 || color === 7) {
4128 color = color / 10.5 * 255;
4129 return [color, color, color];
4132 var mult = (~~(args > 50) + 1) * 0.5;
4133 var r = (color & 1) * mult * 255;
4134 var g = (color >> 1 & 1) * mult * 255;
4135 var b = (color >> 2 & 1) * mult * 255;
4139 convert.ansi256.rgb = function (args) {
4142 var c = (args - 232) * 10 + 8;
4148 var r = Math.floor(args / 36) / 5 * 255;
4149 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
4150 var b = rem % 6 / 5 * 255;
4154 convert.rgb.hex = function (args) {
4155 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
4156 var string = integer.toString(16).toUpperCase();
4157 return '000000'.substring(string.length) + string;
4160 convert.hex.rgb = function (args) {
4161 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
4167 var colorString = match[0];
4169 if (match[0].length === 3) {
4170 colorString = colorString.split('').map(function (char) {
4175 var integer = parseInt(colorString, 16);
4176 var r = integer >> 16 & 0xFF;
4177 var g = integer >> 8 & 0xFF;
4178 var b = integer & 0xFF;
4182 convert.rgb.hcg = function (rgb) {
4183 var r = rgb[0] / 255;
4184 var g = rgb[1] / 255;
4185 var b = rgb[2] / 255;
4186 var max = Math.max(Math.max(r, g), b);
4187 var min = Math.min(Math.min(r, g), b);
4188 var chroma = max - min;
4193 grayscale = min / (1 - chroma);
4200 } else if (max === r) {
4201 hue = (g - b) / chroma % 6;
4202 } else if (max === g) {
4203 hue = 2 + (b - r) / chroma;
4205 hue = 4 + (r - g) / chroma + 4;
4210 return [hue * 360, chroma * 100, grayscale * 100];
4213 convert.hsl.hcg = function (hsl) {
4214 var s = hsl[1] / 100;
4215 var l = hsl[2] / 100;
4222 c = 2.0 * s * (1.0 - l);
4226 f = (l - 0.5 * c) / (1.0 - c);
4229 return [hsl[0], c * 100, f * 100];
4232 convert.hsv.hcg = function (hsv) {
4233 var s = hsv[1] / 100;
4234 var v = hsv[2] / 100;
4239 f = (v - c) / (1 - c);
4242 return [hsv[0], c * 100, f * 100];
4245 convert.hcg.rgb = function (hcg) {
4246 var h = hcg[0] / 360;
4247 var c = hcg[1] / 100;
4248 var g = hcg[2] / 100;
4251 return [g * 255, g * 255, g * 255];
4254 var pure = [0, 0, 0];
4260 switch (Math.floor(hi)) {
4298 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
4301 convert.hcg.hsv = function (hcg) {
4302 var c = hcg[1] / 100;
4303 var g = hcg[2] / 100;
4304 var v = c + g * (1.0 - c);
4311 return [hcg[0], f * 100, v * 100];
4314 convert.hcg.hsl = function (hcg) {
4315 var c = hcg[1] / 100;
4316 var g = hcg[2] / 100;
4317 var l = g * (1.0 - c) + 0.5 * c;
4320 if (l > 0.0 && l < 0.5) {
4322 } else if (l >= 0.5 && l < 1.0) {
4323 s = c / (2 * (1 - l));
4326 return [hcg[0], s * 100, l * 100];
4329 convert.hcg.hwb = function (hcg) {
4330 var c = hcg[1] / 100;
4331 var g = hcg[2] / 100;
4332 var v = c + g * (1.0 - c);
4333 return [hcg[0], (v - c) * 100, (1 - v) * 100];
4336 convert.hwb.hcg = function (hwb) {
4337 var w = hwb[1] / 100;
4338 var b = hwb[2] / 100;
4344 g = (v - c) / (1 - c);
4347 return [hwb[0], c * 100, g * 100];
4350 convert.apple.rgb = function (apple) {
4351 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
4354 convert.rgb.apple = function (rgb) {
4355 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
4358 convert.gray.rgb = function (args) {
4359 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
4362 convert.gray.hsl = convert.gray.hsv = function (args) {
4363 return [0, 0, args[0]];
4366 convert.gray.hwb = function (gray) {
4367 return [0, 100, gray[0]];
4370 convert.gray.cmyk = function (gray) {
4371 return [0, 0, 0, gray[0]];
4374 convert.gray.lab = function (gray) {
4375 return [gray[0], 0, 0];
4378 convert.gray.hex = function (gray) {
4379 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
4380 var integer = (val << 16) + (val << 8) + val;
4381 var string = integer.toString(16).toUpperCase();
4382 return '000000'.substring(string.length) + string;
4385 convert.rgb.gray = function (rgb) {
4386 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
4387 return [val / 255 * 100];
4390 var conversions_1 = conversions.rgb;
4391 var conversions_2 = conversions.hsl;
4392 var conversions_3 = conversions.hsv;
4393 var conversions_4 = conversions.hwb;
4394 var conversions_5 = conversions.cmyk;
4395 var conversions_6 = conversions.xyz;
4396 var conversions_7 = conversions.lab;
4397 var conversions_8 = conversions.lch;
4398 var conversions_9 = conversions.hex;
4399 var conversions_10 = conversions.keyword;
4400 var conversions_11 = conversions.ansi16;
4401 var conversions_12 = conversions.ansi256;
4402 var conversions_13 = conversions.hcg;
4403 var conversions_14 = conversions.apple;
4404 var conversions_15 = conversions.gray;
4407 this function routes a model to all other models.
4409 all functions that are routed have a property `.conversion` attached
4410 to the returned synthetic function. This property is an array
4411 of strings, each with the steps in between the 'from' and 'to'
4412 color models (inclusive).
4414 conversions that are not possible simply are not included.
4417 function buildGraph() {
4418 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
4420 var models = Object.keys(conversions);
4422 for (var len = models.length, i = 0; i < len; i++) {
4423 graph[models[i]] = {
4424 // http://jsperf.com/1-vs-infinity
4425 // micro-opt, but this is simple.
4432 } // https://en.wikipedia.org/wiki/Breadth-first_search
4435 function deriveBFS(fromModel) {
4436 var graph = buildGraph();
4437 var queue = [fromModel]; // unshift -> queue -> pop
4439 graph[fromModel].distance = 0;
4441 while (queue.length) {
4442 var current = queue.pop();
4443 var adjacents = Object.keys(conversions[current]);
4445 for (var len = adjacents.length, i = 0; i < len; i++) {
4446 var adjacent = adjacents[i];
4447 var node = graph[adjacent];
4449 if (node.distance === -1) {
4450 node.distance = graph[current].distance + 1;
4451 node.parent = current;
4452 queue.unshift(adjacent);
4460 function link(from, to) {
4461 return function (args) {
4462 return to(from(args));
4466 function wrapConversion(toModel, graph) {
4467 var path = [graph[toModel].parent, toModel];
4468 var fn = conversions[graph[toModel].parent][toModel];
4469 var cur = graph[toModel].parent;
4471 while (graph[cur].parent) {
4472 path.unshift(graph[cur].parent);
4473 fn = link(conversions[graph[cur].parent][cur], fn);
4474 cur = graph[cur].parent;
4477 fn.conversion = path;
4481 var route = function (fromModel) {
4482 var graph = deriveBFS(fromModel);
4483 var conversion = {};
4484 var models = Object.keys(graph);
4486 for (var len = models.length, i = 0; i < len; i++) {
4487 var toModel = models[i];
4488 var node = graph[toModel];
4490 if (node.parent === null) {
4491 // no possible conversion, or this node is the source model.
4495 conversion[toModel] = wrapConversion(toModel, graph);
4502 var models = Object.keys(conversions);
4504 function wrapRaw(fn) {
4505 var wrappedFn = function (args) {
4506 if (args === undefined || args === null) {
4510 if (arguments.length > 1) {
4511 args = Array.prototype.slice.call(arguments);
4515 }; // preserve .conversion property if there is one
4518 if ('conversion' in fn) {
4519 wrappedFn.conversion = fn.conversion;
4525 function wrapRounded(fn) {
4526 var wrappedFn = function (args) {
4527 if (args === undefined || args === null) {
4531 if (arguments.length > 1) {
4532 args = Array.prototype.slice.call(arguments);
4535 var result = fn(args); // we're assuming the result is an array here.
4536 // see notice in conversions.js; don't use box types
4537 // in conversion functions.
4539 if (typeof result === 'object') {
4540 for (var len = result.length, i = 0; i < len; i++) {
4541 result[i] = Math.round(result[i]);
4546 }; // preserve .conversion property if there is one
4549 if ('conversion' in fn) {
4550 wrappedFn.conversion = fn.conversion;
4556 models.forEach(function (fromModel) {
4557 convert[fromModel] = {};
4558 Object.defineProperty(convert[fromModel], 'channels', {
4559 value: conversions[fromModel].channels
4561 Object.defineProperty(convert[fromModel], 'labels', {
4562 value: conversions[fromModel].labels
4564 var routes = route(fromModel);
4565 var routeModels = Object.keys(routes);
4566 routeModels.forEach(function (toModel) {
4567 var fn = routes[toModel];
4568 convert[fromModel][toModel] = wrapRounded(fn);
4569 convert[fromModel][toModel].raw = wrapRaw(fn);
4572 var colorConvert = convert;
4574 var ansiStyles = createCommonjsModule(function (module) {
4576 const wrapAnsi16 = (fn, offset) => function () {
4577 const code = fn.apply(colorConvert, arguments);
4578 return `\u001B[${code + offset}m`;
4581 const wrapAnsi256 = (fn, offset) => function () {
4582 const code = fn.apply(colorConvert, arguments);
4583 return `\u001B[${38 + offset};5;${code}m`;
4586 const wrapAnsi16m = (fn, offset) => function () {
4587 const rgb = fn.apply(colorConvert, arguments);
4588 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
4591 function assembleStyles() {
4592 const codes = new Map();
4596 // 21 isn't widely supported and 22 does the same thing
4603 strikethrough: [9, 29]
4616 redBright: [91, 39],
4617 greenBright: [92, 39],
4618 yellowBright: [93, 39],
4619 blueBright: [94, 39],
4620 magentaBright: [95, 39],
4621 cyanBright: [96, 39],
4622 whiteBright: [97, 39]
4630 bgMagenta: [45, 49],
4634 bgBlackBright: [100, 49],
4635 bgRedBright: [101, 49],
4636 bgGreenBright: [102, 49],
4637 bgYellowBright: [103, 49],
4638 bgBlueBright: [104, 49],
4639 bgMagentaBright: [105, 49],
4640 bgCyanBright: [106, 49],
4641 bgWhiteBright: [107, 49]
4645 styles.color.grey = styles.color.gray;
4647 for (const groupName of Object.keys(styles)) {
4648 const group = styles[groupName];
4650 for (const styleName of Object.keys(group)) {
4651 const style = group[styleName];
4652 styles[styleName] = {
4653 open: `\u001B[${style[0]}m`,
4654 close: `\u001B[${style[1]}m`
4656 group[styleName] = styles[styleName];
4657 codes.set(style[0], style[1]);
4660 Object.defineProperty(styles, groupName, {
4664 Object.defineProperty(styles, 'codes', {
4670 const ansi2ansi = n => n;
4672 const rgb2rgb = (r, g, b) => [r, g, b];
4674 styles.color.close = '\u001B[39m';
4675 styles.bgColor.close = '\u001B[49m';
4676 styles.color.ansi = {
4677 ansi: wrapAnsi16(ansi2ansi, 0)
4679 styles.color.ansi256 = {
4680 ansi256: wrapAnsi256(ansi2ansi, 0)
4682 styles.color.ansi16m = {
4683 rgb: wrapAnsi16m(rgb2rgb, 0)
4685 styles.bgColor.ansi = {
4686 ansi: wrapAnsi16(ansi2ansi, 10)
4688 styles.bgColor.ansi256 = {
4689 ansi256: wrapAnsi256(ansi2ansi, 10)
4691 styles.bgColor.ansi16m = {
4692 rgb: wrapAnsi16m(rgb2rgb, 10)
4695 for (let key of Object.keys(colorConvert)) {
4696 if (typeof colorConvert[key] !== 'object') {
4700 const suite = colorConvert[key];
4702 if (key === 'ansi16') {
4706 if ('ansi16' in suite) {
4707 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
4708 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
4711 if ('ansi256' in suite) {
4712 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
4713 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
4716 if ('rgb' in suite) {
4717 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
4718 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
4723 } // Make the export immutable
4726 Object.defineProperty(module, 'exports', {
4732 var hasFlag = (flag, argv) => {
4733 argv = argv || process.argv;
4734 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
4735 const pos = argv.indexOf(prefix + flag);
4736 const terminatorPos = argv.indexOf('--');
4737 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
4740 const env = process.env;
4743 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
4745 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
4749 if ('FORCE_COLOR' in env) {
4750 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
4753 function translateLevel(level) {
4766 function supportsColor(stream) {
4767 if (forceColor === false) {
4771 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
4775 if (hasFlag('color=256')) {
4779 if (stream && !stream.isTTY && forceColor !== true) {
4783 const min = forceColor ? 1 : 0;
4785 if (process.platform === 'win32') {
4786 // Node.js 7.5.0 is the first version of Node.js to include a patch to
4787 // libuv that enables 256 color output on Windows. Anything earlier and it
4788 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
4789 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
4790 // release that supports 256 colors. Windows 10 build 14931 is the first release
4791 // that supports 16m/TrueColor.
4792 const osRelease = os$1.release().split('.');
4794 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
4795 return Number(osRelease[2]) >= 14931 ? 3 : 2;
4802 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
4809 if ('TEAMCITY_VERSION' in env) {
4810 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
4813 if (env.COLORTERM === 'truecolor') {
4817 if ('TERM_PROGRAM' in env) {
4818 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
4820 switch (env.TERM_PROGRAM) {
4822 return version >= 3 ? 3 : 2;
4824 case 'Apple_Terminal':
4830 if (/-256(color)?$/i.test(env.TERM)) {
4834 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
4838 if ('COLORTERM' in env) {
4842 if (env.TERM === 'dumb') {
4849 function getSupportLevel(stream) {
4850 const level = supportsColor(stream);
4851 return translateLevel(level);
4854 var supportsColor_1 = {
4855 supportsColor: getSupportLevel,
4856 stdout: getSupportLevel(process.stdout),
4857 stderr: getSupportLevel(process.stderr)
4860 const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
4861 const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
4862 const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
4863 const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
4864 const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
4866 function unescape(c) {
4867 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
4868 return String.fromCharCode(parseInt(c.slice(1), 16));
4871 return ESCAPES.get(c) || c;
4874 function parseArguments(name, args) {
4876 const chunks = args.trim().split(/\s*,\s*/g);
4879 for (const chunk of chunks) {
4880 if (!isNaN(chunk)) {
4881 results.push(Number(chunk));
4882 } else if (matches = chunk.match(STRING_REGEX)) {
4883 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
4885 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
4892 function parseStyle(style) {
4893 STYLE_REGEX.lastIndex = 0;
4897 while ((matches = STYLE_REGEX.exec(style)) !== null) {
4898 const name = matches[1];
4901 const args = parseArguments(name, matches[2]);
4902 results.push([name].concat(args));
4904 results.push([name]);
4911 function buildStyle(chalk, styles) {
4914 for (const layer of styles) {
4915 for (const style of layer.styles) {
4916 enabled[style[0]] = layer.inverse ? null : style.slice(1);
4920 let current = chalk;
4922 for (const styleName of Object.keys(enabled)) {
4923 if (Array.isArray(enabled[styleName])) {
4924 if (!(styleName in current)) {
4925 throw new Error(`Unknown Chalk style: ${styleName}`);
4928 if (enabled[styleName].length > 0) {
4929 current = current[styleName].apply(current, enabled[styleName]);
4931 current = current[styleName];
4939 var templates = (chalk, tmp) => {
4942 let chunk = []; // eslint-disable-next-line max-params
4944 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
4946 chunk.push(unescape(escapeChar));
4948 const str = chunk.join('');
4950 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
4953 styles: parseStyle(style)
4956 if (styles.length === 0) {
4957 throw new Error('Found extraneous } in Chalk template literal');
4960 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
4967 chunks.push(chunk.join(''));
4969 if (styles.length > 0) {
4970 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
4971 throw new Error(errMsg);
4974 return chunks.join('');
4977 var chalk = createCommonjsModule(function (module) {
4979 const stdoutColor = supportsColor_1.stdout;
4980 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
4982 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
4984 const skipModels = new Set(['gray']);
4985 const styles = Object.create(null);
4987 function applyOptions(obj, options) {
4988 options = options || {}; // Detect level if not set manually
4990 const scLevel = stdoutColor ? stdoutColor.level : 0;
4991 obj.level = options.level === undefined ? scLevel : options.level;
4992 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
4995 function Chalk(options) {
4996 // We check for this.template here since calling `chalk.constructor()`
4997 // by itself will have a `this` of a previously constructed chalk object
4998 if (!this || !(this instanceof Chalk) || this.template) {
5000 applyOptions(chalk, options);
5002 chalk.template = function () {
5003 const args = [].slice.call(arguments);
5004 return chalkTag.apply(null, [chalk.template].concat(args));
5007 Object.setPrototypeOf(chalk, Chalk.prototype);
5008 Object.setPrototypeOf(chalk.template, chalk);
5009 chalk.template.constructor = Chalk;
5010 return chalk.template;
5013 applyOptions(this, options);
5014 } // Use bright blue on Windows as the normal blue color is illegible
5017 if (isSimpleWindowsTerm) {
5018 ansiStyles.blue.open = '\u001B[94m';
5021 for (const key of Object.keys(ansiStyles)) {
5022 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
5025 const codes = ansiStyles[key];
5026 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
5034 return build.call(this, this._styles || [], true, 'visible');
5038 ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
5040 for (const model of Object.keys(ansiStyles.color.ansi)) {
5041 if (skipModels.has(model)) {
5047 const level = this.level;
5048 return function () {
5049 const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
5052 close: ansiStyles.color.close,
5053 closeRe: ansiStyles.color.closeRe
5055 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
5062 ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
5064 for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
5065 if (skipModels.has(model)) {
5069 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
5072 const level = this.level;
5073 return function () {
5074 const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
5077 close: ansiStyles.bgColor.close,
5078 closeRe: ansiStyles.bgColor.closeRe
5080 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
5087 const proto = Object.defineProperties(() => {}, styles);
5089 function build(_styles, _empty, key) {
5090 const builder = function () {
5091 return applyStyle.apply(builder, arguments);
5094 builder._styles = _styles;
5095 builder._empty = _empty;
5097 Object.defineProperty(builder, 'level', {
5109 Object.defineProperty(builder, 'enabled', {
5113 return self.enabled;
5117 self.enabled = enabled;
5120 }); // See below for fix regarding invisible grey/dim combination on Windows
5122 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
5123 // no way to create a function with a different prototype
5125 builder.__proto__ = proto; // eslint-disable-line no-proto
5130 function applyStyle() {
5131 // Support varags, but simply cast to string in case there's only one arg
5132 const args = arguments;
5133 const argsLen = args.length;
5134 let str = String(arguments[0]);
5136 if (argsLen === 0) {
5141 // Don't slice `arguments`, it prevents V8 optimizations
5142 for (let a = 1; a < argsLen; a++) {
5143 str += ' ' + args[a];
5147 if (!this.enabled || this.level <= 0 || !str) {
5148 return this._empty ? '' : str;
5149 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
5150 // see https://github.com/chalk/chalk/issues/58
5151 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
5154 const originalDim = ansiStyles.dim.open;
5156 if (isSimpleWindowsTerm && this.hasGrey) {
5157 ansiStyles.dim.open = '';
5160 for (const code of this._styles.slice().reverse()) {
5161 // Replace any instances already present with a re-opening code
5162 // otherwise only the part of the string until said closing code
5163 // will be colored, and the rest will simply be 'plain'.
5164 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
5165 // after next line to fix a bleed issue on macOS
5166 // https://github.com/chalk/chalk/pull/92
5168 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
5169 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
5172 ansiStyles.dim.open = originalDim;
5176 function chalkTag(chalk, strings) {
5177 if (!Array.isArray(strings)) {
5178 // If chalk() was called by itself or with a string,
5179 // return the string itself as a string.
5180 return [].slice.call(arguments, 1).join(' ');
5183 const args = [].slice.call(arguments, 2);
5184 const parts = [strings.raw[0]];
5186 for (let i = 1; i < strings.length; i++) {
5187 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
5188 parts.push(String(strings.raw[i]));
5191 return templates(chalk, parts.join(''));
5194 Object.defineProperties(Chalk.prototype, styles);
5195 module.exports = Chalk(); // eslint-disable-line new-cap
5197 module.exports.supportsColor = stdoutColor;
5198 module.exports.default = module.exports; // For TypeScript
5200 var chalk_1 = chalk.supportsColor;
5202 var common = createCommonjsModule(function (module, exports) {
5204 Object.defineProperty(exports, "__esModule", {
5208 exports.commonDeprecatedHandler = (keyOrPair, redirectTo, {
5211 const messages = [`${chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair))} is deprecated`];
5214 messages.push(`we now treat it as ${chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))}`);
5217 return messages.join('; ') + '.';
5220 unwrapExports(common);
5221 var common_1 = common.commonDeprecatedHandler;
5223 var deprecated = createCommonjsModule(function (module, exports) {
5225 Object.defineProperty(exports, "__esModule", {
5229 tslib_es6.__exportStar(common, exports);
5231 unwrapExports(deprecated);
5233 var common$1 = createCommonjsModule(function (module, exports) {
5235 Object.defineProperty(exports, "__esModule", {
5239 exports.commonInvalidHandler = (key, value, utils) => [`Invalid ${chalk.default.red(utils.descriptor.key(key))} value.`, `Expected ${chalk.default.blue(utils.schemas[key].expected(utils))},`, `but received ${chalk.default.red(utils.descriptor.value(value))}.`].join(' ');
5241 unwrapExports(common$1);
5242 var common_1$1 = common$1.commonInvalidHandler;
5244 var invalid = createCommonjsModule(function (module, exports) {
5246 Object.defineProperty(exports, "__esModule", {
5250 tslib_es6.__exportStar(common$1, exports);
5252 unwrapExports(invalid);
5254 /* eslint-disable no-nested-ternary */
5257 var charCodeCache = [];
5259 var leven = function (a, b) {
5264 var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
5265 // shortest & which one is the longest
5267 if (a.length > b.length) {
5272 var aLen = a.length;
5273 var bLen = b.length;
5281 } // Performing suffix trimming:
5282 // We can linearly drop suffix common to both strings since they
5283 // don't increase distance at all
5284 // Note: `~-` is the bitwise way to perform a `- 1` operation
5287 while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
5294 } // Performing prefix trimming
5295 // We can linearly drop prefix common to both strings since they
5296 // don't increase distance at all
5301 while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
5320 charCodeCache[start + i] = a.charCodeAt(start + i);
5325 bCharCode = b.charCodeAt(start + j);
5329 for (i = 0; i < aLen; i++) {
5330 tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
5332 ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
5339 var leven_1 = createCommonjsModule(function (module, exports) {
5341 Object.defineProperty(exports, "__esModule", {
5345 exports.levenUnknownHandler = (key, value, {
5350 const messages = [`Ignored unknown option ${chalk.default.yellow(descriptor.pair({
5354 const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3);
5357 messages.push(`Did you mean ${chalk.default.blue(descriptor.key(suggestion))}?`);
5360 logger.warn(messages.join(' '));
5363 unwrapExports(leven_1);
5364 var leven_2 = leven_1.levenUnknownHandler;
5366 var unknown = createCommonjsModule(function (module, exports) {
5368 Object.defineProperty(exports, "__esModule", {
5372 tslib_es6.__exportStar(leven_1, exports);
5374 unwrapExports(unknown);
5376 var handlers = createCommonjsModule(function (module, exports) {
5378 Object.defineProperty(exports, "__esModule", {
5382 tslib_es6.__exportStar(deprecated, exports);
5384 tslib_es6.__exportStar(invalid, exports);
5386 tslib_es6.__exportStar(unknown, exports);
5388 unwrapExports(handlers);
5390 var schema = createCommonjsModule(function (module, exports) {
5392 Object.defineProperty(exports, "__esModule", {
5395 const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
5397 function createSchema(SchemaConstructor, parameters) {
5398 const schema = new SchemaConstructor(parameters);
5399 const subSchema = Object.create(schema);
5401 for (const handlerKey of HANDLER_KEYS) {
5402 if (handlerKey in parameters) {
5403 subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
5410 exports.createSchema = createSchema;
5413 constructor(parameters) {
5414 this.name = parameters.name;
5417 static create(parameters) {
5418 // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
5419 return createSchema(this, parameters);
5424 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
5429 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
5432 validate(_value, _utils) {
5436 deprecated(_value, _utils) {
5440 forward(_value, _utils) {
5444 redirect(_value, _utils) {
5448 overlap(currentValue, _newValue, _utils) {
5449 return currentValue;
5452 preprocess(value, _utils) {
5456 postprocess(value, _utils) {
5462 exports.Schema = Schema;
5464 function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
5465 return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler;
5468 unwrapExports(schema);
5469 var schema_1 = schema.createSchema;
5470 var schema_2 = schema.Schema;
5472 var alias = createCommonjsModule(function (module, exports) {
5474 Object.defineProperty(exports, "__esModule", {
5478 class AliasSchema extends schema.Schema {
5479 constructor(parameters) {
5481 this._sourceName = parameters.sourceName;
5485 return utils.schemas[this._sourceName].expected(utils);
5488 validate(value, utils) {
5489 return utils.schemas[this._sourceName].validate(value, utils);
5492 redirect(_value, _utils) {
5493 return this._sourceName;
5498 exports.AliasSchema = AliasSchema;
5500 unwrapExports(alias);
5501 var alias_1 = alias.AliasSchema;
5503 var any = createCommonjsModule(function (module, exports) {
5505 Object.defineProperty(exports, "__esModule", {
5509 class AnySchema extends schema.Schema {
5520 exports.AnySchema = AnySchema;
5523 var any_1 = any.AnySchema;
5525 var array = createCommonjsModule(function (module, exports) {
5527 Object.defineProperty(exports, "__esModule", {
5531 class ArraySchema extends schema.Schema {
5535 name = valueSchema.name
5537 handlers = tslib_es6.__rest(_a, ["valueSchema", "name"]);
5539 super(Object.assign({}, handlers, {
5542 this._valueSchema = valueSchema;
5546 return `an array of ${this._valueSchema.expected(utils)}`;
5549 validate(value, utils) {
5550 if (!Array.isArray(value)) {
5554 const invalidValues = [];
5556 for (const subValue of value) {
5557 const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
5559 if (subValidateResult !== true) {
5560 invalidValues.push(subValidateResult.value);
5564 return invalidValues.length === 0 ? true : {
5565 value: invalidValues
5569 deprecated(value, utils) {
5570 const deprecatedResult = [];
5572 for (const subValue of value) {
5573 const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
5575 if (subDeprecatedResult !== false) {
5576 deprecatedResult.push(...subDeprecatedResult.map(({
5577 value: deprecatedValue
5579 value: [deprecatedValue]
5584 return deprecatedResult;
5587 forward(value, utils) {
5588 const forwardResult = [];
5590 for (const subValue of value) {
5591 const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
5592 forwardResult.push(...subForwardResult.map(wrapTransferResult));
5595 return forwardResult;
5598 redirect(value, utils) {
5600 const redirect = [];
5602 for (const subValue of value) {
5603 const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
5605 if ('remain' in subRedirectResult) {
5606 remain.push(subRedirectResult.remain);
5609 redirect.push(...subRedirectResult.redirect.map(wrapTransferResult));
5612 return remain.length === 0 ? {
5620 overlap(currentValue, newValue) {
5621 return currentValue.concat(newValue);
5626 exports.ArraySchema = ArraySchema;
5628 function wrapTransferResult({
5638 unwrapExports(array);
5639 var array_1 = array.ArraySchema;
5641 var boolean_1 = createCommonjsModule(function (module, exports) {
5643 Object.defineProperty(exports, "__esModule", {
5647 class BooleanSchema extends schema.Schema {
5649 return 'true or false';
5653 return typeof value === 'boolean';
5658 exports.BooleanSchema = BooleanSchema;
5660 unwrapExports(boolean_1);
5661 var boolean_2 = boolean_1.BooleanSchema;
5663 var utils = createCommonjsModule(function (module, exports) {
5665 Object.defineProperty(exports, "__esModule", {
5669 function recordFromArray(array, mainKey) {
5670 const record = Object.create(null);
5672 for (const value of array) {
5673 const key = value[mainKey]; // istanbul ignore next
5676 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
5680 record[key] = value;
5686 exports.recordFromArray = recordFromArray;
5688 function mapFromArray(array, mainKey) {
5689 const map = new Map();
5691 for (const value of array) {
5692 const key = value[mainKey]; // istanbul ignore next
5695 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
5698 map.set(key, value);
5704 exports.mapFromArray = mapFromArray;
5706 function createAutoChecklist() {
5707 const map = Object.create(null);
5709 const idString = JSON.stringify(id);
5711 if (map[idString]) {
5715 map[idString] = true;
5720 exports.createAutoChecklist = createAutoChecklist;
5722 function partition(array, predicate) {
5723 const trueArray = [];
5724 const falseArray = [];
5726 for (const value of array) {
5727 if (predicate(value)) {
5728 trueArray.push(value);
5730 falseArray.push(value);
5734 return [trueArray, falseArray];
5737 exports.partition = partition;
5739 function isInt(value) {
5740 return value === Math.floor(value);
5743 exports.isInt = isInt;
5745 function comparePrimitive(a, b) {
5750 const typeofA = typeof a;
5751 const typeofB = typeof b;
5752 const orders = ['undefined', 'object', 'boolean', 'number', 'string'];
5754 if (typeofA !== typeofB) {
5755 return orders.indexOf(typeofA) - orders.indexOf(typeofB);
5758 if (typeofA !== 'string') {
5759 return Number(a) - Number(b);
5762 return a.localeCompare(b);
5765 exports.comparePrimitive = comparePrimitive;
5767 function normalizeDefaultResult(result) {
5768 return result === undefined ? {} : result;
5771 exports.normalizeDefaultResult = normalizeDefaultResult;
5773 function normalizeValidateResult(result, value) {
5774 return result === true ? true : result === false ? {
5779 exports.normalizeValidateResult = normalizeValidateResult;
5781 function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) {
5782 return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
5784 }] : 'value' in result ? [result] : result.length === 0 ? false : result;
5787 exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
5789 function normalizeTransferResult(result, value) {
5790 return typeof result === 'string' || 'key' in result ? {
5793 } : 'from' in result ? {
5802 exports.normalizeTransferResult = normalizeTransferResult;
5804 function normalizeForwardResult(result, value) {
5805 return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)];
5808 exports.normalizeForwardResult = normalizeForwardResult;
5810 function normalizeRedirectResult(result, value) {
5811 const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value);
5812 return redirect.length === 0 ? {
5815 } : typeof result === 'object' && 'remain' in result ? {
5816 remain: result.remain,
5823 exports.normalizeRedirectResult = normalizeRedirectResult;
5825 unwrapExports(utils);
5826 var utils_1 = utils.recordFromArray;
5827 var utils_2 = utils.mapFromArray;
5828 var utils_3 = utils.createAutoChecklist;
5829 var utils_4 = utils.partition;
5830 var utils_5 = utils.isInt;
5831 var utils_6 = utils.comparePrimitive;
5832 var utils_7 = utils.normalizeDefaultResult;
5833 var utils_8 = utils.normalizeValidateResult;
5834 var utils_9 = utils.normalizeDeprecatedResult;
5835 var utils_10 = utils.normalizeTransferResult;
5836 var utils_11 = utils.normalizeForwardResult;
5837 var utils_12 = utils.normalizeRedirectResult;
5839 var choice = createCommonjsModule(function (module, exports) {
5841 Object.defineProperty(exports, "__esModule", {
5845 class ChoiceSchema extends schema.Schema {
5846 constructor(parameters) {
5848 this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : {
5856 const choiceValues = Array.from(this._choices.keys()).map(value => this._choices.get(value)).filter(choiceInfo => !choiceInfo.deprecated).map(choiceInfo => choiceInfo.value).sort(utils.comparePrimitive).map(descriptor.value);
5857 const head = choiceValues.slice(0, -2);
5858 const tail = choiceValues.slice(-2);
5859 return head.concat(tail.join(' or ')).join(', ');
5863 return this._choices.has(value);
5867 const choiceInfo = this._choices.get(value);
5869 return choiceInfo && choiceInfo.deprecated ? {
5875 const choiceInfo = this._choices.get(value);
5877 return choiceInfo ? choiceInfo.forward : undefined;
5881 const choiceInfo = this._choices.get(value);
5883 return choiceInfo ? choiceInfo.redirect : undefined;
5888 exports.ChoiceSchema = ChoiceSchema;
5890 unwrapExports(choice);
5891 var choice_1 = choice.ChoiceSchema;
5893 var number = createCommonjsModule(function (module, exports) {
5895 Object.defineProperty(exports, "__esModule", {
5899 class NumberSchema extends schema.Schema {
5904 validate(value, _utils) {
5905 return typeof value === 'number';
5910 exports.NumberSchema = NumberSchema;
5912 unwrapExports(number);
5913 var number_1 = number.NumberSchema;
5915 var integer = createCommonjsModule(function (module, exports) {
5917 Object.defineProperty(exports, "__esModule", {
5921 class IntegerSchema extends number.NumberSchema {
5923 return 'an integer';
5926 validate(value, utils$1) {
5927 return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value);
5932 exports.IntegerSchema = IntegerSchema;
5934 unwrapExports(integer);
5935 var integer_1 = integer.IntegerSchema;
5937 var string = createCommonjsModule(function (module, exports) {
5939 Object.defineProperty(exports, "__esModule", {
5943 class StringSchema extends schema.Schema {
5949 return typeof value === 'string';
5954 exports.StringSchema = StringSchema;
5956 unwrapExports(string);
5957 var string_1 = string.StringSchema;
5959 var schemas = createCommonjsModule(function (module, exports) {
5961 Object.defineProperty(exports, "__esModule", {
5965 tslib_es6.__exportStar(alias, exports);
5967 tslib_es6.__exportStar(any, exports);
5969 tslib_es6.__exportStar(array, exports);
5971 tslib_es6.__exportStar(boolean_1, exports);
5973 tslib_es6.__exportStar(choice, exports);
5975 tslib_es6.__exportStar(integer, exports);
5977 tslib_es6.__exportStar(number, exports);
5979 tslib_es6.__exportStar(string, exports);
5981 unwrapExports(schemas);
5983 var defaults = createCommonjsModule(function (module, exports) {
5985 Object.defineProperty(exports, "__esModule", {
5988 exports.defaultDescriptor = api.apiDescriptor;
5989 exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
5990 exports.defaultInvalidHandler = invalid.commonInvalidHandler;
5991 exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
5993 unwrapExports(defaults);
5994 var defaults_1 = defaults.defaultDescriptor;
5995 var defaults_2 = defaults.defaultUnknownHandler;
5996 var defaults_3 = defaults.defaultInvalidHandler;
5997 var defaults_4 = defaults.defaultDeprecatedHandler;
5999 var normalize = createCommonjsModule(function (module, exports) {
6001 Object.defineProperty(exports, "__esModule", {
6005 exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options);
6008 constructor(schemas, opts) {
6009 // istanbul ignore next
6012 descriptor = defaults.defaultDescriptor,
6013 unknown = defaults.defaultUnknownHandler,
6014 invalid = defaults.defaultInvalidHandler,
6015 deprecated = defaults.defaultDeprecatedHandler
6020 /* istanbul ignore next */
6024 schemas: utils.recordFromArray(schemas, 'name'),
6025 normalizeDefaultResult: utils.normalizeDefaultResult,
6026 normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
6027 normalizeForwardResult: utils.normalizeForwardResult,
6028 normalizeRedirectResult: utils.normalizeRedirectResult,
6029 normalizeValidateResult: utils.normalizeValidateResult
6031 this._unknownHandler = unknown;
6032 this._invalidHandler = invalid;
6033 this._deprecatedHandler = deprecated;
6034 this.cleanHistory();
6038 this._hasDeprecationWarned = utils.createAutoChecklist();
6041 normalize(options) {
6042 const normalized = {};
6043 const restOptionsArray = [options];
6045 const applyNormalization = () => {
6046 while (restOptionsArray.length !== 0) {
6047 const currentOptions = restOptionsArray.shift();
6049 const transferredOptionsArray = this._applyNormalization(currentOptions, normalized);
6051 restOptionsArray.push(...transferredOptionsArray);
6055 applyNormalization();
6057 for (const key of Object.keys(this._utils.schemas)) {
6058 const schema = this._utils.schemas[key];
6060 if (!(key in normalized)) {
6061 const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
6063 if ('value' in defaultResult) {
6064 restOptionsArray.push({
6065 [key]: defaultResult.value
6071 applyNormalization();
6073 for (const key of Object.keys(this._utils.schemas)) {
6074 const schema = this._utils.schemas[key];
6076 if (key in normalized) {
6077 normalized[key] = schema.postprocess(normalized[key], this._utils);
6084 _applyNormalization(options, normalized) {
6085 const transferredOptionsArray = [];
6086 const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas);
6088 for (const key of knownOptionNames) {
6089 const schema = this._utils.schemas[key];
6090 const value = schema.preprocess(options[key], this._utils);
6091 const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value);
6093 if (validateResult !== true) {
6098 const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils);
6100 throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
6101 /* istanbul ignore next*/
6102 errorMessageOrError;
6105 const appendTransferredOptions = ({
6109 transferredOptionsArray.push(typeof to === 'string' ? {
6116 const warnDeprecated = ({
6117 value: currentValue,
6120 const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value,
6121 /* doNotNormalizeTrue */
6124 if (deprecatedResult === false) {
6128 if (deprecatedResult === true) {
6129 if (!this._hasDeprecationWarned(key)) {
6130 this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils));
6134 value: deprecatedValue
6135 } of deprecatedResult) {
6138 value: deprecatedValue
6141 if (!this._hasDeprecationWarned(pair)) {
6142 const redirectToPair = typeof redirectTo === 'string' ? {
6144 value: deprecatedValue
6147 this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils));
6153 const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value);
6154 forwardResult.forEach(appendTransferredOptions);
6155 const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value);
6156 redirectResult.redirect.forEach(appendTransferredOptions);
6158 if ('remain' in redirectResult) {
6159 const remainingValue = redirectResult.remain;
6160 normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue;
6162 value: remainingValue
6169 } of redirectResult.redirect) {
6177 for (const key of unknownOptionNames) {
6178 const value = options[key];
6180 const unknownResult = this._unknownHandler(key, value, this._utils);
6182 if (unknownResult) {
6183 for (const unknownKey of Object.keys(unknownResult)) {
6184 const unknownOption = {
6185 [unknownKey]: unknownResult[unknownKey]
6188 if (unknownKey in this._utils.schemas) {
6189 transferredOptionsArray.push(unknownOption);
6191 Object.assign(normalized, unknownOption);
6197 return transferredOptionsArray;
6202 exports.Normalizer = Normalizer;
6204 unwrapExports(normalize);
6205 var normalize_1 = normalize.normalize;
6206 var normalize_2 = normalize.Normalizer;
6208 var lib = createCommonjsModule(function (module, exports) {
6210 Object.defineProperty(exports, "__esModule", {
6214 tslib_es6.__exportStar(descriptors, exports);
6216 tslib_es6.__exportStar(handlers, exports);
6218 tslib_es6.__exportStar(schemas, exports);
6220 tslib_es6.__exportStar(normalize, exports);
6222 tslib_es6.__exportStar(schema, exports);
6227 const charCodeCache$1 = [];
6229 const leven$1 = (left, right) => {
6230 if (left === right) {
6234 const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the
6235 // shortest & which one is the longest
6237 if (left.length > right.length) {
6242 let leftLength = left.length;
6243 let rightLength = right.length; // Performing suffix trimming:
6244 // We can linearly drop suffix common to both strings since they
6245 // don't increase distance at all
6246 // Note: `~-` is the bitwise way to perform a `- 1` operation
6248 while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
6251 } // Performing prefix trimming
6252 // We can linearly drop prefix common to both strings since they
6253 // don't increase distance at all
6258 while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
6262 leftLength -= start;
6263 rightLength -= start;
6265 if (leftLength === 0) {
6276 while (i < leftLength) {
6277 charCodeCache$1[i] = left.charCodeAt(start + i);
6281 while (j < rightLength) {
6282 bCharCode = right.charCodeAt(start + j);
6286 for (i = 0; i < leftLength; i++) {
6287 temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1;
6288 temp = array$1[i]; // eslint-disable-next-line no-multi-assign
6290 result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
6297 var leven_1$1 = leven$1; // TODO: Remove this for the next major release
6299 var default_1 = leven$1;
6300 leven_1$1.default = default_1;
6303 "aliceblue": [240, 248, 255],
6304 "antiquewhite": [250, 235, 215],
6305 "aqua": [0, 255, 255],
6306 "aquamarine": [127, 255, 212],
6307 "azure": [240, 255, 255],
6308 "beige": [245, 245, 220],
6309 "bisque": [255, 228, 196],
6311 "blanchedalmond": [255, 235, 205],
6312 "blue": [0, 0, 255],
6313 "blueviolet": [138, 43, 226],
6314 "brown": [165, 42, 42],
6315 "burlywood": [222, 184, 135],
6316 "cadetblue": [95, 158, 160],
6317 "chartreuse": [127, 255, 0],
6318 "chocolate": [210, 105, 30],
6319 "coral": [255, 127, 80],
6320 "cornflowerblue": [100, 149, 237],
6321 "cornsilk": [255, 248, 220],
6322 "crimson": [220, 20, 60],
6323 "cyan": [0, 255, 255],
6324 "darkblue": [0, 0, 139],
6325 "darkcyan": [0, 139, 139],
6326 "darkgoldenrod": [184, 134, 11],
6327 "darkgray": [169, 169, 169],
6328 "darkgreen": [0, 100, 0],
6329 "darkgrey": [169, 169, 169],
6330 "darkkhaki": [189, 183, 107],
6331 "darkmagenta": [139, 0, 139],
6332 "darkolivegreen": [85, 107, 47],
6333 "darkorange": [255, 140, 0],
6334 "darkorchid": [153, 50, 204],
6335 "darkred": [139, 0, 0],
6336 "darksalmon": [233, 150, 122],
6337 "darkseagreen": [143, 188, 143],
6338 "darkslateblue": [72, 61, 139],
6339 "darkslategray": [47, 79, 79],
6340 "darkslategrey": [47, 79, 79],
6341 "darkturquoise": [0, 206, 209],
6342 "darkviolet": [148, 0, 211],
6343 "deeppink": [255, 20, 147],
6344 "deepskyblue": [0, 191, 255],
6345 "dimgray": [105, 105, 105],
6346 "dimgrey": [105, 105, 105],
6347 "dodgerblue": [30, 144, 255],
6348 "firebrick": [178, 34, 34],
6349 "floralwhite": [255, 250, 240],
6350 "forestgreen": [34, 139, 34],
6351 "fuchsia": [255, 0, 255],
6352 "gainsboro": [220, 220, 220],
6353 "ghostwhite": [248, 248, 255],
6354 "gold": [255, 215, 0],
6355 "goldenrod": [218, 165, 32],
6356 "gray": [128, 128, 128],
6357 "green": [0, 128, 0],
6358 "greenyellow": [173, 255, 47],
6359 "grey": [128, 128, 128],
6360 "honeydew": [240, 255, 240],
6361 "hotpink": [255, 105, 180],
6362 "indianred": [205, 92, 92],
6363 "indigo": [75, 0, 130],
6364 "ivory": [255, 255, 240],
6365 "khaki": [240, 230, 140],
6366 "lavender": [230, 230, 250],
6367 "lavenderblush": [255, 240, 245],
6368 "lawngreen": [124, 252, 0],
6369 "lemonchiffon": [255, 250, 205],
6370 "lightblue": [173, 216, 230],
6371 "lightcoral": [240, 128, 128],
6372 "lightcyan": [224, 255, 255],
6373 "lightgoldenrodyellow": [250, 250, 210],
6374 "lightgray": [211, 211, 211],
6375 "lightgreen": [144, 238, 144],
6376 "lightgrey": [211, 211, 211],
6377 "lightpink": [255, 182, 193],
6378 "lightsalmon": [255, 160, 122],
6379 "lightseagreen": [32, 178, 170],
6380 "lightskyblue": [135, 206, 250],
6381 "lightslategray": [119, 136, 153],
6382 "lightslategrey": [119, 136, 153],
6383 "lightsteelblue": [176, 196, 222],
6384 "lightyellow": [255, 255, 224],
6385 "lime": [0, 255, 0],
6386 "limegreen": [50, 205, 50],
6387 "linen": [250, 240, 230],
6388 "magenta": [255, 0, 255],
6389 "maroon": [128, 0, 0],
6390 "mediumaquamarine": [102, 205, 170],
6391 "mediumblue": [0, 0, 205],
6392 "mediumorchid": [186, 85, 211],
6393 "mediumpurple": [147, 112, 219],
6394 "mediumseagreen": [60, 179, 113],
6395 "mediumslateblue": [123, 104, 238],
6396 "mediumspringgreen": [0, 250, 154],
6397 "mediumturquoise": [72, 209, 204],
6398 "mediumvioletred": [199, 21, 133],
6399 "midnightblue": [25, 25, 112],
6400 "mintcream": [245, 255, 250],
6401 "mistyrose": [255, 228, 225],
6402 "moccasin": [255, 228, 181],
6403 "navajowhite": [255, 222, 173],
6404 "navy": [0, 0, 128],
6405 "oldlace": [253, 245, 230],
6406 "olive": [128, 128, 0],
6407 "olivedrab": [107, 142, 35],
6408 "orange": [255, 165, 0],
6409 "orangered": [255, 69, 0],
6410 "orchid": [218, 112, 214],
6411 "palegoldenrod": [238, 232, 170],
6412 "palegreen": [152, 251, 152],
6413 "paleturquoise": [175, 238, 238],
6414 "palevioletred": [219, 112, 147],
6415 "papayawhip": [255, 239, 213],
6416 "peachpuff": [255, 218, 185],
6417 "peru": [205, 133, 63],
6418 "pink": [255, 192, 203],
6419 "plum": [221, 160, 221],
6420 "powderblue": [176, 224, 230],
6421 "purple": [128, 0, 128],
6422 "rebeccapurple": [102, 51, 153],
6424 "rosybrown": [188, 143, 143],
6425 "royalblue": [65, 105, 225],
6426 "saddlebrown": [139, 69, 19],
6427 "salmon": [250, 128, 114],
6428 "sandybrown": [244, 164, 96],
6429 "seagreen": [46, 139, 87],
6430 "seashell": [255, 245, 238],
6431 "sienna": [160, 82, 45],
6432 "silver": [192, 192, 192],
6433 "skyblue": [135, 206, 235],
6434 "slateblue": [106, 90, 205],
6435 "slategray": [112, 128, 144],
6436 "slategrey": [112, 128, 144],
6437 "snow": [255, 250, 250],
6438 "springgreen": [0, 255, 127],
6439 "steelblue": [70, 130, 180],
6440 "tan": [210, 180, 140],
6441 "teal": [0, 128, 128],
6442 "thistle": [216, 191, 216],
6443 "tomato": [255, 99, 71],
6444 "turquoise": [64, 224, 208],
6445 "violet": [238, 130, 238],
6446 "wheat": [245, 222, 179],
6447 "white": [255, 255, 255],
6448 "whitesmoke": [245, 245, 245],
6449 "yellow": [255, 255, 0],
6450 "yellowgreen": [154, 205, 50]
6455 /* eslint-disable no-mixed-operators */
6456 // NOTE: conversions should only return primitive values (i.e. arrays, or
6457 // values that give correct `typeof` results).
6458 // do not use box values types (i.e. Number(), String(), etc.)
6460 const reverseKeywords = {};
6462 for (const key of Object.keys(colorName$1)) {
6463 reverseKeywords[colorName$1[key]] = key;
6517 labels: ['h', 'c', 'g']
6521 labels: ['r16', 'g16', 'b16']
6528 var conversions$1 = convert$1; // Hide .channels and .labels properties
6530 for (const model of Object.keys(convert$1)) {
6531 if (!('channels' in convert$1[model])) {
6532 throw new Error('missing channels property: ' + model);
6535 if (!('labels' in convert$1[model])) {
6536 throw new Error('missing channel labels property: ' + model);
6539 if (convert$1[model].labels.length !== convert$1[model].channels) {
6540 throw new Error('channel and label counts mismatch: ' + model);
6546 } = convert$1[model];
6547 delete convert$1[model].channels;
6548 delete convert$1[model].labels;
6549 Object.defineProperty(convert$1[model], 'channels', {
6552 Object.defineProperty(convert$1[model], 'labels', {
6557 convert$1.rgb.hsl = function (rgb) {
6558 const r = rgb[0] / 255;
6559 const g = rgb[1] / 255;
6560 const b = rgb[2] / 255;
6561 const min = Math.min(r, g, b);
6562 const max = Math.max(r, g, b);
6563 const delta = max - min;
6569 } else if (r === max) {
6570 h = (g - b) / delta;
6571 } else if (g === max) {
6572 h = 2 + (b - r) / delta;
6573 } else if (b === max) {
6574 h = 4 + (r - g) / delta;
6577 h = Math.min(h * 60, 360);
6583 const l = (min + max) / 2;
6587 } else if (l <= 0.5) {
6588 s = delta / (max + min);
6590 s = delta / (2 - max - min);
6593 return [h, s * 100, l * 100];
6596 convert$1.rgb.hsv = function (rgb) {
6602 const r = rgb[0] / 255;
6603 const g = rgb[1] / 255;
6604 const b = rgb[2] / 255;
6605 const v = Math.max(r, g, b);
6606 const diff = v - Math.min(r, g, b);
6608 const diffc = function (c) {
6609 return (v - c) / 6 / diff + 1 / 2;
6623 } else if (g === v) {
6624 h = 1 / 3 + rdif - bdif;
6625 } else if (b === v) {
6626 h = 2 / 3 + gdif - rdif;
6636 return [h * 360, s * 100, v * 100];
6639 convert$1.rgb.hwb = function (rgb) {
6643 const h = convert$1.rgb.hsl(rgb)[0];
6644 const w = 1 / 255 * Math.min(r, Math.min(g, b));
6645 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
6646 return [h, w * 100, b * 100];
6649 convert$1.rgb.cmyk = function (rgb) {
6650 const r = rgb[0] / 255;
6651 const g = rgb[1] / 255;
6652 const b = rgb[2] / 255;
6653 const k = Math.min(1 - r, 1 - g, 1 - b);
6654 const c = (1 - r - k) / (1 - k) || 0;
6655 const m = (1 - g - k) / (1 - k) || 0;
6656 const y = (1 - b - k) / (1 - k) || 0;
6657 return [c * 100, m * 100, y * 100, k * 100];
6660 function comparativeDistance(x, y) {
6662 See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
6664 return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
6667 convert$1.rgb.keyword = function (rgb) {
6668 const reversed = reverseKeywords[rgb];
6674 let currentClosestDistance = Infinity;
6675 let currentClosestKeyword;
6677 for (const keyword of Object.keys(colorName$1)) {
6678 const value = colorName$1[keyword]; // Compute comparative distance
6680 const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
6682 if (distance < currentClosestDistance) {
6683 currentClosestDistance = distance;
6684 currentClosestKeyword = keyword;
6688 return currentClosestKeyword;
6691 convert$1.keyword.rgb = function (keyword) {
6692 return colorName$1[keyword];
6695 convert$1.rgb.xyz = function (rgb) {
6696 let r = rgb[0] / 255;
6697 let g = rgb[1] / 255;
6698 let b = rgb[2] / 255; // Assume sRGB
6700 r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
6701 g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
6702 b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
6703 const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
6704 const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
6705 const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
6706 return [x * 100, y * 100, z * 100];
6709 convert$1.rgb.lab = function (rgb) {
6710 const xyz = convert$1.rgb.xyz(rgb);
6717 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
6718 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
6719 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
6720 const l = 116 * y - 16;
6721 const a = 500 * (x - y);
6722 const b = 200 * (y - z);
6726 convert$1.hsl.rgb = function (hsl) {
6727 const h = hsl[0] / 360;
6728 const s = hsl[1] / 100;
6729 const l = hsl[2] / 100;
6736 return [val, val, val];
6745 const t1 = 2 * l - t2;
6746 const rgb = [0, 0, 0];
6748 for (let i = 0; i < 3; i++) {
6749 t3 = h + 1 / 3 * -(i - 1);
6760 val = t1 + (t2 - t1) * 6 * t3;
6761 } else if (2 * t3 < 1) {
6763 } else if (3 * t3 < 2) {
6764 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
6775 convert$1.hsl.hsv = function (hsl) {
6777 let s = hsl[1] / 100;
6778 let l = hsl[2] / 100;
6780 const lmin = Math.max(l, 0.01);
6782 s *= l <= 1 ? l : 2 - l;
6783 smin *= lmin <= 1 ? lmin : 2 - lmin;
6784 const v = (l + s) / 2;
6785 const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
6786 return [h, sv * 100, v * 100];
6789 convert$1.hsv.rgb = function (hsv) {
6790 const h = hsv[0] / 60;
6791 const s = hsv[1] / 100;
6792 let v = hsv[2] / 100;
6793 const hi = Math.floor(h) % 6;
6794 const f = h - Math.floor(h);
6795 const p = 255 * v * (1 - s);
6796 const q = 255 * v * (1 - s * f);
6797 const t = 255 * v * (1 - s * (1 - f));
6821 convert$1.hsv.hsl = function (hsv) {
6823 const s = hsv[1] / 100;
6824 const v = hsv[2] / 100;
6825 const vmin = Math.max(v, 0.01);
6829 const lmin = (2 - s) * vmin;
6831 sl /= lmin <= 1 ? lmin : 2 - lmin;
6834 return [h, sl * 100, l * 100];
6835 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
6838 convert$1.hwb.rgb = function (hwb) {
6839 const h = hwb[0] / 360;
6840 let wh = hwb[1] / 100;
6841 let bl = hwb[2] / 100;
6842 const ratio = wh + bl;
6843 let f; // Wh + bl cant be > 1
6850 const i = Math.floor(6 * h);
6854 if ((i & 0x01) !== 0) {
6858 const n = wh + f * (v - wh); // Linear interpolation
6863 /* eslint-disable max-statements-per-line,no-multi-spaces */
6904 /* eslint-enable max-statements-per-line,no-multi-spaces */
6907 return [r * 255, g * 255, b * 255];
6910 convert$1.cmyk.rgb = function (cmyk) {
6911 const c = cmyk[0] / 100;
6912 const m = cmyk[1] / 100;
6913 const y = cmyk[2] / 100;
6914 const k = cmyk[3] / 100;
6915 const r = 1 - Math.min(1, c * (1 - k) + k);
6916 const g = 1 - Math.min(1, m * (1 - k) + k);
6917 const b = 1 - Math.min(1, y * (1 - k) + k);
6918 return [r * 255, g * 255, b * 255];
6921 convert$1.xyz.rgb = function (xyz) {
6922 const x = xyz[0] / 100;
6923 const y = xyz[1] / 100;
6924 const z = xyz[2] / 100;
6928 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
6929 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
6930 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB
6932 r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92;
6933 g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92;
6934 b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92;
6935 r = Math.min(Math.max(0, r), 1);
6936 g = Math.min(Math.max(0, g), 1);
6937 b = Math.min(Math.max(0, b), 1);
6938 return [r * 255, g * 255, b * 255];
6941 convert$1.xyz.lab = function (xyz) {
6948 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
6949 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
6950 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
6951 const l = 116 * y - 16;
6952 const a = 500 * (x - y);
6953 const b = 200 * (y - z);
6957 convert$1.lab.xyz = function (lab) {
6970 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
6971 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
6972 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
6979 convert$1.lab.lch = function (lab) {
6984 const hr = Math.atan2(b, a);
6985 h = hr * 360 / 2 / Math.PI;
6991 const c = Math.sqrt(a * a + b * b);
6995 convert$1.lch.lab = function (lch) {
6999 const hr = h / 360 * 2 * Math.PI;
7000 const a = c * Math.cos(hr);
7001 const b = c * Math.sin(hr);
7005 convert$1.rgb.ansi16 = function (args, saturation = null) {
7006 const [r, g, b] = args;
7007 let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
7009 value = Math.round(value / 50);
7015 let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
7024 convert$1.hsv.ansi16 = function (args) {
7025 // Optimization here; we already know the value and don't need to get
7026 // it converted for us.
7027 return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
7030 convert$1.rgb.ansi256 = function (args) {
7033 const b = args[2]; // We use the extended greyscale palette here, with the exception of
7034 // black and white. normal palette only has 4 greyscale shades.
7036 if (r === g && g === b) {
7045 return Math.round((r - 8) / 247 * 24) + 232;
7048 const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
7052 convert$1.ansi16.rgb = function (args) {
7053 let color = args % 10; // Handle greyscale
7055 if (color === 0 || color === 7) {
7060 color = color / 10.5 * 255;
7061 return [color, color, color];
7064 const mult = (~~(args > 50) + 1) * 0.5;
7065 const r = (color & 1) * mult * 255;
7066 const g = (color >> 1 & 1) * mult * 255;
7067 const b = (color >> 2 & 1) * mult * 255;
7071 convert$1.ansi256.rgb = function (args) {
7074 const c = (args - 232) * 10 + 8;
7080 const r = Math.floor(args / 36) / 5 * 255;
7081 const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
7082 const b = rem % 6 / 5 * 255;
7086 convert$1.rgb.hex = function (args) {
7087 const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
7088 const string = integer.toString(16).toUpperCase();
7089 return '000000'.substring(string.length) + string;
7092 convert$1.hex.rgb = function (args) {
7093 const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
7099 let colorString = match[0];
7101 if (match[0].length === 3) {
7102 colorString = colorString.split('').map(char => {
7107 const integer = parseInt(colorString, 16);
7108 const r = integer >> 16 & 0xFF;
7109 const g = integer >> 8 & 0xFF;
7110 const b = integer & 0xFF;
7114 convert$1.rgb.hcg = function (rgb) {
7115 const r = rgb[0] / 255;
7116 const g = rgb[1] / 255;
7117 const b = rgb[2] / 255;
7118 const max = Math.max(Math.max(r, g), b);
7119 const min = Math.min(Math.min(r, g), b);
7120 const chroma = max - min;
7125 grayscale = min / (1 - chroma);
7132 } else if (max === r) {
7133 hue = (g - b) / chroma % 6;
7134 } else if (max === g) {
7135 hue = 2 + (b - r) / chroma;
7137 hue = 4 + (r - g) / chroma;
7142 return [hue * 360, chroma * 100, grayscale * 100];
7145 convert$1.hsl.hcg = function (hsl) {
7146 const s = hsl[1] / 100;
7147 const l = hsl[2] / 100;
7148 const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
7152 f = (l - 0.5 * c) / (1.0 - c);
7155 return [hsl[0], c * 100, f * 100];
7158 convert$1.hsv.hcg = function (hsv) {
7159 const s = hsv[1] / 100;
7160 const v = hsv[2] / 100;
7165 f = (v - c) / (1 - c);
7168 return [hsv[0], c * 100, f * 100];
7171 convert$1.hcg.rgb = function (hcg) {
7172 const h = hcg[0] / 360;
7173 const c = hcg[1] / 100;
7174 const g = hcg[2] / 100;
7177 return [g * 255, g * 255, g * 255];
7180 const pure = [0, 0, 0];
7181 const hi = h % 1 * 6;
7185 /* eslint-disable max-statements-per-line */
7187 switch (Math.floor(hi)) {
7223 /* eslint-enable max-statements-per-line */
7227 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
7230 convert$1.hcg.hsv = function (hcg) {
7231 const c = hcg[1] / 100;
7232 const g = hcg[2] / 100;
7233 const v = c + g * (1.0 - c);
7240 return [hcg[0], f * 100, v * 100];
7243 convert$1.hcg.hsl = function (hcg) {
7244 const c = hcg[1] / 100;
7245 const g = hcg[2] / 100;
7246 const l = g * (1.0 - c) + 0.5 * c;
7249 if (l > 0.0 && l < 0.5) {
7251 } else if (l >= 0.5 && l < 1.0) {
7252 s = c / (2 * (1 - l));
7255 return [hcg[0], s * 100, l * 100];
7258 convert$1.hcg.hwb = function (hcg) {
7259 const c = hcg[1] / 100;
7260 const g = hcg[2] / 100;
7261 const v = c + g * (1.0 - c);
7262 return [hcg[0], (v - c) * 100, (1 - v) * 100];
7265 convert$1.hwb.hcg = function (hwb) {
7266 const w = hwb[1] / 100;
7267 const b = hwb[2] / 100;
7273 g = (v - c) / (1 - c);
7276 return [hwb[0], c * 100, g * 100];
7279 convert$1.apple.rgb = function (apple) {
7280 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
7283 convert$1.rgb.apple = function (rgb) {
7284 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
7287 convert$1.gray.rgb = function (args) {
7288 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
7291 convert$1.gray.hsl = function (args) {
7292 return [0, 0, args[0]];
7295 convert$1.gray.hsv = convert$1.gray.hsl;
7297 convert$1.gray.hwb = function (gray) {
7298 return [0, 100, gray[0]];
7301 convert$1.gray.cmyk = function (gray) {
7302 return [0, 0, 0, gray[0]];
7305 convert$1.gray.lab = function (gray) {
7306 return [gray[0], 0, 0];
7309 convert$1.gray.hex = function (gray) {
7310 const val = Math.round(gray[0] / 100 * 255) & 0xFF;
7311 const integer = (val << 16) + (val << 8) + val;
7312 const string = integer.toString(16).toUpperCase();
7313 return '000000'.substring(string.length) + string;
7316 convert$1.rgb.gray = function (rgb) {
7317 const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
7318 return [val / 255 * 100];
7322 This function routes a model to all other models.
7324 all functions that are routed have a property `.conversion` attached
7325 to the returned synthetic function. This property is an array
7326 of strings, each with the steps in between the 'from' and 'to'
7327 color models (inclusive).
7329 conversions that are not possible simply are not included.
7332 function buildGraph$1() {
7333 const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
7335 const models = Object.keys(conversions$1);
7337 for (let len = models.length, i = 0; i < len; i++) {
7338 graph[models[i]] = {
7339 // http://jsperf.com/1-vs-infinity
7340 // micro-opt, but this is simple.
7347 } // https://en.wikipedia.org/wiki/Breadth-first_search
7350 function deriveBFS$1(fromModel) {
7351 const graph = buildGraph$1();
7352 const queue = [fromModel]; // Unshift -> queue -> pop
7354 graph[fromModel].distance = 0;
7356 while (queue.length) {
7357 const current = queue.pop();
7358 const adjacents = Object.keys(conversions$1[current]);
7360 for (let len = adjacents.length, i = 0; i < len; i++) {
7361 const adjacent = adjacents[i];
7362 const node = graph[adjacent];
7364 if (node.distance === -1) {
7365 node.distance = graph[current].distance + 1;
7366 node.parent = current;
7367 queue.unshift(adjacent);
7375 function link$1(from, to) {
7376 return function (args) {
7377 return to(from(args));
7381 function wrapConversion$1(toModel, graph) {
7382 const path = [graph[toModel].parent, toModel];
7383 let fn = conversions$1[graph[toModel].parent][toModel];
7384 let cur = graph[toModel].parent;
7386 while (graph[cur].parent) {
7387 path.unshift(graph[cur].parent);
7388 fn = link$1(conversions$1[graph[cur].parent][cur], fn);
7389 cur = graph[cur].parent;
7392 fn.conversion = path;
7396 var route$1 = function (fromModel) {
7397 const graph = deriveBFS$1(fromModel);
7398 const conversion = {};
7399 const models = Object.keys(graph);
7401 for (let len = models.length, i = 0; i < len; i++) {
7402 const toModel = models[i];
7403 const node = graph[toModel];
7405 if (node.parent === null) {
7406 // No possible conversion, or this node is the source model.
7410 conversion[toModel] = wrapConversion$1(toModel, graph);
7416 const convert$2 = {};
7417 const models$1 = Object.keys(conversions$1);
7419 function wrapRaw$1(fn) {
7420 const wrappedFn = function (...args) {
7421 const arg0 = args[0];
7423 if (arg0 === undefined || arg0 === null) {
7427 if (arg0.length > 1) {
7432 }; // Preserve .conversion property if there is one
7435 if ('conversion' in fn) {
7436 wrappedFn.conversion = fn.conversion;
7442 function wrapRounded$1(fn) {
7443 const wrappedFn = function (...args) {
7444 const arg0 = args[0];
7446 if (arg0 === undefined || arg0 === null) {
7450 if (arg0.length > 1) {
7454 const result = fn(args); // We're assuming the result is an array here.
7455 // see notice in conversions.js; don't use box types
7456 // in conversion functions.
7458 if (typeof result === 'object') {
7459 for (let len = result.length, i = 0; i < len; i++) {
7460 result[i] = Math.round(result[i]);
7465 }; // Preserve .conversion property if there is one
7468 if ('conversion' in fn) {
7469 wrappedFn.conversion = fn.conversion;
7475 models$1.forEach(fromModel => {
7476 convert$2[fromModel] = {};
7477 Object.defineProperty(convert$2[fromModel], 'channels', {
7478 value: conversions$1[fromModel].channels
7480 Object.defineProperty(convert$2[fromModel], 'labels', {
7481 value: conversions$1[fromModel].labels
7483 const routes = route$1(fromModel);
7484 const routeModels = Object.keys(routes);
7485 routeModels.forEach(toModel => {
7486 const fn = routes[toModel];
7487 convert$2[fromModel][toModel] = wrapRounded$1(fn);
7488 convert$2[fromModel][toModel].raw = wrapRaw$1(fn);
7491 var colorConvert$1 = convert$2;
7493 var ansiStyles$1 = createCommonjsModule(function (module) {
7495 const wrapAnsi16 = (fn, offset) => (...args) => {
7496 const code = fn(...args);
7497 return `\u001B[${code + offset}m`;
7500 const wrapAnsi256 = (fn, offset) => (...args) => {
7501 const code = fn(...args);
7502 return `\u001B[${38 + offset};5;${code}m`;
7505 const wrapAnsi16m = (fn, offset) => (...args) => {
7506 const rgb = fn(...args);
7507 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
7510 const ansi2ansi = n => n;
7512 const rgb2rgb = (r, g, b) => [r, g, b];
7514 const setLazyProperty = (object, property, get) => {
7515 Object.defineProperty(object, property, {
7517 const value = get();
7518 Object.defineProperty(object, property, {
7529 /** @type {typeof import('color-convert')} */
7534 const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
7535 if (colorConvert === undefined) {
7536 colorConvert = colorConvert$1;
7539 const offset = isBackground ? 10 : 0;
7542 for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
7543 const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
7545 if (sourceSpace === targetSpace) {
7546 styles[name] = wrap(identity, offset);
7547 } else if (typeof suite === 'object') {
7548 styles[name] = wrap(suite[targetSpace], offset);
7555 function assembleStyles() {
7556 const codes = new Map();
7560 // 21 isn't widely supported and 22 does the same thing
7567 strikethrough: [9, 29]
7579 blackBright: [90, 39],
7580 redBright: [91, 39],
7581 greenBright: [92, 39],
7582 yellowBright: [93, 39],
7583 blueBright: [94, 39],
7584 magentaBright: [95, 39],
7585 cyanBright: [96, 39],
7586 whiteBright: [97, 39]
7594 bgMagenta: [45, 49],
7598 bgBlackBright: [100, 49],
7599 bgRedBright: [101, 49],
7600 bgGreenBright: [102, 49],
7601 bgYellowBright: [103, 49],
7602 bgBlueBright: [104, 49],
7603 bgMagentaBright: [105, 49],
7604 bgCyanBright: [106, 49],
7605 bgWhiteBright: [107, 49]
7607 }; // Alias bright black as gray (and grey)
7609 styles.color.gray = styles.color.blackBright;
7610 styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
7611 styles.color.grey = styles.color.blackBright;
7612 styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
7614 for (const [groupName, group] of Object.entries(styles)) {
7615 for (const [styleName, style] of Object.entries(group)) {
7616 styles[styleName] = {
7617 open: `\u001B[${style[0]}m`,
7618 close: `\u001B[${style[1]}m`
7620 group[styleName] = styles[styleName];
7621 codes.set(style[0], style[1]);
7624 Object.defineProperty(styles, groupName, {
7630 Object.defineProperty(styles, 'codes', {
7634 styles.color.close = '\u001B[39m';
7635 styles.bgColor.close = '\u001B[49m';
7636 setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
7637 setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
7638 setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
7639 setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
7640 setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
7641 setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
7643 } // Make the export immutable
7646 Object.defineProperty(module, 'exports', {
7652 var hasFlag$1 = (flag, argv = process.argv) => {
7653 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
7654 const position = argv.indexOf(prefix + flag);
7655 const terminatorPosition = argv.indexOf('--');
7656 return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
7664 if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) {
7666 } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) {
7670 if ('FORCE_COLOR' in env$1) {
7671 if (env$1.FORCE_COLOR === 'true') {
7673 } else if (env$1.FORCE_COLOR === 'false') {
7676 forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
7680 function translateLevel$1(level) {
7693 function supportsColor$1(haveStream, streamIsTTY) {
7694 if (forceColor$1 === 0) {
7698 if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) {
7702 if (hasFlag$1('color=256')) {
7706 if (haveStream && !streamIsTTY && forceColor$1 === undefined) {
7710 const min = forceColor$1 || 0;
7712 if (env$1.TERM === 'dumb') {
7716 if (process.platform === 'win32') {
7717 // Windows 10 build 10586 is the first Windows release that supports 256 colors.
7718 // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
7719 const osRelease = os$1.release().split('.');
7721 if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
7722 return Number(osRelease[2]) >= 14931 ? 3 : 2;
7728 if ('CI' in env$1) {
7729 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
7736 if ('TEAMCITY_VERSION' in env$1) {
7737 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
7740 if ('GITHUB_ACTIONS' in env$1) {
7744 if (env$1.COLORTERM === 'truecolor') {
7748 if ('TERM_PROGRAM' in env$1) {
7749 const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
7751 switch (env$1.TERM_PROGRAM) {
7753 return version >= 3 ? 3 : 2;
7755 case 'Apple_Terminal':
7761 if (/-256(color)?$/i.test(env$1.TERM)) {
7765 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
7769 if ('COLORTERM' in env$1) {
7776 function getSupportLevel$1(stream) {
7777 const level = supportsColor$1(stream, stream && stream.isTTY);
7778 return translateLevel$1(level);
7781 var supportsColor_1$1 = {
7782 supportsColor: getSupportLevel$1,
7783 stdout: translateLevel$1(supportsColor$1(true, tty$1.isatty(1))),
7784 stderr: translateLevel$1(supportsColor$1(true, tty$1.isatty(2)))
7787 const stringReplaceAll = (string, substring, replacer) => {
7788 let index = string.indexOf(substring);
7794 const substringLength = substring.length;
7796 let returnValue = '';
7799 returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
7800 endIndex = index + substringLength;
7801 index = string.indexOf(substring, endIndex);
7802 } while (index !== -1);
7804 returnValue += string.substr(endIndex);
7808 const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
7810 let returnValue = '';
7813 const gotCR = string[index - 1] === '\r';
7814 returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
7815 endIndex = index + 1;
7816 index = string.indexOf('\n', endIndex);
7817 } while (index !== -1);
7819 returnValue += string.substr(endIndex);
7825 stringEncaseCRLFWithFirstIndex
7828 const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
7829 const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
7830 const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
7831 const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
7832 const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
7834 function unescape$1(c) {
7835 const u = c[0] === 'u';
7836 const bracket = c[1] === '{';
7838 if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) {
7839 return String.fromCharCode(parseInt(c.slice(1), 16));
7843 return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
7846 return ESCAPES$1.get(c) || c;
7849 function parseArguments$1(name, arguments_) {
7851 const chunks = arguments_.trim().split(/\s*,\s*/g);
7854 for (const chunk of chunks) {
7855 const number = Number(chunk);
7857 if (!Number.isNaN(number)) {
7858 results.push(number);
7859 } else if (matches = chunk.match(STRING_REGEX$1)) {
7860 results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character));
7862 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
7869 function parseStyle$1(style) {
7870 STYLE_REGEX$1.lastIndex = 0;
7874 while ((matches = STYLE_REGEX$1.exec(style)) !== null) {
7875 const name = matches[1];
7878 const args = parseArguments$1(name, matches[2]);
7879 results.push([name].concat(args));
7881 results.push([name]);
7888 function buildStyle$1(chalk, styles) {
7891 for (const layer of styles) {
7892 for (const style of layer.styles) {
7893 enabled[style[0]] = layer.inverse ? null : style.slice(1);
7897 let current = chalk;
7899 for (const [styleName, styles] of Object.entries(enabled)) {
7900 if (!Array.isArray(styles)) {
7904 if (!(styleName in current)) {
7905 throw new Error(`Unknown Chalk style: ${styleName}`);
7908 current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
7914 var templates$1 = (chalk, temporary) => {
7917 let chunk = []; // eslint-disable-next-line max-params
7919 temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => {
7920 if (escapeCharacter) {
7921 chunk.push(unescape$1(escapeCharacter));
7923 const string = chunk.join('');
7925 chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string));
7928 styles: parseStyle$1(style)
7931 if (styles.length === 0) {
7932 throw new Error('Found extraneous } in Chalk template literal');
7935 chunks.push(buildStyle$1(chalk, styles)(chunk.join('')));
7939 chunk.push(character);
7942 chunks.push(chunk.join(''));
7944 if (styles.length > 0) {
7945 const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
7946 throw new Error(errMessage);
7949 return chunks.join('');
7953 stdout: stdoutColor,
7955 } = supportsColor_1$1;
7957 stringReplaceAll: stringReplaceAll$1,
7958 stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
7959 } = util; // `supportsColor.level` → `ansiStyles.color[name]` mapping
7961 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
7962 const styles = Object.create(null);
7964 const applyOptions = (object, options = {}) => {
7965 if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
7966 throw new Error('The `level` option should be an integer from 0 to 3');
7967 } // Detect level if not set manually
7970 const colorLevel = stdoutColor ? stdoutColor.level : 0;
7971 object.level = options.level === undefined ? colorLevel : options.level;
7975 constructor(options) {
7976 // eslint-disable-next-line no-constructor-return
7977 return chalkFactory(options);
7982 const chalkFactory = options => {
7984 applyOptions(chalk, options);
7986 chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
7988 Object.setPrototypeOf(chalk, Chalk.prototype);
7989 Object.setPrototypeOf(chalk.template, chalk);
7991 chalk.template.constructor = () => {
7992 throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
7995 chalk.template.Instance = ChalkClass;
7996 return chalk.template;
7999 function Chalk(options) {
8000 return chalkFactory(options);
8003 for (const [styleName, style] of Object.entries(ansiStyles$1)) {
8004 styles[styleName] = {
8006 const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
8007 Object.defineProperty(this, styleName, {
8018 const builder = createBuilder(this, this._styler, true);
8019 Object.defineProperty(this, 'visible', {
8026 const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
8028 for (const model of usedModels) {
8034 return function (...arguments_) {
8035 const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler);
8036 return createBuilder(this, styler, this._isEmpty);
8043 for (const model of usedModels) {
8044 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
8050 return function (...arguments_) {
8051 const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler);
8052 return createBuilder(this, styler, this._isEmpty);
8059 const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
8064 return this._generator.level;
8068 this._generator.level = level;
8074 const createStyler = (open, close, parent) => {
8078 if (parent === undefined) {
8082 openAll = parent.openAll + open;
8083 closeAll = close + parent.closeAll;
8095 const createBuilder = (self, _styler, _isEmpty) => {
8096 const builder = (...arguments_) => {
8097 // Single argument is hot path, implicit coercion is faster than anything
8098 // eslint-disable-next-line no-implicit-coercion
8099 return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
8100 }; // We alter the prototype because we must return a function, but there is
8101 // no way to create a function with a different prototype
8104 Object.setPrototypeOf(builder, proto);
8105 builder._generator = self;
8106 builder._styler = _styler;
8107 builder._isEmpty = _isEmpty;
8111 const applyStyle = (self, string) => {
8112 if (self.level <= 0 || !string) {
8113 return self._isEmpty ? '' : string;
8116 let styler = self._styler;
8118 if (styler === undefined) {
8127 if (string.indexOf('\u001B') !== -1) {
8128 while (styler !== undefined) {
8129 // Replace any instances already present with a re-opening code
8130 // otherwise only the part of the string until said closing code
8131 // will be colored, and the rest will simply be 'plain'.
8132 string = stringReplaceAll$1(string, styler.close, styler.open);
8133 styler = styler.parent;
8135 } // We can move both next actions out of loop, because remaining actions in loop won't have
8136 // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
8137 // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
8140 const lfIndex = string.indexOf('\n');
8142 if (lfIndex !== -1) {
8143 string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
8146 return openAll + string + closeAll;
8151 const chalkTag = (chalk, ...strings) => {
8152 const [firstString] = strings;
8154 if (!Array.isArray(firstString)) {
8155 // If chalk() was called by itself or with a string,
8156 // return the string itself as a string.
8157 return strings.join(' ');
8160 const arguments_ = strings.slice(1);
8161 const parts = [firstString.raw[0]];
8163 for (let i = 1; i < firstString.length; i++) {
8164 parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
8167 if (template === undefined) {
8168 template = templates$1;
8171 return template(chalk, parts.join(''));
8174 Object.defineProperties(Chalk.prototype, styles);
8175 const chalk$1 = Chalk(); // eslint-disable-line new-cap
8177 chalk$1.supportsColor = stdoutColor;
8178 chalk$1.stderr = Chalk({
8179 level: stderrColor ? stderrColor.level : 0
8180 }); // eslint-disable-line new-cap
8182 chalk$1.stderr.supportsColor = stderrColor;
8183 var source = chalk$1;
8185 const cliDescriptor = {
8186 key: key => key.length === 1 ? `-${key}` : `--${key}`,
8187 value: value => lib.apiDescriptor.value(value),
8191 }) => value === false ? `--no-${key}` : value === true ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` : `${cliDescriptor.key(key)}=${value}`
8194 class FlagSchema extends lib.ChoiceSchema {
8203 this._flags = flags.slice().sort();
8206 preprocess(value, utils) {
8207 if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) {
8208 const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3);
8211 utils.logger.warn([`Unknown flag ${source.yellow(utils.descriptor.value(value))},`, `did you mean ${source.blue(utils.descriptor.value(suggestion))}?`].join(" "));
8225 let hasDeprecationWarned;
8227 function normalizeOptions(options, optionInfos, {
8232 const unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : {
8234 } : (key, value) => ({
8237 const descriptor = isCLI ? cliDescriptor : lib.apiDescriptor;
8238 const schemas = optionInfosToSchemas(optionInfos, {
8241 const normalizer = new lib.Normalizer(schemas, {
8246 const shouldSuppressDuplicateDeprecationWarnings = logger !== false;
8248 if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
8249 normalizer._hasDeprecationWarned = hasDeprecationWarned;
8252 const normalized = normalizer.normalize(options);
8254 if (shouldSuppressDuplicateDeprecationWarnings) {
8255 hasDeprecationWarned = normalizer._hasDeprecationWarned;
8261 function optionInfosToSchemas(optionInfos, {
8267 schemas.push(lib.AnySchema.create({
8272 for (const optionInfo of optionInfos) {
8273 schemas.push(optionInfoToSchema(optionInfo, {
8278 if (optionInfo.alias && isCLI) {
8279 schemas.push(lib.AliasSchema.create({
8280 name: optionInfo.alias,
8281 sourceName: optionInfo.name
8289 function optionInfoToSchema(optionInfo, {
8293 let SchemaConstructor;
8294 const parameters = {
8295 name: optionInfo.name
8297 const handlers = {};
8299 switch (optionInfo.type) {
8301 SchemaConstructor = lib.IntegerSchema;
8304 parameters.preprocess = value => Number(value);
8310 SchemaConstructor = lib.StringSchema;
8314 SchemaConstructor = lib.ChoiceSchema;
8315 parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
8318 key: optionInfo.name,
8319 value: choiceInfo.redirect
8326 SchemaConstructor = lib.BooleanSchema;
8330 SchemaConstructor = FlagSchema;
8331 parameters.flags = optionInfos.map(optionInfo => [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? `no-${optionInfo.name}` : [])).reduce((a, b) => a.concat(b), []);
8335 SchemaConstructor = lib.StringSchema;
8339 throw new Error(`Unexpected type ${optionInfo.type}`);
8342 if (optionInfo.exception) {
8343 parameters.validate = (value, schema, utils) => {
8344 return optionInfo.exception(value) || schema.validate(value, utils);
8347 parameters.validate = (value, schema, utils) => {
8348 return value === undefined || schema.validate(value, utils);
8352 if (optionInfo.redirect) {
8353 handlers.redirect = value => !value ? undefined : {
8355 key: optionInfo.redirect.option,
8356 value: optionInfo.redirect.value
8361 if (optionInfo.deprecated) {
8362 handlers.deprecated = true;
8363 } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
8366 if (isCLI && !optionInfo.array) {
8367 const originalPreprocess = parameters.preprocess || (x => x);
8369 parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
8372 return optionInfo.array ? lib.ArraySchema.create(Object.assign({}, isCLI ? {
8373 preprocess: v => [].concat(v)
8374 } : {}, {}, handlers, {
8375 valueSchema: SchemaConstructor.create(parameters)
8376 })) : SchemaConstructor.create(Object.assign({}, parameters, {}, handlers));
8379 function normalizeApiOptions(options, optionInfos, opts) {
8380 return normalizeOptions(options, optionInfos, opts);
8383 function normalizeCliOptions(options, optionInfos, opts) {
8384 return normalizeOptions(options, optionInfos, Object.assign({
8389 var optionsNormalizer = {
8390 normalizeApiOptions,
8394 var getLast = arr => arr[arr.length - 1];
8396 function locStart(node, opts) {
8397 opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator
8399 if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) {
8400 return locStart(node.declaration.decorators[0]);
8403 if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) {
8404 return locStart(node.decorators[0]);
8407 if (node.__location) {
8408 return node.__location.startOffset;
8412 return node.range[0];
8415 if (typeof node.start === "number") {
8420 return node.loc.start;
8426 function locEnd(node) {
8427 const endNode = node.nodes && getLast(node.nodes);
8429 if (endNode && node.source && !node.source.end) {
8433 if (node.__location) {
8434 return node.__location.endOffset;
8437 const loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null;
8439 if (node.typeAnnotation) {
8440 return Math.max(loc, locEnd(node.typeAnnotation));
8443 if (node.loc && !loc) {
8444 return node.loc.end;
8450 function composeLoc(startNode, endNodeOrLength = startNode) {
8451 const length = typeof endNodeOrLength === "number" ? endNodeOrLength : -1;
8452 const start = locStart(startNode);
8453 const end = length !== -1 ? start + length : locEnd(endNodeOrLength);
8454 const startLoc = startNode.loc.start;
8458 range: [start, end],
8461 end: length !== -1 ? {
8462 line: startLoc.line,
8463 column: startLoc.column + length
8464 } : endNodeOrLength.loc.end
8475 var jsTokens = createCommonjsModule(function (module, exports) {
8476 // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
8477 // License: MIT. (See LICENSE.)
8478 Object.defineProperty(exports, "__esModule", {
8480 }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
8481 // (run `npm run build`).
8483 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;
8485 exports.matchToToken = function (match) {
8491 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";
8495 unwrapExports(jsTokens);
8496 var jsTokens_1 = jsTokens.matchToToken;
8498 var ast = createCommonjsModule(function (module) {
8500 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
8502 Redistribution and use in source and binary forms, with or without
8503 modification, are permitted provided that the following conditions are met:
8505 * Redistributions of source code must retain the above copyright
8506 notice, this list of conditions and the following disclaimer.
8507 * Redistributions in binary form must reproduce the above copyright
8508 notice, this list of conditions and the following disclaimer in the
8509 documentation and/or other materials provided with the distribution.
8511 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
8512 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8513 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8514 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8515 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8516 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8517 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8518 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8519 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8520 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8524 function isExpression(node) {
8529 switch (node.type) {
8530 case 'ArrayExpression':
8531 case 'AssignmentExpression':
8532 case 'BinaryExpression':
8533 case 'CallExpression':
8534 case 'ConditionalExpression':
8535 case 'FunctionExpression':
8538 case 'LogicalExpression':
8539 case 'MemberExpression':
8540 case 'NewExpression':
8541 case 'ObjectExpression':
8542 case 'SequenceExpression':
8543 case 'ThisExpression':
8544 case 'UnaryExpression':
8545 case 'UpdateExpression':
8552 function isIterationStatement(node) {
8557 switch (node.type) {
8558 case 'DoWhileStatement':
8559 case 'ForInStatement':
8560 case 'ForStatement':
8561 case 'WhileStatement':
8568 function isStatement(node) {
8573 switch (node.type) {
8574 case 'BlockStatement':
8575 case 'BreakStatement':
8576 case 'ContinueStatement':
8577 case 'DebuggerStatement':
8578 case 'DoWhileStatement':
8579 case 'EmptyStatement':
8580 case 'ExpressionStatement':
8581 case 'ForInStatement':
8582 case 'ForStatement':
8584 case 'LabeledStatement':
8585 case 'ReturnStatement':
8586 case 'SwitchStatement':
8587 case 'ThrowStatement':
8588 case 'TryStatement':
8589 case 'VariableDeclaration':
8590 case 'WhileStatement':
8591 case 'WithStatement':
8598 function isSourceElement(node) {
8599 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
8602 function trailingStatement(node) {
8603 switch (node.type) {
8605 if (node.alternate != null) {
8606 return node.alternate;
8609 return node.consequent;
8611 case 'LabeledStatement':
8612 case 'ForStatement':
8613 case 'ForInStatement':
8614 case 'WhileStatement':
8615 case 'WithStatement':
8622 function isProblematicIfStatement(node) {
8625 if (node.type !== 'IfStatement') {
8629 if (node.alternate == null) {
8633 current = node.consequent;
8636 if (current.type === 'IfStatement') {
8637 if (current.alternate == null) {
8642 current = trailingStatement(current);
8649 isExpression: isExpression,
8650 isStatement: isStatement,
8651 isIterationStatement: isIterationStatement,
8652 isSourceElement: isSourceElement,
8653 isProblematicIfStatement: isProblematicIfStatement,
8654 trailingStatement: trailingStatement
8657 /* vim: set sw=4 ts=4 et tw=80 : */
8660 var ast_1 = ast.isExpression;
8661 var ast_2 = ast.isStatement;
8662 var ast_3 = ast.isIterationStatement;
8663 var ast_4 = ast.isSourceElement;
8664 var ast_5 = ast.isProblematicIfStatement;
8665 var ast_6 = ast.trailingStatement;
8667 var code = createCommonjsModule(function (module) {
8669 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
8670 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
8672 Redistribution and use in source and binary forms, with or without
8673 modification, are permitted provided that the following conditions are met:
8675 * Redistributions of source code must retain the above copyright
8676 notice, this list of conditions and the following disclaimer.
8677 * Redistributions in binary form must reproduce the above copyright
8678 notice, this list of conditions and the following disclaimer in the
8679 documentation and/or other materials provided with the distribution.
8681 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
8682 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8683 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8684 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8685 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8686 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8687 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8688 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8689 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8690 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8694 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
8697 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
8698 NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\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\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\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u1877\u1880-\u1884\u1887-\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\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]/,
8699 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
8700 NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/
8703 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
8704 NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\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\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\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u1877\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\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
8705 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
8706 NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
8709 function isDecimalDigit(ch) {
8710 return 0x30 <= ch && ch <= 0x39; // 0..9
8713 function isHexDigit(ch) {
8714 return 0x30 <= ch && ch <= 0x39 || // 0..9
8715 0x61 <= ch && ch <= 0x66 || // a..f
8716 0x41 <= ch && ch <= 0x46; // A..F
8719 function isOctalDigit(ch) {
8720 return ch >= 0x30 && ch <= 0x37; // 0..7
8721 } // 7.2 White Space
8724 NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
8726 function isWhiteSpace(ch) {
8727 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
8728 } // 7.3 Line Terminators
8731 function isLineTerminator(ch) {
8732 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
8733 } // 7.6 Identifier Names and Identifiers
8736 function fromCodePoint(cp) {
8738 return String.fromCharCode(cp);
8741 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
8742 var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
8746 IDENTIFIER_START = new Array(0x80);
8748 for (ch = 0; ch < 0x80; ++ch) {
8749 IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
8750 ch >= 0x41 && ch <= 0x5A || // A..Z
8751 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
8754 IDENTIFIER_PART = new Array(0x80);
8756 for (ch = 0; ch < 0x80; ++ch) {
8757 IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
8758 ch >= 0x41 && ch <= 0x5A || // A..Z
8759 ch >= 0x30 && ch <= 0x39 || // 0..9
8760 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
8763 function isIdentifierStartES5(ch) {
8764 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
8767 function isIdentifierPartES5(ch) {
8768 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
8771 function isIdentifierStartES6(ch) {
8772 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
8775 function isIdentifierPartES6(ch) {
8776 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
8780 isDecimalDigit: isDecimalDigit,
8781 isHexDigit: isHexDigit,
8782 isOctalDigit: isOctalDigit,
8783 isWhiteSpace: isWhiteSpace,
8784 isLineTerminator: isLineTerminator,
8785 isIdentifierStartES5: isIdentifierStartES5,
8786 isIdentifierPartES5: isIdentifierPartES5,
8787 isIdentifierStartES6: isIdentifierStartES6,
8788 isIdentifierPartES6: isIdentifierPartES6
8791 /* vim: set sw=4 ts=4 et tw=80 : */
8794 var code_1 = code.isDecimalDigit;
8795 var code_2 = code.isHexDigit;
8796 var code_3 = code.isOctalDigit;
8797 var code_4 = code.isWhiteSpace;
8798 var code_5 = code.isLineTerminator;
8799 var code_6 = code.isIdentifierStartES5;
8800 var code_7 = code.isIdentifierPartES5;
8801 var code_8 = code.isIdentifierStartES6;
8802 var code_9 = code.isIdentifierPartES6;
8804 var keyword = createCommonjsModule(function (module) {
8806 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
8808 Redistribution and use in source and binary forms, with or without
8809 modification, are permitted provided that the following conditions are met:
8811 * Redistributions of source code must retain the above copyright
8812 notice, this list of conditions and the following disclaimer.
8813 * Redistributions in binary form must reproduce the above copyright
8814 notice, this list of conditions and the following disclaimer in the
8815 documentation and/or other materials provided with the distribution.
8817 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
8818 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8819 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8820 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8821 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8822 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8823 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8824 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8825 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8826 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8832 function isStrictModeReservedWordES6(id) {
8849 function isKeywordES5(id, strict) {
8850 // yield should not be treated as keyword under non-strict mode.
8851 if (!strict && id === 'yield') {
8855 return isKeywordES6(id, strict);
8858 function isKeywordES6(id, strict) {
8859 if (strict && isStrictModeReservedWordES6(id)) {
8863 switch (id.length) {
8865 return id === 'if' || id === 'in' || id === 'do';
8868 return id === 'var' || id === 'for' || id === 'new' || id === 'try';
8871 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
8874 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
8877 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
8880 return id === 'default' || id === 'finally' || id === 'extends';
8883 return id === 'function' || id === 'continue' || id === 'debugger';
8886 return id === 'instanceof';
8893 function isReservedWordES5(id, strict) {
8894 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
8897 function isReservedWordES6(id, strict) {
8898 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
8901 function isRestrictedWord(id) {
8902 return id === 'eval' || id === 'arguments';
8905 function isIdentifierNameES5(id) {
8908 if (id.length === 0) {
8912 ch = id.charCodeAt(0);
8914 if (!code$1.isIdentifierStartES5(ch)) {
8918 for (i = 1, iz = id.length; i < iz; ++i) {
8919 ch = id.charCodeAt(i);
8921 if (!code$1.isIdentifierPartES5(ch)) {
8929 function decodeUtf16(lead, trail) {
8930 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
8933 function isIdentifierNameES6(id) {
8934 var i, iz, ch, lowCh, check;
8936 if (id.length === 0) {
8940 check = code$1.isIdentifierStartES6;
8942 for (i = 0, iz = id.length; i < iz; ++i) {
8943 ch = id.charCodeAt(i);
8945 if (0xD800 <= ch && ch <= 0xDBFF) {
8952 lowCh = id.charCodeAt(i);
8954 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
8958 ch = decodeUtf16(ch, lowCh);
8965 check = code$1.isIdentifierPartES6;
8971 function isIdentifierES5(id, strict) {
8972 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
8975 function isIdentifierES6(id, strict) {
8976 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
8980 isKeywordES5: isKeywordES5,
8981 isKeywordES6: isKeywordES6,
8982 isReservedWordES5: isReservedWordES5,
8983 isReservedWordES6: isReservedWordES6,
8984 isRestrictedWord: isRestrictedWord,
8985 isIdentifierNameES5: isIdentifierNameES5,
8986 isIdentifierNameES6: isIdentifierNameES6,
8987 isIdentifierES5: isIdentifierES5,
8988 isIdentifierES6: isIdentifierES6
8991 /* vim: set sw=4 ts=4 et tw=80 : */
8994 var keyword_1 = keyword.isKeywordES5;
8995 var keyword_2 = keyword.isKeywordES6;
8996 var keyword_3 = keyword.isReservedWordES5;
8997 var keyword_4 = keyword.isReservedWordES6;
8998 var keyword_5 = keyword.isRestrictedWord;
8999 var keyword_6 = keyword.isIdentifierNameES5;
9000 var keyword_7 = keyword.isIdentifierNameES6;
9001 var keyword_8 = keyword.isIdentifierES5;
9002 var keyword_9 = keyword.isIdentifierES6;
9004 var utils$1 = createCommonjsModule(function (module, exports) {
9006 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
9008 Redistribution and use in source and binary forms, with or without
9009 modification, are permitted provided that the following conditions are met:
9011 * Redistributions of source code must retain the above copyright
9012 notice, this list of conditions and the following disclaimer.
9013 * Redistributions in binary form must reproduce the above copyright
9014 notice, this list of conditions and the following disclaimer in the
9015 documentation and/or other materials provided with the distribution.
9017 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
9018 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
9019 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
9020 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
9021 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
9022 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
9023 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
9024 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9025 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
9026 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9031 exports.code = code;
9032 exports.keyword = keyword;
9034 /* vim: set sw=4 ts=4 et tw=80 : */
9037 var utils_1$1 = utils$1.ast;
9038 var utils_2$1 = utils$1.code;
9039 var utils_3$1 = utils$1.keyword;
9041 var matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g;
9043 var escapeStringRegexp$1 = function (str) {
9044 if (typeof str !== 'string') {
9045 throw new TypeError('Expected a string');
9048 return str.replace(matchOperatorsRe$1, '\\$&');
9052 "aliceblue": [240, 248, 255],
9053 "antiquewhite": [250, 235, 215],
9054 "aqua": [0, 255, 255],
9055 "aquamarine": [127, 255, 212],
9056 "azure": [240, 255, 255],
9057 "beige": [245, 245, 220],
9058 "bisque": [255, 228, 196],
9060 "blanchedalmond": [255, 235, 205],
9061 "blue": [0, 0, 255],
9062 "blueviolet": [138, 43, 226],
9063 "brown": [165, 42, 42],
9064 "burlywood": [222, 184, 135],
9065 "cadetblue": [95, 158, 160],
9066 "chartreuse": [127, 255, 0],
9067 "chocolate": [210, 105, 30],
9068 "coral": [255, 127, 80],
9069 "cornflowerblue": [100, 149, 237],
9070 "cornsilk": [255, 248, 220],
9071 "crimson": [220, 20, 60],
9072 "cyan": [0, 255, 255],
9073 "darkblue": [0, 0, 139],
9074 "darkcyan": [0, 139, 139],
9075 "darkgoldenrod": [184, 134, 11],
9076 "darkgray": [169, 169, 169],
9077 "darkgreen": [0, 100, 0],
9078 "darkgrey": [169, 169, 169],
9079 "darkkhaki": [189, 183, 107],
9080 "darkmagenta": [139, 0, 139],
9081 "darkolivegreen": [85, 107, 47],
9082 "darkorange": [255, 140, 0],
9083 "darkorchid": [153, 50, 204],
9084 "darkred": [139, 0, 0],
9085 "darksalmon": [233, 150, 122],
9086 "darkseagreen": [143, 188, 143],
9087 "darkslateblue": [72, 61, 139],
9088 "darkslategray": [47, 79, 79],
9089 "darkslategrey": [47, 79, 79],
9090 "darkturquoise": [0, 206, 209],
9091 "darkviolet": [148, 0, 211],
9092 "deeppink": [255, 20, 147],
9093 "deepskyblue": [0, 191, 255],
9094 "dimgray": [105, 105, 105],
9095 "dimgrey": [105, 105, 105],
9096 "dodgerblue": [30, 144, 255],
9097 "firebrick": [178, 34, 34],
9098 "floralwhite": [255, 250, 240],
9099 "forestgreen": [34, 139, 34],
9100 "fuchsia": [255, 0, 255],
9101 "gainsboro": [220, 220, 220],
9102 "ghostwhite": [248, 248, 255],
9103 "gold": [255, 215, 0],
9104 "goldenrod": [218, 165, 32],
9105 "gray": [128, 128, 128],
9106 "green": [0, 128, 0],
9107 "greenyellow": [173, 255, 47],
9108 "grey": [128, 128, 128],
9109 "honeydew": [240, 255, 240],
9110 "hotpink": [255, 105, 180],
9111 "indianred": [205, 92, 92],
9112 "indigo": [75, 0, 130],
9113 "ivory": [255, 255, 240],
9114 "khaki": [240, 230, 140],
9115 "lavender": [230, 230, 250],
9116 "lavenderblush": [255, 240, 245],
9117 "lawngreen": [124, 252, 0],
9118 "lemonchiffon": [255, 250, 205],
9119 "lightblue": [173, 216, 230],
9120 "lightcoral": [240, 128, 128],
9121 "lightcyan": [224, 255, 255],
9122 "lightgoldenrodyellow": [250, 250, 210],
9123 "lightgray": [211, 211, 211],
9124 "lightgreen": [144, 238, 144],
9125 "lightgrey": [211, 211, 211],
9126 "lightpink": [255, 182, 193],
9127 "lightsalmon": [255, 160, 122],
9128 "lightseagreen": [32, 178, 170],
9129 "lightskyblue": [135, 206, 250],
9130 "lightslategray": [119, 136, 153],
9131 "lightslategrey": [119, 136, 153],
9132 "lightsteelblue": [176, 196, 222],
9133 "lightyellow": [255, 255, 224],
9134 "lime": [0, 255, 0],
9135 "limegreen": [50, 205, 50],
9136 "linen": [250, 240, 230],
9137 "magenta": [255, 0, 255],
9138 "maroon": [128, 0, 0],
9139 "mediumaquamarine": [102, 205, 170],
9140 "mediumblue": [0, 0, 205],
9141 "mediumorchid": [186, 85, 211],
9142 "mediumpurple": [147, 112, 219],
9143 "mediumseagreen": [60, 179, 113],
9144 "mediumslateblue": [123, 104, 238],
9145 "mediumspringgreen": [0, 250, 154],
9146 "mediumturquoise": [72, 209, 204],
9147 "mediumvioletred": [199, 21, 133],
9148 "midnightblue": [25, 25, 112],
9149 "mintcream": [245, 255, 250],
9150 "mistyrose": [255, 228, 225],
9151 "moccasin": [255, 228, 181],
9152 "navajowhite": [255, 222, 173],
9153 "navy": [0, 0, 128],
9154 "oldlace": [253, 245, 230],
9155 "olive": [128, 128, 0],
9156 "olivedrab": [107, 142, 35],
9157 "orange": [255, 165, 0],
9158 "orangered": [255, 69, 0],
9159 "orchid": [218, 112, 214],
9160 "palegoldenrod": [238, 232, 170],
9161 "palegreen": [152, 251, 152],
9162 "paleturquoise": [175, 238, 238],
9163 "palevioletred": [219, 112, 147],
9164 "papayawhip": [255, 239, 213],
9165 "peachpuff": [255, 218, 185],
9166 "peru": [205, 133, 63],
9167 "pink": [255, 192, 203],
9168 "plum": [221, 160, 221],
9169 "powderblue": [176, 224, 230],
9170 "purple": [128, 0, 128],
9171 "rebeccapurple": [102, 51, 153],
9173 "rosybrown": [188, 143, 143],
9174 "royalblue": [65, 105, 225],
9175 "saddlebrown": [139, 69, 19],
9176 "salmon": [250, 128, 114],
9177 "sandybrown": [244, 164, 96],
9178 "seagreen": [46, 139, 87],
9179 "seashell": [255, 245, 238],
9180 "sienna": [160, 82, 45],
9181 "silver": [192, 192, 192],
9182 "skyblue": [135, 206, 235],
9183 "slateblue": [106, 90, 205],
9184 "slategray": [112, 128, 144],
9185 "slategrey": [112, 128, 144],
9186 "snow": [255, 250, 250],
9187 "springgreen": [0, 255, 127],
9188 "steelblue": [70, 130, 180],
9189 "tan": [210, 180, 140],
9190 "teal": [0, 128, 128],
9191 "thistle": [216, 191, 216],
9192 "tomato": [255, 99, 71],
9193 "turquoise": [64, 224, 208],
9194 "violet": [238, 130, 238],
9195 "wheat": [245, 222, 179],
9196 "white": [255, 255, 255],
9197 "whitesmoke": [245, 245, 245],
9198 "yellow": [255, 255, 0],
9199 "yellowgreen": [154, 205, 50]
9202 var conversions$2 = createCommonjsModule(function (module) {
9204 // NOTE: conversions should only return primitive values (i.e. arrays, or
9205 // values that give correct `typeof` results).
9206 // do not use box values types (i.e. Number(), String(), etc.)
9207 var reverseKeywords = {};
9209 for (var key in colorName$2) {
9210 if (colorName$2.hasOwnProperty(key)) {
9211 reverseKeywords[colorName$2[key]] = key;
9215 var convert = module.exports = {
9266 labels: ['h', 'c', 'g']
9270 labels: ['r16', 'g16', 'b16']
9276 }; // hide .channels and .labels properties
9278 for (var model in convert) {
9279 if (convert.hasOwnProperty(model)) {
9280 if (!('channels' in convert[model])) {
9281 throw new Error('missing channels property: ' + model);
9284 if (!('labels' in convert[model])) {
9285 throw new Error('missing channel labels property: ' + model);
9288 if (convert[model].labels.length !== convert[model].channels) {
9289 throw new Error('channel and label counts mismatch: ' + model);
9292 var channels = convert[model].channels;
9293 var labels = convert[model].labels;
9294 delete convert[model].channels;
9295 delete convert[model].labels;
9296 Object.defineProperty(convert[model], 'channels', {
9299 Object.defineProperty(convert[model], 'labels', {
9305 convert.rgb.hsl = function (rgb) {
9306 var r = rgb[0] / 255;
9307 var g = rgb[1] / 255;
9308 var b = rgb[2] / 255;
9309 var min = Math.min(r, g, b);
9310 var max = Math.max(r, g, b);
9311 var delta = max - min;
9318 } else if (r === max) {
9319 h = (g - b) / delta;
9320 } else if (g === max) {
9321 h = 2 + (b - r) / delta;
9322 } else if (b === max) {
9323 h = 4 + (r - g) / delta;
9326 h = Math.min(h * 60, 360);
9332 l = (min + max) / 2;
9336 } else if (l <= 0.5) {
9337 s = delta / (max + min);
9339 s = delta / (2 - max - min);
9342 return [h, s * 100, l * 100];
9345 convert.rgb.hsv = function (rgb) {
9351 var r = rgb[0] / 255;
9352 var g = rgb[1] / 255;
9353 var b = rgb[2] / 255;
9354 var v = Math.max(r, g, b);
9355 var diff = v - Math.min(r, g, b);
9357 var diffc = function (c) {
9358 return (v - c) / 6 / diff + 1 / 2;
9371 } else if (g === v) {
9372 h = 1 / 3 + rdif - bdif;
9373 } else if (b === v) {
9374 h = 2 / 3 + gdif - rdif;
9384 return [h * 360, s * 100, v * 100];
9387 convert.rgb.hwb = function (rgb) {
9391 var h = convert.rgb.hsl(rgb)[0];
9392 var w = 1 / 255 * Math.min(r, Math.min(g, b));
9393 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
9394 return [h, w * 100, b * 100];
9397 convert.rgb.cmyk = function (rgb) {
9398 var r = rgb[0] / 255;
9399 var g = rgb[1] / 255;
9400 var b = rgb[2] / 255;
9405 k = Math.min(1 - r, 1 - g, 1 - b);
9406 c = (1 - r - k) / (1 - k) || 0;
9407 m = (1 - g - k) / (1 - k) || 0;
9408 y = (1 - b - k) / (1 - k) || 0;
9409 return [c * 100, m * 100, y * 100, k * 100];
9412 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
9416 function comparativeDistance(x, y) {
9417 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
9420 convert.rgb.keyword = function (rgb) {
9421 var reversed = reverseKeywords[rgb];
9427 var currentClosestDistance = Infinity;
9428 var currentClosestKeyword;
9430 for (var keyword in colorName$2) {
9431 if (colorName$2.hasOwnProperty(keyword)) {
9432 var value = colorName$2[keyword]; // Compute comparative distance
9434 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
9436 if (distance < currentClosestDistance) {
9437 currentClosestDistance = distance;
9438 currentClosestKeyword = keyword;
9443 return currentClosestKeyword;
9446 convert.keyword.rgb = function (keyword) {
9447 return colorName$2[keyword];
9450 convert.rgb.xyz = function (rgb) {
9451 var r = rgb[0] / 255;
9452 var g = rgb[1] / 255;
9453 var b = rgb[2] / 255; // assume sRGB
9455 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
9456 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
9457 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
9458 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
9459 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
9460 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
9461 return [x * 100, y * 100, z * 100];
9464 convert.rgb.lab = function (rgb) {
9465 var xyz = convert.rgb.xyz(rgb);
9475 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
9476 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
9477 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
9484 convert.hsl.rgb = function (hsl) {
9485 var h = hsl[0] / 360;
9486 var s = hsl[1] / 100;
9487 var l = hsl[2] / 100;
9496 return [val, val, val];
9508 for (var i = 0; i < 3; i++) {
9509 t3 = h + 1 / 3 * -(i - 1);
9520 val = t1 + (t2 - t1) * 6 * t3;
9521 } else if (2 * t3 < 1) {
9523 } else if (3 * t3 < 2) {
9524 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
9535 convert.hsl.hsv = function (hsl) {
9537 var s = hsl[1] / 100;
9538 var l = hsl[2] / 100;
9540 var lmin = Math.max(l, 0.01);
9544 s *= l <= 1 ? l : 2 - l;
9545 smin *= lmin <= 1 ? lmin : 2 - lmin;
9547 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
9548 return [h, sv * 100, v * 100];
9551 convert.hsv.rgb = function (hsv) {
9552 var h = hsv[0] / 60;
9553 var s = hsv[1] / 100;
9554 var v = hsv[2] / 100;
9555 var hi = Math.floor(h) % 6;
9556 var f = h - Math.floor(h);
9557 var p = 255 * v * (1 - s);
9558 var q = 255 * v * (1 - s * f);
9559 var t = 255 * v * (1 - s * (1 - f));
9583 convert.hsv.hsl = function (hsv) {
9585 var s = hsv[1] / 100;
9586 var v = hsv[2] / 100;
9587 var vmin = Math.max(v, 0.01);
9592 lmin = (2 - s) * vmin;
9594 sl /= lmin <= 1 ? lmin : 2 - lmin;
9597 return [h, sl * 100, l * 100];
9598 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
9601 convert.hwb.rgb = function (hwb) {
9602 var h = hwb[0] / 360;
9603 var wh = hwb[1] / 100;
9604 var bl = hwb[2] / 100;
9605 var ratio = wh + bl;
9609 var n; // wh + bl cant be > 1
9616 i = Math.floor(6 * h);
9620 if ((i & 0x01) !== 0) {
9624 n = wh + f * (v - wh); // linear interpolation
9670 return [r * 255, g * 255, b * 255];
9673 convert.cmyk.rgb = function (cmyk) {
9674 var c = cmyk[0] / 100;
9675 var m = cmyk[1] / 100;
9676 var y = cmyk[2] / 100;
9677 var k = cmyk[3] / 100;
9681 r = 1 - Math.min(1, c * (1 - k) + k);
9682 g = 1 - Math.min(1, m * (1 - k) + k);
9683 b = 1 - Math.min(1, y * (1 - k) + k);
9684 return [r * 255, g * 255, b * 255];
9687 convert.xyz.rgb = function (xyz) {
9688 var x = xyz[0] / 100;
9689 var y = xyz[1] / 100;
9690 var z = xyz[2] / 100;
9694 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
9695 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
9696 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
9698 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
9699 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
9700 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
9701 r = Math.min(Math.max(0, r), 1);
9702 g = Math.min(Math.max(0, g), 1);
9703 b = Math.min(Math.max(0, b), 1);
9704 return [r * 255, g * 255, b * 255];
9707 convert.xyz.lab = function (xyz) {
9717 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
9718 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
9719 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
9726 convert.lab.xyz = function (lab) {
9736 var y2 = Math.pow(y, 3);
9737 var x2 = Math.pow(x, 3);
9738 var z2 = Math.pow(z, 3);
9739 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
9740 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
9741 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
9748 convert.lab.lch = function (lab) {
9755 hr = Math.atan2(b, a);
9756 h = hr * 360 / 2 / Math.PI;
9762 c = Math.sqrt(a * a + b * b);
9766 convert.lch.lab = function (lch) {
9773 hr = h / 360 * 2 * Math.PI;
9774 a = c * Math.cos(hr);
9775 b = c * Math.sin(hr);
9779 convert.rgb.ansi16 = function (args) {
9783 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
9785 value = Math.round(value / 50);
9791 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
9800 convert.hsv.ansi16 = function (args) {
9801 // optimization here; we already know the value and don't need to get
9802 // it converted for us.
9803 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
9806 convert.rgb.ansi256 = function (args) {
9809 var b = args[2]; // we use the extended greyscale palette here, with the exception of
9810 // black and white. normal palette only has 4 greyscale shades.
9812 if (r === g && g === b) {
9821 return Math.round((r - 8) / 247 * 24) + 232;
9824 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
9828 convert.ansi16.rgb = function (args) {
9829 var color = args % 10; // handle greyscale
9831 if (color === 0 || color === 7) {
9836 color = color / 10.5 * 255;
9837 return [color, color, color];
9840 var mult = (~~(args > 50) + 1) * 0.5;
9841 var r = (color & 1) * mult * 255;
9842 var g = (color >> 1 & 1) * mult * 255;
9843 var b = (color >> 2 & 1) * mult * 255;
9847 convert.ansi256.rgb = function (args) {
9850 var c = (args - 232) * 10 + 8;
9856 var r = Math.floor(args / 36) / 5 * 255;
9857 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
9858 var b = rem % 6 / 5 * 255;
9862 convert.rgb.hex = function (args) {
9863 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
9864 var string = integer.toString(16).toUpperCase();
9865 return '000000'.substring(string.length) + string;
9868 convert.hex.rgb = function (args) {
9869 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
9875 var colorString = match[0];
9877 if (match[0].length === 3) {
9878 colorString = colorString.split('').map(function (char) {
9883 var integer = parseInt(colorString, 16);
9884 var r = integer >> 16 & 0xFF;
9885 var g = integer >> 8 & 0xFF;
9886 var b = integer & 0xFF;
9890 convert.rgb.hcg = function (rgb) {
9891 var r = rgb[0] / 255;
9892 var g = rgb[1] / 255;
9893 var b = rgb[2] / 255;
9894 var max = Math.max(Math.max(r, g), b);
9895 var min = Math.min(Math.min(r, g), b);
9896 var chroma = max - min;
9901 grayscale = min / (1 - chroma);
9908 } else if (max === r) {
9909 hue = (g - b) / chroma % 6;
9910 } else if (max === g) {
9911 hue = 2 + (b - r) / chroma;
9913 hue = 4 + (r - g) / chroma + 4;
9918 return [hue * 360, chroma * 100, grayscale * 100];
9921 convert.hsl.hcg = function (hsl) {
9922 var s = hsl[1] / 100;
9923 var l = hsl[2] / 100;
9930 c = 2.0 * s * (1.0 - l);
9934 f = (l - 0.5 * c) / (1.0 - c);
9937 return [hsl[0], c * 100, f * 100];
9940 convert.hsv.hcg = function (hsv) {
9941 var s = hsv[1] / 100;
9942 var v = hsv[2] / 100;
9947 f = (v - c) / (1 - c);
9950 return [hsv[0], c * 100, f * 100];
9953 convert.hcg.rgb = function (hcg) {
9954 var h = hcg[0] / 360;
9955 var c = hcg[1] / 100;
9956 var g = hcg[2] / 100;
9959 return [g * 255, g * 255, g * 255];
9962 var pure = [0, 0, 0];
9968 switch (Math.floor(hi)) {
10005 mg = (1.0 - c) * g;
10006 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
10009 convert.hcg.hsv = function (hcg) {
10010 var c = hcg[1] / 100;
10011 var g = hcg[2] / 100;
10012 var v = c + g * (1.0 - c);
10019 return [hcg[0], f * 100, v * 100];
10022 convert.hcg.hsl = function (hcg) {
10023 var c = hcg[1] / 100;
10024 var g = hcg[2] / 100;
10025 var l = g * (1.0 - c) + 0.5 * c;
10028 if (l > 0.0 && l < 0.5) {
10030 } else if (l >= 0.5 && l < 1.0) {
10031 s = c / (2 * (1 - l));
10034 return [hcg[0], s * 100, l * 100];
10037 convert.hcg.hwb = function (hcg) {
10038 var c = hcg[1] / 100;
10039 var g = hcg[2] / 100;
10040 var v = c + g * (1.0 - c);
10041 return [hcg[0], (v - c) * 100, (1 - v) * 100];
10044 convert.hwb.hcg = function (hwb) {
10045 var w = hwb[1] / 100;
10046 var b = hwb[2] / 100;
10052 g = (v - c) / (1 - c);
10055 return [hwb[0], c * 100, g * 100];
10058 convert.apple.rgb = function (apple) {
10059 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
10062 convert.rgb.apple = function (rgb) {
10063 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
10066 convert.gray.rgb = function (args) {
10067 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
10070 convert.gray.hsl = convert.gray.hsv = function (args) {
10071 return [0, 0, args[0]];
10074 convert.gray.hwb = function (gray) {
10075 return [0, 100, gray[0]];
10078 convert.gray.cmyk = function (gray) {
10079 return [0, 0, 0, gray[0]];
10082 convert.gray.lab = function (gray) {
10083 return [gray[0], 0, 0];
10086 convert.gray.hex = function (gray) {
10087 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
10088 var integer = (val << 16) + (val << 8) + val;
10089 var string = integer.toString(16).toUpperCase();
10090 return '000000'.substring(string.length) + string;
10093 convert.rgb.gray = function (rgb) {
10094 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
10095 return [val / 255 * 100];
10098 var conversions_1$1 = conversions$2.rgb;
10099 var conversions_2$1 = conversions$2.hsl;
10100 var conversions_3$1 = conversions$2.hsv;
10101 var conversions_4$1 = conversions$2.hwb;
10102 var conversions_5$1 = conversions$2.cmyk;
10103 var conversions_6$1 = conversions$2.xyz;
10104 var conversions_7$1 = conversions$2.lab;
10105 var conversions_8$1 = conversions$2.lch;
10106 var conversions_9$1 = conversions$2.hex;
10107 var conversions_10$1 = conversions$2.keyword;
10108 var conversions_11$1 = conversions$2.ansi16;
10109 var conversions_12$1 = conversions$2.ansi256;
10110 var conversions_13$1 = conversions$2.hcg;
10111 var conversions_14$1 = conversions$2.apple;
10112 var conversions_15$1 = conversions$2.gray;
10115 this function routes a model to all other models.
10117 all functions that are routed have a property `.conversion` attached
10118 to the returned synthetic function. This property is an array
10119 of strings, each with the steps in between the 'from' and 'to'
10120 color models (inclusive).
10122 conversions that are not possible simply are not included.
10125 function buildGraph$2() {
10126 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
10128 var models = Object.keys(conversions$2);
10130 for (var len = models.length, i = 0; i < len; i++) {
10131 graph[models[i]] = {
10132 // http://jsperf.com/1-vs-infinity
10133 // micro-opt, but this is simple.
10140 } // https://en.wikipedia.org/wiki/Breadth-first_search
10143 function deriveBFS$2(fromModel) {
10144 var graph = buildGraph$2();
10145 var queue = [fromModel]; // unshift -> queue -> pop
10147 graph[fromModel].distance = 0;
10149 while (queue.length) {
10150 var current = queue.pop();
10151 var adjacents = Object.keys(conversions$2[current]);
10153 for (var len = adjacents.length, i = 0; i < len; i++) {
10154 var adjacent = adjacents[i];
10155 var node = graph[adjacent];
10157 if (node.distance === -1) {
10158 node.distance = graph[current].distance + 1;
10159 node.parent = current;
10160 queue.unshift(adjacent);
10168 function link$2(from, to) {
10169 return function (args) {
10170 return to(from(args));
10174 function wrapConversion$2(toModel, graph) {
10175 var path = [graph[toModel].parent, toModel];
10176 var fn = conversions$2[graph[toModel].parent][toModel];
10177 var cur = graph[toModel].parent;
10179 while (graph[cur].parent) {
10180 path.unshift(graph[cur].parent);
10181 fn = link$2(conversions$2[graph[cur].parent][cur], fn);
10182 cur = graph[cur].parent;
10185 fn.conversion = path;
10189 var route$2 = function (fromModel) {
10190 var graph = deriveBFS$2(fromModel);
10191 var conversion = {};
10192 var models = Object.keys(graph);
10194 for (var len = models.length, i = 0; i < len; i++) {
10195 var toModel = models[i];
10196 var node = graph[toModel];
10198 if (node.parent === null) {
10199 // no possible conversion, or this node is the source model.
10203 conversion[toModel] = wrapConversion$2(toModel, graph);
10209 var convert$3 = {};
10210 var models$2 = Object.keys(conversions$2);
10212 function wrapRaw$2(fn) {
10213 var wrappedFn = function (args) {
10214 if (args === undefined || args === null) {
10218 if (arguments.length > 1) {
10219 args = Array.prototype.slice.call(arguments);
10223 }; // preserve .conversion property if there is one
10226 if ('conversion' in fn) {
10227 wrappedFn.conversion = fn.conversion;
10233 function wrapRounded$2(fn) {
10234 var wrappedFn = function (args) {
10235 if (args === undefined || args === null) {
10239 if (arguments.length > 1) {
10240 args = Array.prototype.slice.call(arguments);
10243 var result = fn(args); // we're assuming the result is an array here.
10244 // see notice in conversions.js; don't use box types
10245 // in conversion functions.
10247 if (typeof result === 'object') {
10248 for (var len = result.length, i = 0; i < len; i++) {
10249 result[i] = Math.round(result[i]);
10254 }; // preserve .conversion property if there is one
10257 if ('conversion' in fn) {
10258 wrappedFn.conversion = fn.conversion;
10264 models$2.forEach(function (fromModel) {
10265 convert$3[fromModel] = {};
10266 Object.defineProperty(convert$3[fromModel], 'channels', {
10267 value: conversions$2[fromModel].channels
10269 Object.defineProperty(convert$3[fromModel], 'labels', {
10270 value: conversions$2[fromModel].labels
10272 var routes = route$2(fromModel);
10273 var routeModels = Object.keys(routes);
10274 routeModels.forEach(function (toModel) {
10275 var fn = routes[toModel];
10276 convert$3[fromModel][toModel] = wrapRounded$2(fn);
10277 convert$3[fromModel][toModel].raw = wrapRaw$2(fn);
10280 var colorConvert$2 = convert$3;
10282 var ansiStyles$2 = createCommonjsModule(function (module) {
10284 const wrapAnsi16 = (fn, offset) => function () {
10285 const code = fn.apply(colorConvert$2, arguments);
10286 return `\u001B[${code + offset}m`;
10289 const wrapAnsi256 = (fn, offset) => function () {
10290 const code = fn.apply(colorConvert$2, arguments);
10291 return `\u001B[${38 + offset};5;${code}m`;
10294 const wrapAnsi16m = (fn, offset) => function () {
10295 const rgb = fn.apply(colorConvert$2, arguments);
10296 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
10299 function assembleStyles() {
10300 const codes = new Map();
10304 // 21 isn't widely supported and 22 does the same thing
10308 underline: [4, 24],
10311 strikethrough: [9, 29]
10324 redBright: [91, 39],
10325 greenBright: [92, 39],
10326 yellowBright: [93, 39],
10327 blueBright: [94, 39],
10328 magentaBright: [95, 39],
10329 cyanBright: [96, 39],
10330 whiteBright: [97, 39]
10336 bgYellow: [43, 49],
10338 bgMagenta: [45, 49],
10342 bgBlackBright: [100, 49],
10343 bgRedBright: [101, 49],
10344 bgGreenBright: [102, 49],
10345 bgYellowBright: [103, 49],
10346 bgBlueBright: [104, 49],
10347 bgMagentaBright: [105, 49],
10348 bgCyanBright: [106, 49],
10349 bgWhiteBright: [107, 49]
10353 styles.color.grey = styles.color.gray;
10355 for (const groupName of Object.keys(styles)) {
10356 const group = styles[groupName];
10358 for (const styleName of Object.keys(group)) {
10359 const style = group[styleName];
10360 styles[styleName] = {
10361 open: `\u001B[${style[0]}m`,
10362 close: `\u001B[${style[1]}m`
10364 group[styleName] = styles[styleName];
10365 codes.set(style[0], style[1]);
10368 Object.defineProperty(styles, groupName, {
10372 Object.defineProperty(styles, 'codes', {
10378 const ansi2ansi = n => n;
10380 const rgb2rgb = (r, g, b) => [r, g, b];
10382 styles.color.close = '\u001B[39m';
10383 styles.bgColor.close = '\u001B[49m';
10384 styles.color.ansi = {
10385 ansi: wrapAnsi16(ansi2ansi, 0)
10387 styles.color.ansi256 = {
10388 ansi256: wrapAnsi256(ansi2ansi, 0)
10390 styles.color.ansi16m = {
10391 rgb: wrapAnsi16m(rgb2rgb, 0)
10393 styles.bgColor.ansi = {
10394 ansi: wrapAnsi16(ansi2ansi, 10)
10396 styles.bgColor.ansi256 = {
10397 ansi256: wrapAnsi256(ansi2ansi, 10)
10399 styles.bgColor.ansi16m = {
10400 rgb: wrapAnsi16m(rgb2rgb, 10)
10403 for (let key of Object.keys(colorConvert$2)) {
10404 if (typeof colorConvert$2[key] !== 'object') {
10408 const suite = colorConvert$2[key];
10410 if (key === 'ansi16') {
10414 if ('ansi16' in suite) {
10415 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
10416 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
10419 if ('ansi256' in suite) {
10420 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
10421 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
10424 if ('rgb' in suite) {
10425 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
10426 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
10431 } // Make the export immutable
10434 Object.defineProperty(module, 'exports', {
10436 get: assembleStyles
10440 const env$2 = process.env;
10443 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
10444 forceColor$2 = false;
10445 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
10446 forceColor$2 = true;
10449 if ('FORCE_COLOR' in env$2) {
10450 forceColor$2 = env$2.FORCE_COLOR.length === 0 || parseInt(env$2.FORCE_COLOR, 10) !== 0;
10453 function translateLevel$2(level) {
10461 has256: level >= 2,
10466 function supportsColor$2(stream) {
10467 if (forceColor$2 === false) {
10471 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
10475 if (hasFlag('color=256')) {
10479 if (stream && !stream.isTTY && forceColor$2 !== true) {
10483 const min = forceColor$2 ? 1 : 0;
10485 if (process.platform === 'win32') {
10486 // Node.js 7.5.0 is the first version of Node.js to include a patch to
10487 // libuv that enables 256 color output on Windows. Anything earlier and it
10488 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
10489 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
10490 // release that supports 256 colors. Windows 10 build 14931 is the first release
10491 // that supports 16m/TrueColor.
10492 const osRelease = os$1.release().split('.');
10494 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
10495 return Number(osRelease[2]) >= 14931 ? 3 : 2;
10501 if ('CI' in env$2) {
10502 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') {
10509 if ('TEAMCITY_VERSION' in env$2) {
10510 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0;
10513 if (env$2.COLORTERM === 'truecolor') {
10517 if ('TERM_PROGRAM' in env$2) {
10518 const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
10520 switch (env$2.TERM_PROGRAM) {
10522 return version >= 3 ? 3 : 2;
10524 case 'Apple_Terminal':
10530 if (/-256(color)?$/i.test(env$2.TERM)) {
10534 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) {
10538 if ('COLORTERM' in env$2) {
10542 if (env$2.TERM === 'dumb') {
10549 function getSupportLevel$2(stream) {
10550 const level = supportsColor$2(stream);
10551 return translateLevel$2(level);
10554 var supportsColor_1$2 = {
10555 supportsColor: getSupportLevel$2,
10556 stdout: getSupportLevel$2(process.stdout),
10557 stderr: getSupportLevel$2(process.stderr)
10560 const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
10561 const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
10562 const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
10563 const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
10564 const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
10566 function unescape$2(c) {
10567 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
10568 return String.fromCharCode(parseInt(c.slice(1), 16));
10571 return ESCAPES$2.get(c) || c;
10574 function parseArguments$2(name, args) {
10575 const results = [];
10576 const chunks = args.trim().split(/\s*,\s*/g);
10579 for (const chunk of chunks) {
10580 if (!isNaN(chunk)) {
10581 results.push(Number(chunk));
10582 } else if (matches = chunk.match(STRING_REGEX$2)) {
10583 results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr));
10585 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
10592 function parseStyle$2(style) {
10593 STYLE_REGEX$2.lastIndex = 0;
10594 const results = [];
10597 while ((matches = STYLE_REGEX$2.exec(style)) !== null) {
10598 const name = matches[1];
10601 const args = parseArguments$2(name, matches[2]);
10602 results.push([name].concat(args));
10604 results.push([name]);
10611 function buildStyle$2(chalk, styles) {
10612 const enabled = {};
10614 for (const layer of styles) {
10615 for (const style of layer.styles) {
10616 enabled[style[0]] = layer.inverse ? null : style.slice(1);
10620 let current = chalk;
10622 for (const styleName of Object.keys(enabled)) {
10623 if (Array.isArray(enabled[styleName])) {
10624 if (!(styleName in current)) {
10625 throw new Error(`Unknown Chalk style: ${styleName}`);
10628 if (enabled[styleName].length > 0) {
10629 current = current[styleName].apply(current, enabled[styleName]);
10631 current = current[styleName];
10639 var templates$2 = (chalk, tmp) => {
10642 let chunk = []; // eslint-disable-next-line max-params
10644 tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => {
10646 chunk.push(unescape$2(escapeChar));
10647 } else if (style) {
10648 const str = chunk.join('');
10650 chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str));
10653 styles: parseStyle$2(style)
10655 } else if (close) {
10656 if (styles.length === 0) {
10657 throw new Error('Found extraneous } in Chalk template literal');
10660 chunks.push(buildStyle$2(chalk, styles)(chunk.join('')));
10667 chunks.push(chunk.join(''));
10669 if (styles.length > 0) {
10670 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
10671 throw new Error(errMsg);
10674 return chunks.join('');
10677 var chalk$2 = createCommonjsModule(function (module) {
10679 const stdoutColor = supportsColor_1$2.stdout;
10680 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
10682 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
10684 const skipModels = new Set(['gray']);
10685 const styles = Object.create(null);
10687 function applyOptions(obj, options) {
10688 options = options || {}; // Detect level if not set manually
10690 const scLevel = stdoutColor ? stdoutColor.level : 0;
10691 obj.level = options.level === undefined ? scLevel : options.level;
10692 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
10695 function Chalk(options) {
10696 // We check for this.template here since calling `chalk.constructor()`
10697 // by itself will have a `this` of a previously constructed chalk object
10698 if (!this || !(this instanceof Chalk) || this.template) {
10700 applyOptions(chalk, options);
10702 chalk.template = function () {
10703 const args = [].slice.call(arguments);
10704 return chalkTag.apply(null, [chalk.template].concat(args));
10707 Object.setPrototypeOf(chalk, Chalk.prototype);
10708 Object.setPrototypeOf(chalk.template, chalk);
10709 chalk.template.constructor = Chalk;
10710 return chalk.template;
10713 applyOptions(this, options);
10714 } // Use bright blue on Windows as the normal blue color is illegible
10717 if (isSimpleWindowsTerm) {
10718 ansiStyles$2.blue.open = '\u001B[94m';
10721 for (const key of Object.keys(ansiStyles$2)) {
10722 ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2[key].close), 'g');
10725 const codes = ansiStyles$2[key];
10726 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
10734 return build.call(this, this._styles || [], true, 'visible');
10738 ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.color.close), 'g');
10740 for (const model of Object.keys(ansiStyles$2.color.ansi)) {
10741 if (skipModels.has(model)) {
10747 const level = this.level;
10748 return function () {
10749 const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments);
10752 close: ansiStyles$2.color.close,
10753 closeRe: ansiStyles$2.color.closeRe
10755 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
10762 ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.bgColor.close), 'g');
10764 for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) {
10765 if (skipModels.has(model)) {
10769 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
10770 styles[bgModel] = {
10772 const level = this.level;
10773 return function () {
10774 const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments);
10777 close: ansiStyles$2.bgColor.close,
10778 closeRe: ansiStyles$2.bgColor.closeRe
10780 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
10787 const proto = Object.defineProperties(() => {}, styles);
10789 function build(_styles, _empty, key) {
10790 const builder = function () {
10791 return applyStyle.apply(builder, arguments);
10794 builder._styles = _styles;
10795 builder._empty = _empty;
10797 Object.defineProperty(builder, 'level', {
10805 self.level = level;
10809 Object.defineProperty(builder, 'enabled', {
10813 return self.enabled;
10817 self.enabled = enabled;
10820 }); // See below for fix regarding invisible grey/dim combination on Windows
10822 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
10823 // no way to create a function with a different prototype
10825 builder.__proto__ = proto; // eslint-disable-line no-proto
10830 function applyStyle() {
10831 // Support varags, but simply cast to string in case there's only one arg
10832 const args = arguments;
10833 const argsLen = args.length;
10834 let str = String(arguments[0]);
10836 if (argsLen === 0) {
10841 // Don't slice `arguments`, it prevents V8 optimizations
10842 for (let a = 1; a < argsLen; a++) {
10843 str += ' ' + args[a];
10847 if (!this.enabled || this.level <= 0 || !str) {
10848 return this._empty ? '' : str;
10849 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
10850 // see https://github.com/chalk/chalk/issues/58
10851 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
10854 const originalDim = ansiStyles$2.dim.open;
10856 if (isSimpleWindowsTerm && this.hasGrey) {
10857 ansiStyles$2.dim.open = '';
10860 for (const code of this._styles.slice().reverse()) {
10861 // Replace any instances already present with a re-opening code
10862 // otherwise only the part of the string until said closing code
10863 // will be colored, and the rest will simply be 'plain'.
10864 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
10865 // after next line to fix a bleed issue on macOS
10866 // https://github.com/chalk/chalk/pull/92
10868 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
10869 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
10872 ansiStyles$2.dim.open = originalDim;
10876 function chalkTag(chalk, strings) {
10877 if (!Array.isArray(strings)) {
10878 // If chalk() was called by itself or with a string,
10879 // return the string itself as a string.
10880 return [].slice.call(arguments, 1).join(' ');
10883 const args = [].slice.call(arguments, 2);
10884 const parts = [strings.raw[0]];
10886 for (let i = 1; i < strings.length; i++) {
10887 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
10888 parts.push(String(strings.raw[i]));
10891 return templates$2(chalk, parts.join(''));
10894 Object.defineProperties(Chalk.prototype, styles);
10895 module.exports = Chalk(); // eslint-disable-line new-cap
10897 module.exports.supportsColor = stdoutColor;
10898 module.exports.default = module.exports; // For TypeScript
10900 var chalk_1$1 = chalk$2.supportsColor;
10902 var lib$1 = createCommonjsModule(function (module, exports) {
10904 Object.defineProperty(exports, "__esModule", {
10907 exports.shouldHighlight = shouldHighlight;
10908 exports.getChalk = getChalk;
10909 exports.default = highlight;
10911 var _jsTokens = _interopRequireWildcard(jsTokens);
10913 var _esutils = _interopRequireDefault(utils$1);
10915 var _chalk = _interopRequireDefault(chalk$2);
10917 function _interopRequireDefault(obj) {
10918 return obj && obj.__esModule ? obj : {
10923 function _getRequireWildcardCache() {
10924 if (typeof WeakMap !== "function") return null;
10925 var cache = new WeakMap();
10927 _getRequireWildcardCache = function () {
10934 function _interopRequireWildcard(obj) {
10935 if (obj && obj.__esModule) {
10939 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
10945 var cache = _getRequireWildcardCache();
10947 if (cache && cache.has(obj)) {
10948 return cache.get(obj);
10952 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
10954 for (var key in obj) {
10955 if (Object.prototype.hasOwnProperty.call(obj, key)) {
10956 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
10958 if (desc && (desc.get || desc.set)) {
10959 Object.defineProperty(newObj, key, desc);
10961 newObj[key] = obj[key];
10966 newObj.default = obj;
10969 cache.set(obj, newObj);
10975 function getDefs(chalk) {
10977 keyword: chalk.cyan,
10978 capitalized: chalk.yellow,
10979 jsx_tag: chalk.yellow,
10980 punctuator: chalk.yellow,
10981 number: chalk.magenta,
10982 string: chalk.green,
10983 regex: chalk.magenta,
10984 comment: chalk.grey,
10985 invalid: chalk.white.bgRed.bold
10989 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
10990 const JSX_TAG = /^[a-z][\w-]*$/i;
10991 const BRACKET = /^[()[\]{}]$/;
10993 function getTokenType(match) {
10994 const [offset, text] = match.slice(-2);
10995 const token = (0, _jsTokens.matchToToken)(match);
10997 if (token.type === "name") {
10998 if (_esutils.default.keyword.isReservedWordES6(token.value)) {
11002 if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
11006 if (token.value[0] !== token.value[0].toLowerCase()) {
11007 return "capitalized";
11011 if (token.type === "punctuator" && BRACKET.test(token.value)) {
11015 if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
11016 return "punctuator";
11022 function highlightTokens(defs, text) {
11023 return text.replace(_jsTokens.default, function (...args) {
11024 const type = getTokenType(args);
11025 const colorize = defs[type];
11028 return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
11035 function shouldHighlight(options) {
11036 return _chalk.default.supportsColor || options.forceColor;
11039 function getChalk(options) {
11040 let chalk = _chalk.default;
11042 if (options.forceColor) {
11043 chalk = new _chalk.default.constructor({
11052 function highlight(code, options = {}) {
11053 if (shouldHighlight(options)) {
11054 const chalk = getChalk(options);
11055 const defs = getDefs(chalk);
11056 return highlightTokens(defs, code);
11062 unwrapExports(lib$1);
11063 var lib_1 = lib$1.shouldHighlight;
11064 var lib_2 = lib$1.getChalk;
11066 var lib$2 = createCommonjsModule(function (module, exports) {
11068 Object.defineProperty(exports, "__esModule", {
11071 exports.codeFrameColumns = codeFrameColumns;
11072 exports.default = _default;
11074 var _highlight = _interopRequireWildcard(lib$1);
11076 function _getRequireWildcardCache() {
11077 if (typeof WeakMap !== "function") return null;
11078 var cache = new WeakMap();
11080 _getRequireWildcardCache = function () {
11087 function _interopRequireWildcard(obj) {
11088 if (obj && obj.__esModule) {
11092 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
11098 var cache = _getRequireWildcardCache();
11100 if (cache && cache.has(obj)) {
11101 return cache.get(obj);
11105 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
11107 for (var key in obj) {
11108 if (Object.prototype.hasOwnProperty.call(obj, key)) {
11109 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
11111 if (desc && (desc.get || desc.set)) {
11112 Object.defineProperty(newObj, key, desc);
11114 newObj[key] = obj[key];
11119 newObj.default = obj;
11122 cache.set(obj, newObj);
11128 let deprecationWarningShown = false;
11130 function getDefs(chalk) {
11132 gutter: chalk.grey,
11133 marker: chalk.red.bold,
11134 message: chalk.red.bold
11138 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
11140 function getMarkerLines(loc, source, opts) {
11141 const startLoc = Object.assign({
11145 const endLoc = Object.assign({}, startLoc, {}, loc.end);
11150 const startLine = startLoc.line;
11151 const startColumn = startLoc.column;
11152 const endLine = endLoc.line;
11153 const endColumn = endLoc.column;
11154 let start = Math.max(startLine - (linesAbove + 1), 0);
11155 let end = Math.min(source.length, endLine + linesBelow);
11157 if (startLine === -1) {
11161 if (endLine === -1) {
11162 end = source.length;
11165 const lineDiff = endLine - startLine;
11166 const markerLines = {};
11169 for (let i = 0; i <= lineDiff; i++) {
11170 const lineNumber = i + startLine;
11172 if (!startColumn) {
11173 markerLines[lineNumber] = true;
11174 } else if (i === 0) {
11175 const sourceLength = source[lineNumber - 1].length;
11176 markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
11177 } else if (i === lineDiff) {
11178 markerLines[lineNumber] = [0, endColumn];
11180 const sourceLength = source[lineNumber - i].length;
11181 markerLines[lineNumber] = [0, sourceLength];
11185 if (startColumn === endColumn) {
11187 markerLines[startLine] = [startColumn, 0];
11189 markerLines[startLine] = true;
11192 markerLines[startLine] = [startColumn, endColumn - startColumn];
11203 function codeFrameColumns(rawLines, loc, opts = {}) {
11204 const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
11205 const chalk = (0, _highlight.getChalk)(opts);
11206 const defs = getDefs(chalk);
11208 const maybeHighlight = (chalkFn, string) => {
11209 return highlighted ? chalkFn(string) : string;
11212 const lines = rawLines.split(NEWLINE);
11217 } = getMarkerLines(loc, lines, opts);
11218 const hasColumns = loc.start && typeof loc.start.column === "number";
11219 const numberMaxWidth = String(end).length;
11220 const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
11221 let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
11222 const number = start + 1 + index;
11223 const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
11224 const gutter = ` ${paddedNumber} | `;
11225 const hasMarker = markerLines[number];
11226 const lastMarkerLine = !markerLines[number + 1];
11229 let markerLine = "";
11231 if (Array.isArray(hasMarker)) {
11232 const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
11233 const numberOfMarkers = hasMarker[1] || 1;
11234 markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
11236 if (lastMarkerLine && opts.message) {
11237 markerLine += " " + maybeHighlight(defs.message, opts.message);
11241 return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
11243 return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
11247 if (opts.message && !hasColumns) {
11248 frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
11252 return chalk.reset(frame);
11258 function _default(rawLines, lineNumber, colNumber, opts = {}) {
11259 if (!deprecationWarningShown) {
11260 deprecationWarningShown = true;
11261 const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
11263 if (process.emitWarning) {
11264 process.emitWarning(message, "DeprecationWarning");
11266 const deprecationError = new Error(message);
11267 deprecationError.name = "DeprecationWarning";
11268 console.warn(new Error(message));
11272 colNumber = Math.max(colNumber, 0);
11279 return codeFrameColumns(rawLines, location, opts);
11282 unwrapExports(lib$2);
11283 var lib_1$1 = lib$2.codeFrameColumns;
11286 ConfigError: ConfigError$1
11289 locStart: locStart$1,
11291 } = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
11292 // triggering the parsers getters.
11294 const ownNames = Object.getOwnPropertyNames;
11295 const ownDescriptor = Object.getOwnPropertyDescriptor;
11297 function getParsers(options) {
11298 const parsers = {};
11300 for (const plugin of options.plugins) {
11301 if (!plugin.parsers) {
11305 for (const name of ownNames(plugin.parsers)) {
11306 Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
11313 function resolveParser(opts, parsers) {
11314 parsers = parsers || getParsers(opts);
11316 if (typeof opts.parser === "function") {
11317 // Custom parser API always works with JavaScript.
11319 parse: opts.parser,
11320 astFormat: "estree",
11321 locStart: locStart$1,
11326 if (typeof opts.parser === "string") {
11327 if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) {
11328 return parsers[opts.parser];
11330 /* istanbul ignore next */
11336 parse: require(path$2.resolve(process.cwd(), opts.parser)),
11337 astFormat: "estree",
11338 locStart: locStart$1,
11342 /* istanbul ignore next */
11343 throw new ConfigError$1(`Couldn't resolve parser "${opts.parser}"`);
11349 function parse(text, opts) {
11350 const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
11351 // the parsers getters when actually calling the parser `parse` function.
11353 const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, {
11357 return parsers[parserName].parse;
11361 const parser = resolveParser(opts, parsers);
11364 if (parser.preprocess) {
11365 text = parser.preprocess(text, opts);
11370 ast: parser.parse(text, parsersForCustomParserApi, opts)
11378 const codeFrame = lib$2;
11379 error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
11380 highlightCode: true
11382 error.message += "\n" + error.codeFrame;
11385 /* istanbul ignore next */
11398 UndefinedParserError: UndefinedParserError$1
11401 getSupportInfo: getSupportInfo$1
11404 resolveParser: resolveParser$1
11406 const hiddenDefaults = {
11407 astFormat: "estree",
11409 originalText: undefined,
11412 }; // Copy options and fill in default values.
11414 function normalize$1(options, opts) {
11416 const rawOptions = Object.assign({}, options);
11417 const supportOptions = getSupportInfo$1({
11418 plugins: options.plugins,
11419 showUnreleased: true,
11420 showDeprecated: true
11422 const defaults = Object.assign({}, hiddenDefaults, {}, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default])));
11424 if (!rawOptions.parser) {
11425 if (!rawOptions.filepath) {
11426 const logger = opts.logger || console;
11427 logger.warn("No parser and no filepath given, using 'babel' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred.");
11428 rawOptions.parser = "babel";
11430 rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
11432 if (!rawOptions.parser) {
11433 throw new UndefinedParserError$1(`No parser could be inferred for file: ${rawOptions.filepath}`);
11438 const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], {
11442 rawOptions.astFormat = parser.astFormat;
11443 rawOptions.locEnd = parser.locEnd;
11444 rawOptions.locStart = parser.locStart;
11445 const plugin = getPlugin(rawOptions);
11446 rawOptions.printer = plugin.printers[rawOptions.astFormat];
11447 const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, {
11448 [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
11450 const mixedDefaults = Object.assign({}, defaults, {}, pluginDefaults);
11451 Object.keys(mixedDefaults).forEach(k => {
11452 if (rawOptions[k] == null) {
11453 rawOptions[k] = mixedDefaults[k];
11457 if (rawOptions.parser === "json") {
11458 rawOptions.trailingComma = "none";
11461 return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
11462 passThrough: Object.keys(hiddenDefaults)
11466 function getPlugin(options) {
11472 throw new Error("getPlugin() requires astFormat to be set");
11475 const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]);
11477 if (!printerPlugin) {
11478 throw new Error(`Couldn't find plugin for AST format "${astFormat}"`);
11481 return printerPlugin;
11484 function getInterpreter(filepath) {
11485 if (typeof filepath !== "string") {
11492 fd = fs$3.openSync(filepath, "r");
11494 // istanbul ignore next
11499 const liner = new readlines(fd);
11500 const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
11502 const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
11506 } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
11509 const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
11517 // There are some weird cases where paths are missing, causing Jest
11518 // failures. It's unclear what these correspond to in the real world.
11522 // There are some weird cases where paths are missing, causing Jest
11523 // failures. It's unclear what these correspond to in the real world.
11524 fs$3.closeSync(fd);
11525 } catch (err) {// nop
11530 function inferParser(filepath, plugins) {
11531 const filename = path$2.basename(filepath).toLowerCase();
11532 const languages = getSupportInfo$1({
11534 }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the
11535 // interpreter in the shebang line, if any; but since this requires FS access,
11538 let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.find(name => name.toLowerCase() === filename));
11540 if (!language && !filename.includes(".")) {
11541 const interpreter = getInterpreter(filepath);
11542 language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter));
11545 return language && language.parsers[0];
11549 normalize: normalize$1,
11554 function massageAST(ast, options, parent) {
11555 if (Array.isArray(ast)) {
11556 return ast.map(e => massageAST(e, options, parent)).filter(Boolean);
11559 if (!ast || typeof ast !== "object") {
11565 for (const key of Object.keys(ast)) {
11566 if (typeof ast[key] !== "function") {
11567 newObj[key] = massageAST(ast[key], options, ast);
11571 if (options.printer.massageAstNode) {
11572 const result = options.printer.massageAstNode(ast, newObj, parent);
11574 if (result === null) {
11586 var massageAst = massageAST;
11589 * @param {Doc[]} parts
11594 function concat(parts) {
11595 // access the internals of a document directly.
11596 // if(parts.length === 1) {
11597 // // If it's a single document, no need to concat it.
11598 // return parts[0];
11608 * @param {Doc} contents
11613 function indent(contents) {
11621 * @param {number} n
11622 * @param {Doc} contents
11627 function align(n, contents) {
11636 * @param {Doc} contents
11637 * @param {object} [opts] - TBD ???
11642 function group(contents, opts) {
11649 break: !!opts.shouldBreak,
11650 expandedStates: opts.expandedStates
11654 * @param {Doc} contents
11659 function dedentToRoot(contents) {
11660 return align(-Infinity, contents);
11663 * @param {Doc} contents
11668 function markAsRoot(contents) {
11669 // @ts-ignore - TBD ???:
11675 * @param {Doc} contents
11680 function dedent(contents) {
11681 return align(-1, contents);
11684 * @param {Doc[]} states
11685 * @param {object} [opts] - TBD ???
11690 function conditionalGroup(states, opts) {
11691 return group(states[0], Object.assign({}, opts, {
11692 expandedStates: states
11696 * @param {Doc[]} parts
11701 function fill(parts) {
11709 * @param {Doc} [breakContents]
11710 * @param {Doc} [flatContents]
11711 * @param {object} [opts] - TBD ???
11716 function ifBreak(breakContents, flatContents, opts) {
11723 groupId: opts.groupId
11727 * @param {Doc} contents
11732 function lineSuffix(contents) {
11735 type: "line-suffix",
11740 const lineSuffixBoundary = {
11741 type: "line-suffix-boundary"
11743 const breakParent = {
11744 type: "break-parent"
11756 const hardline = concat([{
11760 const literalline = concat([{
11767 placeholder: Symbol("cursor")
11771 * @param {Doc[]} arr
11775 function join(sep, arr) {
11778 for (let i = 0; i < arr.length; i++) {
11786 return concat(res);
11790 * @param {number} size
11791 * @param {number} tabWidth
11795 function addAlignmentToDoc(doc, size, tabWidth) {
11799 // Use indent to add tabs for all the levels of tabs we need
11800 for (let i = 0; i < Math.floor(size / tabWidth); ++i) {
11801 aligned = indent(aligned);
11802 } // Use align for all the spaces that are needed
11805 aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
11806 // indentation, so we use -Infinity to reset the indentation to 0
11808 aligned = align(-Infinity, aligned);
11814 var docBuilders = {
11825 lineSuffixBoundary,
11841 const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
11842 return new RegExp(pattern, onlyFirst ? undefined : 'g');
11845 var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
11847 /* eslint-disable yoda */
11849 const isFullwidthCodePoint = codePoint => {
11850 if (Number.isNaN(codePoint)) {
11852 } // Code points are derived from:
11853 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
11856 if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
11857 codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
11858 codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
11859 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
11860 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
11861 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
11862 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
11863 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
11864 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
11865 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
11866 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
11867 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
11868 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
11869 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
11870 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
11871 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
11878 var isFullwidthCodePoint_1 = isFullwidthCodePoint;
11879 var default_1$1 = isFullwidthCodePoint;
11880 isFullwidthCodePoint_1.default = default_1$1;
11882 var emojiRegex = function () {
11883 // https://mths.be/emoji
11884 return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
11887 const stringWidth = string => {
11888 string = string.replace(emojiRegex(), ' ');
11890 if (typeof string !== 'string' || string.length === 0) {
11894 string = stripAnsi(string);
11897 for (let i = 0; i < string.length; i++) {
11898 const code = string.codePointAt(i); // Ignore control characters
11900 if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
11902 } // Ignore combining characters
11905 if (code >= 0x300 && code <= 0x36F) {
11910 if (code > 0xFFFF) {
11914 width += isFullwidthCodePoint_1(code) ? 2 : 1;
11920 var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
11922 var default_1$2 = stringWidth;
11923 stringWidth_1.default = default_1$2;
11925 const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
11927 var escapeStringRegexp$2 = string => {
11928 if (typeof string !== 'string') {
11929 throw new TypeError('Expected a string');
11932 return string.replace(matchOperatorsRegex, '\\$&');
11935 const notAsciiRegex = /[^\x20-\x7F]/;
11937 function getPenultimate(arr) {
11938 if (arr.length > 1) {
11939 return arr[arr.length - 2];
11945 * @typedef {{backwards?: boolean}} SkipOptions
11949 * @param {string | RegExp} chars
11950 * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
11954 function skip(chars) {
11955 return (text, index, opts) => {
11956 const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
11957 // to check for failures (did someone say monads?).
11959 if (index === false) {
11966 let cursor = index;
11968 while (cursor >= 0 && cursor < length) {
11969 const c = text.charAt(cursor);
11971 if (chars instanceof RegExp) {
11972 if (!chars.test(c)) {
11975 } else if (!chars.includes(c)) {
11979 backwards ? cursor-- : cursor++;
11982 if (cursor === -1 || cursor === length) {
11983 // If we reached the beginning or end of the file, return the
11984 // out-of-bounds cursor. It's up to the caller to handle this
11985 // correctly. We don't want to indicate `false` though if it
11986 // actually skipped valid characters.
11994 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
11998 const skipWhitespace = skip(/\s/);
12000 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12003 const skipSpaces = skip(" \t");
12005 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12008 const skipToLineEnd = skip(",; \t");
12010 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12013 const skipEverythingButNewLine = skip(/[^\r\n]/);
12015 * @param {string} text
12016 * @param {number | false} index
12017 * @returns {number | false}
12020 function skipInlineComment(text, index) {
12021 if (index === false) {
12025 if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
12026 for (let i = index + 2; i < text.length; ++i) {
12027 if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
12036 * @param {string} text
12037 * @param {number | false} index
12038 * @returns {number | false}
12042 function skipTrailingComment(text, index) {
12043 if (index === false) {
12047 if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
12048 return skipEverythingButNewLine(text, index);
12052 } // This one doesn't use the above helper function because it wants to
12053 // test \r\n in order and `skip` doesn't support ordering and we only
12054 // want to skip one newline. It's simple to implement.
12057 * @param {string} text
12058 * @param {number | false} index
12059 * @param {SkipOptions=} opts
12060 * @returns {number | false}
12064 function skipNewline(text, index, opts) {
12065 const backwards = opts && opts.backwards;
12067 if (index === false) {
12071 const atIndex = text.charAt(index);
12074 if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
12078 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
12082 if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
12086 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
12094 * @param {string} text
12095 * @param {number} index
12096 * @param {SkipOptions=} opts
12097 * @returns {boolean}
12101 function hasNewline(text, index, opts) {
12103 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
12104 const idx2 = skipNewline(text, idx, opts);
12105 return idx !== idx2;
12108 * @param {string} text
12109 * @param {number} start
12110 * @param {number} end
12111 * @returns {boolean}
12115 function hasNewlineInRange(text, start, end) {
12116 for (let i = start; i < end; ++i) {
12117 if (text.charAt(i) === "\n") {
12123 } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
12127 * @param {string} text
12129 * @param {(node: N) => number} locStart
12133 function isPreviousLineEmpty(text, node, locStart) {
12134 /** @type {number | false} */
12135 let idx = locStart(node) - 1;
12136 idx = skipSpaces(text, idx, {
12139 idx = skipNewline(text, idx, {
12142 idx = skipSpaces(text, idx, {
12145 const idx2 = skipNewline(text, idx, {
12148 return idx !== idx2;
12151 * @param {string} text
12152 * @param {number} index
12153 * @returns {boolean}
12157 function isNextLineEmptyAfterIndex(text, index) {
12158 /** @type {number | false} */
12160 /** @type {number | false} */
12164 while (idx !== oldIdx) {
12165 // We need to skip all the potential trailing inline comments
12167 idx = skipToLineEnd(text, idx);
12168 idx = skipInlineComment(text, idx);
12169 idx = skipSpaces(text, idx);
12172 idx = skipTrailingComment(text, idx);
12173 idx = skipNewline(text, idx);
12174 return idx !== false && hasNewline(text, idx);
12178 * @param {string} text
12180 * @param {(node: N) => number} locEnd
12181 * @returns {boolean}
12185 function isNextLineEmpty(text, node, locEnd) {
12186 return isNextLineEmptyAfterIndex(text, locEnd(node));
12189 * @param {string} text
12190 * @param {number} idx
12191 * @returns {number | false}
12195 function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
12196 /** @type {number | false} */
12198 /** @type {number | false} */
12202 while (nextIdx !== oldIdx) {
12204 nextIdx = skipSpaces(text, nextIdx);
12205 nextIdx = skipInlineComment(text, nextIdx);
12206 nextIdx = skipTrailingComment(text, nextIdx);
12207 nextIdx = skipNewline(text, nextIdx);
12214 * @param {string} text
12216 * @param {(node: N) => number} locEnd
12217 * @returns {number | false}
12221 function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
12222 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
12226 * @param {string} text
12228 * @param {(node: N) => number} locEnd
12229 * @returns {string}
12233 function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
12234 return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
12235 getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
12238 * @param {string} text
12239 * @param {number} index
12240 * @param {SkipOptions=} opts
12241 * @returns {boolean}
12245 function hasSpaces(text, index, opts) {
12247 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
12248 return idx !== index;
12251 * @param {{range?: [number, number], start?: number}} node
12252 * @param {number} index
12256 function setLocStart(node, index) {
12258 node.range[0] = index;
12260 node.start = index;
12264 * @param {{range?: [number, number], end?: number}} node
12265 * @param {number} index
12269 function setLocEnd(node, index) {
12271 node.range[1] = index;
12277 const PRECEDENCE = {};
12278 [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => {
12279 tier.forEach(op => {
12280 PRECEDENCE[op] = i;
12284 function getPrecedence(op) {
12285 return PRECEDENCE[op];
12288 const equalityOperators = {
12294 const multiplicativeOperators = {
12299 const bitshiftOperators = {
12305 function shouldFlatten(parentOp, nodeOp) {
12306 if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
12308 } // ** is right-associative
12309 // x ** y ** z --> x ** (y ** z)
12312 if (parentOp === "**") {
12314 } // x == y == z --> (x == y) == z
12317 if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
12319 } // x * y % z --> (x * y) % z
12322 if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
12324 } // x * y / z --> (x * y) / z
12325 // x / y * z --> (x / y) * z
12328 if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
12330 } // x << y << z --> (x << y) << z
12333 if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
12340 function isBitwiseOperator(operator) {
12341 return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
12342 } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
12343 // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
12344 // already necessary grouping parentheses.
12347 function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
12348 node = getLeftMost(node);
12350 switch (node.type) {
12351 case "FunctionExpression":
12352 case "ClassExpression":
12353 case "DoExpression":
12354 return forbidFunctionClassAndDoExpr;
12356 case "ObjectExpression":
12359 case "MemberExpression":
12360 case "OptionalMemberExpression":
12361 return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
12363 case "TaggedTemplateExpression":
12364 if (node.tag.type === "FunctionExpression") {
12365 // IIFEs are always already parenthesized
12369 return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
12371 case "CallExpression":
12372 case "OptionalCallExpression":
12373 if (node.callee.type === "FunctionExpression") {
12374 // IIFEs are always already parenthesized
12378 return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
12380 case "ConditionalExpression":
12381 return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
12383 case "UpdateExpression":
12384 return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
12386 case "BindExpression":
12387 return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
12389 case "SequenceExpression":
12390 return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
12392 case "TSAsExpression":
12393 return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
12400 function getLeftMost(node) {
12402 return getLeftMost(node.left);
12408 * @param {string} value
12409 * @param {number} tabWidth
12410 * @param {number=} startIndex
12411 * @returns {number}
12415 function getAlignmentSize(value, tabWidth, startIndex) {
12416 startIndex = startIndex || 0;
12419 for (let i = startIndex; i < value.length; ++i) {
12420 if (value[i] === "\t") {
12421 // Tabs behave in a way that they are aligned to the nearest
12422 // multiple of tabWidth:
12423 // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
12424 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
12425 size = size + tabWidth - size % tabWidth;
12434 * @param {string} value
12435 * @param {number} tabWidth
12436 * @returns {number}
12440 function getIndentSize(value, tabWidth) {
12441 const lastNewlineIndex = value.lastIndexOf("\n");
12443 if (lastNewlineIndex === -1) {
12447 return getAlignmentSize( // All the leading whitespaces
12448 value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
12451 * @typedef {'"' | "'"} Quote
12456 * @param {string} raw
12457 * @param {Quote} preferredQuote
12462 function getPreferredQuote(raw, preferredQuote) {
12463 // `rawContent` is the string exactly like it appeared in the input source
12464 // code, without its enclosing quotes.
12465 const rawContent = raw.slice(1, -1);
12466 /** @type {{ quote: '"', regex: RegExp }} */
12472 /** @type {{ quote: "'", regex: RegExp }} */
12478 const preferred = preferredQuote === "'" ? single : double;
12479 const alternate = preferred === single ? double : single;
12480 let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
12481 // the string, we might want to enclose with the alternate quote instead, to
12482 // minimize the number of escaped quotes.
12484 if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
12485 const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
12486 const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
12487 result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
12493 function printString(raw, options, isDirectiveLiteral) {
12494 // `rawContent` is the string exactly like it appeared in the input source
12495 // code, without its enclosing quotes.
12496 const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
12497 // the quotes on a DirectiveLiteral.
12499 const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
12500 /** @type {Quote} */
12502 const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
12503 // change the escape sequences they use.
12504 // See https://github.com/prettier/prettier/issues/1555
12505 // and https://tc39.github.io/ecma262/#directive-prologue
12507 if (isDirectiveLiteral) {
12508 if (canChangeDirectiveQuotes) {
12509 return enclosingQuote + rawContent + enclosingQuote;
12513 } // It might sound unnecessary to use `makeString` even if the string already
12514 // is enclosed with `enclosingQuote`, but it isn't. The string could contain
12515 // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
12516 // sure that we consistently output the minimum amount of escaped quotes.
12519 return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
12522 * @param {string} rawContent
12523 * @param {Quote} enclosingQuote
12524 * @param {boolean=} unescapeUnnecessaryEscapes
12525 * @returns {string}
12529 function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
12530 const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
12532 const regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
12533 // enclose `rawContent` with `enclosingQuote`.
12535 const newContent = rawContent.replace(regex, (match, escaped, quote) => {
12536 // If we matched an escape, and the escaped character is a quote of the
12537 // other type than we intend to enclose the string with, there's no need for
12538 // it to be escaped, so return it _without_ the backslash.
12539 if (escaped === otherQuote) {
12541 } // If we matched an unescaped quote and it is of the _same_ type as we
12542 // intend to enclose the string with, it must be escaped, so return it with
12546 if (quote === enclosingQuote) {
12547 return "\\" + quote;
12552 } // Unescape any unnecessarily escaped character.
12553 // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
12556 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
12558 return enclosingQuote + newContent + enclosingQuote;
12561 function printNumber(rawNumber) {
12562 return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
12563 .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
12564 .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
12565 .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
12566 .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
12567 .replace(/\.(?=e|$)/, "");
12570 * @param {string} str
12571 * @param {string} target
12572 * @returns {number}
12576 function getMaxContinuousCount(str, target) {
12577 const results = str.match(new RegExp(`(${escapeStringRegexp$2(target)})+`, "g"));
12579 if (results === null) {
12583 return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0);
12586 function getMinNotPresentContinuousCount(str, target) {
12587 const matches = str.match(new RegExp(`(${escapeStringRegexp$2(target)})+`, "g"));
12589 if (matches === null) {
12593 const countPresent = new Map();
12596 for (const match of matches) {
12597 const count = match.length / target.length;
12598 countPresent.set(count, true);
12605 for (let i = 1; i < max; i++) {
12606 if (!countPresent.get(i)) {
12614 * @param {string} text
12615 * @returns {number}
12619 function getStringWidth(text) {
12622 } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
12625 if (!notAsciiRegex.test(text)) {
12626 return text.length;
12629 return stringWidth_1(text);
12632 function hasIgnoreComment(path) {
12633 const node = path.getValue();
12634 return hasNodeIgnoreComment(node);
12637 function hasNodeIgnoreComment(node) {
12638 return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore);
12641 function isNodeIgnoreComment(comment) {
12642 return comment.value.trim() === "prettier-ignore";
12645 function addCommentHelper(node, comment) {
12646 const comments = node.comments || (node.comments = []);
12647 comments.push(comment);
12648 comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
12649 // We already "print" it via the raw text, we don't need to re-print it as a
12652 if (node.type === "JSXText") {
12653 comment.printed = true;
12657 function addLeadingComment(node, comment) {
12658 comment.leading = true;
12659 comment.trailing = false;
12660 addCommentHelper(node, comment);
12663 function addDanglingComment(node, comment) {
12664 comment.leading = false;
12665 comment.trailing = false;
12666 addCommentHelper(node, comment);
12669 function addTrailingComment(node, comment) {
12670 comment.leading = false;
12671 comment.trailing = true;
12672 addCommentHelper(node, comment);
12675 function isWithinParentArrayProperty(path, propertyName) {
12676 const node = path.getValue();
12677 const parent = path.getParentNode();
12679 if (parent == null) {
12683 if (!Array.isArray(parent[propertyName])) {
12687 const key = path.getName();
12688 return parent[propertyName][key] === node;
12691 function replaceEndOfLineWith(text, replacement) {
12694 for (const part of text.split("\n")) {
12695 if (parts.length !== 0) {
12696 parts.push(replacement);
12706 replaceEndOfLineWith,
12708 getMaxContinuousCount,
12709 getMinNotPresentContinuousCount,
12715 getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
12716 getNextNonSpaceNonCommentCharacterIndex,
12717 getNextNonSpaceNonCommentCharacter,
12722 skipEverythingButNewLine,
12724 skipTrailingComment,
12726 isNextLineEmptyAfterIndex,
12728 isPreviousLineEmpty,
12734 startsWithNoLookaheadToken,
12741 hasNodeIgnoreComment,
12742 isNodeIgnoreComment,
12745 addDanglingComment,
12746 addTrailingComment,
12747 isWithinParentArrayProperty
12750 function guessEndOfLine(text) {
12751 const index = text.indexOf("\r");
12754 return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
12760 function convertEndOfLineToChars(value) {
12775 convertEndOfLineToChars
12779 getStringWidth: getStringWidth$1
12782 convertEndOfLineToChars: convertEndOfLineToChars$1
12789 /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
12792 const MODE_BREAK = 1;
12793 const MODE_FLAT = 2;
12795 function rootIndent() {
12803 function makeIndent(ind, options) {
12804 return generateInd(ind, {
12809 function makeAlign(ind, n, options) {
12810 return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
12812 }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
12814 }) : typeof n === "string" ? generateInd(ind, {
12815 type: "stringAlign",
12817 }, options) : generateInd(ind, {
12818 type: "numberAlign",
12823 function generateInd(ind, newPart, options) {
12824 const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
12828 let lastSpaces = 0;
12830 for (const part of queue) {
12831 switch (part.type) {
12835 if (options.useTabs) {
12838 addSpaces(options.tabWidth);
12843 case "stringAlign":
12846 length += part.n.length;
12849 case "numberAlign":
12851 lastSpaces += part.n;
12854 /* istanbul ignore next */
12857 throw new Error(`Unexpected type '${part.type}'`);
12862 return Object.assign({}, ind, {
12868 function addTabs(count) {
12869 value += "\t".repeat(count);
12870 length += options.tabWidth * count;
12873 function addSpaces(count) {
12874 value += " ".repeat(count);
12879 if (options.useTabs) {
12886 function flushTabs() {
12887 if (lastTabs > 0) {
12894 function flushSpaces() {
12895 if (lastSpaces > 0) {
12896 addSpaces(lastSpaces);
12902 function resetLast() {
12908 function trim$1(out) {
12909 if (out.length === 0) {
12913 let trimCount = 0; // Trim whitespace at the end of line
12915 while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
12916 trimCount += out.pop().length;
12919 if (out.length && typeof out[out.length - 1] === "string") {
12920 const trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
12921 trimCount += out[out.length - 1].length - trimmed.length;
12922 out[out.length - 1] = trimmed;
12928 function fits(next, restCommands, width, options, mustBeFlat) {
12929 let restIdx = restCommands.length;
12930 const cmds = [next]; // `out` is only used for width counting because `trim` requires to look
12931 // backwards for space characters.
12935 while (width >= 0) {
12936 if (cmds.length === 0) {
12937 if (restIdx === 0) {
12941 cmds.push(restCommands[restIdx - 1]);
12946 const [ind, mode, doc] = cmds.pop();
12948 if (typeof doc === "string") {
12950 width -= getStringWidth$1(doc);
12952 switch (doc.type) {
12954 for (let i = doc.parts.length - 1; i >= 0; i--) {
12955 cmds.push([ind, mode, doc.parts[i]]);
12961 cmds.push([makeIndent(ind, options), mode, doc.contents]);
12965 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
12969 width += trim$1(out);
12973 if (mustBeFlat && doc.break) {
12977 cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
12980 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
12986 for (let i = doc.parts.length - 1; i >= 0; i--) {
12987 cmds.push([ind, mode, doc.parts[i]]);
12994 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
12996 if (groupMode === MODE_BREAK) {
12997 if (doc.breakContents) {
12998 cmds.push([ind, mode, doc.breakContents]);
13002 if (groupMode === MODE_FLAT) {
13003 if (doc.flatContents) {
13004 cmds.push([ind, mode, doc.flatContents]);
13038 function printDocToString(doc, options) {
13040 const width = options.printWidth;
13041 const newLine = convertEndOfLineToChars$1(options.endOfLine);
13042 let pos = 0; // cmds is basically a stack. We've turned a recursive call into a
13043 // while loop which is much faster. The while loop below adds new
13044 // cmds to the array instead of recursively calling `print`.
13046 const cmds = [[rootIndent(), MODE_BREAK, doc]];
13048 let shouldRemeasure = false;
13049 let lineSuffix = [];
13051 while (cmds.length !== 0) {
13052 const [ind, mode, doc] = cmds.pop();
13054 if (typeof doc === "string") {
13055 const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc;
13056 out.push(formatted);
13057 pos += getStringWidth$1(formatted);
13059 switch (doc.type) {
13061 out.push(cursor$1.placeholder);
13065 for (let i = doc.parts.length - 1; i >= 0; i--) {
13066 cmds.push([ind, mode, doc.parts[i]]);
13072 cmds.push([makeIndent(ind, options), mode, doc.contents]);
13076 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
13080 pos -= trim$1(out);
13086 if (!shouldRemeasure) {
13087 cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]);
13095 shouldRemeasure = false;
13096 const next = [ind, MODE_FLAT, doc.contents];
13097 const rem = width - pos;
13099 if (!doc.break && fits(next, cmds, rem, options)) {
13102 // Expanded states are a rare case where a document
13103 // can manually provide multiple representations of
13104 // itself. It provides an array of documents
13105 // going from the least expanded (most flattened)
13106 // representation first to the most expanded. If a
13107 // group has these, we need to manually go through
13108 // these states and find the first one that fits.
13109 if (doc.expandedStates) {
13110 const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1];
13113 cmds.push([ind, MODE_BREAK, mostExpanded]);
13116 for (let i = 1; i < doc.expandedStates.length + 1; i++) {
13117 if (i >= doc.expandedStates.length) {
13118 cmds.push([ind, MODE_BREAK, mostExpanded]);
13121 const state = doc.expandedStates[i];
13122 const cmd = [ind, MODE_FLAT, state];
13124 if (fits(cmd, cmds, rem, options)) {
13132 cmds.push([ind, MODE_BREAK, doc.contents]);
13141 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
13145 // Fills each line with as much code as possible before moving to a new
13146 // line with the same indentation.
13148 // Expects doc.parts to be an array of alternating content and
13149 // whitespace. The whitespace contains the linebreaks.
13152 // ["I", line, "love", line, "monkeys"]
13154 // [{ type: group, ... }, softline, { type: group, ... }]
13156 // It uses this parts structure to handle three main layout cases:
13157 // * The first two content items fit on the same line without
13159 // -> output the first content item and the whitespace "flat".
13160 // * Only the first content item fits on the line without breaking
13161 // -> output the first content item "flat" and the whitespace with
13163 // * Neither content item fits on the line without breaking
13164 // -> output the first content item and the whitespace with "break".
13168 const rem = width - pos;
13173 if (parts.length === 0) {
13177 const [content, whitespace] = parts;
13178 const contentFlatCmd = [ind, MODE_FLAT, content];
13179 const contentBreakCmd = [ind, MODE_BREAK, content];
13180 const contentFits = fits(contentFlatCmd, [], rem, options, true);
13182 if (parts.length === 1) {
13184 cmds.push(contentFlatCmd);
13186 cmds.push(contentBreakCmd);
13192 const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
13193 const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
13195 if (parts.length === 2) {
13197 cmds.push(whitespaceFlatCmd);
13198 cmds.push(contentFlatCmd);
13200 cmds.push(whitespaceBreakCmd);
13201 cmds.push(contentBreakCmd);
13205 } // At this point we've handled the first pair (context, separator)
13206 // and will create a new fill doc for the rest of the content.
13207 // Ideally we wouldn't mutate the array here but copying all the
13208 // elements to a new array would make this algorithm quadratic,
13209 // which is unusable for large arrays (e.g. large texts in JSX).
13212 parts.splice(0, 2);
13213 const remainingCmd = [ind, mode, fill$1(parts)];
13214 const secondContent = parts[0];
13215 const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
13216 const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true);
13218 if (firstAndSecondContentFits) {
13219 cmds.push(remainingCmd);
13220 cmds.push(whitespaceFlatCmd);
13221 cmds.push(contentFlatCmd);
13222 } else if (contentFits) {
13223 cmds.push(remainingCmd);
13224 cmds.push(whitespaceBreakCmd);
13225 cmds.push(contentFlatCmd);
13227 cmds.push(remainingCmd);
13228 cmds.push(whitespaceBreakCmd);
13229 cmds.push(contentBreakCmd);
13237 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
13239 if (groupMode === MODE_BREAK) {
13240 if (doc.breakContents) {
13241 cmds.push([ind, mode, doc.breakContents]);
13245 if (groupMode === MODE_FLAT) {
13246 if (doc.flatContents) {
13247 cmds.push([ind, mode, doc.flatContents]);
13254 case "line-suffix":
13255 lineSuffix.push([ind, mode, doc.contents]);
13258 case "line-suffix-boundary":
13259 if (lineSuffix.length > 0) {
13260 cmds.push([ind, mode, {
13279 // This line was forced into the output even if we
13280 // were in flattened mode, so we need to tell the next
13281 // group that no matter what, it needs to remeasure
13282 // because the previous measurement didn't accurately
13283 // capture the entire expression (this is necessary
13284 // for nested groups)
13285 shouldRemeasure = true;
13291 if (lineSuffix.length) {
13292 cmds.push([ind, mode, doc]);
13293 cmds.push(...lineSuffix.reverse());
13300 out.push(newLine, ind.root.value);
13301 pos = ind.root.length;
13307 pos -= trim$1(out);
13308 out.push(newLine + ind.value);
13320 const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
13322 if (cursorPlaceholderIndex !== -1) {
13323 const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
13324 const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
13325 const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
13326 const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
13328 formatted: beforeCursor + aroundCursor + afterCursor,
13329 cursorNodeStart: beforeCursor.length,
13330 cursorNodeText: aroundCursor
13335 formatted: out.join("")
13343 const traverseDocOnExitStackMarker = {};
13345 function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
13346 const docsStack = [doc];
13348 while (docsStack.length !== 0) {
13349 const doc = docsStack.pop();
13351 if (doc === traverseDocOnExitStackMarker) {
13352 onExit(docsStack.pop());
13356 let shouldRecurse = true;
13359 if (onEnter(doc) === false) {
13360 shouldRecurse = false;
13365 docsStack.push(doc);
13366 docsStack.push(traverseDocOnExitStackMarker);
13369 if (shouldRecurse) {
13370 // When there are multiple parts to process,
13371 // the parts need to be pushed onto the stack in reverse order,
13372 // so that they are processed in the original order
13373 // when the stack is popped.
13374 if (doc.type === "concat" || doc.type === "fill") {
13375 for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) {
13376 docsStack.push(doc.parts[i]);
13378 } else if (doc.type === "if-break") {
13379 if (doc.flatContents) {
13380 docsStack.push(doc.flatContents);
13383 if (doc.breakContents) {
13384 docsStack.push(doc.breakContents);
13386 } else if (doc.type === "group" && doc.expandedStates) {
13387 if (shouldTraverseConditionalGroups) {
13388 for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) {
13389 docsStack.push(doc.expandedStates[i]);
13392 docsStack.push(doc.contents);
13394 } else if (doc.contents) {
13395 docsStack.push(doc.contents);
13401 function mapDoc(doc, cb) {
13402 if (doc.type === "concat" || doc.type === "fill") {
13403 const parts = doc.parts.map(part => mapDoc(part, cb));
13404 return cb(Object.assign({}, doc, {
13407 } else if (doc.type === "if-break") {
13408 const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
13409 const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
13410 return cb(Object.assign({}, doc, {
13414 } else if (doc.contents) {
13415 const contents = mapDoc(doc.contents, cb);
13416 return cb(Object.assign({}, doc, {
13424 function findInDoc(doc, fn, defaultValue) {
13425 let result = defaultValue;
13426 let hasStopped = false;
13428 function findInDocOnEnterFn(doc) {
13429 const maybeResult = fn(doc);
13431 if (maybeResult !== undefined) {
13433 result = maybeResult;
13441 traverseDoc(doc, findInDocOnEnterFn);
13445 function isEmpty(n) {
13446 return typeof n === "string" && n.length === 0;
13449 function isLineNextFn(doc) {
13450 if (typeof doc === "string") {
13454 if (doc.type === "line") {
13459 function isLineNext(doc) {
13460 return findInDoc(doc, isLineNextFn, false);
13463 function willBreakFn(doc) {
13464 if (doc.type === "group" && doc.break) {
13468 if (doc.type === "line" && doc.hard) {
13472 if (doc.type === "break-parent") {
13477 function willBreak(doc) {
13478 return findInDoc(doc, willBreakFn, false);
13481 function breakParentGroup(groupStack) {
13482 if (groupStack.length > 0) {
13483 const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
13484 // the user is expected to manually handle what breaks.
13486 if (!parentGroup.expandedStates) {
13487 parentGroup.break = true;
13494 function propagateBreaks(doc) {
13495 const alreadyVisitedSet = new Set();
13496 const groupStack = [];
13498 function propagateBreaksOnEnterFn(doc) {
13499 if (doc.type === "break-parent") {
13500 breakParentGroup(groupStack);
13503 if (doc.type === "group") {
13504 groupStack.push(doc);
13506 if (alreadyVisitedSet.has(doc)) {
13510 alreadyVisitedSet.add(doc);
13514 function propagateBreaksOnExitFn(doc) {
13515 if (doc.type === "group") {
13516 const group = groupStack.pop();
13519 breakParentGroup(groupStack);
13524 traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
13525 /* shouldTraverseConditionalGroups */
13529 function removeLinesFn(doc) {
13530 // Force this doc into flat mode by statically converting all
13531 // lines into spaces (or soft lines into nothing). Hard lines
13532 // should still output because there's too great of a chance
13533 // of breaking existing assumptions otherwise.
13534 if (doc.type === "line" && !doc.hard) {
13535 return doc.soft ? "" : " ";
13536 } else if (doc.type === "if-break") {
13537 return doc.flatContents || "";
13543 function removeLines(doc) {
13544 return mapDoc(doc, removeLinesFn);
13547 function stripTrailingHardline(doc) {
13548 // HACK remove ending hardline, original PR: #1984
13549 if (doc.type === "concat" && doc.parts.length !== 0) {
13550 const lastPart = doc.parts[doc.parts.length - 1];
13552 if (lastPart.type === "concat") {
13553 if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
13556 parts: doc.parts.slice(0, -1)
13562 parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
13579 stripTrailingHardline
13582 function flattenDoc(doc) {
13583 if (doc.type === "concat") {
13586 for (let i = 0; i < doc.parts.length; ++i) {
13587 const doc2 = doc.parts[i];
13589 if (typeof doc2 !== "string" && doc2.type === "concat") {
13590 res.push(...flattenDoc(doc2).parts);
13592 const flattened = flattenDoc(doc2);
13594 if (flattened !== "") {
13595 res.push(flattened);
13600 return Object.assign({}, doc, {
13603 } else if (doc.type === "if-break") {
13604 return Object.assign({}, doc, {
13605 breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
13606 flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
13608 } else if (doc.type === "group") {
13609 return Object.assign({}, doc, {
13610 contents: flattenDoc(doc.contents),
13611 expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
13613 } else if (doc.contents) {
13614 return Object.assign({}, doc, {
13615 contents: flattenDoc(doc.contents)
13622 function printDoc(doc) {
13623 if (typeof doc === "string") {
13624 return JSON.stringify(doc);
13627 if (doc.type === "line") {
13629 return "literalline";
13643 if (doc.type === "break-parent") {
13644 return "breakParent";
13647 if (doc.type === "trim") {
13651 if (doc.type === "concat") {
13652 return "[" + doc.parts.map(printDoc).join(", ") + "]";
13655 if (doc.type === "indent") {
13656 return "indent(" + printDoc(doc.contents) + ")";
13659 if (doc.type === "align") {
13660 return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")";
13663 if (doc.type === "if-break") {
13664 return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
13667 if (doc.type === "group") {
13668 if (doc.expandedStates) {
13669 return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
13672 return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
13675 if (doc.type === "fill") {
13676 return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
13679 if (doc.type === "line-suffix") {
13680 return "lineSuffix(" + printDoc(doc.contents) + ")";
13683 if (doc.type === "line-suffix-boundary") {
13684 return "lineSuffixBoundary";
13687 throw new Error("Unknown doc type " + doc.type);
13691 printDocToDebug(doc) {
13692 return printDoc(flattenDoc(doc));
13698 builders: docBuilders,
13699 printer: docPrinter,
13705 getMaxContinuousCount: getMaxContinuousCount$1,
13706 getStringWidth: getStringWidth$2,
13707 getAlignmentSize: getAlignmentSize$1,
13708 getIndentSize: getIndentSize$1,
13710 skipWhitespace: skipWhitespace$1,
13711 skipSpaces: skipSpaces$1,
13712 skipNewline: skipNewline$1,
13713 skipToLineEnd: skipToLineEnd$1,
13714 skipEverythingButNewLine: skipEverythingButNewLine$1,
13715 skipInlineComment: skipInlineComment$1,
13716 skipTrailingComment: skipTrailingComment$1,
13717 hasNewline: hasNewline$1,
13718 hasNewlineInRange: hasNewlineInRange$1,
13719 hasSpaces: hasSpaces$1,
13720 isNextLineEmpty: isNextLineEmpty$1,
13721 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
13722 isPreviousLineEmpty: isPreviousLineEmpty$1,
13723 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
13724 makeString: makeString$1,
13725 addLeadingComment: addLeadingComment$1,
13726 addDanglingComment: addDanglingComment$1,
13727 addTrailingComment: addTrailingComment$1
13730 getMaxContinuousCount: getMaxContinuousCount$1,
13731 getStringWidth: getStringWidth$2,
13732 getAlignmentSize: getAlignmentSize$1,
13733 getIndentSize: getIndentSize$1,
13735 skipWhitespace: skipWhitespace$1,
13736 skipSpaces: skipSpaces$1,
13737 skipNewline: skipNewline$1,
13738 skipToLineEnd: skipToLineEnd$1,
13739 skipEverythingButNewLine: skipEverythingButNewLine$1,
13740 skipInlineComment: skipInlineComment$1,
13741 skipTrailingComment: skipTrailingComment$1,
13742 hasNewline: hasNewline$1,
13743 hasNewlineInRange: hasNewlineInRange$1,
13744 hasSpaces: hasSpaces$1,
13745 isNextLineEmpty: isNextLineEmpty$1,
13746 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
13747 isPreviousLineEmpty: isPreviousLineEmpty$1,
13748 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
13749 makeString: makeString$1,
13750 addLeadingComment: addLeadingComment$1,
13751 addDanglingComment: addDanglingComment$1,
13752 addTrailingComment: addTrailingComment$1
13758 hardline: hardline$1,
13759 breakParent: breakParent$1,
13761 lineSuffix: lineSuffix$1,
13764 } = document.builders;
13766 hasNewline: hasNewline$2,
13767 skipNewline: skipNewline$2,
13768 isPreviousLineEmpty: isPreviousLineEmpty$2
13771 addLeadingComment: addLeadingComment$2,
13772 addDanglingComment: addDanglingComment$2,
13773 addTrailingComment: addTrailingComment$2
13775 const childNodesCacheKey = Symbol("child-nodes");
13777 function getSortedChildNodes(node, options, resultArray) {
13789 if (printer.canAttachComment && printer.canAttachComment(node)) {
13790 // This reverse insertion sort almost always takes constant
13791 // time because we almost always (maybe always?) append the
13792 // nodes in order anyway.
13795 for (i = resultArray.length - 1; i >= 0; --i) {
13796 if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
13801 resultArray.splice(i + 1, 0, node);
13804 } else if (node[childNodesCacheKey]) {
13805 return node[childNodesCacheKey];
13808 const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === "object" && Object.keys(node).filter(n => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode").map(n => node[n]);
13814 if (!resultArray) {
13815 Object.defineProperty(node, childNodesCacheKey, {
13816 value: resultArray = [],
13821 childNodes.forEach(childNode => {
13822 getSortedChildNodes(childNode, options, resultArray);
13824 return resultArray;
13825 } // As efficiently as possible, decorate the comment object with
13826 // .precedingNode, .enclosingNode, and/or .followingNode properties, at
13827 // least one of which is guaranteed to be defined.
13830 function decorateComment(node, comment, options) {
13835 const childNodes = getSortedChildNodes(node, options);
13837 let followingNode; // Time to dust off the old binary search robes and wizard hat.
13840 let right = childNodes.length;
13842 while (left < right) {
13843 const middle = left + right >> 1;
13844 const child = childNodes[middle];
13846 if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) {
13847 // The comment is completely contained by this child node.
13848 comment.enclosingNode = child;
13849 decorateComment(child, comment, options);
13850 return; // Abandon the binary search at this level.
13853 if (locEnd(child) - locStart(comment) <= 0) {
13854 // This child node falls completely before the comment.
13855 // Because we will never consider this node or any nodes
13856 // before it again, this node must be the closest preceding
13857 // node we have encountered so far.
13858 precedingNode = child;
13863 if (locEnd(comment) - locStart(child) <= 0) {
13864 // This child node falls completely after the comment.
13865 // Because we will never consider this node or any nodes after
13866 // it again, this node must be the closest following node we
13867 // have encountered so far.
13868 followingNode = child;
13872 /* istanbul ignore next */
13875 throw new Error("Comment location overlaps with node location");
13876 } // We don't want comments inside of different expressions inside of the same
13877 // template literal to move to another expression.
13880 if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
13883 } = comment.enclosingNode;
13884 const commentIndex = findExpressionIndexForComment(quasis, comment, options);
13886 if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
13887 precedingNode = null;
13890 if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
13891 followingNode = null;
13895 if (precedingNode) {
13896 comment.precedingNode = precedingNode;
13899 if (followingNode) {
13900 comment.followingNode = followingNode;
13904 function attach(comments, ast, text, options) {
13905 if (!Array.isArray(comments)) {
13909 const tiesToBreak = [];
13914 comments.forEach((comment, i) => {
13915 if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
13916 if (locStart(comment) - locStart(ast) <= 0) {
13917 addLeadingComment$2(ast, comment);
13921 if (locEnd(comment) - locEnd(ast) >= 0) {
13922 addTrailingComment$2(ast, comment);
13927 decorateComment(ast, comment, options);
13933 const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false;
13934 const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false;
13935 const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false;
13936 const isLastComment = comments.length - 1 === i;
13938 if (hasNewline$2(text, locStart(comment), {
13941 // If a comment exists on its own line, prefer a leading comment.
13942 // We also need to check if it's the first line of the file.
13943 if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) {
13944 // Always a leading comment.
13945 addLeadingComment$2(followingNode, comment);
13946 } else if (precedingNode) {
13947 addTrailingComment$2(precedingNode, comment);
13948 } else if (enclosingNode) {
13949 addDanglingComment$2(enclosingNode, comment);
13951 // There are no nodes, let's attach it to the root of the ast
13953 /* istanbul ignore next */
13954 addDanglingComment$2(ast, comment);
13956 } else if (hasNewline$2(text, locEnd(comment))) {
13957 if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) {
13958 // There is content before this comment on the same line, but
13959 // none after it, so prefer a trailing comment of the previous node.
13960 addTrailingComment$2(precedingNode, comment);
13961 } else if (followingNode) {
13962 addLeadingComment$2(followingNode, comment);
13963 } else if (enclosingNode) {
13964 addDanglingComment$2(enclosingNode, comment);
13966 // There are no nodes, let's attach it to the root of the ast
13968 /* istanbul ignore next */
13969 addDanglingComment$2(ast, comment);
13972 if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) {
13973 // Otherwise, text exists both before and after the comment on
13974 // the same line. If there is both a preceding and following
13975 // node, use a tie-breaking algorithm to determine if it should
13976 // be attached to the next or previous node. In the last case,
13977 // simply attach the right node;
13978 const tieCount = tiesToBreak.length;
13980 if (tieCount > 0) {
13981 const lastTie = tiesToBreak[tieCount - 1];
13983 if (lastTie.followingNode !== comment.followingNode) {
13984 breakTies(tiesToBreak, text, options);
13988 tiesToBreak.push(comment);
13989 } else if (precedingNode) {
13990 addTrailingComment$2(precedingNode, comment);
13991 } else if (followingNode) {
13992 addLeadingComment$2(followingNode, comment);
13993 } else if (enclosingNode) {
13994 addDanglingComment$2(enclosingNode, comment);
13996 // There are no nodes, let's attach it to the root of the ast
13998 /* istanbul ignore next */
13999 addDanglingComment$2(ast, comment);
14003 breakTies(tiesToBreak, text, options);
14004 comments.forEach(comment => {
14005 // These node references were useful for breaking ties, but we
14006 // don't need them anymore, and they create cycles in the AST that
14007 // may lead to infinite recursion if we don't delete them here.
14008 delete comment.precedingNode;
14009 delete comment.enclosingNode;
14010 delete comment.followingNode;
14014 function breakTies(tiesToBreak, text, options) {
14015 const tieCount = tiesToBreak.length;
14017 if (tieCount === 0) {
14025 } = tiesToBreak[0];
14026 const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/;
14027 let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
14028 // between the tied comments. In order to qualify as leading, a
14029 // comment must be separated from followingNode by an unbroken series of
14030 // gaps (or other comments). Gaps should only contain whitespace or open
14033 let indexOfFirstLeadingComment;
14035 for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
14036 const comment = tiesToBreak[indexOfFirstLeadingComment - 1];
14037 assert$1.strictEqual(comment.precedingNode, precedingNode);
14038 assert$1.strictEqual(comment.followingNode, followingNode);
14039 const gap = text.slice(options.locEnd(comment), gapEndPos);
14041 if (gapRegExp.test(gap)) {
14042 gapEndPos = options.locStart(comment);
14044 // The gap string contained something other than whitespace or open
14050 tiesToBreak.forEach((comment, i) => {
14051 if (i < indexOfFirstLeadingComment) {
14052 addTrailingComment$2(precedingNode, comment);
14054 addLeadingComment$2(followingNode, comment);
14057 tiesToBreak.length = 0;
14060 function printComment(commentPath, options) {
14061 const comment = commentPath.getValue();
14062 comment.printed = true;
14063 return options.printer.printComment(commentPath, options);
14066 function findExpressionIndexForComment(quasis, comment, options) {
14067 const startPos = options.locStart(comment) - 1;
14069 for (let i = 1; i < quasis.length; ++i) {
14070 if (startPos < getQuasiRange(quasis[i]).start) {
14073 } // We haven't found it, it probably means that some of the locations are off.
14074 // Let's just return the first one.
14076 /* istanbul ignore next */
14082 function getQuasiRange(expr) {
14083 if (expr.start !== undefined) {
14093 start: expr.range[0],
14098 function printLeadingComment(commentPath, print, options) {
14099 const comment = commentPath.getValue();
14100 const contents = printComment(commentPath, options);
14106 const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
14107 // same line or not.
14110 const lineBreak = hasNewline$2(options.originalText, options.locEnd(comment)) ? hasNewline$2(options.originalText, options.locStart(comment), {
14112 }) ? hardline$1 : line$1 : " ";
14113 return concat$2([contents, lineBreak]);
14116 return concat$2([contents, hardline$1]);
14119 function printTrailingComment(commentPath, print, options) {
14120 const comment = commentPath.getValue();
14121 const contents = printComment(commentPath, options);
14127 const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break
14128 // when the parentParentNode is a ClassDeclaration/-Expression
14129 // And the parentNode is in the superClass property
14131 const parentNode = commentPath.getNode(1);
14132 const parentParentNode = commentPath.getNode(2);
14133 const isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode;
14135 if (hasNewline$2(options.originalText, options.locStart(comment), {
14138 // This allows comments at the end of nested structures:
14144 // Those kinds of comments are almost always leading comments, but
14145 // here it doesn't go "outside" the block and turns it into a
14146 // trailing comment for `2`. We can simulate the above by checking
14147 // if this a comment on its own line; normal trailing comments are
14148 // always at the end of another expression.
14149 const isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart);
14150 return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents]));
14151 } else if (isBlock || isParentSuperClass) {
14152 // Trailing block comments never need a newline
14153 return concat$2([" ", contents]);
14156 return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]);
14159 function printDanglingComments(path, options, sameIndent, filter) {
14161 const node = path.getValue();
14163 if (!node || !node.comments) {
14167 path.each(commentPath => {
14168 const comment = commentPath.getValue();
14170 if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
14171 parts.push(printComment(commentPath, options));
14175 if (parts.length === 0) {
14180 return join$1(hardline$1, parts);
14183 return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)]));
14186 function prependCursorPlaceholder(path, options, printed) {
14187 if (path.getNode() === options.cursorNode && path.getValue()) {
14188 return concat$2([cursor$2, printed, cursor$2]);
14194 function printComments(path, print, options, needsSemi) {
14195 const value = path.getValue();
14196 const printed = print(path);
14197 const comments = value && value.comments;
14199 if (!comments || comments.length === 0) {
14200 return prependCursorPlaceholder(path, options, printed);
14203 const leadingParts = [];
14204 const trailingParts = [needsSemi ? ";" : "", printed];
14205 path.each(commentPath => {
14206 const comment = commentPath.getValue();
14213 const contents = printLeadingComment(commentPath, print, options);
14219 leadingParts.push(contents);
14220 const text = options.originalText;
14221 const index = skipNewline$2(text, options.locEnd(comment));
14223 if (index !== false && hasNewline$2(text, index)) {
14224 leadingParts.push(hardline$1);
14226 } else if (trailing) {
14227 trailingParts.push(printTrailingComment(commentPath, print, options));
14230 return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts)));
14236 printDanglingComments,
14237 getSortedChildNodes
14240 function getNodeHelper(path, count) {
14241 const stackIndex = getNodeStackIndexHelper(path.stack, count);
14242 return stackIndex === -1 ? null : path.stack[stackIndex];
14245 function getNodeStackIndexHelper(stack, count) {
14246 for (let i = stack.length - 1; i >= 0; i -= 2) {
14247 const value = stack[i];
14249 if (value && !Array.isArray(value) && --count < 0) {
14258 constructor(value) {
14259 this.stack = [value];
14260 } // The name of the current property is always the penultimate element of
14261 // this.stack, and always a String.
14273 return stack[length - 2];
14274 } // Since the name is always a string, null is a safe sentinel value to
14275 // return if we do not know the name of the (root) value.
14277 /* istanbul ignore next */
14281 } // The value of the current property is always the final element of
14286 return getLast(this.stack);
14289 getNode(count = 0) {
14290 return getNodeHelper(this, count);
14293 getParentNode(count = 0) {
14294 return getNodeHelper(this, count + 1);
14295 } // Temporarily push properties named by string arguments given after the
14296 // callback function onto this.stack, then call the callback with a
14297 // reference to this (modified) FastPath object. Note that the stack will
14298 // be restored to its original state after the callback is finished, so it
14299 // is probably a mistake to retain a reference to the path.
14302 call(callback, ...names) {
14309 let value = getLast(stack);
14311 for (const name of names) {
14312 value = value[name];
14313 stack.push(name, value);
14316 const result = callback(this);
14317 stack.length = length;
14321 callParent(callback, count = 0) {
14322 const stackIndex = getNodeStackIndexHelper(this.stack, count + 1);
14323 const parentValues = this.stack.splice(stackIndex + 1);
14324 const result = callback(this);
14325 this.stack.push(...parentValues);
14327 } // Similar to FastPath.prototype.call, except that the value obtained by
14328 // accessing this.getValue()[name1][name2]... should be array-like. The
14329 // callback will be called with a reference to this path object for each
14330 // element of the array.
14333 each(callback, ...names) {
14340 let value = getLast(stack);
14342 for (const name of names) {
14343 value = value[name];
14344 stack.push(name, value);
14347 for (let i = 0; i < value.length; ++i) {
14349 stack.push(i, value[i]); // If the callback needs to know the value of i, call
14350 // path.getName(), assuming path is the parameter name.
14357 stack.length = length;
14358 } // Similar to FastPath.prototype.each, except that the results of the
14359 // callback function invocations are stored in an array and returned at
14360 // the end of the iteration.
14363 map(callback, ...names) {
14370 let value = getLast(stack);
14372 for (const name of names) {
14373 value = value[name];
14374 stack.push(name, value);
14377 const result = new Array(value.length);
14379 for (let i = 0; i < value.length; ++i) {
14381 stack.push(i, value[i]);
14382 result[i] = callback(this, i);
14387 stack.length = length;
14392 * | ((node: any, name: string | null, number: number | null) => boolean)
14398 match(...predicates) {
14399 let stackPointer = this.stack.length - 1;
14401 let node = this.stack[stackPointer--];
14403 for (const predicate of predicates) {
14404 if (node === undefined) {
14406 } // skip index/array
14411 if (typeof name === "number") {
14413 name = this.stack[stackPointer--];
14414 node = this.stack[stackPointer--];
14417 if (predicate && !predicate(node, name, number)) {
14421 name = this.stack[stackPointer--];
14422 node = this.stack[stackPointer--];
14430 var fastPath = FastPath;
14433 normalize: normalize$2
14436 function printSubtree(path, print, options, printAstToDoc) {
14437 if (options.printer.embed) {
14438 return options.printer.embed(path, print, (text, partialNextOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc), options);
14442 function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) {
14443 const nextOptions = normalize$2(Object.assign({}, parentOptions, {}, partialNextOptions, {
14444 parentParser: parentOptions.parser,
14445 embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"),
14450 const result = parser.parse(text, nextOptions);
14454 text = result.text;
14455 const astComments = ast.comments;
14456 delete ast.comments;
14457 comments.attach(astComments, ast, text, nextOptions);
14458 return printAstToDoc(ast, nextOptions);
14461 var multiparser = {
14465 const doc = document;
14466 const docBuilders$1 = doc.builders;
14469 hardline: hardline$2,
14470 addAlignmentToDoc: addAlignmentToDoc$1
14472 const docUtils$1 = doc.utils;
14474 * Takes an abstract syntax tree (AST) and recursively converts it to a
14475 * document (series of printing primitives).
14477 * This is done by descending down the AST recursively. The recursion
14478 * involves two functions that call each other:
14480 * 1. printGenerically(), which is defined as an inner function here.
14481 * It basically takes care of node caching.
14482 * 2. callPluginPrintFunction(), which checks for some options, and
14483 * ultimately calls the print() function provided by the plugin.
14485 * The plugin function will call printGenerically() again for child nodes
14486 * of the current node, which will do its housekeeping, then call the
14487 * plugin function again, and so on.
14489 * All the while, these functions pass a "path" variable around, which
14490 * is a stack-like data structure (FastPath) that maintains the current
14491 * state of the recursion. It is called "path", because it represents
14492 * the path to the current node through the Abstract Syntax Tree.
14495 function printAstToDoc(ast, options, alignmentSize = 0) {
14500 if (printer.preprocess) {
14501 ast = printer.preprocess(ast, options);
14504 const cache = new Map();
14506 function printGenerically(path, args) {
14507 const node = path.getValue();
14508 const shouldCache = node && typeof node === "object" && args === undefined;
14510 if (shouldCache && cache.has(node)) {
14511 return cache.get(node);
14512 } // We let JSXElement print its comments itself because it adds () around
14513 // UnionTypeAnnotation has to align the child without the comments
14518 if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) {
14519 res = callPluginPrintFunction(path, options, printGenerically, args);
14521 // printComments will call the plugin print function and check for
14522 // comments to print
14523 res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi);
14527 cache.set(node, res);
14533 let doc = printGenerically(new fastPath(ast));
14535 if (alignmentSize > 0) {
14536 // Add a hardline to make the indents take effect
14537 // It should be removed in index.js format()
14538 doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth);
14541 docUtils$1.propagateBreaks(doc);
14545 function callPluginPrintFunction(path, options, printPath, args) {
14546 assert$1.ok(path instanceof fastPath);
14547 const node = path.getValue();
14550 } = options; // Escape hatch
14552 if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
14553 return options.originalText.slice(options.locStart(node), options.locEnd(node));
14558 // Potentially switch to a different parser
14559 const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc);
14565 /* istanbul ignore if */
14566 if (process.env.PRETTIER_DEBUG) {
14568 } // Continue with current parser
14573 return printer.print(path, options, printPath, args);
14576 var astToDoc = printAstToDoc;
14578 function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
14579 let resultStartNode = startNodeAndParents.node;
14580 let resultEndNode = endNodeAndParents.node;
14582 if (resultStartNode === resultEndNode) {
14584 startNode: resultStartNode,
14585 endNode: resultEndNode
14589 for (const endParent of endNodeAndParents.parentNodes) {
14590 if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
14591 resultEndNode = endParent;
14597 for (const startParent of startNodeAndParents.parentNodes) {
14598 if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
14599 resultStartNode = startParent;
14606 startNode: resultStartNode,
14607 endNode: resultEndNode
14611 function findNodeAtOffset(node, offset, options, predicate, parentNodes) {
14612 predicate = predicate || (() => true);
14614 parentNodes = parentNodes || [];
14615 const start = options.locStart(node, options.locStart);
14616 const end = options.locEnd(node, options.locEnd);
14618 if (start <= offset && offset <= end) {
14619 for (const childNode of comments.getSortedChildNodes(node, options)) {
14620 const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes));
14623 return childResult;
14627 if (predicate(node)) {
14634 } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
14637 function isSourceElement(opts, node) {
14638 if (node == null) {
14640 } // JS and JS like to avoid repetitions
14643 const jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015
14644 "ImportDeclaration", // Module
14645 "ExportDefaultDeclaration", // Module
14646 "ExportNamedDeclaration", // Module
14647 "ExportAllDeclaration", // Module
14648 "TypeAlias", // Flow
14649 "InterfaceDeclaration", // Flow, TypeScript
14650 "TypeAliasDeclaration", // TypeScript
14651 "ExportAssignment", // TypeScript
14652 "ExportDeclaration" // TypeScript
14654 const jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"];
14655 const graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"];
14657 switch (opts.parser) {
14663 return jsSourceElements.includes(node.type);
14666 return jsonSourceElements.includes(node.type);
14669 return graphqlSourceElements.includes(node.kind);
14672 return node.tag !== "root";
14678 function calculateRange(text, opts, ast) {
14679 // Contract the range so that it has non-whitespace characters at its endpoints.
14680 // This ensures we can format a range that doesn't end on a node.
14681 const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
14682 const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
14683 let endNonWhitespace;
14685 for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
14686 if (text[endNonWhitespace - 1].match(/\S/)) {
14691 const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node));
14692 const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node));
14694 if (!startNodeAndParents || !endNodeAndParents) {
14701 const siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
14705 } = siblingAncestors;
14706 const rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart));
14707 const rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd));
14719 const normalizeOptions$1 = options$1.normalize;
14721 guessEndOfLine: guessEndOfLine$1,
14722 convertEndOfLineToChars: convertEndOfLineToChars$2
14726 printDocToString: printDocToString$1
14732 const BOM = "\uFEFF";
14733 const CURSOR = Symbol("cursor");
14734 const PLACEHOLDERS = {
14735 cursorOffset: "<<<PRETTIER_CURSOR>>>",
14736 rangeStart: "<<<PRETTIER_RANGE_START>>>",
14737 rangeEnd: "<<<PRETTIER_RANGE_END>>>"
14740 function ensureAllCommentsPrinted(astComments) {
14741 if (!astComments) {
14745 for (let i = 0; i < astComments.length; ++i) {
14746 if (util$1.isNodeIgnoreComment(astComments[i])) {
14747 // If there's a prettier-ignore, we're not printing that sub-tree so we
14748 // don't know if the comments was printed or not.
14753 astComments.forEach(comment => {
14754 if (!comment.printed) {
14755 throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
14758 delete comment.printed;
14762 function attachComments(text, ast, opts) {
14763 const astComments = ast.comments;
14766 delete ast.comments;
14767 comments.attach(astComments, ast, text, opts);
14771 opts.originalText = opts.parser === "yaml" ? text : text.trimEnd();
14772 return astComments;
14775 function coreFormat(text, opts, addAlignmentSize) {
14776 if (!text || !text.trim().length) {
14783 addAlignmentSize = addAlignmentSize || 0;
14784 const parsed = parser.parse(text, opts);
14788 text = parsed.text;
14790 if (opts.cursorOffset >= 0) {
14791 const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
14793 if (nodeResult && nodeResult.node) {
14794 opts.cursorNode = nodeResult.node;
14798 const astComments = attachComments(text, ast, opts);
14799 const doc = astToDoc(ast, opts, addAlignmentSize);
14800 const result = printDocToString$1(doc, opts);
14801 ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
14803 if (addAlignmentSize > 0) {
14804 const trimmed = result.formatted.trim();
14806 if (result.cursorNodeStart !== undefined) {
14807 result.cursorNodeStart -= result.formatted.indexOf(trimmed);
14810 result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine);
14813 if (opts.cursorOffset >= 0) {
14814 let oldCursorNodeStart;
14815 let oldCursorNodeText;
14816 let cursorOffsetRelativeToOldCursorNode;
14817 let newCursorNodeStart;
14818 let newCursorNodeText;
14820 if (opts.cursorNode && result.cursorNodeText) {
14821 oldCursorNodeStart = opts.locStart(opts.cursorNode);
14822 oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
14823 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
14824 newCursorNodeStart = result.cursorNodeStart;
14825 newCursorNodeText = result.cursorNodeText;
14827 oldCursorNodeStart = 0;
14828 oldCursorNodeText = text;
14829 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
14830 newCursorNodeStart = 0;
14831 newCursorNodeText = result.formatted;
14834 if (oldCursorNodeText === newCursorNodeText) {
14836 formatted: result.formatted,
14837 cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
14839 } // diff old and new cursor node texts, with a special cursor
14840 // symbol inserted to find out where it moves to
14843 const oldCursorNodeCharArray = oldCursorNodeText.split("");
14844 oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
14845 const newCursorNodeCharArray = newCursorNodeText.split("");
14846 const cursorNodeDiff = index_es6.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
14847 let cursorOffset = newCursorNodeStart;
14849 for (const entry of cursorNodeDiff) {
14850 if (entry.removed) {
14851 if (entry.value.includes(CURSOR)) {
14855 cursorOffset += entry.count;
14860 formatted: result.formatted,
14866 formatted: result.formatted
14870 function formatRange(text, opts) {
14871 const parsed = parser.parse(text, opts);
14875 text = parsed.text;
14876 const range = rangeUtil.calculateRange(text, opts, ast);
14881 const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
14882 // This is so we can detect indentation correctly and restore it.
14883 // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
14885 const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
14886 const indentString = text.slice(rangeStart2, rangeStart);
14887 const alignmentSize = util$1.getAlignmentSize(indentString, opts.tabWidth);
14888 const rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
14890 rangeEnd: Infinity,
14891 // track the cursor offset only if it's within our range
14892 cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1
14893 }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
14894 // we need to remove the newline that was inserted by the `format` call.
14896 const rangeTrimmed = rangeResult.formatted.trimEnd();
14897 const rangeLeft = text.slice(0, rangeStart);
14898 const rangeRight = text.slice(rangeEnd);
14903 if (opts.cursorOffset >= rangeEnd) {
14904 // handle the case where the cursor was past the end of the range
14905 cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length);
14906 } else if (rangeResult.cursorOffset !== undefined) {
14907 // handle the case where the cursor was in the range
14908 cursorOffset = rangeResult.cursorOffset + rangeStart;
14909 } // keep the cursor as it was if it was before the start of the range
14914 if (opts.endOfLine === "lf") {
14915 formatted = rangeLeft + rangeTrimmed + rangeRight;
14917 const eol = convertEndOfLineToChars$2(opts.endOfLine);
14919 if (cursorOffset >= 0) {
14920 const parts = [rangeLeft, rangeTrimmed, rangeRight];
14922 let partOffset = cursorOffset;
14924 while (partIndex < parts.length) {
14925 const part = parts[partIndex];
14927 if (partOffset < part.length) {
14928 parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset);
14933 partOffset -= part.length;
14936 const [newRangeLeft, newRangeTrimmed, newRangeRight] = parts;
14937 formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, (_, index) => {
14938 cursorOffset = index;
14942 formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol);
14952 function format(text, opts) {
14953 const selectedParser = parser.resolveParser(opts);
14954 const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
14956 if (opts.requirePragma && !hasPragma) {
14962 if (opts.endOfLine === "auto") {
14963 opts.endOfLine = guessEndOfLine$1(text);
14966 const hasCursor = opts.cursorOffset >= 0;
14967 const hasRangeStart = opts.rangeStart > 0;
14968 const hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing
14970 if (text.includes("\r")) {
14971 const offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort((aKey, bKey) => opts[aKey] - opts[bKey]);
14973 for (let i = offsetKeys.length - 1; i >= 0; i--) {
14974 const key = offsetKeys[i];
14975 text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]);
14978 text = text.replace(/\r\n?/g, "\n");
14980 for (let i = 0; i < offsetKeys.length; i++) {
14981 const key = offsetKeys[i];
14982 text = text.replace(PLACEHOLDERS[key], (_, index) => {
14989 const hasUnicodeBOM = text.charAt(0) === BOM;
14991 if (hasUnicodeBOM) {
14992 text = text.slice(1);
14995 opts.cursorOffset++;
14998 if (hasRangeStart) {
15008 opts.cursorOffset = -1;
15011 if (opts.rangeStart < 0) {
15012 opts.rangeStart = 0;
15015 if (opts.rangeEnd > text.length) {
15016 opts.rangeEnd = text.length;
15019 const result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts);
15021 if (hasUnicodeBOM) {
15022 result.formatted = BOM + result.formatted;
15025 result.cursorOffset++;
15033 formatWithCursor(text, opts) {
15034 opts = normalizeOptions$1(opts);
15035 return format(text, opts);
15038 parse(text, opts, massage) {
15039 opts = normalizeOptions$1(opts);
15041 if (text.includes("\r")) {
15042 text = text.replace(/\r\n?/g, "\n");
15045 const parsed = parser.parse(text, opts);
15048 parsed.ast = massageAst(parsed.ast, opts);
15054 formatAST(ast, opts) {
15055 opts = normalizeOptions$1(opts);
15056 const doc = astToDoc(ast, opts);
15057 return printDocToString$1(doc, opts);
15060 // Doesn't handle shebang for now
15061 formatDoc(doc, opts) {
15062 const debug = printDocToDebug(doc);
15063 opts = normalizeOptions$1(Object.assign({}, opts, {
15066 return format(debug, opts).formatted;
15069 printToDoc(text, opts) {
15070 opts = normalizeOptions$1(opts);
15071 const parsed = parser.parse(text, opts);
15075 text = parsed.text;
15076 attachComments(text, ast, opts);
15077 return astToDoc(ast, opts);
15080 printDocToString(doc, opts) {
15081 return printDocToString$1(doc, normalizeOptions$1(opts));
15086 // A simple implementation of make-array
15087 function make_array(subject) {
15088 return Array.isArray(subject) ? subject : [subject];
15091 const REGEX_BLANK_LINE = /^\s+$/;
15092 const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
15093 const REGEX_LEADING_EXCAPED_HASH = /^\\#/;
15095 const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
15096 /* istanbul ignore next */
15099 const define = (object, key, value) => Object.defineProperty(object, key, {
15103 const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
15104 // The cases are complicated, see test cases for details
15106 const sanitizeRange = range => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
15107 // fatal for JavaScript regular expression, so eliminate it.
15108 : ''); // > If the pattern ends with a slash,
15109 // > it is removed for the purpose of the following description,
15110 // > but it would only find a match with a directory.
15111 // > In other words, foo/ will match a directory foo and paths underneath it,
15112 // > but will not match a regular file or a symbolic link foo
15113 // > (this is consistent with the way how pathspec works in general in Git).
15114 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
15115 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
15116 // you could use option `mark: true` with `glob`
15117 // '`foo/`' should not continue with the '`..`'
15120 const DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
15124 /\\?\s+$/, match => match.indexOf('\\') === 0 ? ' ' : ''], // replace (\ ) with ' '
15125 [/\\\s/g, () => ' '], // Escape metacharacters
15126 // which is written down by users but means special for regular expressions.
15127 // > There are 12 characters with special meanings:
15128 // > - the backslash \,
15129 // > - the caret ^,
15130 // > - the dollar sign $,
15131 // > - the period or dot .,
15132 // > - the vertical bar or pipe symbol |,
15133 // > - the question mark ?,
15134 // > - the asterisk or star *,
15135 // > - the plus sign +,
15136 // > - the opening parenthesis (,
15137 // > - the closing parenthesis ),
15138 // > - and the opening square bracket [,
15139 // > - the opening curly brace {,
15140 // > These special characters are often called "metacharacters".
15141 [/[\\^$.|*+(){]/g, match => `\\${match}`], [// > [abc] matches any character inside the brackets
15142 // > (in this case a, b, or c);
15143 /\[([^\]/]*)($|\])/g, (match, p1, p2) => p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`], [// > a question mark (?) matches a single character
15144 /(?!\\)\?/g, () => '[^/]'], // leading slash
15145 [// > A leading slash matches the beginning of the pathname.
15146 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
15147 // A leading slash matches the beginning of the pathname
15148 /^\//, () => '^'], // replace special metacharacter slash after the leading slash
15149 [/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
15150 // > For example, "**/foo" matches file or directory "foo" anywhere,
15151 // > the same as pattern "foo".
15152 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
15153 // > under directory "foo".
15154 // Notice that the '*'s have been replaced as '\\*'
15155 /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
15156 () => '^(?:.*\\/)?']];
15157 const DEFAULT_REPLACER_SUFFIX = [// starting
15158 [// there will be no leading '/'
15159 // (which has been replaced by section "leading slash")
15160 // If starts with '**', adding a '^' to the regular expression also works
15161 /^(?=[^^])/, function startingReplacer() {
15162 return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /,
15163 // > Git treats it as a shell glob pattern
15164 // Actually, if there is only a trailing slash,
15165 // git also treats it as a shell glob pattern
15166 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
15167 // > consumption by fnmatch(3)
15169 }], // two globstars
15170 [// Use lookahead assertions so that we could match more than one `'/**'`
15171 /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
15172 // should not use '*', or it will be replaced by the next replacer
15173 // Check if it is not the last `'/**'`
15174 (match, index, str) => index + 6 < str.length // case: /**/
15175 // > A slash followed by two consecutive asterisks then a slash matches
15176 // > zero or more directories.
15177 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
15179 ? '(?:\\/[^\\/]+)*' // case: /**
15180 // > A trailing `"/**"` matches everything inside.
15181 // #21: everything inside but it should not include the current folder
15182 : '\\/.+'], // intermediate wildcards
15183 [// Never replace escaped '*'
15184 // ignore rule '\*' will match the path '*'
15186 // 'abc.*' -> skip this rule
15187 /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
15188 // '*.js' doesn't match 'abc'
15189 (match, p1) => `${p1}[^\\/]*`], // trailing wildcard
15190 [/(\^|\\\/)?\\\*$/, (match, p1) => {
15191 const prefix = p1 // '\^':
15192 // '/*' does not match ''
15193 // '/*' does not match everything
15195 // 'abc/*' does not match 'abc/'
15196 ? `${p1}[^/]+` // 'a*' matches 'a'
15197 // 'a*' matches 'aa'
15199 return `${prefix}(?=$|\\/$)`;
15201 /\\\\\\/g, () => '\\']];
15202 const POSITIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // 'f'
15214 [// 'js' will not match 'js.'
15215 // 'ab' will not match 'abc'
15216 /(?:[^*/])$/, // 'js*' will not match 'a.js'
15217 // 'js/' will not match 'a.js'
15218 // 'js' will match 'a.js' and 'a.js/'
15219 match => `${match}(?=$|\\/)`], ...DEFAULT_REPLACER_SUFFIX];
15220 const NEGATIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // #24, #38
15221 // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
15222 // A negative pattern without a trailing wildcard should not
15223 // re-include the things inside that directory.
15225 // ['node_modules/*', '!node_modules']
15226 // should ignore `node_modules/a.js`
15227 [/(?:[^*])$/, match => `${match}(?=$|\\/$)`], ...DEFAULT_REPLACER_SUFFIX]; // A simple cache, because an ignore rule only has only one certain meaning
15229 const cache = Object.create(null); // @param {pattern}
15231 const make_regex = (pattern, negative, ignorecase) => {
15232 const r = cache[pattern];
15238 const replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
15239 const source = replacers.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
15240 return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
15241 }; // > A blank line matches no files, so it can serve as a separator for readability.
15244 const checkPattern = pattern => pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
15245 && pattern.indexOf('#') !== 0;
15247 const createRule = (pattern, ignorecase) => {
15248 const origin = pattern;
15249 let negative = false; // > An optional prefix "!" which negates the pattern;
15251 if (pattern.indexOf('!') === 0) {
15253 pattern = pattern.substr(1);
15256 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
15257 // > begin with a literal "!", for example, `"\!important!.txt"`.
15258 .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
15259 // > begin with a hash.
15260 .replace(REGEX_LEADING_EXCAPED_HASH, '#');
15261 const regex = make_regex(pattern, negative, ignorecase);
15275 this._ignorecase = ignorecase;
15276 define(this, KEY_IGNORE, true);
15282 this._cache = Object.create(null);
15283 } // @param {Array.<string>|string|Ignore} pattern
15287 this._added = false;
15289 if (typeof pattern === 'string') {
15290 pattern = pattern.split(/\r?\n/g);
15293 make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
15294 // making the behavior changed.
15304 addPattern(pattern) {
15305 return this.add(pattern);
15308 _addPattern(pattern) {
15310 if (pattern && pattern[KEY_IGNORE]) {
15311 this._rules = this._rules.concat(pattern._rules);
15312 this._added = true;
15316 if (checkPattern(pattern)) {
15317 const rule = createRule(pattern, this._ignorecase);
15318 this._added = true;
15320 this._rules.push(rule);
15325 return make_array(paths).filter(path => this._filter(path));
15329 return path => this._filter(path);
15333 return !this._filter(path);
15334 } // @returns `Boolean` true if the `path` is NOT ignored
15337 _filter(path, slices) {
15342 if (path in this._cache) {
15343 return this._cache[path];
15348 // ['path', 'to', 'a.js']
15349 slices = path.split(SLASH);
15353 return this._cache[path] = slices.length // > It is not possible to re-include a file if a parent directory of
15354 // > that file is excluded.
15355 // If the path contains a parent directory, check the parent first
15356 ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) // Or only test the path
15357 : this._test(path);
15358 } // @returns {Boolean} true if a file is NOT ignored
15362 // Explicitly define variable type by setting matched to `0`
15365 this._rules.forEach(rule => {
15366 // if matched = true, then we only test negative rules
15367 // if matched = false, then we test non-negative rules
15368 if (!(matched ^ rule.negative)) {
15369 matched = rule.negative ^ rule.regex.test(path);
15377 // --------------------------------------------------------------
15379 /* istanbul ignore if */
15382 if ( // Detect `process` so that it can run in browsers.
15383 typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
15384 const filter = IgnoreBase.prototype._filter;
15385 /* eslint no-control-regex: "off" */
15387 const make_posix = str => /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/');
15389 IgnoreBase.prototype._filter = function filterWin32(path, slices) {
15390 path = make_posix(path);
15391 return filter.call(this, path, slices);
15395 var ignore = options => new IgnoreBase(options);
15398 * @param {string} filename
15399 * @returns {Promise<null | string>}
15403 function getFileContentOrNull(filename) {
15404 return new Promise((resolve, reject) => {
15405 fs$3.readFile(filename, "utf8", (error, data) => {
15406 if (error && error.code !== "ENOENT") {
15407 reject(createError(filename, error));
15409 resolve(error ? null : data);
15415 * @param {string} filename
15416 * @returns {null | string}
15420 getFileContentOrNull.sync = function (filename) {
15422 return fs$3.readFileSync(filename, "utf8");
15424 if (error && error.code === "ENOENT") {
15428 throw createError(filename, error);
15432 function createError(filename, error) {
15433 return new Error(`Unable to read ${filename}: ${error.message}`);
15436 var getFileContentOrNull_1 = getFileContentOrNull;
15439 * @param {undefined | string} ignorePath
15440 * @param {undefined | boolean} withNodeModules
15444 async function createIgnorer(ignorePath, withNodeModules) {
15445 const ignoreContent = ignorePath ? await getFileContentOrNull_1(path$2.resolve(ignorePath)) : null;
15446 return _createIgnorer(ignoreContent, withNodeModules);
15449 * @param {undefined | string} ignorePath
15450 * @param {undefined | boolean} withNodeModules
15454 createIgnorer.sync = function (ignorePath, withNodeModules) {
15455 const ignoreContent = !ignorePath ? null : getFileContentOrNull_1.sync(path$2.resolve(ignorePath));
15456 return _createIgnorer(ignoreContent, withNodeModules);
15459 * @param {null | string} ignoreContent
15460 * @param {undefined | boolean} withNodeModules
15464 function _createIgnorer(ignoreContent, withNodeModules) {
15465 const ignorer = ignore().add(ignoreContent || "");
15467 if (!withNodeModules) {
15468 ignorer.add("node_modules");
15474 var createIgnorer_1 = createIgnorer;
15476 var thirdParty = require("./third-party");
15478 var concatMap = function (xs, fn) {
15481 for (var i = 0; i < xs.length; i++) {
15482 var x = fn(xs[i], i);
15483 if (isArray(x)) res.push.apply(res, x);else res.push(x);
15489 var isArray = Array.isArray || function (xs) {
15490 return Object.prototype.toString.call(xs) === '[object Array]';
15493 var balancedMatch = balanced;
15495 function balanced(a, b, str) {
15496 if (a instanceof RegExp) a = maybeMatch(a, str);
15497 if (b instanceof RegExp) b = maybeMatch(b, str);
15498 var r = range(a, b, str);
15502 pre: str.slice(0, r[0]),
15503 body: str.slice(r[0] + a.length, r[1]),
15504 post: str.slice(r[1] + b.length)
15508 function maybeMatch(reg, str) {
15509 var m = str.match(reg);
15510 return m ? m[0] : null;
15513 balanced.range = range;
15515 function range(a, b, str) {
15516 var begs, beg, left, right, result;
15517 var ai = str.indexOf(a);
15518 var bi = str.indexOf(b, ai + 1);
15521 if (ai >= 0 && bi > 0) {
15525 while (i >= 0 && !result) {
15528 ai = str.indexOf(a, i + 1);
15529 } else if (begs.length == 1) {
15530 result = [begs.pop(), bi];
15539 bi = str.indexOf(b, i + 1);
15542 i = ai < bi && ai >= 0 ? ai : bi;
15546 result = [left, right];
15553 var braceExpansion = expandTop;
15554 var escSlash = '\0SLASH' + Math.random() + '\0';
15555 var escOpen = '\0OPEN' + Math.random() + '\0';
15556 var escClose = '\0CLOSE' + Math.random() + '\0';
15557 var escComma = '\0COMMA' + Math.random() + '\0';
15558 var escPeriod = '\0PERIOD' + Math.random() + '\0';
15560 function numeric$1(str) {
15561 return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
15564 function escapeBraces(str) {
15565 return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
15568 function unescapeBraces(str) {
15569 return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
15570 } // Basically just str.split(","), but handling cases
15571 // where we have nested braced sections, which should be
15572 // treated as individual members, like {a,{b,c},d}
15575 function parseCommaParts(str) {
15576 if (!str) return [''];
15578 var m = balancedMatch('{', '}', str);
15579 if (!m) return str.split(',');
15583 var p = pre.split(',');
15584 p[p.length - 1] += '{' + body + '}';
15585 var postParts = parseCommaParts(post);
15588 p[p.length - 1] += postParts.shift();
15589 p.push.apply(p, postParts);
15592 parts.push.apply(parts, p);
15596 function expandTop(str) {
15597 if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
15598 // Anything starting with {} will have the first two bytes preserved
15599 // but *only* at the top level, so {},a}b will not expand to anything,
15600 // but a{},b}c will be expanded to [a}c,abc].
15601 // One could argue that this is a bug in Bash, but since the goal of
15602 // this module is to match Bash's rules, we escape a leading {}
15604 if (str.substr(0, 2) === '{}') {
15605 str = '\\{\\}' + str.substr(2);
15608 return expand(escapeBraces(str), true).map(unescapeBraces);
15611 function embrace(str) {
15612 return '{' + str + '}';
15615 function isPadded(el) {
15616 return /^-?0\d/.test(el);
15619 function lte(i, y) {
15623 function gte$1(i, y) {
15627 function expand(str, isTop) {
15628 var expansions = [];
15629 var m = balancedMatch('{', '}', str);
15630 if (!m || /\$$/.test(m.pre)) return [str];
15631 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
15632 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
15633 var isSequence = isNumericSequence || isAlphaSequence;
15634 var isOptions = m.body.indexOf(',') >= 0;
15636 if (!isSequence && !isOptions) {
15638 if (m.post.match(/,.*\}/)) {
15639 str = m.pre + '{' + m.body + escClose + m.post;
15640 return expand(str);
15649 n = m.body.split(/\.\./);
15651 n = parseCommaParts(m.body);
15653 if (n.length === 1) {
15654 // x{{a,b}}y ==> x{a}y x{b}y
15655 n = expand(n[0], false).map(embrace);
15657 if (n.length === 1) {
15658 var post = m.post.length ? expand(m.post, false) : [''];
15659 return post.map(function (p) {
15660 return m.pre + n[0] + p;
15664 } // at this point, n is the parts, and we know it's not a comma set
15665 // with a single entry.
15666 // no need to expand pre, since it is guaranteed to be free of brace-sets
15670 var post = m.post.length ? expand(m.post, false) : [''];
15674 var x = numeric$1(n[0]);
15675 var y = numeric$1(n[1]);
15676 var width = Math.max(n[0].length, n[1].length);
15677 var incr = n.length == 3 ? Math.abs(numeric$1(n[2])) : 1;
15679 var reverse = y < x;
15686 var pad = n.some(isPadded);
15689 for (var i = x; test(i, y); i += incr) {
15692 if (isAlphaSequence) {
15693 c = String.fromCharCode(i);
15694 if (c === '\\') c = '';
15699 var need = width - c.length;
15702 var z = new Array(need + 1).join('0');
15703 if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
15711 N = concatMap(n, function (el) {
15712 return expand(el, false);
15716 for (var j = 0; j < N.length; j++) {
15717 for (var k = 0; k < post.length; k++) {
15718 var expansion = pre + N[j] + post[k];
15719 if (!isTop || isSequence || expansion) expansions.push(expansion);
15726 var minimatch_1 = minimatch;
15727 minimatch.Minimatch = Minimatch;
15736 var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
15758 }; // any single thing other than /
15759 // don't need to escape / when using new RegExp()
15761 var qmark = '[^/]'; // * => any number of characters
15763 var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
15764 // not (^ or / followed by one or two dots followed by $ or /),
15765 // followed by anything, any number of times.
15767 var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
15768 // followed by anything, any number of times.
15770 var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
15772 var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
15774 function charSet(s) {
15775 return s.split('').reduce(function (set, c) {
15779 } // normalizes slashes.
15782 var slashSplit = /\/+/;
15783 minimatch.filter = filter;
15785 function filter(pattern, options) {
15786 options = options || {};
15787 return function (p, i, list) {
15788 return minimatch(p, pattern, options);
15792 function ext(a, b) {
15796 Object.keys(b).forEach(function (k) {
15799 Object.keys(a).forEach(function (k) {
15805 minimatch.defaults = function (def) {
15806 if (!def || !Object.keys(def).length) return minimatch;
15807 var orig = minimatch;
15809 var m = function minimatch(p, pattern, options) {
15810 return orig.minimatch(p, pattern, ext(def, options));
15813 m.Minimatch = function Minimatch(pattern, options) {
15814 return new orig.Minimatch(pattern, ext(def, options));
15820 Minimatch.defaults = function (def) {
15821 if (!def || !Object.keys(def).length) return Minimatch;
15822 return minimatch.defaults(def).Minimatch;
15825 function minimatch(p, pattern, options) {
15826 if (typeof pattern !== 'string') {
15827 throw new TypeError('glob pattern string required');
15830 if (!options) options = {}; // shortcut: comments match nothing.
15832 if (!options.nocomment && pattern.charAt(0) === '#') {
15834 } // "" only matches ""
15837 if (pattern.trim() === '') return p === '';
15838 return new Minimatch(pattern, options).match(p);
15841 function Minimatch(pattern, options) {
15842 if (!(this instanceof Minimatch)) {
15843 return new Minimatch(pattern, options);
15846 if (typeof pattern !== 'string') {
15847 throw new TypeError('glob pattern string required');
15850 if (!options) options = {};
15851 pattern = pattern.trim(); // windows support: need to use /, not \
15853 if (path.sep !== '/') {
15854 pattern = pattern.split(path.sep).join('/');
15857 this.options = options;
15859 this.pattern = pattern;
15860 this.regexp = null;
15861 this.negate = false;
15862 this.comment = false;
15863 this.empty = false; // make the set of regexps etc.
15868 Minimatch.prototype.debug = function () {};
15870 Minimatch.prototype.make = make;
15873 // don't do it more than once.
15874 if (this._made) return;
15875 var pattern = this.pattern;
15876 var options = this.options; // empty patterns and comments match nothing.
15878 if (!options.nocomment && pattern.charAt(0) === '#') {
15879 this.comment = true;
15886 } // step 1: figure out negation, etc.
15889 this.parseNegate(); // step 2: expand braces
15891 var set = this.globSet = this.braceExpand();
15892 if (options.debug) this.debug = console.error;
15893 this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
15894 // matching patterns.
15895 // These will be regexps, except in the case of "**", which is
15896 // set to the GLOBSTAR object for globstar behavior,
15897 // and will not contain any / characters
15899 set = this.globParts = set.map(function (s) {
15900 return s.split(slashSplit);
15902 this.debug(this.pattern, set); // glob --> regexps
15904 set = set.map(function (s, si, set) {
15905 return s.map(this.parse, this);
15907 this.debug(this.pattern, set); // filter out everything that didn't compile properly.
15909 set = set.filter(function (s) {
15910 return s.indexOf(false) === -1;
15912 this.debug(this.pattern, set);
15916 Minimatch.prototype.parseNegate = parseNegate;
15918 function parseNegate() {
15919 var pattern = this.pattern;
15920 var negate = false;
15921 var options = this.options;
15922 var negateOffset = 0;
15923 if (options.nonegate) return;
15925 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
15930 if (negateOffset) this.pattern = pattern.substr(negateOffset);
15931 this.negate = negate;
15932 } // Brace expansion:
15933 // a{b,c}d -> abd acd
15934 // a{b,}c -> abc ac
15935 // a{0..3}d -> a0d a1d a2d a3d
15936 // a{b,c{d,e}f}g -> abg acdfg acefg
15937 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
15939 // Invalid sets are not expanded.
15940 // a{2..}b -> a{2..}b
15944 minimatch.braceExpand = function (pattern, options) {
15945 return braceExpand(pattern, options);
15948 Minimatch.prototype.braceExpand = braceExpand;
15950 function braceExpand(pattern, options) {
15952 if (this instanceof Minimatch) {
15953 options = this.options;
15959 pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
15961 if (typeof pattern === 'undefined') {
15962 throw new TypeError('undefined pattern');
15965 if (options.nobrace || !pattern.match(/\{.*\}/)) {
15966 // shortcut. no need to expand.
15970 return braceExpansion(pattern);
15971 } // parse a component of the expanded set.
15972 // At this point, no pattern may contain "/" in it
15973 // so we're going to return a 2d array, where each entry is the full
15974 // pattern, split on '/', and then turned into a regular expression.
15975 // A regexp is made at the end which joins each array with an
15976 // escaped /, and another full one which joins each regexp with |.
15978 // Following the lead of Bash 4.1, note that "**" only has special meaning
15979 // when it is the *only* thing in a path portion. Otherwise, any series
15980 // of * is equivalent to a single *. Globstar behavior is enabled by
15981 // default, and can be disabled by setting options.noglobstar.
15984 Minimatch.prototype.parse = parse$1;
15987 function parse$1(pattern, isSub) {
15988 if (pattern.length > 1024 * 64) {
15989 throw new TypeError('pattern is too long');
15992 var options = this.options; // shortcuts
15994 if (!options.noglobstar && pattern === '**') return GLOBSTAR;
15995 if (pattern === '') return '';
15997 var hasMagic = !!options.nocase;
15998 var escaping = false; // ? => one single character
16000 var patternListStack = [];
16001 var negativeLists = [];
16003 var inClass = false;
16004 var reClassStart = -1;
16005 var classStart = -1; // . and .. never match anything that doesn't start with .,
16006 // even when options.dot is set.
16008 var patternStart = pattern.charAt(0) === '.' ? '' // anything
16009 // not (start or / followed by . or .. followed by / or end)
16010 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
16013 function clearStateChar() {
16015 // we had some state-tracking character
16016 // that wasn't consumed by this pass.
16017 switch (stateChar) {
16029 re += '\\' + stateChar;
16033 self.debug('clearStateChar %j %j', stateChar, re);
16038 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
16039 this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
16041 if (escaping && reSpecials[c]) {
16049 // completely not allowed, even escaped.
16050 // Should already be path-split by now.
16057 // the various stateChar values
16058 // for the "extglob" stuff.
16065 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
16066 // the glob [!a] means [^a] in regexp
16069 this.debug(' in class');
16070 if (c === '!' && i === classStart + 1) c = '^';
16073 } // if we already have a stateChar, then it means
16074 // that there was something like ** or +? in there.
16075 // Handle the stateChar, then proceed with this one.
16078 self.debug('call clearStateChar %j', stateChar);
16080 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
16081 // just clear the statechar *now*, rather than even diving into
16082 // the patternList stuff.
16084 if (options.noext) clearStateChar();
16098 patternListStack.push({
16101 reStart: re.length,
16102 open: plTypes[stateChar].open,
16103 close: plTypes[stateChar].close
16104 }); // negation is (?:(?!js)[^/]*)
16106 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
16107 this.debug('plType %j %j', stateChar, re);
16112 if (inClass || !patternListStack.length) {
16119 var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
16120 // The others are (?:<pattern>)<type>
16124 if (pl.type === '!') {
16125 negativeLists.push(pl);
16128 pl.reEnd = re.length;
16132 if (inClass || !patternListStack.length || escaping) {
16141 // these are mostly the same in regexp and glob
16144 // swallow any state-tracking char before the [
16154 reClassStart = re.length;
16159 // a right bracket shall lose its special
16160 // meaning and represent itself in
16161 // a bracket expression if it occurs
16162 // first in the list. -- POSIX.2 2.8.3.2
16163 if (i === classStart + 1 || !inClass) {
16167 } // handle the case where we left a class open.
16168 // "[z-a]" is valid, equivalent to "\[z-a\]"
16172 // split where the last [ was, make sure we don't have
16173 // an invalid re. if so, re-walk the contents of the
16174 // would-be class to re-translate any characters that
16175 // were passed through as-is
16176 // TODO: It would probably be faster to determine this
16177 // without a try/catch and a new RegExp, but it's tricky
16178 // to do safely. For now, this is safe and works.
16179 var cs = pattern.substring(classStart + 1, i);
16182 RegExp('[' + cs + ']');
16184 // not a valid class!
16185 var sp = this.parse(cs, SUBPARSE);
16186 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
16187 hasMagic = hasMagic || sp[1];
16191 } // finish up the class.
16200 // swallow any state char that wasn't consumed
16206 } else if (reSpecials[c] && !(c === '^' && inClass)) {
16214 // handle the case where we left a class open.
16215 // "[abc" is valid, equivalent to "\[abc"
16219 // split where the last [ was, and escape it
16220 // this is a huge pita. We now have to re-walk
16221 // the contents of the would-be class to re-translate
16222 // any characters that were passed through as-is
16223 cs = pattern.substr(classStart + 1);
16224 sp = this.parse(cs, SUBPARSE);
16225 re = re.substr(0, reClassStart) + '\\[' + sp[0];
16226 hasMagic = hasMagic || sp[1];
16227 } // handle the case where we had a +( thing at the *end*
16229 // each pattern list stack adds 3 chars, and we need to go through
16230 // and escape any | chars that were passed through as-is for the regexp.
16231 // Go through and escape them, taking care not to double-escape any
16232 // | chars that were already escaped.
16235 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
16236 var tail = re.slice(pl.reStart + pl.open.length);
16237 this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
16239 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
16241 // the | isn't already escaped, so escape it.
16243 } // need to escape all those slashes *again*, without escaping the
16244 // one that we need for escaping the | character. As it works out,
16245 // escaping an even number of slashes can be done by simply repeating
16246 // it exactly after itself. That's why this trick works.
16248 // I am sorry that you have to see this.
16251 return $1 + $1 + $2 + '|';
16253 this.debug('tail=%j\n %s', tail, tail, pl, re);
16254 var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
16256 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
16257 } // handle trailing things that only matter at the very end.
16265 } // only need to apply the nodot start if the re starts with
16266 // something that could conceivably capture a dot
16269 var addPatternStart = false;
16271 switch (re.charAt(0)) {
16275 addPatternStart = true;
16276 } // Hack to work around lack of negative lookbehind in JS
16277 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
16278 // like 'a.xyz.yz' doesn't match. So, the first negative
16279 // lookahead, has to look ALL the way ahead, to the end of
16283 for (var n = negativeLists.length - 1; n > -1; n--) {
16284 var nl = negativeLists[n];
16285 var nlBefore = re.slice(0, nl.reStart);
16286 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
16287 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
16288 var nlAfter = re.slice(nl.reEnd);
16289 nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
16290 // mean that we should *not* include the ) in the bit that is considered
16291 // "after" the negated section.
16293 var openParensBefore = nlBefore.split('(').length - 1;
16294 var cleanAfter = nlAfter;
16296 for (i = 0; i < openParensBefore; i++) {
16297 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
16300 nlAfter = cleanAfter;
16303 if (nlAfter === '' && isSub !== SUBPARSE) {
16307 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
16309 } // if the re is not "" at this point, then we need to make sure
16310 // it doesn't match against an empty path part.
16311 // Otherwise a/* will match a/, which it should not.
16314 if (re !== '' && hasMagic) {
16318 if (addPatternStart) {
16319 re = patternStart + re;
16320 } // parsing just a piece of a larger pattern.
16323 if (isSub === SUBPARSE) {
16324 return [re, hasMagic];
16325 } // skip the regexp for non-magical patterns
16326 // unescape anything in it, though, so that it'll be
16327 // an exact match against a file etc.
16331 return globUnescape(pattern);
16334 var flags = options.nocase ? 'i' : '';
16337 var regExp = new RegExp('^' + re + '$', flags);
16339 // If it was an invalid regular expression, then it can't match
16340 // anything. This trick looks for a character after the end of
16341 // the string, which is of course impossible, except in multi-line
16342 // mode, but it's not a /m regex.
16343 return new RegExp('$.');
16346 regExp._glob = pattern;
16351 minimatch.makeRe = function (pattern, options) {
16352 return new Minimatch(pattern, options || {}).makeRe();
16355 Minimatch.prototype.makeRe = makeRe;
16357 function makeRe() {
16358 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
16359 // pattern strings, or "**".
16361 // It's better to use .match(). This function shouldn't
16362 // be used, really, but it's pretty convenient sometimes,
16363 // when you just want to work with a regex.
16365 var set = this.set;
16368 this.regexp = false;
16369 return this.regexp;
16372 var options = this.options;
16373 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
16374 var flags = options.nocase ? 'i' : '';
16375 var re = set.map(function (pattern) {
16376 return pattern.map(function (p) {
16377 return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
16379 }).join('|'); // must match entire pattern
16380 // ending in a * or ** will make it less strict.
16382 re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
16384 if (this.negate) re = '^(?!' + re + ').*$';
16387 this.regexp = new RegExp(re, flags);
16389 this.regexp = false;
16392 return this.regexp;
16395 minimatch.match = function (list, pattern, options) {
16396 options = options || {};
16397 var mm = new Minimatch(pattern, options);
16398 list = list.filter(function (f) {
16399 return mm.match(f);
16402 if (mm.options.nonull && !list.length) {
16403 list.push(pattern);
16409 Minimatch.prototype.match = match;
16411 function match(f, partial) {
16412 this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
16415 if (this.comment) return false;
16416 if (this.empty) return f === '';
16417 if (f === '/' && partial) return true;
16418 var options = this.options; // windows: need to use /, not \
16420 if (path.sep !== '/') {
16421 f = f.split(path.sep).join('/');
16422 } // treat the test path as a set of pathparts.
16425 f = f.split(slashSplit);
16426 this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
16427 // in order for it to be valid. If negating, then just one
16428 // match means that we have failed.
16429 // Either way, return on the first hit.
16431 var set = this.set;
16432 this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
16437 for (i = f.length - 1; i >= 0; i--) {
16439 if (filename) break;
16442 for (i = 0; i < set.length; i++) {
16443 var pattern = set[i];
16446 if (options.matchBase && pattern.length === 1) {
16450 var hit = this.matchOne(file, pattern, partial);
16453 if (options.flipNegate) return true;
16454 return !this.negate;
16456 } // didn't get any hits. this is success if it's a negative
16457 // pattern, failure otherwise.
16460 if (options.flipNegate) return false;
16461 return this.negate;
16462 } // set partial to true to test if, for example,
16463 // "/a/b" matches the start of "/*/b/*/d"
16464 // Partial means, if you run out of file before you run
16465 // out of pattern, then that's fine, as long as all
16466 // the parts match.
16469 Minimatch.prototype.matchOne = function (file, pattern, partial) {
16470 var options = this.options;
16471 this.debug('matchOne', {
16476 this.debug('matchOne', file.length, pattern.length);
16478 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
16479 this.debug('matchOne loop');
16480 var p = pattern[pi];
16482 this.debug(pattern, p, f); // should be impossible.
16483 // some invalid regexp stuff in the set.
16485 if (p === false) return false;
16487 if (p === GLOBSTAR) {
16488 this.debug('GLOBSTAR', [pattern, p, f]); // "**"
16489 // a/**/b/**/c would match the following:
16494 // To do this, take the rest of the pattern after
16495 // the **, and see if it would match the file remainder.
16496 // If so, return success.
16497 // If not, the ** "swallows" a segment, and try again.
16498 // This is recursively awful.
16500 // a/**/b/**/c matching a/b/x/y/z/c
16503 // - matchOne(b/x/y/z/c, b/**/c)
16506 // - matchOne(x/y/z/c, c) -> no
16507 // - matchOne(y/z/c, c) -> no
16508 // - matchOne(z/c, c) -> no
16509 // - matchOne(c, c) yes, hit
16515 this.debug('** at the end'); // a ** at the end will just swallow the rest.
16516 // We have found a match.
16517 // however, it will not swallow /.x, unless
16518 // options.dot is set.
16519 // . and .. are *never* matched by **, for explosively
16520 // exponential reasons.
16522 for (; fi < fl; fi++) {
16523 if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
16527 } // ok, let's see if we can swallow whatever we can.
16531 var swallowee = file[fr];
16532 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
16534 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
16535 this.debug('globstar found match!', fr, fl, swallowee); // found a match.
16539 // can't swallow "." or ".." ever.
16540 // can only swallow ".foo" when explicitly asked.
16541 if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
16542 this.debug('dot detected!', file, fr, pattern, pr);
16544 } // ** swallows a segment, and continue.
16547 this.debug('globstar swallow a segment, and continue');
16550 } // no match was found.
16551 // However, in partial mode, we can't say this is necessarily over.
16552 // If there's more *pattern* left, then
16557 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
16558 if (fr === fl) return true;
16562 } // something other than **
16563 // non-magic patterns just have to match exactly
16564 // patterns with magic have been turned into regexps.
16569 if (typeof p === 'string') {
16570 if (options.nocase) {
16571 hit = f.toLowerCase() === p.toLowerCase();
16576 this.debug('string match', p, f, hit);
16579 this.debug('pattern match', p, f, hit);
16582 if (!hit) return false;
16583 } // Note: ending in / means that we'll get a final ""
16584 // at the end of the pattern. This can only match a
16585 // corresponding "" at the end of the file.
16586 // If the file ends in /, then it can only match a
16587 // a pattern that ends in /, unless the pattern just
16588 // doesn't have any more for it. But, a/b/ should *not*
16589 // match "a/b/*", even though "" matches against the
16590 // [^/]*? pattern, except in partial mode, where it might
16591 // simply not be reached yet.
16592 // However, a/b/ should still satisfy a/*
16593 // now either we fell off the end of the pattern, or we're done.
16596 if (fi === fl && pi === pl) {
16597 // ran out of pattern and filename at the same time.
16600 } else if (fi === fl) {
16601 // ran out of file, but still had pattern left.
16602 // this is ok if we're doing the match as part of
16603 // a glob fs traversal.
16605 } else if (pi === pl) {
16606 // ran out of pattern, still have file left.
16607 // this is only acceptable if we're on the very last
16608 // empty segment of a file with a trailing slash.
16609 // a/* should match a/b/
16610 var emptyFileEnd = fi === fl - 1 && file[fi] === '';
16611 return emptyFileEnd;
16612 } // should be unreachable.
16615 throw new Error('wtf?');
16616 }; // replace stuff like \* with *
16619 function globUnescape(s) {
16620 return s.replace(/\\(.)/g, '$1');
16623 function regExpEscape(s) {
16624 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
16627 const copyProperty = (to, from, property, ignoreNonConfigurable) => {
16628 // `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
16629 // `Function#prototype` is non-writable and non-configurable so can never be modified.
16630 if (property === 'length' || property === 'prototype') {
16634 const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
16635 const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
16637 if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
16641 Object.defineProperty(to, property, fromDescriptor);
16642 }; // `Object.defineProperty()` throws if the property exists, is not configurable and either:
16643 // - one its descriptors is changed
16644 // - it is non-writable and its value is changed
16647 const canCopyProperty = function (toDescriptor, fromDescriptor) {
16648 return toDescriptor === undefined || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
16651 const changePrototype = (to, from) => {
16652 const fromPrototype = Object.getPrototypeOf(from);
16654 if (fromPrototype === Object.getPrototypeOf(to)) {
16658 Object.setPrototypeOf(to, fromPrototype);
16661 const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;
16663 const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
16664 const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
16665 // We use `bind()` instead of a closure for the same reason.
16666 // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
16668 const changeToString = (to, from, name) => {
16669 const withName = name === '' ? '' : `with ${name.trim()}() `;
16670 const newToString = wrappedToString.bind(null, withName, from.toString()); // Ensure `to.toString.toString` is non-enumerable and has the same `same`
16672 Object.defineProperty(newToString, 'name', toStringName);
16673 Object.defineProperty(to, 'toString', Object.assign({}, toStringDescriptor, {
16678 const mimicFn = (to, from, {
16679 ignoreNonConfigurable = false
16685 for (const property of Reflect.ownKeys(from)) {
16686 copyProperty(to, from, property, ignoreNonConfigurable);
16689 changePrototype(to, from);
16690 changeToString(to, from, name);
16694 var mimicFn_1 = mimicFn;
16696 var pDefer = () => {
16698 ret.promise = new Promise((resolve, reject) => {
16699 ret.resolve = resolve;
16700 ret.reject = reject;
16705 var dist = createCommonjsModule(function (module, exports) {
16707 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
16708 return new (P || (P = Promise))(function (resolve, reject) {
16709 function fulfilled(value) {
16711 step(generator.next(value));
16717 function rejected(value) {
16719 step(generator["throw"](value));
16725 function step(result) {
16726 result.done ? resolve(result.value) : new P(function (resolve) {
16727 resolve(result.value);
16728 }).then(fulfilled, rejected);
16731 step((generator = generator.apply(thisArg, _arguments || [])).next());
16735 var __importDefault = this && this.__importDefault || function (mod) {
16736 return mod && mod.__esModule ? mod : {
16741 Object.defineProperty(exports, "__esModule", {
16745 const p_defer_1 = __importDefault(pDefer);
16747 function mapAgeCleaner(map, property = 'maxAge') {
16749 let processingTimer;
16750 let processingDeferred;
16752 const cleanup = () => __awaiter(this, void 0, void 0, function* () {
16753 if (processingKey !== undefined) {
16754 // If we are already processing an item, we can safely exit
16758 const setupTimer = item => __awaiter(this, void 0, void 0, function* () {
16759 processingDeferred = p_defer_1.default();
16760 const delay = item[1][property] - Date.now();
16763 // Remove the item immediately if the delay is equal to or below 0
16764 map.delete(item[0]);
16765 processingDeferred.resolve();
16767 } // Keep track of the current processed key
16770 processingKey = item[0];
16771 processingTimer = setTimeout(() => {
16772 // Remove the item when the timeout fires
16773 map.delete(item[0]);
16775 if (processingDeferred) {
16776 processingDeferred.resolve();
16778 }, delay); // tslint:disable-next-line:strict-type-predicates
16780 if (typeof processingTimer.unref === 'function') {
16781 // Don't hold up the process from exiting
16782 processingTimer.unref();
16785 return processingDeferred.promise;
16789 for (const entry of map) {
16790 yield setupTimer(entry);
16792 } catch (_a) {// Do nothing if an error occurs, this means the timer was cleaned up and we should stop processing
16795 processingKey = undefined;
16798 const reset = () => {
16799 processingKey = undefined;
16801 if (processingTimer !== undefined) {
16802 clearTimeout(processingTimer);
16803 processingTimer = undefined;
16806 if (processingDeferred !== undefined) {
16807 // tslint:disable-line:early-exit
16808 processingDeferred.reject(undefined);
16809 processingDeferred = undefined;
16813 const originalSet = map.set.bind(map);
16815 map.set = (key, value) => {
16816 if (map.has(key)) {
16817 // If the key already exist, remove it so we can add it back at the end of the map.
16819 } // Call the original `map.set`
16822 const result = originalSet(key, value); // If we are already processing a key and the key added is the current processed key, stop processing it
16824 if (processingKey && processingKey === key) {
16826 } // Always run the cleanup method in case it wasn't started yet
16829 cleanup(); // tslint:disable-line:no-floating-promises
16834 cleanup(); // tslint:disable-line:no-floating-promises
16839 exports.default = mapAgeCleaner; // Add support for CJS
16841 module.exports = mapAgeCleaner;
16842 module.exports.default = mapAgeCleaner;
16844 unwrapExports(dist);
16846 const cacheStore = new WeakMap();
16849 cacheKey = ([firstArgument]) => firstArgument,
16853 if (typeof maxAge === 'number') {
16857 const memoized = function (...arguments_) {
16858 const key = cacheKey(arguments_);
16860 if (cache.has(key)) {
16861 return cache.get(key).data;
16864 const cacheItem = fn.apply(this, arguments_);
16867 maxAge: maxAge ? Date.now() + maxAge : Infinity
16873 // The below call will throw in some host environments
16874 // See https://github.com/sindresorhus/mimic-fn/issues/10
16875 mimicFn_1(memoized, fn);
16878 cacheStore.set(memoized, cache);
16884 var clear = fn => {
16885 if (!cacheStore.has(fn)) {
16886 throw new Error('Can\'t clear a function that was not memoized!');
16889 const cache = cacheStore.get(fn);
16891 if (typeof cache.clear === 'function') {
16895 mem_1.clear = clear;
16897 var semver$2 = createCommonjsModule(function (module, exports) {
16898 exports = module.exports = SemVer;
16900 /* istanbul ignore next */
16902 if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
16903 debug = function () {
16904 var args = Array.prototype.slice.call(arguments, 0);
16905 args.unshift('SEMVER');
16906 console.log.apply(console, args);
16909 debug = function () {};
16910 } // Note: this is the semver.org version of the spec that it implements
16911 // Not necessarily the package version of this code.
16914 exports.SEMVER_SPEC_VERSION = '2.0.0';
16915 var MAX_LENGTH = 256;
16916 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
16917 /* istanbul ignore next */
16918 9007199254740991; // Max safe segment length for coercion.
16920 var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
16922 var re = exports.re = [];
16923 var src = exports.src = [];
16924 var R = 0; // The following Regular Expressions can be used for tokenizing,
16925 // validating, and parsing SemVer version strings.
16926 // ## Numeric Identifier
16927 // A single `0`, or a non-zero digit followed by zero or more digits.
16929 var NUMERICIDENTIFIER = R++;
16930 src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
16931 var NUMERICIDENTIFIERLOOSE = R++;
16932 src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
16933 // Zero or more digits, followed by a letter or hyphen, and then zero or
16934 // more letters, digits, or hyphens.
16936 var NONNUMERICIDENTIFIER = R++;
16937 src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
16938 // Three dot-separated numeric identifiers.
16940 var MAINVERSION = R++;
16941 src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
16942 var MAINVERSIONLOOSE = R++;
16943 src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
16944 // A numeric identifier, or a non-numeric identifier.
16946 var PRERELEASEIDENTIFIER = R++;
16947 src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
16948 var PRERELEASEIDENTIFIERLOOSE = R++;
16949 src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
16950 // Hyphen, followed by one or more dot-separated pre-release version
16953 var PRERELEASE = R++;
16954 src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
16955 var PRERELEASELOOSE = R++;
16956 src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
16957 // Any combination of digits, letters, or hyphens.
16959 var BUILDIDENTIFIER = R++;
16960 src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
16961 // Plus sign, followed by one or more period-separated build metadata
16965 src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
16966 // A main version, followed optionally by a pre-release version and
16968 // Note that the only major, minor, patch, and pre-release sections of
16969 // the version string are capturing groups. The build metadata is not a
16970 // capturing group, because it should not ever be used in version
16974 var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
16975 src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
16976 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
16977 // common in the npm registry.
16979 var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
16981 src[LOOSE] = '^' + LOOSEPLAIN + '$';
16983 src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
16984 // Note that "x.x" is a valid xRange identifer, meaning "any version"
16985 // Only the first item is strictly required.
16987 var XRANGEIDENTIFIERLOOSE = R++;
16988 src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
16989 var XRANGEIDENTIFIER = R++;
16990 src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
16991 var XRANGEPLAIN = R++;
16992 src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
16993 var XRANGEPLAINLOOSE = R++;
16994 src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
16996 src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
16997 var XRANGELOOSE = R++;
16998 src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion.
16999 // Extract anything that could conceivably be a part of a valid semver
17002 src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges.
17003 // Meaning is "reasonably at or greater than"
17005 var LONETILDE = R++;
17006 src[LONETILDE] = '(?:~>?)';
17007 var TILDETRIM = R++;
17008 src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
17009 re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
17010 var tildeTrimReplace = '$1~';
17012 src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
17013 var TILDELOOSE = R++;
17014 src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
17015 // Meaning is "at least and backwards compatible with"
17017 var LONECARET = R++;
17018 src[LONECARET] = '(?:\\^)';
17019 var CARETTRIM = R++;
17020 src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
17021 re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
17022 var caretTrimReplace = '$1^';
17024 src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
17025 var CARETLOOSE = R++;
17026 src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
17028 var COMPARATORLOOSE = R++;
17029 src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
17030 var COMPARATOR = R++;
17031 src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
17032 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
17034 var COMPARATORTRIM = R++;
17035 src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
17037 re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
17038 var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
17039 // Note that these all use the loose form, because they'll be
17040 // checked against either the strict or loose comparator form
17043 var HYPHENRANGE = R++;
17044 src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
17045 var HYPHENRANGELOOSE = R++;
17046 src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
17049 src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
17050 // All are flag-free, unless they were created above with a flag.
17052 for (var i = 0; i < R; i++) {
17056 re[i] = new RegExp(src[i]);
17060 exports.parse = parse;
17062 function parse(version, options) {
17063 if (!options || typeof options !== 'object') {
17066 includePrerelease: false
17070 if (version instanceof SemVer) {
17074 if (typeof version !== 'string') {
17078 if (version.length > MAX_LENGTH) {
17082 var r = options.loose ? re[LOOSE] : re[FULL];
17084 if (!r.test(version)) {
17089 return new SemVer(version, options);
17095 exports.valid = valid;
17097 function valid(version, options) {
17098 var v = parse(version, options);
17099 return v ? v.version : null;
17102 exports.clean = clean;
17104 function clean(version, options) {
17105 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
17106 return s ? s.version : null;
17109 exports.SemVer = SemVer;
17111 function SemVer(version, options) {
17112 if (!options || typeof options !== 'object') {
17115 includePrerelease: false
17119 if (version instanceof SemVer) {
17120 if (version.loose === options.loose) {
17123 version = version.version;
17125 } else if (typeof version !== 'string') {
17126 throw new TypeError('Invalid Version: ' + version);
17129 if (version.length > MAX_LENGTH) {
17130 throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
17133 if (!(this instanceof SemVer)) {
17134 return new SemVer(version, options);
17137 debug('SemVer', version, options);
17138 this.options = options;
17139 this.loose = !!options.loose;
17140 var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);
17143 throw new TypeError('Invalid Version: ' + version);
17146 this.raw = version; // these are actually numbers
17148 this.major = +m[1];
17149 this.minor = +m[2];
17150 this.patch = +m[3];
17152 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
17153 throw new TypeError('Invalid major version');
17156 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
17157 throw new TypeError('Invalid minor version');
17160 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
17161 throw new TypeError('Invalid patch version');
17162 } // numberify any prerelease numeric ids
17166 this.prerelease = [];
17168 this.prerelease = m[4].split('.').map(function (id) {
17169 if (/^[0-9]+$/.test(id)) {
17172 if (num >= 0 && num < MAX_SAFE_INTEGER) {
17181 this.build = m[5] ? m[5].split('.') : [];
17185 SemVer.prototype.format = function () {
17186 this.version = this.major + '.' + this.minor + '.' + this.patch;
17188 if (this.prerelease.length) {
17189 this.version += '-' + this.prerelease.join('.');
17192 return this.version;
17195 SemVer.prototype.toString = function () {
17196 return this.version;
17199 SemVer.prototype.compare = function (other) {
17200 debug('SemVer.compare', this.version, this.options, other);
17202 if (!(other instanceof SemVer)) {
17203 other = new SemVer(other, this.options);
17206 return this.compareMain(other) || this.comparePre(other);
17209 SemVer.prototype.compareMain = function (other) {
17210 if (!(other instanceof SemVer)) {
17211 other = new SemVer(other, this.options);
17214 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
17217 SemVer.prototype.comparePre = function (other) {
17218 if (!(other instanceof SemVer)) {
17219 other = new SemVer(other, this.options);
17220 } // NOT having a prerelease is > having one
17223 if (this.prerelease.length && !other.prerelease.length) {
17225 } else if (!this.prerelease.length && other.prerelease.length) {
17227 } else if (!this.prerelease.length && !other.prerelease.length) {
17234 var a = this.prerelease[i];
17235 var b = other.prerelease[i];
17236 debug('prerelease compare', i, a, b);
17238 if (a === undefined && b === undefined) {
17240 } else if (b === undefined) {
17242 } else if (a === undefined) {
17244 } else if (a === b) {
17247 return compareIdentifiers(a, b);
17250 }; // preminor will bump the version up to the next minor release, and immediately
17251 // down to pre-release. premajor and prepatch work the same way.
17254 SemVer.prototype.inc = function (release, identifier) {
17257 this.prerelease.length = 0;
17261 this.inc('pre', identifier);
17265 this.prerelease.length = 0;
17268 this.inc('pre', identifier);
17272 // If this is already a prerelease, it will bump to the next version
17273 // drop any prereleases that might already exist, since they are not
17274 // relevant at this point.
17275 this.prerelease.length = 0;
17276 this.inc('patch', identifier);
17277 this.inc('pre', identifier);
17279 // If the input is a non-prerelease version, this acts the same as
17283 if (this.prerelease.length === 0) {
17284 this.inc('patch', identifier);
17287 this.inc('pre', identifier);
17291 // If this is a pre-major version, bump up to the same major version.
17292 // Otherwise increment major.
17293 // 1.0.0-5 bumps to 1.0.0
17294 // 1.1.0 bumps to 2.0.0
17295 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
17301 this.prerelease = [];
17305 // If this is a pre-minor version, bump up to the same minor version.
17306 // Otherwise increment minor.
17307 // 1.2.0-5 bumps to 1.2.0
17308 // 1.2.1 bumps to 1.3.0
17309 if (this.patch !== 0 || this.prerelease.length === 0) {
17314 this.prerelease = [];
17318 // If this is not a pre-release version, it will increment the patch.
17319 // If it is a pre-release it will bump up to the same patch version.
17320 // 1.2.0-5 patches to 1.2.0
17321 // 1.2.0 patches to 1.2.1
17322 if (this.prerelease.length === 0) {
17326 this.prerelease = [];
17328 // This probably shouldn't be used publicly.
17329 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
17332 if (this.prerelease.length === 0) {
17333 this.prerelease = [0];
17335 var i = this.prerelease.length;
17338 if (typeof this.prerelease[i] === 'number') {
17339 this.prerelease[i]++;
17345 // didn't increment anything
17346 this.prerelease.push(0);
17351 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
17352 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
17353 if (this.prerelease[0] === identifier) {
17354 if (isNaN(this.prerelease[1])) {
17355 this.prerelease = [identifier, 0];
17358 this.prerelease = [identifier, 0];
17365 throw new Error('invalid increment argument: ' + release);
17369 this.raw = this.version;
17375 function inc(version, release, loose, identifier) {
17376 if (typeof loose === 'string') {
17377 identifier = loose;
17382 return new SemVer(version, loose).inc(release, identifier).version;
17388 exports.diff = diff;
17390 function diff(version1, version2) {
17391 if (eq(version1, version2)) {
17394 var v1 = parse(version1);
17395 var v2 = parse(version2);
17398 if (v1.prerelease.length || v2.prerelease.length) {
17400 var defaultResult = 'prerelease';
17403 for (var key in v1) {
17404 if (key === 'major' || key === 'minor' || key === 'patch') {
17405 if (v1[key] !== v2[key]) {
17406 return prefix + key;
17411 return defaultResult; // may be undefined
17415 exports.compareIdentifiers = compareIdentifiers;
17416 var numeric = /^[0-9]+$/;
17418 function compareIdentifiers(a, b) {
17419 var anum = numeric.test(a);
17420 var bnum = numeric.test(b);
17422 if (anum && bnum) {
17427 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
17430 exports.rcompareIdentifiers = rcompareIdentifiers;
17432 function rcompareIdentifiers(a, b) {
17433 return compareIdentifiers(b, a);
17436 exports.major = major;
17438 function major(a, loose) {
17439 return new SemVer(a, loose).major;
17442 exports.minor = minor;
17444 function minor(a, loose) {
17445 return new SemVer(a, loose).minor;
17448 exports.patch = patch;
17450 function patch(a, loose) {
17451 return new SemVer(a, loose).patch;
17454 exports.compare = compare;
17456 function compare(a, b, loose) {
17457 return new SemVer(a, loose).compare(new SemVer(b, loose));
17460 exports.compareLoose = compareLoose;
17462 function compareLoose(a, b) {
17463 return compare(a, b, true);
17466 exports.rcompare = rcompare;
17468 function rcompare(a, b, loose) {
17469 return compare(b, a, loose);
17472 exports.sort = sort;
17474 function sort(list, loose) {
17475 return list.sort(function (a, b) {
17476 return exports.compare(a, b, loose);
17480 exports.rsort = rsort;
17482 function rsort(list, loose) {
17483 return list.sort(function (a, b) {
17484 return exports.rcompare(a, b, loose);
17490 function gt(a, b, loose) {
17491 return compare(a, b, loose) > 0;
17496 function lt(a, b, loose) {
17497 return compare(a, b, loose) < 0;
17502 function eq(a, b, loose) {
17503 return compare(a, b, loose) === 0;
17508 function neq(a, b, loose) {
17509 return compare(a, b, loose) !== 0;
17514 function gte(a, b, loose) {
17515 return compare(a, b, loose) >= 0;
17520 function lte(a, b, loose) {
17521 return compare(a, b, loose) <= 0;
17526 function cmp(a, op, b, loose) {
17529 if (typeof a === 'object') a = a.version;
17530 if (typeof b === 'object') b = b.version;
17534 if (typeof a === 'object') a = a.version;
17535 if (typeof b === 'object') b = b.version;
17541 return eq(a, b, loose);
17544 return neq(a, b, loose);
17547 return gt(a, b, loose);
17550 return gte(a, b, loose);
17553 return lt(a, b, loose);
17556 return lte(a, b, loose);
17559 throw new TypeError('Invalid operator: ' + op);
17563 exports.Comparator = Comparator;
17565 function Comparator(comp, options) {
17566 if (!options || typeof options !== 'object') {
17569 includePrerelease: false
17573 if (comp instanceof Comparator) {
17574 if (comp.loose === !!options.loose) {
17581 if (!(this instanceof Comparator)) {
17582 return new Comparator(comp, options);
17585 debug('comparator', comp, options);
17586 this.options = options;
17587 this.loose = !!options.loose;
17590 if (this.semver === ANY) {
17593 this.value = this.operator + this.semver.version;
17596 debug('comp', this);
17601 Comparator.prototype.parse = function (comp) {
17602 var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
17603 var m = comp.match(r);
17606 throw new TypeError('Invalid comparator: ' + comp);
17609 this.operator = m[1];
17611 if (this.operator === '=') {
17612 this.operator = '';
17613 } // if it literally is just '>' or '' then allow anything.
17619 this.semver = new SemVer(m[2], this.options.loose);
17623 Comparator.prototype.toString = function () {
17627 Comparator.prototype.test = function (version) {
17628 debug('Comparator.test', version, this.options.loose);
17630 if (this.semver === ANY) {
17634 if (typeof version === 'string') {
17635 version = new SemVer(version, this.options);
17638 return cmp(version, this.operator, this.semver, this.options);
17641 Comparator.prototype.intersects = function (comp, options) {
17642 if (!(comp instanceof Comparator)) {
17643 throw new TypeError('a Comparator is required');
17646 if (!options || typeof options !== 'object') {
17649 includePrerelease: false
17655 if (this.operator === '') {
17656 rangeTmp = new Range(comp.value, options);
17657 return satisfies(this.value, rangeTmp, options);
17658 } else if (comp.operator === '') {
17659 rangeTmp = new Range(this.value, options);
17660 return satisfies(comp.semver, rangeTmp, options);
17663 var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
17664 var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
17665 var sameSemVer = this.semver.version === comp.semver.version;
17666 var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
17667 var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
17668 var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
17669 return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
17672 exports.Range = Range;
17674 function Range(range, options) {
17675 if (!options || typeof options !== 'object') {
17678 includePrerelease: false
17682 if (range instanceof Range) {
17683 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
17686 return new Range(range.raw, options);
17690 if (range instanceof Comparator) {
17691 return new Range(range.value, options);
17694 if (!(this instanceof Range)) {
17695 return new Range(range, options);
17698 this.options = options;
17699 this.loose = !!options.loose;
17700 this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
17703 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
17704 return this.parseRange(range.trim());
17705 }, this).filter(function (c) {
17706 // throw out any that are not relevant for whatever reason
17710 if (!this.set.length) {
17711 throw new TypeError('Invalid SemVer Range: ' + range);
17717 Range.prototype.format = function () {
17718 this.range = this.set.map(function (comps) {
17719 return comps.join(' ').trim();
17720 }).join('||').trim();
17724 Range.prototype.toString = function () {
17728 Range.prototype.parseRange = function (range) {
17729 var loose = this.options.loose;
17730 range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
17732 var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
17733 range = range.replace(hr, hyphenReplace);
17734 debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
17736 range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
17737 debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
17739 range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
17741 range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
17743 range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
17744 // ready to be split into comparators.
17746 var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
17747 var set = range.split(' ').map(function (comp) {
17748 return parseComparator(comp, this.options);
17749 }, this).join(' ').split(/\s+/);
17751 if (this.options.loose) {
17752 // in loose mode, throw out any that are not valid comparators
17753 set = set.filter(function (comp) {
17754 return !!comp.match(compRe);
17758 set = set.map(function (comp) {
17759 return new Comparator(comp, this.options);
17764 Range.prototype.intersects = function (range, options) {
17765 if (!(range instanceof Range)) {
17766 throw new TypeError('a Range is required');
17769 return this.set.some(function (thisComparators) {
17770 return thisComparators.every(function (thisComparator) {
17771 return range.set.some(function (rangeComparators) {
17772 return rangeComparators.every(function (rangeComparator) {
17773 return thisComparator.intersects(rangeComparator, options);
17778 }; // Mostly just for testing and legacy API reasons
17781 exports.toComparators = toComparators;
17783 function toComparators(range, options) {
17784 return new Range(range, options).set.map(function (comp) {
17785 return comp.map(function (c) {
17787 }).join(' ').trim().split(' ');
17789 } // comprised of xranges, tildes, stars, and gtlt's at this point.
17790 // already replaced the hyphen ranges
17791 // turn into a set of JUST comparators.
17794 function parseComparator(comp, options) {
17795 debug('comp', comp, options);
17796 comp = replaceCarets(comp, options);
17797 debug('caret', comp);
17798 comp = replaceTildes(comp, options);
17799 debug('tildes', comp);
17800 comp = replaceXRanges(comp, options);
17801 debug('xrange', comp);
17802 comp = replaceStars(comp, options);
17803 debug('stars', comp);
17808 return !id || id.toLowerCase() === 'x' || id === '*';
17809 } // ~, ~> --> * (any, kinda silly)
17810 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
17811 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
17812 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
17813 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
17814 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
17817 function replaceTildes(comp, options) {
17818 return comp.trim().split(/\s+/).map(function (comp) {
17819 return replaceTilde(comp, options);
17823 function replaceTilde(comp, options) {
17824 var r = options.loose ? re[TILDELOOSE] : re[TILDE];
17825 return comp.replace(r, function (_, M, m, p, pr) {
17826 debug('tilde', comp, _, M, m, p, pr);
17831 } else if (isX(m)) {
17832 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
17833 } else if (isX(p)) {
17834 // ~1.2 == >=1.2.0 <1.3.0
17835 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
17837 debug('replaceTilde pr', pr);
17838 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
17840 // ~1.2.3 == >=1.2.3 <1.3.0
17841 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
17844 debug('tilde return', ret);
17847 } // ^ --> * (any, kinda silly)
17848 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
17849 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
17850 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
17851 // ^1.2.3 --> >=1.2.3 <2.0.0
17852 // ^1.2.0 --> >=1.2.0 <2.0.0
17855 function replaceCarets(comp, options) {
17856 return comp.trim().split(/\s+/).map(function (comp) {
17857 return replaceCaret(comp, options);
17861 function replaceCaret(comp, options) {
17862 debug('caret', comp, options);
17863 var r = options.loose ? re[CARETLOOSE] : re[CARET];
17864 return comp.replace(r, function (_, M, m, p, pr) {
17865 debug('caret', comp, _, M, m, p, pr);
17870 } else if (isX(m)) {
17871 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
17872 } else if (isX(p)) {
17874 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
17876 ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
17879 debug('replaceCaret pr', pr);
17883 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1);
17885 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
17888 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0';
17895 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);
17897 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
17900 ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
17904 debug('caret return', ret);
17909 function replaceXRanges(comp, options) {
17910 debug('replaceXRanges', comp, options);
17911 return comp.split(/\s+/).map(function (comp) {
17912 return replaceXRange(comp, options);
17916 function replaceXRange(comp, options) {
17917 comp = comp.trim();
17918 var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
17919 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
17920 debug('xRange', comp, ret, gtlt, M, m, p, pr);
17922 var xm = xM || isX(m);
17923 var xp = xm || isX(p);
17926 if (gtlt === '=' && anyX) {
17931 if (gtlt === '>' || gtlt === '<') {
17932 // nothing is allowed
17935 // nothing is forbidden
17938 } else if (gtlt && anyX) {
17939 // we know patch is an x, because we have any x at all.
17940 // replace X with 0
17947 if (gtlt === '>') {
17950 // >1.2.3 => >= 1.2.4
17961 } else if (gtlt === '<=') {
17962 // <=0.7.x is actually <0.8.0, since any 0.7.x should
17963 // pass. Similarly, <=7.x is actually <8.0.0, etc.
17973 ret = gtlt + M + '.' + m + '.' + p;
17975 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
17977 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
17980 debug('xRange return', ret);
17983 } // Because * is AND-ed with everything else in the comparator,
17984 // and '' means "any version", just remove the *s entirely.
17987 function replaceStars(comp, options) {
17988 debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
17990 return comp.trim().replace(re[STAR], '');
17991 } // This function is passed to string.replace(re[HYPHENRANGE])
17992 // M, m, patch, prerelease, build
17993 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
17994 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
17995 // 1.2 - 3.4 => >=1.2.0 <3.5.0
17998 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
18001 } else if (isX(fm)) {
18002 from = '>=' + fM + '.0.0';
18003 } else if (isX(fp)) {
18004 from = '>=' + fM + '.' + fm + '.0';
18006 from = '>=' + from;
18011 } else if (isX(tm)) {
18012 to = '<' + (+tM + 1) + '.0.0';
18013 } else if (isX(tp)) {
18014 to = '<' + tM + '.' + (+tm + 1) + '.0';
18016 to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
18021 return (from + ' ' + to).trim();
18022 } // if ANY of the sets match ALL of its comparators, then pass
18025 Range.prototype.test = function (version) {
18030 if (typeof version === 'string') {
18031 version = new SemVer(version, this.options);
18034 for (var i = 0; i < this.set.length; i++) {
18035 if (testSet(this.set[i], version, this.options)) {
18043 function testSet(set, version, options) {
18044 for (var i = 0; i < set.length; i++) {
18045 if (!set[i].test(version)) {
18050 if (version.prerelease.length && !options.includePrerelease) {
18051 // Find the set of versions that are allowed to have prereleases
18052 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
18053 // That should allow `1.2.3-pr.2` to pass.
18054 // However, `1.2.4-alpha.notready` should NOT be allowed,
18055 // even though it's within the range set by the comparators.
18056 for (i = 0; i < set.length; i++) {
18057 debug(set[i].semver);
18059 if (set[i].semver === ANY) {
18063 if (set[i].semver.prerelease.length > 0) {
18064 var allowed = set[i].semver;
18066 if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
18070 } // Version has a -pre, but it's not one of the ones we like.
18079 exports.satisfies = satisfies;
18081 function satisfies(version, range, options) {
18083 range = new Range(range, options);
18088 return range.test(version);
18091 exports.maxSatisfying = maxSatisfying;
18093 function maxSatisfying(versions, range, options) {
18098 var rangeObj = new Range(range, options);
18103 versions.forEach(function (v) {
18104 if (rangeObj.test(v)) {
18105 // satisfies(v, range, options)
18106 if (!max || maxSV.compare(v) === -1) {
18107 // compare(max, v, true)
18109 maxSV = new SemVer(max, options);
18116 exports.minSatisfying = minSatisfying;
18118 function minSatisfying(versions, range, options) {
18123 var rangeObj = new Range(range, options);
18128 versions.forEach(function (v) {
18129 if (rangeObj.test(v)) {
18130 // satisfies(v, range, options)
18131 if (!min || minSV.compare(v) === 1) {
18132 // compare(min, v, true)
18134 minSV = new SemVer(min, options);
18141 exports.minVersion = minVersion;
18143 function minVersion(range, loose) {
18144 range = new Range(range, loose);
18145 var minver = new SemVer('0.0.0');
18147 if (range.test(minver)) {
18151 minver = new SemVer('0.0.0-0');
18153 if (range.test(minver)) {
18159 for (var i = 0; i < range.set.length; ++i) {
18160 var comparators = range.set[i];
18161 comparators.forEach(function (comparator) {
18162 // Clone to avoid manipulating the comparator's semver object.
18163 var compver = new SemVer(comparator.semver.version);
18165 switch (comparator.operator) {
18167 if (compver.prerelease.length === 0) {
18170 compver.prerelease.push(0);
18173 compver.raw = compver.format();
18179 if (!minver || gt(minver, compver)) {
18187 /* Ignore maximum versions */
18190 /* istanbul ignore next */
18193 throw new Error('Unexpected operation: ' + comparator.operator);
18198 if (minver && range.test(minver)) {
18205 exports.validRange = validRange;
18207 function validRange(range, options) {
18209 // Return '*' instead of '' so that truthiness works.
18210 // This will throw if it's invalid anyway
18211 return new Range(range, options).range || '*';
18215 } // Determine if version is less than all the versions possible in the range
18220 function ltr(version, range, options) {
18221 return outside(version, range, '<', options);
18222 } // Determine if version is greater than all the versions possible in the range.
18227 function gtr(version, range, options) {
18228 return outside(version, range, '>', options);
18231 exports.outside = outside;
18233 function outside(version, range, hilo, options) {
18234 version = new SemVer(version, options);
18235 range = new Range(range, options);
18236 var gtfn, ltefn, ltfn, comp, ecomp;
18256 throw new TypeError('Must provide a hilo val of "<" or ">"');
18257 } // If it satisifes the range it is not outside
18260 if (satisfies(version, range, options)) {
18262 } // From now on, variable terms are as if we're in "gtr" mode.
18263 // but note that everything is flipped for the "ltr" function.
18266 for (var i = 0; i < range.set.length; ++i) {
18267 var comparators = range.set[i];
18270 comparators.forEach(function (comparator) {
18271 if (comparator.semver === ANY) {
18272 comparator = new Comparator('>=0.0.0');
18275 high = high || comparator;
18276 low = low || comparator;
18278 if (gtfn(comparator.semver, high.semver, options)) {
18280 } else if (ltfn(comparator.semver, low.semver, options)) {
18283 }); // If the edge version comparator has a operator then our version
18284 // isn't outside it
18286 if (high.operator === comp || high.operator === ecomp) {
18288 } // If the lowest version comparator has an operator and our version
18289 // is less than it then it isn't higher than the range
18292 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
18294 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
18302 exports.prerelease = prerelease;
18304 function prerelease(version, options) {
18305 var parsed = parse(version, options);
18306 return parsed && parsed.prerelease.length ? parsed.prerelease : null;
18309 exports.intersects = intersects;
18311 function intersects(r1, r2, options) {
18312 r1 = new Range(r1, options);
18313 r2 = new Range(r2, options);
18314 return r1.intersects(r2);
18317 exports.coerce = coerce;
18319 function coerce(version) {
18320 if (version instanceof SemVer) {
18324 if (typeof version !== 'string') {
18328 var match = version.match(re[COERCE]);
18330 if (match == null) {
18334 return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
18337 var semver_1 = semver$2.SEMVER_SPEC_VERSION;
18338 var semver_2 = semver$2.re;
18339 var semver_3 = semver$2.src;
18340 var semver_4 = semver$2.parse;
18341 var semver_5 = semver$2.valid;
18342 var semver_6 = semver$2.clean;
18343 var semver_7 = semver$2.SemVer;
18344 var semver_8 = semver$2.inc;
18345 var semver_9 = semver$2.diff;
18346 var semver_10 = semver$2.compareIdentifiers;
18347 var semver_11 = semver$2.rcompareIdentifiers;
18348 var semver_12 = semver$2.major;
18349 var semver_13 = semver$2.minor;
18350 var semver_14 = semver$2.patch;
18351 var semver_15 = semver$2.compare;
18352 var semver_16 = semver$2.compareLoose;
18353 var semver_17 = semver$2.rcompare;
18354 var semver_18 = semver$2.sort;
18355 var semver_19 = semver$2.rsort;
18356 var semver_20 = semver$2.gt;
18357 var semver_21 = semver$2.lt;
18358 var semver_22 = semver$2.eq;
18359 var semver_23 = semver$2.neq;
18360 var semver_24 = semver$2.gte;
18361 var semver_25 = semver$2.lte;
18362 var semver_26 = semver$2.cmp;
18363 var semver_27 = semver$2.Comparator;
18364 var semver_28 = semver$2.Range;
18365 var semver_29 = semver$2.toComparators;
18366 var semver_30 = semver$2.satisfies;
18367 var semver_31 = semver$2.maxSatisfying;
18368 var semver_32 = semver$2.minSatisfying;
18369 var semver_33 = semver$2.minVersion;
18370 var semver_34 = semver$2.validRange;
18371 var semver_35 = semver$2.ltr;
18372 var semver_36 = semver$2.gtr;
18373 var semver_37 = semver$2.outside;
18374 var semver_38 = semver$2.prerelease;
18375 var semver_39 = semver$2.intersects;
18376 var semver_40 = semver$2.coerce;
18378 var hasOwnProperty = Object.prototype.hasOwnProperty;
18379 var pseudomap = PseudoMap;
18381 function PseudoMap(set) {
18382 if (!(this instanceof PseudoMap)) // whyyyyyyy
18383 throw new TypeError("Constructor PseudoMap requires 'new'");
18387 if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) {
18388 this.set(key, value);
18389 }, this);else if (Array.isArray(set)) set.forEach(function (kv) {
18390 this.set(kv[0], kv[1]);
18391 }, this);else throw new TypeError('invalid argument');
18395 PseudoMap.prototype.forEach = function (fn, thisp) {
18396 thisp = thisp || this;
18397 Object.keys(this._data).forEach(function (k) {
18398 if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key);
18402 PseudoMap.prototype.has = function (k) {
18403 return !!find(this._data, k);
18406 PseudoMap.prototype.get = function (k) {
18407 var res = find(this._data, k);
18408 return res && res.value;
18411 PseudoMap.prototype.set = function (k, v) {
18412 set(this._data, k, v);
18415 PseudoMap.prototype.delete = function (k) {
18416 var res = find(this._data, k);
18419 delete this._data[res._index];
18424 PseudoMap.prototype.clear = function () {
18425 var data = Object.create(null);
18427 Object.defineProperty(this, '_data', {
18430 configurable: true,
18435 Object.defineProperty(PseudoMap.prototype, 'size', {
18437 return this._data.size;
18439 set: function (n) {},
18444 PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () {
18445 throw new Error('iterators are not implemented in this version');
18446 }; // Either identical, or both NaN
18449 function same(a, b) {
18450 return a === b || a !== a && b !== b;
18453 function Entry(k, v, i) {
18459 function find(data, k) {
18460 for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
18461 if (same(data[key].key, k)) return data[key];
18465 function set(data, k, v) {
18466 for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
18467 if (same(data[key].key, k)) {
18468 data[key].value = v;
18474 data[key] = new Entry(k, v, key);
18477 var map = createCommonjsModule(function (module) {
18478 if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true';
18480 if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
18481 module.exports = Map;
18483 module.exports = pseudomap;
18487 var yallist = Yallist;
18488 Yallist.Node = Node;
18489 Yallist.create = Yallist;
18491 function Yallist(list) {
18494 if (!(self instanceof Yallist)) {
18495 self = new Yallist();
18502 if (list && typeof list.forEach === 'function') {
18503 list.forEach(function (item) {
18506 } else if (arguments.length > 0) {
18507 for (var i = 0, l = arguments.length; i < l; i++) {
18508 self.push(arguments[i]);
18515 Yallist.prototype.removeNode = function (node) {
18516 if (node.list !== this) {
18517 throw new Error('removing node which does not belong to this list');
18520 var next = node.next;
18521 var prev = node.prev;
18531 if (node === this.head) {
18535 if (node === this.tail) {
18539 node.list.length--;
18545 Yallist.prototype.unshiftNode = function (node) {
18546 if (node === this.head) {
18551 node.list.removeNode(node);
18554 var head = this.head;
18571 Yallist.prototype.pushNode = function (node) {
18572 if (node === this.tail) {
18577 node.list.removeNode(node);
18580 var tail = this.tail;
18597 Yallist.prototype.push = function () {
18598 for (var i = 0, l = arguments.length; i < l; i++) {
18599 push(this, arguments[i]);
18602 return this.length;
18605 Yallist.prototype.unshift = function () {
18606 for (var i = 0, l = arguments.length; i < l; i++) {
18607 unshift(this, arguments[i]);
18610 return this.length;
18613 Yallist.prototype.pop = function () {
18618 var res = this.tail.value;
18619 this.tail = this.tail.prev;
18622 this.tail.next = null;
18631 Yallist.prototype.shift = function () {
18636 var res = this.head.value;
18637 this.head = this.head.next;
18640 this.head.prev = null;
18649 Yallist.prototype.forEach = function (fn, thisp) {
18650 thisp = thisp || this;
18652 for (var walker = this.head, i = 0; walker !== null; i++) {
18653 fn.call(thisp, walker.value, i, this);
18654 walker = walker.next;
18658 Yallist.prototype.forEachReverse = function (fn, thisp) {
18659 thisp = thisp || this;
18661 for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
18662 fn.call(thisp, walker.value, i, this);
18663 walker = walker.prev;
18667 Yallist.prototype.get = function (n) {
18668 for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
18669 // abort out of the list early if we hit a cycle
18670 walker = walker.next;
18673 if (i === n && walker !== null) {
18674 return walker.value;
18678 Yallist.prototype.getReverse = function (n) {
18679 for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
18680 // abort out of the list early if we hit a cycle
18681 walker = walker.prev;
18684 if (i === n && walker !== null) {
18685 return walker.value;
18689 Yallist.prototype.map = function (fn, thisp) {
18690 thisp = thisp || this;
18691 var res = new Yallist();
18693 for (var walker = this.head; walker !== null;) {
18694 res.push(fn.call(thisp, walker.value, this));
18695 walker = walker.next;
18701 Yallist.prototype.mapReverse = function (fn, thisp) {
18702 thisp = thisp || this;
18703 var res = new Yallist();
18705 for (var walker = this.tail; walker !== null;) {
18706 res.push(fn.call(thisp, walker.value, this));
18707 walker = walker.prev;
18713 Yallist.prototype.reduce = function (fn, initial) {
18715 var walker = this.head;
18717 if (arguments.length > 1) {
18719 } else if (this.head) {
18720 walker = this.head.next;
18721 acc = this.head.value;
18723 throw new TypeError('Reduce of empty list with no initial value');
18726 for (var i = 0; walker !== null; i++) {
18727 acc = fn(acc, walker.value, i);
18728 walker = walker.next;
18734 Yallist.prototype.reduceReverse = function (fn, initial) {
18736 var walker = this.tail;
18738 if (arguments.length > 1) {
18740 } else if (this.tail) {
18741 walker = this.tail.prev;
18742 acc = this.tail.value;
18744 throw new TypeError('Reduce of empty list with no initial value');
18747 for (var i = this.length - 1; walker !== null; i--) {
18748 acc = fn(acc, walker.value, i);
18749 walker = walker.prev;
18755 Yallist.prototype.toArray = function () {
18756 var arr = new Array(this.length);
18758 for (var i = 0, walker = this.head; walker !== null; i++) {
18759 arr[i] = walker.value;
18760 walker = walker.next;
18766 Yallist.prototype.toArrayReverse = function () {
18767 var arr = new Array(this.length);
18769 for (var i = 0, walker = this.tail; walker !== null; i++) {
18770 arr[i] = walker.value;
18771 walker = walker.prev;
18777 Yallist.prototype.slice = function (from, to) {
18778 to = to || this.length;
18787 from += this.length;
18790 var ret = new Yallist();
18792 if (to < from || to < 0) {
18800 if (to > this.length) {
18804 for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
18805 walker = walker.next;
18808 for (; walker !== null && i < to; i++, walker = walker.next) {
18809 ret.push(walker.value);
18815 Yallist.prototype.sliceReverse = function (from, to) {
18816 to = to || this.length;
18825 from += this.length;
18828 var ret = new Yallist();
18830 if (to < from || to < 0) {
18838 if (to > this.length) {
18842 for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
18843 walker = walker.prev;
18846 for (; walker !== null && i > from; i--, walker = walker.prev) {
18847 ret.push(walker.value);
18853 Yallist.prototype.reverse = function () {
18854 var head = this.head;
18855 var tail = this.tail;
18857 for (var walker = head; walker !== null; walker = walker.prev) {
18858 var p = walker.prev;
18859 walker.prev = walker.next;
18868 function push(self, item) {
18869 self.tail = new Node(item, self.tail, null, self);
18872 self.head = self.tail;
18878 function unshift(self, item) {
18879 self.head = new Node(item, null, self.head, self);
18882 self.tail = self.head;
18888 function Node(value, prev, next, list) {
18889 if (!(this instanceof Node)) {
18890 return new Node(value, prev, next, list);
18894 this.value = value;
18911 var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it,
18912 // or a fakey-fake PseudoMap in older versions.
18913 // A linked list to keep track of recently-used-ness
18914 // use symbols if possible, otherwise just _props
18916 var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1';
18920 makeSymbol = function (key) {
18921 return Symbol(key);
18924 makeSymbol = function (key) {
18929 var MAX = makeSymbol('max');
18930 var LENGTH = makeSymbol('length');
18931 var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
18932 var ALLOW_STALE = makeSymbol('allowStale');
18933 var MAX_AGE = makeSymbol('maxAge');
18934 var DISPOSE = makeSymbol('dispose');
18935 var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
18936 var LRU_LIST = makeSymbol('lruList');
18937 var CACHE = makeSymbol('cache');
18939 function naiveLength() {
18941 } // lruList is a yallist where the head is the youngest
18942 // item, and the tail is the oldest. the list contains the Hit
18943 // objects as the entries.
18944 // Each Hit object has a reference to its Yallist.Node. This
18947 // cache is a Map (or PseudoMap) that matches the keys to
18948 // the Yallist.Node object.
18951 function LRUCache(options) {
18952 if (!(this instanceof LRUCache)) {
18953 return new LRUCache(options);
18956 if (typeof options === 'number') {
18966 var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well.
18968 if (!max || !(typeof max === 'number') || max <= 0) {
18969 this[MAX] = Infinity;
18972 var lc = options.length || naiveLength;
18974 if (typeof lc !== 'function') {
18978 this[LENGTH_CALCULATOR] = lc;
18979 this[ALLOW_STALE] = options.stale || false;
18980 this[MAX_AGE] = options.maxAge || 0;
18981 this[DISPOSE] = options.dispose;
18982 this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
18984 } // resize the cache when the max changes.
18987 Object.defineProperty(LRUCache.prototype, 'max', {
18988 set: function (mL) {
18989 if (!mL || !(typeof mL === 'number') || mL <= 0) {
19001 Object.defineProperty(LRUCache.prototype, 'allowStale', {
19002 set: function (allowStale) {
19003 this[ALLOW_STALE] = !!allowStale;
19006 return this[ALLOW_STALE];
19010 Object.defineProperty(LRUCache.prototype, 'maxAge', {
19011 set: function (mA) {
19012 if (!mA || !(typeof mA === 'number') || mA < 0) {
19016 this[MAX_AGE] = mA;
19020 return this[MAX_AGE];
19023 }); // resize the cache when the lengthCalculator changes.
19025 Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
19026 set: function (lC) {
19027 if (typeof lC !== 'function') {
19031 if (lC !== this[LENGTH_CALCULATOR]) {
19032 this[LENGTH_CALCULATOR] = lC;
19034 this[LRU_LIST].forEach(function (hit) {
19035 hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
19036 this[LENGTH] += hit.length;
19043 return this[LENGTH_CALCULATOR];
19047 Object.defineProperty(LRUCache.prototype, 'length', {
19049 return this[LENGTH];
19053 Object.defineProperty(LRUCache.prototype, 'itemCount', {
19055 return this[LRU_LIST].length;
19060 LRUCache.prototype.rforEach = function (fn, thisp) {
19061 thisp = thisp || this;
19063 for (var walker = this[LRU_LIST].tail; walker !== null;) {
19064 var prev = walker.prev;
19065 forEachStep(this, fn, walker, thisp);
19070 function forEachStep(self, fn, node, thisp) {
19071 var hit = node.value;
19073 if (isStale(self, hit)) {
19076 if (!self[ALLOW_STALE]) {
19082 fn.call(thisp, hit.value, hit.key, self);
19086 LRUCache.prototype.forEach = function (fn, thisp) {
19087 thisp = thisp || this;
19089 for (var walker = this[LRU_LIST].head; walker !== null;) {
19090 var next = walker.next;
19091 forEachStep(this, fn, walker, thisp);
19096 LRUCache.prototype.keys = function () {
19097 return this[LRU_LIST].toArray().map(function (k) {
19102 LRUCache.prototype.values = function () {
19103 return this[LRU_LIST].toArray().map(function (k) {
19108 LRUCache.prototype.reset = function () {
19109 if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
19110 this[LRU_LIST].forEach(function (hit) {
19111 this[DISPOSE](hit.key, hit.value);
19115 this[CACHE] = new map(); // hash of items by key
19117 this[LRU_LIST] = new yallist(); // list of items in order of use recency
19119 this[LENGTH] = 0; // length of items in the list
19122 LRUCache.prototype.dump = function () {
19123 return this[LRU_LIST].map(function (hit) {
19124 if (!isStale(this, hit)) {
19128 e: hit.now + (hit.maxAge || 0)
19131 }, this).toArray().filter(function (h) {
19136 LRUCache.prototype.dumpLru = function () {
19137 return this[LRU_LIST];
19139 /* istanbul ignore next */
19142 LRUCache.prototype.inspect = function (n, opts) {
19143 var str = 'LRUCache {';
19144 var extras = false;
19145 var as = this[ALLOW_STALE];
19148 str += '\n allowStale: true';
19152 var max = this[MAX];
19154 if (max && max !== Infinity) {
19159 str += '\n max: ' + util$3.inspect(max, opts);
19163 var maxAge = this[MAX_AGE];
19170 str += '\n maxAge: ' + util$3.inspect(maxAge, opts);
19174 var lc = this[LENGTH_CALCULATOR];
19176 if (lc && lc !== naiveLength) {
19181 str += '\n length: ' + util$3.inspect(this[LENGTH], opts);
19185 var didFirst = false;
19186 this[LRU_LIST].forEach(function (item) {
19198 var key = util$3.inspect(item.key).split('\n').join('\n ');
19203 if (item.maxAge !== maxAge) {
19204 val.maxAge = item.maxAge;
19207 if (lc !== naiveLength) {
19208 val.length = item.length;
19211 if (isStale(this, item)) {
19215 val = util$3.inspect(val, opts).split('\n').join('\n ');
19216 str += key + ' => ' + val;
19219 if (didFirst || extras) {
19227 LRUCache.prototype.set = function (key, value, maxAge) {
19228 maxAge = maxAge || this[MAX_AGE];
19229 var now = maxAge ? Date.now() : 0;
19230 var len = this[LENGTH_CALCULATOR](value, key);
19232 if (this[CACHE].has(key)) {
19233 if (len > this[MAX]) {
19234 del(this, this[CACHE].get(key));
19238 var node = this[CACHE].get(key);
19239 var item = node.value; // dispose of the old one before overwriting
19240 // split out into 2 ifs for better coverage tracking
19242 if (this[DISPOSE]) {
19243 if (!this[NO_DISPOSE_ON_SET]) {
19244 this[DISPOSE](key, item.value);
19249 item.maxAge = maxAge;
19250 item.value = value;
19251 this[LENGTH] += len - item.length;
19258 var hit = new Entry$1(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
19260 if (hit.length > this[MAX]) {
19261 if (this[DISPOSE]) {
19262 this[DISPOSE](key, value);
19268 this[LENGTH] += hit.length;
19269 this[LRU_LIST].unshift(hit);
19270 this[CACHE].set(key, this[LRU_LIST].head);
19275 LRUCache.prototype.has = function (key) {
19276 if (!this[CACHE].has(key)) return false;
19277 var hit = this[CACHE].get(key).value;
19279 if (isStale(this, hit)) {
19286 LRUCache.prototype.get = function (key) {
19287 return get(this, key, true);
19290 LRUCache.prototype.peek = function (key) {
19291 return get(this, key, false);
19294 LRUCache.prototype.pop = function () {
19295 var node = this[LRU_LIST].tail;
19296 if (!node) return null;
19301 LRUCache.prototype.del = function (key) {
19302 del(this, this[CACHE].get(key));
19305 LRUCache.prototype.load = function (arr) {
19308 var now = Date.now(); // A previous serialized cache has the most recent items first
19310 for (var l = arr.length - 1; l >= 0; l--) {
19312 var expiresAt = hit.e || 0;
19314 if (expiresAt === 0) {
19315 // the item was created without expiration in a non aged cache
19316 this.set(hit.k, hit.v);
19318 var maxAge = expiresAt - now; // dont add already expired items
19321 this.set(hit.k, hit.v, maxAge);
19327 LRUCache.prototype.prune = function () {
19329 this[CACHE].forEach(function (value, key) {
19330 get(self, key, false);
19334 function get(self, key, doUse) {
19335 var node = self[CACHE].get(key);
19338 var hit = node.value;
19340 if (isStale(self, hit)) {
19342 if (!self[ALLOW_STALE]) hit = undefined;
19345 self[LRU_LIST].unshiftNode(node);
19349 if (hit) hit = hit.value;
19355 function isStale(self, hit) {
19356 if (!hit || !hit.maxAge && !self[MAX_AGE]) {
19361 var diff = Date.now() - hit.now;
19364 stale = diff > hit.maxAge;
19366 stale = self[MAX_AGE] && diff > self[MAX_AGE];
19372 function trim$2(self) {
19373 if (self[LENGTH] > self[MAX]) {
19374 for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
19375 // We know that we're about to delete this one, and also
19376 // what the next least recently used key will be, so just
19377 // go ahead and set it now.
19378 var prev = walker.prev;
19385 function del(self, node) {
19387 var hit = node.value;
19389 if (self[DISPOSE]) {
19390 self[DISPOSE](hit.key, hit.value);
19393 self[LENGTH] -= hit.length;
19394 self[CACHE].delete(hit.key);
19395 self[LRU_LIST].removeNode(node);
19397 } // classy, since V8 prefers predictable objects.
19400 function Entry$1(key, value, length, now, maxAge) {
19402 this.value = value;
19403 this.length = length;
19405 this.maxAge = maxAge || 0;
19408 var sigmund_1 = sigmund;
19410 function sigmund(subject, maxSessions) {
19411 maxSessions = maxSessions || 10;
19416 function psychoAnalyze(subject, session) {
19417 if (session > maxSessions) return;
19419 if (typeof subject === 'function' || typeof subject === 'undefined') {
19423 if (typeof subject !== 'object' || !subject || subject instanceof RE) {
19424 analysis += subject;
19428 if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
19429 notes.push(subject);
19431 Object.keys(subject).forEach(function (issue, _, __) {
19432 // pseudo-private values. skip those.
19433 if (issue.charAt(0) === '_') return;
19434 var to = typeof subject[issue];
19435 if (to === 'function' || to === 'undefined') return;
19437 psychoAnalyze(subject[issue], session + 1);
19441 psychoAnalyze(subject, 0);
19443 } // vim: set softtabstop=4 shiftwidth=4:
19445 var fnmatch = createCommonjsModule(function (module, exports) {
19446 // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch>
19447 var platform = typeof process === "object" ? process.platform : "win32";
19448 if (module) module.exports = minimatch;else exports.minimatch = minimatch;
19449 minimatch.Minimatch = Minimatch;
19450 var cache = minimatch.cache = new lruCache({
19453 GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
19454 var qmark = "[^/]" // * => any number of characters
19456 star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and .
19457 // not (^ or / followed by one or two dots followed by $ or /),
19458 // followed by anything, any number of times.
19460 twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot,
19461 // followed by anything, any number of times.
19463 twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp.
19465 reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true }
19467 function charSet(s) {
19468 return s.split("").reduce(function (set, c) {
19472 } // normalizes slashes.
19475 var slashSplit = /\/+/;
19476 minimatch.monkeyPatch = monkeyPatch;
19478 function monkeyPatch() {
19479 var desc = Object.getOwnPropertyDescriptor(String.prototype, "match");
19480 var orig = desc.value;
19482 desc.value = function (p) {
19483 if (p instanceof Minimatch) return p.match(this);
19484 return orig.call(this, p);
19487 Object.defineProperty(String.prototype, desc);
19490 minimatch.filter = filter;
19492 function filter(pattern, options) {
19493 options = options || {};
19494 return function (p, i, list) {
19495 return minimatch(p, pattern, options);
19499 function ext(a, b) {
19503 Object.keys(b).forEach(function (k) {
19506 Object.keys(a).forEach(function (k) {
19512 minimatch.defaults = function (def) {
19513 if (!def || !Object.keys(def).length) return minimatch;
19514 var orig = minimatch;
19516 var m = function minimatch(p, pattern, options) {
19517 return orig.minimatch(p, pattern, ext(def, options));
19520 m.Minimatch = function Minimatch(pattern, options) {
19521 return new orig.Minimatch(pattern, ext(def, options));
19527 Minimatch.defaults = function (def) {
19528 if (!def || !Object.keys(def).length) return Minimatch;
19529 return minimatch.defaults(def).Minimatch;
19532 function minimatch(p, pattern, options) {
19533 if (typeof pattern !== "string") {
19534 throw new TypeError("glob pattern string required");
19537 if (!options) options = {}; // shortcut: comments match nothing.
19539 if (!options.nocomment && pattern.charAt(0) === "#") {
19541 } // "" only matches ""
19544 if (pattern.trim() === "") return p === "";
19545 return new Minimatch(pattern, options).match(p);
19548 function Minimatch(pattern, options) {
19549 if (!(this instanceof Minimatch)) {
19550 return new Minimatch(pattern, options, cache);
19553 if (typeof pattern !== "string") {
19554 throw new TypeError("glob pattern string required");
19557 if (!options) options = {}; // windows: need to use /, not \
19558 // On other platforms, \ is a valid (albeit bad) filename char.
19560 if (platform === "win32") {
19561 pattern = pattern.split("\\").join("/");
19563 // these things aren't particularly big, but walking down the string
19564 // and turning it into a regexp can get pretty costly.
19567 var cacheKey = pattern + "\n" + sigmund_1(options);
19568 var cached = minimatch.cache.get(cacheKey);
19569 if (cached) return cached;
19570 minimatch.cache.set(cacheKey, this);
19571 this.options = options;
19573 this.pattern = pattern;
19574 this.regexp = null;
19575 this.negate = false;
19576 this.comment = false;
19577 this.empty = false; // make the set of regexps etc.
19582 Minimatch.prototype.make = make;
19585 // don't do it more than once.
19586 if (this._made) return;
19587 var pattern = this.pattern;
19588 var options = this.options; // empty patterns and comments match nothing.
19590 if (!options.nocomment && pattern.charAt(0) === "#") {
19591 this.comment = true;
19598 } // step 1: figure out negation, etc.
19601 this.parseNegate(); // step 2: expand braces
19603 var set = this.globSet = this.braceExpand();
19604 if (options.debug) console.error(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
19605 // matching patterns.
19606 // These will be regexps, except in the case of "**", which is
19607 // set to the GLOBSTAR object for globstar behavior,
19608 // and will not contain any / characters
19610 set = this.globParts = set.map(function (s) {
19611 return s.split(slashSplit);
19613 if (options.debug) console.error(this.pattern, set); // glob --> regexps
19615 set = set.map(function (s, si, set) {
19616 return s.map(this.parse, this);
19618 if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly.
19620 set = set.filter(function (s) {
19621 return -1 === s.indexOf(false);
19623 if (options.debug) console.error(this.pattern, set);
19627 Minimatch.prototype.parseNegate = parseNegate;
19629 function parseNegate() {
19630 var pattern = this.pattern,
19632 options = this.options,
19634 if (options.nonegate) return;
19636 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
19641 if (negateOffset) this.pattern = pattern.substr(negateOffset);
19642 this.negate = negate;
19643 } // Brace expansion:
19644 // a{b,c}d -> abd acd
19645 // a{b,}c -> abc ac
19646 // a{0..3}d -> a0d a1d a2d a3d
19647 // a{b,c{d,e}f}g -> abg acdfg acefg
19648 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
19650 // Invalid sets are not expanded.
19651 // a{2..}b -> a{2..}b
19655 minimatch.braceExpand = function (pattern, options) {
19656 return new Minimatch(pattern, options).braceExpand();
19659 Minimatch.prototype.braceExpand = braceExpand;
19661 function braceExpand(pattern, options) {
19662 options = options || this.options;
19663 pattern = typeof pattern === "undefined" ? this.pattern : pattern;
19665 if (typeof pattern === "undefined") {
19666 throw new Error("undefined pattern");
19669 if (options.nobrace || !pattern.match(/\{.*\}/)) {
19670 // shortcut. no need to expand.
19674 var escaping = false; // examples and comments refer to this crazy pattern:
19675 // a{b,c{d,e},{f,g}h}x{y,z}
19687 // everything before the first \{ is just a prefix.
19688 // So, we pluck that off, and work with the rest,
19689 // and then prepend it to everything we find.
19691 if (pattern.charAt(0) !== "{") {
19692 // console.error(pattern)
19695 for (var i = 0, l = pattern.length; i < l; i++) {
19696 var c = pattern.charAt(i); // console.error(i, c)
19699 escaping = !escaping;
19700 } else if (c === "{" && !escaping) {
19701 prefix = pattern.substr(0, i);
19704 } // actually no sets, all { were escaped.
19707 if (prefix === null) {
19708 // console.error("no sets")
19712 var tail = braceExpand(pattern.substr(i), options);
19713 return tail.map(function (t) {
19716 } // now we have something like:
19717 // {b,c{d,e},{f,g}h}x{y,z}
19718 // walk through the set, expanding each part, until
19719 // the set ends. then, we'll expand the suffix.
19720 // If the set only has a single member, then'll put the {} back
19721 // first, handle numeric sets, since they're easier
19724 var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/);
19727 // console.error("numset", numset[1], numset[2])
19728 var suf = braceExpand(pattern.substr(numset[0].length), options),
19729 start = +numset[1],
19731 inc = start > end ? -1 : 1,
19734 for (var i = start; i != end + inc; i += inc) {
19735 // append all the suffixes
19736 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
19737 set.push(i + suf[ii]);
19742 } // ok, walk through the set
19743 // We hope, somewhat optimistically, that there
19744 // will be a } at the end.
19745 // If the closing brace isn't found, then the pattern is
19746 // interpreted as braceExpand("\\" + pattern) so that
19747 // the leading \{ will be interpreted literally.
19750 var i = 1 // skip the \{
19757 function addMember() {
19760 } // console.error("Entering for")
19763 FOR: for (i = 1, l = pattern.length; i < l; i++) {
19764 var c = pattern.charAt(i); // console.error("", i, c)
19768 member += "\\" + c;
19781 depth--; // if this closes the actual set, then we're done
19784 addMember(); // pluck off the close-brace
19810 // now we've either finished the set, and the suffix is
19811 // pattern.substr(i), or we have *not* closed the set,
19812 // and need to escape the leading brace
19816 // console.error("didn't close", pattern)
19817 return braceExpand("\\" + pattern, options);
19818 } // x{y,z} -> ["xy", "xz"]
19819 // console.error("set", set)
19820 // console.error("suffix", pattern.substr(i))
19823 var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] ->
19824 // [["b"], ["cd", "ce"], ["fh", "gh"]]
19826 var addBraces = set.length === 1; // console.error("set pre-expanded", set)
19828 set = set.map(function (p) {
19829 return braceExpand(p, options);
19830 }); // console.error("set expanded", set)
19831 // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
19832 // ["b", "cd", "ce", "fh", "gh"]
19834 set = set.reduce(function (l, r) {
19835 return l.concat(r);
19839 set = set.map(function (s) {
19840 return "{" + s + "}";
19842 } // now attach the suffixes.
19847 for (var i = 0, l = set.length; i < l; i++) {
19848 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
19849 ret.push(set[i] + suf[ii]);
19854 } // parse a component of the expanded set.
19855 // At this point, no pattern may contain "/" in it
19856 // so we're going to return a 2d array, where each entry is the full
19857 // pattern, split on '/', and then turned into a regular expression.
19858 // A regexp is made at the end which joins each array with an
19859 // escaped /, and another full one which joins each regexp with |.
19861 // Following the lead of Bash 4.1, note that "**" only has special meaning
19862 // when it is the *only* thing in a path portion. Otherwise, any series
19863 // of * is equivalent to a single *. Globstar behavior is enabled by
19864 // default, and can be disabled by setting options.noglobstar.
19867 Minimatch.prototype.parse = parse;
19870 function parse(pattern, isSub) {
19871 var options = this.options; // shortcuts
19873 if (!options.noglobstar && pattern === "**") return GLOBSTAR;
19874 if (pattern === "") return "";
19876 hasMagic = !!options.nocase,
19877 escaping = false // ? => one single character
19879 patternListStack = [],
19884 classStart = -1 // . and .. never match anything that doesn't start with .,
19885 // even when options.dot is set.
19887 patternStart = pattern.charAt(0) === "." ? "" // anything
19888 // not (start or / followed by . or .. followed by / or end)
19889 : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)";
19891 function clearStateChar() {
19893 // we had some state-tracking character
19894 // that wasn't consumed by this pass.
19895 switch (stateChar) {
19907 re += "\\" + stateChar;
19915 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
19916 if (options.debug) {
19917 console.error("%s\t%s %s %j", pattern, i, re, c);
19918 } // skip over any that are escaped.
19921 if (escaping && reSpecials[c]) {
19929 // completely not allowed, even escaped.
19930 // Should already be path-split by now.
19937 // the various stateChar values
19938 // for the "extglob" stuff.
19945 if (options.debug) {
19946 console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c);
19947 } // all of those are literals inside a class, except that
19948 // the glob [!a] means [^a] in regexp
19952 if (c === "!" && i === classStart + 1) c = "^";
19955 } // if we already have a stateChar, then it means
19956 // that there was something like ** or +? in there.
19957 // Handle the stateChar, then proceed with this one.
19961 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
19962 // just clear the statechar *now*, rather than even diving into
19963 // the patternList stuff.
19965 if (options.noext) clearStateChar();
19979 plType = stateChar;
19980 patternListStack.push({
19984 }); // negation is (?:(?!js)[^/]*)
19986 re += stateChar === "!" ? "(?:(?!" : "(?:";
19991 if (inClass || !patternListStack.length) {
19998 plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*)
19999 // The others are (?:<pattern>)<type>
20010 // the default anyway
20016 if (inClass || !patternListStack.length || escaping) {
20024 // these are mostly the same in regexp and glob
20027 // swallow any state-tracking char before the [
20037 reClassStart = re.length;
20042 // a right bracket shall lose its special
20043 // meaning and represent itself in
20044 // a bracket expression if it occurs
20045 // first in the list. -- POSIX.2 2.8.3.2
20046 if (i === classStart + 1 || !inClass) {
20050 } // finish up the class.
20059 // swallow any state char that wasn't consumed
20065 } else if (reSpecials[c] && !(c === "^" && inClass)) {
20073 // handle the case where we left a class open.
20074 // "[abc" is valid, equivalent to "\[abc"
20078 // split where the last [ was, and escape it
20079 // this is a huge pita. We now have to re-walk
20080 // the contents of the would-be class to re-translate
20081 // any characters that were passed through as-is
20082 var cs = pattern.substr(classStart + 1),
20083 sp = this.parse(cs, SUBPARSE);
20084 re = re.substr(0, reClassStart) + "\\[" + sp[0];
20085 hasMagic = hasMagic || sp[1];
20086 } // handle the case where we had a +( thing at the *end*
20088 // each pattern list stack adds 3 chars, and we need to go through
20089 // and escape any | chars that were passed through as-is for the regexp.
20090 // Go through and escape them, taking care not to double-escape any
20091 // | chars that were already escaped.
20096 while (pl = patternListStack.pop()) {
20097 var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a |
20099 tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
20101 // the | isn't already escaped, so escape it.
20103 } // need to escape all those slashes *again*, without escaping the
20104 // one that we need for escaping the | character. As it works out,
20105 // escaping an even number of slashes can be done by simply repeating
20106 // it exactly after itself. That's why this trick works.
20108 // I am sorry that you have to see this.
20111 return $1 + $1 + $2 + "|";
20112 }); // console.error("tail=%j\n %s", tail, tail)
20114 var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
20116 re = re.slice(0, pl.reStart) + t + "\\(" + tail;
20117 } // handle trailing things that only matter at the very end.
20125 } // only need to apply the nodot start if the re starts with
20126 // something that could conceivably capture a dot
20129 var addPatternStart = false;
20131 switch (re.charAt(0)) {
20135 addPatternStart = true;
20136 } // if the re is not "" at this point, then we need to make sure
20137 // it doesn't match against an empty path part.
20138 // Otherwise a/* will match a/, which it should not.
20141 if (re !== "" && hasMagic) re = "(?=.)" + re;
20142 if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern.
20144 if (isSub === SUBPARSE) {
20145 return [re, hasMagic];
20146 } // skip the regexp for non-magical patterns
20147 // unescape anything in it, though, so that it'll be
20148 // an exact match against a file etc.
20152 return globUnescape(pattern);
20155 var flags = options.nocase ? "i" : "",
20156 regExp = new RegExp("^" + re + "$", flags);
20157 regExp._glob = pattern;
20162 minimatch.makeRe = function (pattern, options) {
20163 return new Minimatch(pattern, options || {}).makeRe();
20166 Minimatch.prototype.makeRe = makeRe;
20168 function makeRe() {
20169 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
20170 // pattern strings, or "**".
20172 // It's better to use .match(). This function shouldn't
20173 // be used, really, but it's pretty convenient sometimes,
20174 // when you just want to work with a regex.
20176 var set = this.set;
20177 if (!set.length) return this.regexp = false;
20178 var options = this.options;
20179 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot,
20180 flags = options.nocase ? "i" : "";
20181 var re = set.map(function (pattern) {
20182 return pattern.map(function (p) {
20183 return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
20185 }).join("|"); // must match entire pattern
20186 // ending in a * or ** will make it less strict.
20188 re = "^(?:" + re + ")$"; // can match anything, as long as it's not this.
20190 if (this.negate) re = "^(?!" + re + ").*$";
20193 return this.regexp = new RegExp(re, flags);
20195 return this.regexp = false;
20199 minimatch.match = function (list, pattern, options) {
20200 var mm = new Minimatch(pattern, options);
20201 list = list.filter(function (f) {
20202 return mm.match(f);
20205 if (options.nonull && !list.length) {
20206 list.push(pattern);
20212 Minimatch.prototype.match = match;
20214 function match(f, partial) {
20215 // console.error("match", f, this.pattern)
20216 // short-circuit in the case of busted things.
20218 if (this.comment) return false;
20219 if (this.empty) return f === "";
20220 if (f === "/" && partial) return true;
20221 var options = this.options; // windows: need to use /, not \
20222 // On other platforms, \ is a valid (albeit bad) filename char.
20224 if (platform === "win32") {
20225 f = f.split("\\").join("/");
20226 } // treat the test path as a set of pathparts.
20229 f = f.split(slashSplit);
20231 if (options.debug) {
20232 console.error(this.pattern, "split", f);
20233 } // just ONE of the pattern sets in this.set needs to match
20234 // in order for it to be valid. If negating, then just one
20235 // match means that we have failed.
20236 // Either way, return on the first hit.
20239 var set = this.set; // console.error(this.pattern, "set", set)
20241 for (var i = 0, l = set.length; i < l; i++) {
20242 var pattern = set[i];
20243 var hit = this.matchOne(f, pattern, partial);
20246 if (options.flipNegate) return true;
20247 return !this.negate;
20249 } // didn't get any hits. this is success if it's a negative
20250 // pattern, failure otherwise.
20253 if (options.flipNegate) return false;
20254 return this.negate;
20255 } // set partial to true to test if, for example,
20256 // "/a/b" matches the start of "/*/b/*/d"
20257 // Partial means, if you run out of file before you run
20258 // out of pattern, then that's fine, as long as all
20259 // the parts match.
20262 Minimatch.prototype.matchOne = function (file, pattern, partial) {
20263 var options = this.options;
20265 if (options.debug) {
20266 console.error("matchOne", {
20273 if (options.matchBase && pattern.length === 1) {
20274 file = path$2.basename(file.join("/")).split("/");
20277 if (options.debug) {
20278 console.error("matchOne", file.length, pattern.length);
20281 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
20282 if (options.debug) {
20283 console.error("matchOne loop");
20286 var p = pattern[pi],
20289 if (options.debug) {
20290 console.error(pattern, p, f);
20291 } // should be impossible.
20292 // some invalid regexp stuff in the set.
20295 if (p === false) return false;
20297 if (p === GLOBSTAR) {
20298 if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**"
20299 // a/**/b/**/c would match the following:
20304 // To do this, take the rest of the pattern after
20305 // the **, and see if it would match the file remainder.
20306 // If so, return success.
20307 // If not, the ** "swallows" a segment, and try again.
20308 // This is recursively awful.
20310 // a/**/b/**/c matching a/b/x/y/z/c
20313 // - matchOne(b/x/y/z/c, b/**/c)
20316 // - matchOne(x/y/z/c, c) -> no
20317 // - matchOne(y/z/c, c) -> no
20318 // - matchOne(z/c, c) -> no
20319 // - matchOne(c, c) yes, hit
20325 if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest.
20326 // We have found a match.
20327 // however, it will not swallow /.x, unless
20328 // options.dot is set.
20329 // . and .. are *never* matched by **, for explosively
20330 // exponential reasons.
20332 for (; fi < fl; fi++) {
20333 if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
20337 } // ok, let's see if we can swallow whatever we can.
20340 WHILE: while (fr < fl) {
20341 var swallowee = file[fr];
20343 if (options.debug) {
20344 console.error('\nglobstar while', file, fr, pattern, pr, swallowee);
20345 } // XXX remove this slice. Just pass the start index.
20348 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
20349 if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match.
20353 // can't swallow "." or ".." ever.
20354 // can only swallow ".foo" when explicitly asked.
20355 if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
20356 if (options.debug) console.error("dot detected!", file, fr, pattern, pr);
20358 } // ** swallows a segment, and continue.
20361 if (options.debug) console.error('globstar swallow a segment, and continue');
20364 } // no match was found.
20365 // However, in partial mode, we can't say this is necessarily over.
20366 // If there's more *pattern* left, then
20371 // console.error("\n>>> no match, partial?", file, fr, pattern, pr)
20372 if (fr === fl) return true;
20376 } // something other than **
20377 // non-magic patterns just have to match exactly
20378 // patterns with magic have been turned into regexps.
20383 if (typeof p === "string") {
20384 if (options.nocase) {
20385 hit = f.toLowerCase() === p.toLowerCase();
20390 if (options.debug) {
20391 console.error("string match", p, f, hit);
20396 if (options.debug) {
20397 console.error("pattern match", p, f, hit);
20401 if (!hit) return false;
20402 } // Note: ending in / means that we'll get a final ""
20403 // at the end of the pattern. This can only match a
20404 // corresponding "" at the end of the file.
20405 // If the file ends in /, then it can only match a
20406 // a pattern that ends in /, unless the pattern just
20407 // doesn't have any more for it. But, a/b/ should *not*
20408 // match "a/b/*", even though "" matches against the
20409 // [^/]*? pattern, except in partial mode, where it might
20410 // simply not be reached yet.
20411 // However, a/b/ should still satisfy a/*
20412 // now either we fell off the end of the pattern, or we're done.
20415 if (fi === fl && pi === pl) {
20416 // ran out of pattern and filename at the same time.
20419 } else if (fi === fl) {
20420 // ran out of file, but still had pattern left.
20421 // this is ok if we're doing the match as part of
20422 // a glob fs traversal.
20424 } else if (pi === pl) {
20425 // ran out of pattern, still have file left.
20426 // this is only acceptable if we're on the very last
20427 // empty segment of a file with a trailing slash.
20428 // a/* should match a/b/
20429 var emptyFileEnd = fi === fl - 1 && file[fi] === "";
20430 return emptyFileEnd;
20431 } // should be unreachable.
20434 throw new Error("wtf?");
20435 }; // replace stuff like \* with *
20438 function globUnescape(s) {
20439 return s.replace(/\\(.)/g, "$1");
20442 function regExpEscape(s) {
20443 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
20446 var fnmatch_1 = fnmatch.minimatch;
20448 var ini = createCommonjsModule(function (module, exports) {
20450 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
20451 return new (P || (P = Promise))(function (resolve, reject) {
20452 function fulfilled(value) {
20454 step(generator.next(value));
20460 function rejected(value) {
20462 step(generator["throw"](value));
20468 function step(result) {
20469 result.done ? resolve(result.value) : new P(function (resolve) {
20470 resolve(result.value);
20471 }).then(fulfilled, rejected);
20474 step((generator = generator.apply(thisArg, _arguments || [])).next());
20478 var __generator = this && this.__generator || function (thisArg, body) {
20481 sent: function () {
20482 if (t[0] & 1) throw t[1];
20496 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
20501 return function (v) {
20502 return step([n, v]);
20506 function step(op) {
20507 if (f) throw new TypeError("Generator is already executing.");
20510 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
20511 if (y = 0, t) op = [op[0] & 2, t.value];
20540 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
20545 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
20550 if (op[0] === 6 && _.label < t[1]) {
20556 if (t && _.label < t[2]) {
20564 if (t[2]) _.ops.pop();
20571 op = body.call(thisArg, _);
20579 if (op[0] & 5) throw op[1];
20581 value: op[0] ? op[1] : void 0,
20587 var __importStar = this && this.__importStar || function (mod) {
20588 if (mod && mod.__esModule) return mod;
20590 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
20591 result["default"] = mod;
20595 Object.defineProperty(exports, "__esModule", {
20599 var fs = __importStar(fs$3);
20601 * define the possible values:
\r
20602 * section: [section]
\r
20603 * param: key=value
\r
20604 * comment: ;this is a comment
\r
20609 section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
20610 param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
20611 comment: /^\s*[#;].*$/
20614 * Parses an .ini file
\r
20615 * @param file The location of the .ini file
\r
20618 function parse(file) {
20619 return __awaiter(this, void 0, void 0, function () {
20620 return __generator(this, function (_a) {
20623 , new Promise(function (resolve, reject) {
20624 fs.readFile(file, 'utf8', function (err, data) {
20630 resolve(parseString(data));
20637 exports.parse = parse;
20639 function parseSync(file) {
20640 return parseString(fs.readFileSync(file, 'utf8'));
20643 exports.parseSync = parseSync;
20645 function parseString(data) {
20646 var sectionBody = {};
20647 var sectionName = null;
20648 var value = [[sectionName, sectionBody]];
20649 var lines = data.split(/\r\n|\r|\n/);
20650 lines.forEach(function (line) {
20653 if (regex.comment.test(line)) {
20657 if (regex.param.test(line)) {
20658 match = line.match(regex.param);
20659 sectionBody[match[1]] = match[2];
20660 } else if (regex.section.test(line)) {
20661 match = line.match(regex.section);
20662 sectionName = match[1];
20664 value.push([sectionName, sectionBody]);
20670 exports.parseString = parseString;
20672 unwrapExports(ini);
20673 var ini_1 = ini.parse;
20674 var ini_2 = ini.parseSync;
20675 var ini_3 = ini.parseString;
20677 var name$1 = "editorconfig";
20678 var version$1 = "0.15.3";
20679 var description$1 = "EditorConfig File Locator and Interpreter for Node.js";
20684 var main$1 = "src/index.js";
20685 var contributors = [
20686 "Hong Xu (topbug.net)",
20687 "Jed Mao (https://github.com/jedmao/)",
20688 "Trey Hunner (http://treyhunner.com)"
20690 var directories = {
20695 clean: "rimraf dist",
20696 prebuild: "npm run clean",
20698 pretest: "npm run lint && npm run build && npm run copy && cmake .",
20700 "pretest:ci": "npm run pretest",
20701 "test:ci": "ctest -VV --output-on-failure .",
20702 lint: "npm run eclint && npm run tslint",
20703 eclint: "eclint check --indent_size ignore \"src/**\"",
20704 tslint: "tslint --project tsconfig.json --exclude package.json",
20705 copy: "cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib",
20706 prepub: "npm run lint && npm run build && npm run copy",
20707 pub: "npm publish ./dist"
20709 var repository$1 = {
20711 url: "git://github.com/editorconfig/editorconfig-core-js.git"
20713 var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues";
20714 var author$1 = "EditorConfig Team";
20715 var license$1 = "MIT";
20716 var dependencies$1 = {
20717 commander: "^2.19.0",
20718 "lru-cache": "^4.1.5",
20722 var devDependencies$1 = {
20723 "@types/mocha": "^5.2.6",
20724 "@types/node": "^10.12.29",
20725 "@types/semver": "^5.5.0",
20726 "cpy-cli": "^2.0.0",
20732 typescript: "^3.3.3333"
20736 version: version$1,
20737 description: description$1,
20738 keywords: keywords,
20740 contributors: contributors,
20741 directories: directories,
20742 scripts: scripts$1,
20743 repository: repository$1,
20746 license: license$1,
20747 dependencies: dependencies$1,
20748 devDependencies: devDependencies$1
20751 var _package$3 = /*#__PURE__*/Object.freeze({
20754 version: version$1,
20755 description: description$1,
20756 keywords: keywords,
20758 contributors: contributors,
20759 directories: directories,
20760 scripts: scripts$1,
20761 repository: repository$1,
20764 license: license$1,
20765 dependencies: dependencies$1,
20766 devDependencies: devDependencies$1,
20767 'default': _package$2
20770 var require$$4 = getCjsExportFromNamespace(_package$3);
20772 var src = createCommonjsModule(function (module, exports) {
20774 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
20775 return new (P || (P = Promise))(function (resolve, reject) {
20776 function fulfilled(value) {
20778 step(generator.next(value));
20784 function rejected(value) {
20786 step(generator["throw"](value));
20792 function step(result) {
20793 result.done ? resolve(result.value) : new P(function (resolve) {
20794 resolve(result.value);
20795 }).then(fulfilled, rejected);
20798 step((generator = generator.apply(thisArg, _arguments || [])).next());
20802 var __generator = this && this.__generator || function (thisArg, body) {
20805 sent: function () {
20806 if (t[0] & 1) throw t[1];
20820 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
20825 return function (v) {
20826 return step([n, v]);
20830 function step(op) {
20831 if (f) throw new TypeError("Generator is already executing.");
20834 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
20835 if (y = 0, t) op = [op[0] & 2, t.value];
20864 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
20869 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
20874 if (op[0] === 6 && _.label < t[1]) {
20880 if (t && _.label < t[2]) {
20888 if (t[2]) _.ops.pop();
20895 op = body.call(thisArg, _);
20903 if (op[0] & 5) throw op[1];
20905 value: op[0] ? op[1] : void 0,
20911 var __importStar = this && this.__importStar || function (mod) {
20912 if (mod && mod.__esModule) return mod;
20914 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
20915 result["default"] = mod;
20919 var __importDefault = this && this.__importDefault || function (mod) {
20920 return mod && mod.__esModule ? mod : {
20925 Object.defineProperty(exports, "__esModule", {
20929 var fs = __importStar(fs$3);
20931 var path = __importStar(path$2);
20933 var semver = __importStar(semver$2);
20935 var fnmatch_1 = __importDefault(fnmatch);
20937 exports.parseString = ini.parseString;
20939 var package_json_1 = __importDefault(require$$4);
20943 indent_style: true,
20945 insert_final_newline: true,
20946 trim_trailing_whitespace: true,
20950 function fnmatch$1(filepath, glob) {
20951 var matchOptions = {
20956 glob = glob.replace(/\*\*/g, '{*,**/**/**}');
20957 return fnmatch_1.default(filepath, glob, matchOptions);
20960 function getConfigFileNames(filepath, options) {
20964 filepath = path.dirname(filepath);
20965 paths.push(path.join(filepath, options.config));
20966 } while (filepath !== options.root);
20971 function processMatches(matches, version) {
20972 // Set indent_size to 'tab' if indent_size is unspecified and
20973 // indent_style is set to 'tab'.
20974 if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) {
20975 matches.indent_size = 'tab';
20976 } // Set tab_width to indent_size if indent_size is specified and
20977 // tab_width is unspecified
20980 if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') {
20981 matches.tab_width = matches.indent_size;
20982 } // Set indent_size to tab_width if indent_size is 'tab'
20985 if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') {
20986 matches.indent_size = matches.tab_width;
20992 function processOptions(options, filepath) {
20993 if (options === void 0) {
20998 config: options.config || '.editorconfig',
20999 version: options.version || package_json_1.default.version,
21000 root: path.resolve(options.root || path.parse(filepath).root)
21004 function buildFullGlob(pathPrefix, glob) {
21005 switch (glob.indexOf('/')) {
21007 glob = '**/' + glob;
21011 glob = glob.substring(1);
21015 return path.join(pathPrefix, glob);
21018 function extendProps(props, options) {
21019 if (props === void 0) {
21023 if (options === void 0) {
21027 for (var key in options) {
21028 if (options.hasOwnProperty(key)) {
21029 var value = options[key];
21030 var key2 = key.toLowerCase();
21031 var value2 = value;
21033 if (knownProps[key2]) {
21034 value2 = value.toLowerCase();
21038 value2 = JSON.parse(value);
21041 if (typeof value === 'undefined' || value === null) {
21042 // null and undefined are values specific to JSON (no special meaning
21043 // in editorconfig) & should just be returned as regular strings.
21044 value2 = String(value);
21047 props[key2] = value2;
21054 function parseFromConfigs(configs, filepath, options) {
21055 return processMatches(configs.reverse().reduce(function (matches, file) {
21056 var pathPrefix = path.dirname(file.name);
21057 file.contents.forEach(function (section) {
21058 var glob = section[0];
21059 var options2 = section[1];
21065 var fullGlob = buildFullGlob(pathPrefix, glob);
21067 if (!fnmatch$1(filepath, fullGlob)) {
21071 matches = extendProps(matches, options2);
21074 }, {}), options.version);
21077 function getConfigsForFiles(files) {
21080 for (var i in files) {
21081 if (files.hasOwnProperty(i)) {
21082 var file = files[i];
21083 var contents = ini.parseString(file.contents);
21089 if ((contents[0][1].root || '').toLowerCase() === 'true') {
21098 function readConfigFiles(filepaths) {
21099 return __awaiter(this, void 0, void 0, function () {
21100 return __generator(this, function (_a) {
21103 , Promise.all(filepaths.map(function (name) {
21104 return new Promise(function (resolve) {
21105 fs.readFile(name, 'utf8', function (err, data) {
21108 contents: err ? '' : data
21117 function readConfigFilesSync(filepaths) {
21120 filepaths.forEach(function (filepath) {
21122 file = fs.readFileSync(filepath, 'utf8');
21135 function opts(filepath, options) {
21136 if (options === void 0) {
21140 var resolvedFilePath = path.resolve(filepath);
21141 return [resolvedFilePath, processOptions(options, resolvedFilePath)];
21144 function parseFromFiles(filepath, files, options) {
21145 if (options === void 0) {
21149 return __awaiter(this, void 0, void 0, function () {
21150 var _a, resolvedFilePath, processedOptions;
21152 return __generator(this, function (_b) {
21153 _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1];
21156 , files.then(getConfigsForFiles).then(function (configs) {
21157 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
21163 exports.parseFromFiles = parseFromFiles;
21165 function parseFromFilesSync(filepath, files, options) {
21166 if (options === void 0) {
21170 var _a = opts(filepath, options),
21171 resolvedFilePath = _a[0],
21172 processedOptions = _a[1];
21174 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
21177 exports.parseFromFilesSync = parseFromFilesSync;
21179 function parse(_filepath, _options) {
21180 if (_options === void 0) {
21184 return __awaiter(this, void 0, void 0, function () {
21185 var _a, resolvedFilePath, processedOptions, filepaths;
21187 return __generator(this, function (_b) {
21188 _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1];
21189 filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
21192 , readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) {
21193 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
21199 exports.parse = parse;
21201 function parseSync(_filepath, _options) {
21202 if (_options === void 0) {
21206 var _a = opts(_filepath, _options),
21207 resolvedFilePath = _a[0],
21208 processedOptions = _a[1];
21210 var filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
21211 var files = readConfigFilesSync(filepaths);
21212 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
21215 exports.parseSync = parseSync;
21217 unwrapExports(src);
21218 var src_1 = src.parseString;
21219 var src_2 = src.parseFromFiles;
21220 var src_3 = src.parseFromFilesSync;
21221 var src_4 = src.parse;
21222 var src_5 = src.parseSync;
21224 var editorconfigToPrettier = editorConfigToPrettier;
21226 function removeUnset(editorConfig) {
21228 const keys = Object.keys(editorConfig);
21230 for (let i = 0; i < keys.length; i++) {
21231 const key = keys[i];
21233 if (editorConfig[key] === "unset") {
21237 result[key] = editorConfig[key];
21243 function editorConfigToPrettier(editorConfig) {
21244 if (!editorConfig) {
21248 editorConfig = removeUnset(editorConfig);
21250 if (Object.keys(editorConfig).length === 0) {
21256 if (editorConfig.indent_style) {
21257 result.useTabs = editorConfig.indent_style === "tab";
21260 if (editorConfig.indent_size === "tab") {
21261 result.useTabs = true;
21264 if (result.useTabs && editorConfig.tab_width) {
21265 result.tabWidth = editorConfig.tab_width;
21266 } else if (editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab") {
21267 result.tabWidth = editorConfig.indent_size;
21268 } else if (editorConfig.tab_width !== undefined) {
21269 result.tabWidth = editorConfig.tab_width;
21272 if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") {
21273 result.printWidth = editorConfig.max_line_length;
21276 if (editorConfig.quote_type === "single") {
21277 result.singleQuote = true;
21278 } else if (editorConfig.quote_type === "double") {
21279 result.singleQuote = false;
21282 if (["cr", "crlf", "lf"].indexOf(editorConfig.end_of_line) !== -1) {
21283 result.endOfLine = editorConfig.end_of_line;
21289 function markerExists(files, markers) {
21290 return markers.some(function (marker) {
21291 return files.some(function (file) {
21292 return file === marker;
21297 function traverseFolder(directory, levels, markers) {
21298 var files = fs$3.readdirSync(directory);
21300 if (levels === 0) {
21302 } else if (markerExists(files, markers)) {
21305 return traverseFolder(path$2.resolve(directory, '..'), levels - 1, markers);
21309 var findProjectRoot = function findRoot(dir, opts) {
21310 if (!dir) throw new Error("Directory not defined");
21312 var levels = opts.maxDepth || findRoot.MAX_DEPTH;
21313 var markers = opts.markers || findRoot.MARKERS;
21314 return traverseFolder(dir, levels, markers);
21318 var MARKERS = ['.git', '.hg'];
21319 findProjectRoot.MAX_DEPTH = MAX_DEPTH;
21320 findProjectRoot.MARKERS = MARKERS;
21322 const jsonStringifyMem = fn => mem_1(fn, {
21323 cacheKey: JSON.stringify
21326 const maybeParse = (filePath, parse) => {
21327 // findProjectRoot will throw an error if we pass a nonexistent directory to
21328 // it, which is possible, for example, when the path is given via
21329 // --stdin-filepath. So, first, traverse up until we find an existing
21331 let dirPath = path$2.dirname(path$2.resolve(filePath));
21332 const fsRoot = path$2.parse(dirPath).root;
21334 while (dirPath !== fsRoot && !fs$3.existsSync(dirPath)) {
21335 dirPath = path$2.dirname(dirPath);
21338 const root = findProjectRoot(dirPath);
21339 return filePath && parse(filePath, {
21344 const editorconfigAsyncNoCache = async filePath => {
21345 const editorConfig = await maybeParse(filePath, src.parse);
21346 return editorconfigToPrettier(editorConfig);
21349 const editorconfigAsyncWithCache = jsonStringifyMem(editorconfigAsyncNoCache);
21351 const editorconfigSyncNoCache = filePath => {
21352 return editorconfigToPrettier(maybeParse(filePath, src.parseSync));
21355 const editorconfigSyncWithCache = jsonStringifyMem(editorconfigSyncNoCache);
21357 function getLoadFunction(opts) {
21358 if (!opts.editorconfig) {
21363 return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache;
21366 return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache;
21369 function clearCache() {
21370 mem_1.clear(editorconfigSyncWithCache);
21371 mem_1.clear(editorconfigAsyncWithCache);
21374 var resolveConfigEditorconfig = {
21379 const ParserEND = 0x110000;
21381 class ParserError extends Error {
21382 /* istanbul ignore next */
21383 constructor(msg, filename, linenumber) {
21384 super('[ParserError] ' + msg, filename, linenumber);
21385 this.name = 'ParserError';
21386 this.code = 'ParserError';
21387 if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError);
21393 constructor(parser) {
21394 this.parser = parser;
21396 this.returned = null;
21397 this.result = null;
21398 this.resultTable = null;
21399 this.resultArr = null;
21410 this.ctx = this.obj;
21415 this.state = new State(this.parseStart);
21419 /* istanbul ignore next */
21420 if (str.length === 0 || str.length == null) return;
21421 this._buf = String(str);
21426 while (getNext === false || this.nextChar()) {
21427 getNext = this.runOne();
21434 if (this.char === 0x0A) {
21440 this.char = this._buf.codePointAt(this.ii);
21443 return this.haveBuffer();
21447 return this.ii < this._buf.length;
21451 return this.state.parser.call(this, this.state.returned);
21455 this.char = ParserEND;
21459 last = this.state.parser;
21461 } while (this.state.parser !== last);
21470 /* istanbul ignore next */
21471 if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn));
21472 this.state.parser = fn;
21477 return this.runOne();
21480 call(fn, returnWith) {
21481 if (returnWith) this.next(returnWith);
21482 this.stack.push(this.state);
21483 this.state = new State(fn);
21486 callNow(fn, returnWith) {
21487 this.call(fn, returnWith);
21488 return this.runOne();
21492 /* istanbul ignore next */
21493 if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'));
21494 if (value === undefined) value = this.state.buf;
21495 this.state = this.stack.pop();
21496 this.state.returned = value;
21500 this.return(value);
21501 return this.runOne();
21505 /* istanbul ignore next */
21506 if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'));
21507 this.state.buf += this._buf[this.ii];
21511 err.line = this.line;
21512 err.col = this.col;
21513 err.pos = this.pos;
21516 /* istanbul ignore next */
21520 throw new ParserError('Must declare a parseStart method');
21525 Parser.END = ParserEND;
21526 Parser.Error = ParserError;
21527 var parser$1 = Parser;
21529 var createDatetime = value => {
21530 const date = new Date(value);
21531 /* istanbul ignore if */
21534 throw new TypeError('Invalid Datetime');
21540 var formatNum = (d, num) => {
21543 while (num.length < d) num = '0' + num;
21548 class FloatingDateTime extends Date {
21549 constructor(value) {
21550 super(value + 'Z');
21551 this.isFloating = true;
21555 const date = `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
21556 const time = `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
21557 return `${date}T${time}`;
21562 var createDatetimeFloat = value => {
21563 const date = new FloatingDateTime(value);
21564 /* istanbul ignore if */
21567 throw new TypeError('Invalid Datetime');
21573 const DateTime = global.Date;
21575 class Date$1 extends DateTime {
21576 constructor(value) {
21578 this.isDate = true;
21582 return `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
21587 var createDate = value => {
21588 const date = new Date$1(value);
21589 /* istanbul ignore if */
21592 throw new TypeError('Invalid Datetime');
21598 class Time extends Date {
21599 constructor(value) {
21600 super(`0000-01-01T${value}Z`);
21601 this.isTime = true;
21605 return `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
21610 var createTime = value => {
21611 const date = new Time(value);
21612 /* istanbul ignore if */
21615 throw new TypeError('Invalid Datetime');
21621 /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */
21624 var tomlParser = makeParserClass(parser$1);
21625 var makeParserClass_1 = makeParserClass;
21627 class TomlError extends Error {
21630 this.name = 'TomlError';
21631 /* istanbul ignore next */
21633 if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError);
21634 this.fromTOML = true;
21635 this.wrapped = null;
21640 TomlError.wrap = err => {
21641 const terr = new TomlError(err.message);
21642 terr.code = err.code;
21643 terr.wrapped = err;
21647 var TomlError_1 = TomlError;
21648 const CTRL_I = 0x09;
21649 const CTRL_J = 0x0A;
21650 const CTRL_M = 0x0D;
21651 const CTRL_CHAR_BOUNDARY = 0x1F; // the last non-character in the latin1 region of unicode, except DEL
21653 const CHAR_SP = 0x20;
21654 const CHAR_QUOT = 0x22;
21655 const CHAR_NUM = 0x23;
21656 const CHAR_APOS = 0x27;
21657 const CHAR_PLUS = 0x2B;
21658 const CHAR_COMMA = 0x2C;
21659 const CHAR_HYPHEN = 0x2D;
21660 const CHAR_PERIOD = 0x2E;
21661 const CHAR_0 = 0x30;
21662 const CHAR_1 = 0x31;
21663 const CHAR_7 = 0x37;
21664 const CHAR_9 = 0x39;
21665 const CHAR_COLON = 0x3A;
21666 const CHAR_EQUALS = 0x3D;
21667 const CHAR_A = 0x41;
21668 const CHAR_E = 0x45;
21669 const CHAR_F = 0x46;
21670 const CHAR_T = 0x54;
21671 const CHAR_U = 0x55;
21672 const CHAR_Z = 0x5A;
21673 const CHAR_LOWBAR = 0x5F;
21674 const CHAR_a = 0x61;
21675 const CHAR_b = 0x62;
21676 const CHAR_e = 0x65;
21677 const CHAR_f = 0x66;
21678 const CHAR_i = 0x69;
21679 const CHAR_l = 0x6C;
21680 const CHAR_n = 0x6E;
21681 const CHAR_o = 0x6F;
21682 const CHAR_r = 0x72;
21683 const CHAR_s = 0x73;
21684 const CHAR_t = 0x74;
21685 const CHAR_u = 0x75;
21686 const CHAR_x = 0x78;
21687 const CHAR_z = 0x7A;
21688 const CHAR_LCUB = 0x7B;
21689 const CHAR_RCUB = 0x7D;
21690 const CHAR_LSQB = 0x5B;
21691 const CHAR_BSOL = 0x5C;
21692 const CHAR_RSQB = 0x5D;
21693 const CHAR_DEL = 0x7F;
21694 const SURROGATE_FIRST = 0xD800;
21695 const SURROGATE_LAST = 0xDFFF;
21697 [CHAR_b]: '\u0008',
21698 [CHAR_t]: '\u0009',
21699 [CHAR_n]: '\u000A',
21700 [CHAR_f]: '\u000C',
21701 [CHAR_r]: '\u000D',
21702 [CHAR_QUOT]: '\u0022',
21703 [CHAR_BSOL]: '\u005C'
21706 function isDigit(cp) {
21707 return cp >= CHAR_0 && cp <= CHAR_9;
21710 function isHexit(cp) {
21711 return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
21714 function isBit(cp) {
21715 return cp === CHAR_1 || cp === CHAR_0;
21718 function isOctit(cp) {
21719 return cp >= CHAR_0 && cp <= CHAR_7;
21722 function isAlphaNumQuoteHyphen(cp) {
21723 return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
21726 function isAlphaNumHyphen(cp) {
21727 return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
21730 const _type = Symbol('type');
21732 const _declared = Symbol('declared');
21734 const hasOwnProperty$1 = Object.prototype.hasOwnProperty;
21735 const defineProperty = Object.defineProperty;
21736 const descriptor = {
21737 configurable: true,
21743 function hasKey(obj, key) {
21744 if (hasOwnProperty$1.call(obj, key)) return true;
21745 if (key === '__proto__') defineProperty(obj, '__proto__', descriptor);
21749 const INLINE_TABLE = Symbol('inline-table');
21751 function InlineTable() {
21752 return Object.defineProperties({}, {
21754 value: INLINE_TABLE
21759 function isInlineTable(obj) {
21760 if (obj === null || typeof obj !== 'object') return false;
21761 return obj[_type] === INLINE_TABLE;
21764 const TABLE = Symbol('table');
21767 return Object.defineProperties({}, {
21778 function isTable(obj) {
21779 if (obj === null || typeof obj !== 'object') return false;
21780 return obj[_type] === TABLE;
21783 const _contentType = Symbol('content-type');
21785 const INLINE_LIST = Symbol('inline-list');
21787 function InlineList(type) {
21788 return Object.defineProperties([], {
21798 function isInlineList(obj) {
21799 if (obj === null || typeof obj !== 'object') return false;
21800 return obj[_type] === INLINE_LIST;
21803 const LIST = Symbol('list');
21806 return Object.defineProperties([], {
21813 function isList(obj) {
21814 if (obj === null || typeof obj !== 'object') return false;
21815 return obj[_type] === LIST;
21816 } // in an eval, to let bundlers not slurp in a util proxy
21822 const utilInspect = util$3.inspect;
21823 _custom = utilInspect.custom;
21825 /* eval require not available in transpiled bundle */
21827 /* istanbul ignore next */
21830 const _inspect = _custom || 'inspect';
21832 class BoxedBigInt {
21833 constructor(value) {
21835 this.value = global.BigInt.asIntN(64, value);
21837 /* istanbul ignore next */
21841 Object.defineProperty(this, _type, {
21847 return this.value === null;
21849 /* istanbul ignore next */
21853 return String(this.value);
21855 /* istanbul ignore next */
21859 return `[BigInt: ${this.toString()}]}`;
21868 const INTEGER = Symbol('integer');
21870 function Integer(value) {
21871 let num = Number(value); // -0 is a float thing, not an int thing
21873 if (Object.is(num, -0)) num = 0;
21874 /* istanbul ignore else */
21876 if (global.BigInt && !Number.isSafeInteger(num)) {
21877 return new BoxedBigInt(value);
21879 /* istanbul ignore next */
21880 return Object.defineProperties(new Number(num), {
21882 value: function () {
21883 return isNaN(this);
21890 value: () => `[Integer: ${value}]`
21896 function isInteger(obj) {
21897 if (obj === null || typeof obj !== 'object') return false;
21898 return obj[_type] === INTEGER;
21901 const FLOAT = Symbol('float');
21903 function Float(value) {
21904 /* istanbul ignore next */
21905 return Object.defineProperties(new Number(value), {
21910 value: () => `[Float: ${value}]`
21915 function isFloat(obj) {
21916 if (obj === null || typeof obj !== 'object') return false;
21917 return obj[_type] === FLOAT;
21920 function tomlType(value) {
21921 const type = typeof value;
21923 if (type === 'object') {
21924 /* istanbul ignore if */
21925 if (value === null) return 'null';
21926 if (value instanceof Date) return 'datetime';
21927 /* istanbul ignore else */
21929 if (_type in value) {
21930 switch (value[_type]) {
21932 return 'inline-table';
21935 return 'inline-list';
21937 /* istanbul ignore next */
21942 /* istanbul ignore next */
21959 function makeParserClass(Parser) {
21960 class TOMLParser extends Parser {
21963 this.ctx = this.obj = Table();
21969 return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
21973 return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
21977 if (this.char === Parser.END) {
21979 } else if (this.char === CHAR_LSQB) {
21980 return this.call(this.parseTableOrList);
21981 } else if (this.char === CHAR_NUM) {
21982 return this.call(this.parseComment);
21983 } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
21985 } else if (isAlphaNumQuoteHyphen(this.char)) {
21986 return this.callNow(this.parseAssignStatement);
21988 throw this.error(new TomlError(`Unknown character "${this.char}"`));
21990 } // HELPER, this strips any whitespace and comments to the end of the line
21991 // then RETURNS. Last state in a production.
21994 parseWhitespaceToEOL() {
21995 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
21997 } else if (this.char === CHAR_NUM) {
21998 return this.goto(this.parseComment);
21999 } else if (this.char === Parser.END || this.char === CTRL_J) {
22000 return this.return();
22002 throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'));
22005 /* ASSIGNMENT: key = value */
22008 parseAssignStatement() {
22009 return this.callNow(this.parseAssign, this.recordAssignStatement);
22012 recordAssignStatement(kv) {
22013 let target = this.ctx;
22014 let finalKey = kv.key.pop();
22016 for (let kw of kv.key) {
22017 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
22018 throw this.error(new TomlError("Can't redefine existing key"));
22021 target = target[kw] = target[kw] || Table();
22024 if (hasKey(target, finalKey)) {
22025 throw this.error(new TomlError("Can't redefine existing key"));
22026 } // unbox our numbers
22029 if (isInteger(kv.value) || isFloat(kv.value)) {
22030 target[finalKey] = kv.value.valueOf();
22032 target[finalKey] = kv.value;
22035 return this.goto(this.parseWhitespaceToEOL);
22037 /* ASSSIGNMENT expression, key = value possibly inside an inline table */
22041 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
22044 recordAssignKeyword(key) {
22045 if (this.state.resultTable) {
22046 this.state.resultTable.push(key);
22048 this.state.resultTable = [key];
22051 return this.goto(this.parseAssignKeywordPreDot);
22054 parseAssignKeywordPreDot() {
22055 if (this.char === CHAR_PERIOD) {
22056 return this.next(this.parseAssignKeywordPostDot);
22057 } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
22058 return this.goto(this.parseAssignEqual);
22062 parseAssignKeywordPostDot() {
22063 if (this.char !== CHAR_SP && this.char !== CTRL_I) {
22064 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
22068 parseAssignEqual() {
22069 if (this.char === CHAR_EQUALS) {
22070 return this.next(this.parseAssignPreValue);
22072 throw this.error(new TomlError('Invalid character, expected "="'));
22076 parseAssignPreValue() {
22077 if (this.char === CHAR_SP || this.char === CTRL_I) {
22080 return this.callNow(this.parseValue, this.recordAssignValue);
22084 recordAssignValue(value) {
22085 return this.returnNow({
22086 key: this.state.resultTable,
22090 /* COMMENTS: #...eol */
22095 if (this.char === Parser.END || this.char === CTRL_J) {
22096 return this.return();
22098 } while (this.nextChar());
22100 /* TABLES AND LISTS, [foo] and [[foo]] */
22103 parseTableOrList() {
22104 if (this.char === CHAR_LSQB) {
22105 this.next(this.parseList);
22107 return this.goto(this.parseTable);
22110 /* TABLE [foo.bar.baz] */
22114 this.ctx = this.obj;
22115 return this.goto(this.parseTableNext);
22119 if (this.char === CHAR_SP || this.char === CTRL_I) {
22122 return this.callNow(this.parseKeyword, this.parseTableMore);
22126 parseTableMore(keyword) {
22127 if (this.char === CHAR_SP || this.char === CTRL_I) {
22129 } else if (this.char === CHAR_RSQB) {
22130 if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
22131 throw this.error(new TomlError("Can't redefine existing key"));
22133 this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
22134 this.ctx[_declared] = true;
22137 return this.next(this.parseWhitespaceToEOL);
22138 } else if (this.char === CHAR_PERIOD) {
22139 if (!hasKey(this.ctx, keyword)) {
22140 this.ctx = this.ctx[keyword] = Table();
22141 } else if (isTable(this.ctx[keyword])) {
22142 this.ctx = this.ctx[keyword];
22143 } else if (isList(this.ctx[keyword])) {
22144 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
22146 throw this.error(new TomlError("Can't redefine existing key"));
22149 return this.next(this.parseTableNext);
22151 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
22154 /* LIST [[a.b.c]] */
22158 this.ctx = this.obj;
22159 return this.goto(this.parseListNext);
22163 if (this.char === CHAR_SP || this.char === CTRL_I) {
22166 return this.callNow(this.parseKeyword, this.parseListMore);
22170 parseListMore(keyword) {
22171 if (this.char === CHAR_SP || this.char === CTRL_I) {
22173 } else if (this.char === CHAR_RSQB) {
22174 if (!hasKey(this.ctx, keyword)) {
22175 this.ctx[keyword] = List();
22178 if (isInlineList(this.ctx[keyword])) {
22179 throw this.error(new TomlError("Can't extend an inline array"));
22180 } else if (isList(this.ctx[keyword])) {
22181 const next = Table();
22182 this.ctx[keyword].push(next);
22185 throw this.error(new TomlError("Can't redefine an existing key"));
22188 return this.next(this.parseListEnd);
22189 } else if (this.char === CHAR_PERIOD) {
22190 if (!hasKey(this.ctx, keyword)) {
22191 this.ctx = this.ctx[keyword] = Table();
22192 } else if (isInlineList(this.ctx[keyword])) {
22193 throw this.error(new TomlError("Can't extend an inline array"));
22194 } else if (isInlineTable(this.ctx[keyword])) {
22195 throw this.error(new TomlError("Can't extend an inline table"));
22196 } else if (isList(this.ctx[keyword])) {
22197 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
22198 } else if (isTable(this.ctx[keyword])) {
22199 this.ctx = this.ctx[keyword];
22201 throw this.error(new TomlError("Can't redefine an existing key"));
22204 return this.next(this.parseListNext);
22206 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
22210 parseListEnd(keyword) {
22211 if (this.char === CHAR_RSQB) {
22212 return this.next(this.parseWhitespaceToEOL);
22214 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
22217 /* VALUE string, number, boolean, inline list, inline object */
22221 if (this.char === Parser.END) {
22222 throw this.error(new TomlError('Key without value'));
22223 } else if (this.char === CHAR_QUOT) {
22224 return this.next(this.parseDoubleString);
22227 if (this.char === CHAR_APOS) {
22228 return this.next(this.parseSingleString);
22229 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22230 return this.goto(this.parseNumberSign);
22231 } else if (this.char === CHAR_i) {
22232 return this.next(this.parseInf);
22233 } else if (this.char === CHAR_n) {
22234 return this.next(this.parseNan);
22235 } else if (isDigit(this.char)) {
22236 return this.goto(this.parseNumberOrDateTime);
22237 } else if (this.char === CHAR_t || this.char === CHAR_f) {
22238 return this.goto(this.parseBoolean);
22239 } else if (this.char === CHAR_LSQB) {
22240 return this.call(this.parseInlineList, this.recordValue);
22241 } else if (this.char === CHAR_LCUB) {
22242 return this.call(this.parseInlineTable, this.recordValue);
22244 throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'));
22248 recordValue(value) {
22249 return this.returnNow(value);
22253 if (this.char === CHAR_n) {
22254 return this.next(this.parseInf2);
22256 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
22261 if (this.char === CHAR_f) {
22262 if (this.state.buf === '-') {
22263 return this.return(-Infinity);
22265 return this.return(Infinity);
22268 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
22273 if (this.char === CHAR_a) {
22274 return this.next(this.parseNan2);
22276 throw this.error(new TomlError('Unexpected character, expected "nan"'));
22281 if (this.char === CHAR_n) {
22282 return this.return(NaN);
22284 throw this.error(new TomlError('Unexpected character, expected "nan"'));
22287 /* KEYS, barewords or basic, literal, or dotted */
22291 if (this.char === CHAR_QUOT) {
22292 return this.next(this.parseBasicString);
22293 } else if (this.char === CHAR_APOS) {
22294 return this.next(this.parseLiteralString);
22296 return this.goto(this.parseBareKey);
22299 /* KEYS: barewords */
22304 if (this.char === Parser.END) {
22305 throw this.error(new TomlError('Key ended without value'));
22306 } else if (isAlphaNumHyphen(this.char)) {
22308 } else if (this.state.buf.length === 0) {
22309 throw this.error(new TomlError('Empty bare keys are not allowed'));
22311 return this.returnNow();
22313 } while (this.nextChar());
22315 /* STRINGS, single quoted (literal) */
22318 parseSingleString() {
22319 if (this.char === CHAR_APOS) {
22320 return this.next(this.parseLiteralMultiStringMaybe);
22322 return this.goto(this.parseLiteralString);
22326 parseLiteralString() {
22328 if (this.char === CHAR_APOS) {
22329 return this.return();
22330 } else if (this.atEndOfLine()) {
22331 throw this.error(new TomlError('Unterminated string'));
22332 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
22333 throw this.errorControlCharInString();
22337 } while (this.nextChar());
22340 parseLiteralMultiStringMaybe() {
22341 if (this.char === CHAR_APOS) {
22342 return this.next(this.parseLiteralMultiString);
22344 return this.returnNow();
22348 parseLiteralMultiString() {
22349 if (this.char === CTRL_M) {
22351 } else if (this.char === CTRL_J) {
22352 return this.next(this.parseLiteralMultiStringContent);
22354 return this.goto(this.parseLiteralMultiStringContent);
22358 parseLiteralMultiStringContent() {
22360 if (this.char === CHAR_APOS) {
22361 return this.next(this.parseLiteralMultiEnd);
22362 } else if (this.char === Parser.END) {
22363 throw this.error(new TomlError('Unterminated multi-line string'));
22364 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
22365 throw this.errorControlCharInString();
22369 } while (this.nextChar());
22372 parseLiteralMultiEnd() {
22373 if (this.char === CHAR_APOS) {
22374 return this.next(this.parseLiteralMultiEnd2);
22376 this.state.buf += "'";
22377 return this.goto(this.parseLiteralMultiStringContent);
22381 parseLiteralMultiEnd2() {
22382 if (this.char === CHAR_APOS) {
22383 return this.return();
22385 this.state.buf += "''";
22386 return this.goto(this.parseLiteralMultiStringContent);
22389 /* STRINGS double quoted */
22392 parseDoubleString() {
22393 if (this.char === CHAR_QUOT) {
22394 return this.next(this.parseMultiStringMaybe);
22396 return this.goto(this.parseBasicString);
22400 parseBasicString() {
22402 if (this.char === CHAR_BSOL) {
22403 return this.call(this.parseEscape, this.recordEscapeReplacement);
22404 } else if (this.char === CHAR_QUOT) {
22405 return this.return();
22406 } else if (this.atEndOfLine()) {
22407 throw this.error(new TomlError('Unterminated string'));
22408 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
22409 throw this.errorControlCharInString();
22413 } while (this.nextChar());
22416 recordEscapeReplacement(replacement) {
22417 this.state.buf += replacement;
22418 return this.goto(this.parseBasicString);
22421 parseMultiStringMaybe() {
22422 if (this.char === CHAR_QUOT) {
22423 return this.next(this.parseMultiString);
22425 return this.returnNow();
22429 parseMultiString() {
22430 if (this.char === CTRL_M) {
22432 } else if (this.char === CTRL_J) {
22433 return this.next(this.parseMultiStringContent);
22435 return this.goto(this.parseMultiStringContent);
22439 parseMultiStringContent() {
22441 if (this.char === CHAR_BSOL) {
22442 return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
22443 } else if (this.char === CHAR_QUOT) {
22444 return this.next(this.parseMultiEnd);
22445 } else if (this.char === Parser.END) {
22446 throw this.error(new TomlError('Unterminated multi-line string'));
22447 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
22448 throw this.errorControlCharInString();
22452 } while (this.nextChar());
22455 errorControlCharInString() {
22456 let displayCode = '\\u00';
22458 if (this.char < 16) {
22459 displayCode += '0';
22462 displayCode += this.char.toString(16);
22463 return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
22466 recordMultiEscapeReplacement(replacement) {
22467 this.state.buf += replacement;
22468 return this.goto(this.parseMultiStringContent);
22472 if (this.char === CHAR_QUOT) {
22473 return this.next(this.parseMultiEnd2);
22475 this.state.buf += '"';
22476 return this.goto(this.parseMultiStringContent);
22481 if (this.char === CHAR_QUOT) {
22482 return this.return();
22484 this.state.buf += '""';
22485 return this.goto(this.parseMultiStringContent);
22489 parseMultiEscape() {
22490 if (this.char === CTRL_M || this.char === CTRL_J) {
22491 return this.next(this.parseMultiTrim);
22492 } else if (this.char === CHAR_SP || this.char === CTRL_I) {
22493 return this.next(this.parsePreMultiTrim);
22495 return this.goto(this.parseEscape);
22499 parsePreMultiTrim() {
22500 if (this.char === CHAR_SP || this.char === CTRL_I) {
22502 } else if (this.char === CTRL_M || this.char === CTRL_J) {
22503 return this.next(this.parseMultiTrim);
22505 throw this.error(new TomlError("Can't escape whitespace"));
22510 // explicitly whitespace here, END should follow the same path as chars
22511 if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
22514 return this.returnNow();
22519 if (this.char in escapes) {
22520 return this.return(escapes[this.char]);
22521 } else if (this.char === CHAR_u) {
22522 return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
22523 } else if (this.char === CHAR_U) {
22524 return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
22526 throw this.error(new TomlError('Unknown escape character: ' + this.char));
22530 parseUnicodeReturn(char) {
22532 const codePoint = parseInt(char, 16);
22534 if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
22535 throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'));
22538 return this.returnNow(String.fromCodePoint(codePoint));
22540 throw this.error(TomlError.wrap(err));
22544 parseSmallUnicode() {
22545 if (!isHexit(this.char)) {
22546 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
22549 if (this.state.buf.length >= 4) return this.return();
22553 parseLargeUnicode() {
22554 if (!isHexit(this.char)) {
22555 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
22558 if (this.state.buf.length >= 8) return this.return();
22564 parseNumberSign() {
22566 return this.next(this.parseMaybeSignedInfOrNan);
22569 parseMaybeSignedInfOrNan() {
22570 if (this.char === CHAR_i) {
22571 return this.next(this.parseInf);
22572 } else if (this.char === CHAR_n) {
22573 return this.next(this.parseNan);
22575 return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
22579 parseNumberIntegerStart() {
22580 if (this.char === CHAR_0) {
22582 return this.next(this.parseNumberIntegerExponentOrDecimal);
22584 return this.goto(this.parseNumberInteger);
22588 parseNumberIntegerExponentOrDecimal() {
22589 if (this.char === CHAR_PERIOD) {
22591 return this.call(this.parseNoUnder, this.parseNumberFloat);
22592 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22594 return this.next(this.parseNumberExponentSign);
22596 return this.returnNow(Integer(this.state.buf));
22600 parseNumberInteger() {
22601 if (isDigit(this.char)) {
22603 } else if (this.char === CHAR_LOWBAR) {
22604 return this.call(this.parseNoUnder);
22605 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22607 return this.next(this.parseNumberExponentSign);
22608 } else if (this.char === CHAR_PERIOD) {
22610 return this.call(this.parseNoUnder, this.parseNumberFloat);
22612 const result = Integer(this.state.buf);
22613 /* istanbul ignore if */
22615 if (result.isNaN()) {
22616 throw this.error(new TomlError('Invalid number'));
22618 return this.returnNow(result);
22624 if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
22625 throw this.error(new TomlError('Unexpected character, expected digit'));
22626 } else if (this.atEndOfWord()) {
22627 throw this.error(new TomlError('Incomplete number'));
22630 return this.returnNow();
22633 parseNumberFloat() {
22634 if (this.char === CHAR_LOWBAR) {
22635 return this.call(this.parseNoUnder, this.parseNumberFloat);
22636 } else if (isDigit(this.char)) {
22638 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22640 return this.next(this.parseNumberExponentSign);
22642 return this.returnNow(Float(this.state.buf));
22646 parseNumberExponentSign() {
22647 if (isDigit(this.char)) {
22648 return this.goto(this.parseNumberExponent);
22649 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22651 this.call(this.parseNoUnder, this.parseNumberExponent);
22653 throw this.error(new TomlError('Unexpected character, expected -, + or digit'));
22657 parseNumberExponent() {
22658 if (isDigit(this.char)) {
22660 } else if (this.char === CHAR_LOWBAR) {
22661 return this.call(this.parseNoUnder);
22663 return this.returnNow(Float(this.state.buf));
22666 /* NUMBERS or DATETIMES */
22669 parseNumberOrDateTime() {
22670 if (this.char === CHAR_0) {
22672 return this.next(this.parseNumberBaseOrDateTime);
22674 return this.goto(this.parseNumberOrDateTimeOnly);
22678 parseNumberOrDateTimeOnly() {
22679 // note, if two zeros are in a row then it MUST be a date
22680 if (this.char === CHAR_LOWBAR) {
22681 return this.call(this.parseNoUnder, this.parseNumberInteger);
22682 } else if (isDigit(this.char)) {
22684 if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
22685 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22687 return this.next(this.parseNumberExponentSign);
22688 } else if (this.char === CHAR_PERIOD) {
22690 return this.call(this.parseNoUnder, this.parseNumberFloat);
22691 } else if (this.char === CHAR_HYPHEN) {
22692 return this.goto(this.parseDateTime);
22693 } else if (this.char === CHAR_COLON) {
22694 return this.goto(this.parseOnlyTimeHour);
22696 return this.returnNow(Integer(this.state.buf));
22700 parseDateTimeOnly() {
22701 if (this.state.buf.length < 4) {
22702 if (isDigit(this.char)) {
22703 return this.consume();
22704 } else if (this.char === CHAR_COLON) {
22705 return this.goto(this.parseOnlyTimeHour);
22707 throw this.error(new TomlError('Expected digit while parsing year part of a date'));
22710 if (this.char === CHAR_HYPHEN) {
22711 return this.goto(this.parseDateTime);
22713 throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'));
22718 parseNumberBaseOrDateTime() {
22719 if (this.char === CHAR_b) {
22721 return this.call(this.parseNoUnder, this.parseIntegerBin);
22722 } else if (this.char === CHAR_o) {
22724 return this.call(this.parseNoUnder, this.parseIntegerOct);
22725 } else if (this.char === CHAR_x) {
22727 return this.call(this.parseNoUnder, this.parseIntegerHex);
22728 } else if (this.char === CHAR_PERIOD) {
22729 return this.goto(this.parseNumberInteger);
22730 } else if (isDigit(this.char)) {
22731 return this.goto(this.parseDateTimeOnly);
22733 return this.returnNow(Integer(this.state.buf));
22737 parseIntegerHex() {
22738 if (isHexit(this.char)) {
22740 } else if (this.char === CHAR_LOWBAR) {
22741 return this.call(this.parseNoUnder);
22743 const result = Integer(this.state.buf);
22744 /* istanbul ignore if */
22746 if (result.isNaN()) {
22747 throw this.error(new TomlError('Invalid number'));
22749 return this.returnNow(result);
22754 parseIntegerOct() {
22755 if (isOctit(this.char)) {
22757 } else if (this.char === CHAR_LOWBAR) {
22758 return this.call(this.parseNoUnder);
22760 const result = Integer(this.state.buf);
22761 /* istanbul ignore if */
22763 if (result.isNaN()) {
22764 throw this.error(new TomlError('Invalid number'));
22766 return this.returnNow(result);
22771 parseIntegerBin() {
22772 if (isBit(this.char)) {
22774 } else if (this.char === CHAR_LOWBAR) {
22775 return this.call(this.parseNoUnder);
22777 const result = Integer(this.state.buf);
22778 /* istanbul ignore if */
22780 if (result.isNaN()) {
22781 throw this.error(new TomlError('Invalid number'));
22783 return this.returnNow(result);
22791 // we enter here having just consumed the year and about to consume the hyphen
22792 if (this.state.buf.length < 4) {
22793 throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'));
22796 this.state.result = this.state.buf;
22797 this.state.buf = '';
22798 return this.next(this.parseDateMonth);
22802 if (this.char === CHAR_HYPHEN) {
22803 if (this.state.buf.length < 2) {
22804 throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'));
22807 this.state.result += '-' + this.state.buf;
22808 this.state.buf = '';
22809 return this.next(this.parseDateDay);
22810 } else if (isDigit(this.char)) {
22813 throw this.error(new TomlError('Incomplete datetime'));
22818 if (this.char === CHAR_T || this.char === CHAR_SP) {
22819 if (this.state.buf.length < 2) {
22820 throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'));
22823 this.state.result += '-' + this.state.buf;
22824 this.state.buf = '';
22825 return this.next(this.parseStartTimeHour);
22826 } else if (this.atEndOfWord()) {
22827 return this.return(createDate(this.state.result + '-' + this.state.buf));
22828 } else if (isDigit(this.char)) {
22831 throw this.error(new TomlError('Incomplete datetime'));
22835 parseStartTimeHour() {
22836 if (this.atEndOfWord()) {
22837 return this.returnNow(createDate(this.state.result));
22839 return this.goto(this.parseTimeHour);
22844 if (this.char === CHAR_COLON) {
22845 if (this.state.buf.length < 2) {
22846 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
22849 this.state.result += 'T' + this.state.buf;
22850 this.state.buf = '';
22851 return this.next(this.parseTimeMin);
22852 } else if (isDigit(this.char)) {
22855 throw this.error(new TomlError('Incomplete datetime'));
22860 if (this.state.buf.length < 2 && isDigit(this.char)) {
22862 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
22863 this.state.result += ':' + this.state.buf;
22864 this.state.buf = '';
22865 return this.next(this.parseTimeSec);
22867 throw this.error(new TomlError('Incomplete datetime'));
22872 if (isDigit(this.char)) {
22875 if (this.state.buf.length === 2) {
22876 this.state.result += ':' + this.state.buf;
22877 this.state.buf = '';
22878 return this.next(this.parseTimeZoneOrFraction);
22881 throw this.error(new TomlError('Incomplete datetime'));
22885 parseOnlyTimeHour() {
22886 /* istanbul ignore else */
22887 if (this.char === CHAR_COLON) {
22888 if (this.state.buf.length < 2) {
22889 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
22892 this.state.result = this.state.buf;
22893 this.state.buf = '';
22894 return this.next(this.parseOnlyTimeMin);
22896 throw this.error(new TomlError('Incomplete time'));
22900 parseOnlyTimeMin() {
22901 if (this.state.buf.length < 2 && isDigit(this.char)) {
22903 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
22904 this.state.result += ':' + this.state.buf;
22905 this.state.buf = '';
22906 return this.next(this.parseOnlyTimeSec);
22908 throw this.error(new TomlError('Incomplete time'));
22912 parseOnlyTimeSec() {
22913 if (isDigit(this.char)) {
22916 if (this.state.buf.length === 2) {
22917 return this.next(this.parseOnlyTimeFractionMaybe);
22920 throw this.error(new TomlError('Incomplete time'));
22924 parseOnlyTimeFractionMaybe() {
22925 this.state.result += ':' + this.state.buf;
22927 if (this.char === CHAR_PERIOD) {
22928 this.state.buf = '';
22929 this.next(this.parseOnlyTimeFraction);
22931 return this.return(createTime(this.state.result));
22935 parseOnlyTimeFraction() {
22936 if (isDigit(this.char)) {
22938 } else if (this.atEndOfWord()) {
22939 if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'));
22940 return this.returnNow(createTime(this.state.result + '.' + this.state.buf));
22942 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22946 parseTimeZoneOrFraction() {
22947 if (this.char === CHAR_PERIOD) {
22949 this.next(this.parseDateTimeFraction);
22950 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22952 this.next(this.parseTimeZoneHour);
22953 } else if (this.char === CHAR_Z) {
22955 return this.return(createDatetime(this.state.result + this.state.buf));
22956 } else if (this.atEndOfWord()) {
22957 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
22959 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22963 parseDateTimeFraction() {
22964 if (isDigit(this.char)) {
22966 } else if (this.state.buf.length === 1) {
22967 throw this.error(new TomlError('Expected digit in milliseconds'));
22968 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22970 this.next(this.parseTimeZoneHour);
22971 } else if (this.char === CHAR_Z) {
22973 return this.return(createDatetime(this.state.result + this.state.buf));
22974 } else if (this.atEndOfWord()) {
22975 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
22977 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22981 parseTimeZoneHour() {
22982 if (isDigit(this.char)) {
22983 this.consume(); // FIXME: No more regexps
22985 if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
22987 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
22991 parseTimeZoneSep() {
22992 if (this.char === CHAR_COLON) {
22994 this.next(this.parseTimeZoneMin);
22996 throw this.error(new TomlError('Unexpected character in datetime, expected colon'));
23000 parseTimeZoneMin() {
23001 if (isDigit(this.char)) {
23003 if (/\d\d$/.test(this.state.buf)) return this.return(createDatetime(this.state.result + this.state.buf));
23005 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
23012 /* istanbul ignore else */
23013 if (this.char === CHAR_t) {
23015 return this.next(this.parseTrue_r);
23016 } else if (this.char === CHAR_f) {
23018 return this.next(this.parseFalse_a);
23023 if (this.char === CHAR_r) {
23025 return this.next(this.parseTrue_u);
23027 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23032 if (this.char === CHAR_u) {
23034 return this.next(this.parseTrue_e);
23036 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23041 if (this.char === CHAR_e) {
23042 return this.return(true);
23044 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23049 if (this.char === CHAR_a) {
23051 return this.next(this.parseFalse_l);
23053 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23058 if (this.char === CHAR_l) {
23060 return this.next(this.parseFalse_s);
23062 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23067 if (this.char === CHAR_s) {
23069 return this.next(this.parseFalse_e);
23071 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23076 if (this.char === CHAR_e) {
23077 return this.return(false);
23079 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23085 parseInlineList() {
23086 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
23088 } else if (this.char === Parser.END) {
23089 throw this.error(new TomlError('Unterminated inline array'));
23090 } else if (this.char === CHAR_NUM) {
23091 return this.call(this.parseComment);
23092 } else if (this.char === CHAR_RSQB) {
23093 return this.return(this.state.resultArr || InlineList());
23095 return this.callNow(this.parseValue, this.recordInlineListValue);
23099 recordInlineListValue(value) {
23100 if (this.state.resultArr) {
23101 const listType = this.state.resultArr[_contentType];
23102 const valueType = tomlType(value);
23104 if (listType !== valueType) {
23105 throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
23108 this.state.resultArr = InlineList(tomlType(value));
23111 if (isFloat(value) || isInteger(value)) {
23112 // unbox now that we've verified they're ok
23113 this.state.resultArr.push(value.valueOf());
23115 this.state.resultArr.push(value);
23118 return this.goto(this.parseInlineListNext);
23121 parseInlineListNext() {
23122 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
23124 } else if (this.char === CHAR_NUM) {
23125 return this.call(this.parseComment);
23126 } else if (this.char === CHAR_COMMA) {
23127 return this.next(this.parseInlineList);
23128 } else if (this.char === CHAR_RSQB) {
23129 return this.goto(this.parseInlineList);
23131 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
23137 parseInlineTable() {
23138 if (this.char === CHAR_SP || this.char === CTRL_I) {
23140 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
23141 throw this.error(new TomlError('Unterminated inline array'));
23142 } else if (this.char === CHAR_RCUB) {
23143 return this.return(this.state.resultTable || InlineTable());
23145 if (!this.state.resultTable) this.state.resultTable = InlineTable();
23146 return this.callNow(this.parseAssign, this.recordInlineTableValue);
23150 recordInlineTableValue(kv) {
23151 let target = this.state.resultTable;
23152 let finalKey = kv.key.pop();
23154 for (let kw of kv.key) {
23155 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
23156 throw this.error(new TomlError("Can't redefine existing key"));
23159 target = target[kw] = target[kw] || Table();
23162 if (hasKey(target, finalKey)) {
23163 throw this.error(new TomlError("Can't redefine existing key"));
23166 if (isInteger(kv.value) || isFloat(kv.value)) {
23167 target[finalKey] = kv.value.valueOf();
23169 target[finalKey] = kv.value;
23172 return this.goto(this.parseInlineTableNext);
23175 parseInlineTableNext() {
23176 if (this.char === CHAR_SP || this.char === CTRL_I) {
23178 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
23179 throw this.error(new TomlError('Unterminated inline array'));
23180 } else if (this.char === CHAR_COMMA) {
23181 return this.next(this.parseInlineTable);
23182 } else if (this.char === CHAR_RCUB) {
23183 return this.goto(this.parseInlineTable);
23185 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
23193 tomlParser.makeParserClass = makeParserClass_1;
23194 tomlParser.TomlError = TomlError_1;
23196 var parsePrettyError = prettyError;
23198 function prettyError(err, buf) {
23199 /* istanbul ignore if */
23200 if (err.pos == null || err.line == null) return err;
23201 let msg = err.message;
23202 msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`;
23203 /* istanbul ignore else */
23205 if (buf && buf.split) {
23206 const lines = buf.split(/\n/);
23207 const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
23208 let linePadding = ' ';
23210 while (linePadding.length < lineNumWidth) linePadding += ' ';
23212 for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
23213 let lineNum = String(ii + 1);
23214 if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum;
23216 if (err.line === ii) {
23217 msg += lineNum + '> ' + lines[ii] + '\n';
23218 msg += linePadding + ' ';
23220 for (let hh = 0; hh < err.col; ++hh) {
23226 msg += lineNum + ': ' + lines[ii] + '\n';
23231 err.message = msg + '\n';
23235 var parseString_1 = parseString;
23237 function parseString(str) {
23238 if (global.Buffer && global.Buffer.isBuffer(str)) {
23239 str = str.toString('utf8');
23242 const parser = new tomlParser();
23246 return parser.finish();
23248 throw parsePrettyError(err, str);
23252 var loadToml = function (filePath, content) {
23254 return parseString_1(content);
23256 error.message = `TOML Error in ${filePath}:\n${error.message}`;
23261 var caller = function () {
23262 // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
23263 var origPrepareStackTrace = Error.prepareStackTrace;
23265 Error.prepareStackTrace = function (_, stack) {
23269 var stack = new Error().stack;
23270 Error.prepareStackTrace = origPrepareStackTrace;
23271 return stack[2].getFileName();
23274 var pathParse = createCommonjsModule(function (module) {
23276 var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash,
23277 // tail] windows-only
23279 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext]
23281 var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
23282 var win32 = {}; // Function to split a filename into [root, dir, basename, ext]
23284 function win32SplitPath(filename) {
23285 // Separate device+slash from tail
23286 var result = splitDeviceRe.exec(filename),
23287 device = (result[1] || '') + (result[2] || ''),
23288 tail = result[3] || ''; // Split the tail into dir, basename and extension
23290 var result2 = splitTailRe.exec(tail),
23292 basename = result2[2],
23294 return [device, dir, basename, ext];
23297 win32.parse = function (pathString) {
23298 if (typeof pathString !== 'string') {
23299 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
23302 var allParts = win32SplitPath(pathString);
23304 if (!allParts || allParts.length !== 4) {
23305 throw new TypeError("Invalid path '" + pathString + "'");
23310 dir: allParts[0] + allParts[1].slice(0, -1),
23313 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
23315 }; // Split a filename into [root, dir, basename, ext], unix version
23316 // 'root' is just a slash, or nothing.
23319 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
23322 function posixSplitPath(filename) {
23323 return splitPathRe.exec(filename).slice(1);
23326 posix.parse = function (pathString) {
23327 if (typeof pathString !== 'string') {
23328 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
23331 var allParts = posixSplitPath(pathString);
23333 if (!allParts || allParts.length !== 4) {
23334 throw new TypeError("Invalid path '" + pathString + "'");
23337 allParts[1] = allParts[1] || '';
23338 allParts[2] = allParts[2] || '';
23339 allParts[3] = allParts[3] || '';
23342 dir: allParts[0] + allParts[1].slice(0, -1),
23345 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
23349 if (isWindows) module.exports = win32.parse;else
23351 module.exports = posix.parse;
23352 module.exports.posix = posix.parse;
23353 module.exports.win32 = win32.parse;
23355 var pathParse_1 = pathParse.posix;
23356 var pathParse_2 = pathParse.win32;
23358 var parse$2 = path$2.parse || pathParse;
23360 var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
23363 if (/^([A-Za-z]:)/.test(absoluteStart)) {
23365 } else if (/^\\\\/.test(absoluteStart)) {
23369 var paths = [absoluteStart];
23370 var parsed = parse$2(absoluteStart);
23372 while (parsed.dir !== paths[paths.length - 1]) {
23373 paths.push(parsed.dir);
23374 parsed = parse$2(parsed.dir);
23377 return paths.reduce(function (dirs, aPath) {
23378 return dirs.concat(modules.map(function (moduleDir) {
23379 return path$2.resolve(prefix, aPath, moduleDir);
23384 var nodeModulesPaths = function nodeModulesPaths(start, opts, request) {
23385 var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'];
23387 if (opts && typeof opts.paths === 'function') {
23388 return opts.paths(request, start, function () {
23389 return getNodeModulesDirs(start, modules);
23393 var dirs = getNodeModulesDirs(start, modules);
23394 return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
23397 var normalizeOptions$2 = function (x, opts) {
23399 * This file is purposefully a passthrough. It's expected that third-party
23400 * environments will override it at runtime in order to inject special logic
23401 * into `resolve` (by manipulating the options). One such example is the PnP
23402 * code path in Yarn.
23408 var async_hooks = ">= 8";
23409 var buffer_ieee754 = "< 0.9.7";
23411 var child_process = true;
23412 var cluster = true;
23413 var console$1 = true;
23414 var constants$1 = true;
23416 var _debug_agent = ">= 1 && < 8";
23417 var _debugger = "< 8";
23422 var freelist = "< 6";
23424 var _http_agent = ">= 0.11.1";
23425 var _http_client = ">= 0.11.1";
23426 var _http_common = ">= 0.11.1";
23427 var _http_incoming = ">= 0.11.1";
23428 var _http_outgoing = ">= 0.11.1";
23429 var _http_server = ">= 0.11.1";
23431 var http2 = ">= 8.8";
23433 var inspector = ">= 8.0.0";
23434 var _linklist = "< 8";
23435 var module$1 = true;
23439 var perf_hooks = ">= 8.5";
23440 var process$1 = ">= 1";
23441 var punycode = true;
23442 var querystring = true;
23443 var readline = true;
23445 var smalloc = ">= 0.11.5 && < 3";
23446 var _stream_duplex = ">= 0.9.4";
23447 var _stream_transform = ">= 0.9.4";
23448 var _stream_wrap = ">= 1.4.1";
23449 var _stream_passthrough = ">= 0.9.4";
23450 var _stream_readable = ">= 0.9.4";
23451 var _stream_writable = ">= 0.9.4";
23453 var string_decoder = true;
23456 var _tls_common = ">= 0.11.13";
23457 var _tls_legacy = ">= 0.11.3 && < 10";
23458 var _tls_wrap = ">= 0.11.3";
23460 var trace_events = ">= 10";
23466 var wasi = ">= 13.4 && < 13.5";
23467 var worker_threads = ">= 11.7";
23471 async_hooks: async_hooks,
23472 buffer_ieee754: buffer_ieee754,
23474 child_process: child_process,
23476 console: console$1,
23477 constants: constants$1,
23479 _debug_agent: _debug_agent,
23480 _debugger: _debugger,
23485 freelist: freelist,
23491 _http_agent: _http_agent,
23492 _http_client: _http_client,
23493 _http_common: _http_common,
23494 _http_incoming: _http_incoming,
23495 _http_outgoing: _http_outgoing,
23496 _http_server: _http_server,
23500 inspector: inspector,
23501 _linklist: _linklist,
23504 "node-inspect/lib/_inspect": ">= 7.6.0 && < 12",
23505 "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12",
23506 "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12",
23509 perf_hooks: perf_hooks,
23510 process: process$1,
23511 punycode: punycode,
23512 querystring: querystring,
23513 readline: readline,
23516 _stream_duplex: _stream_duplex,
23517 _stream_transform: _stream_transform,
23518 _stream_wrap: _stream_wrap,
23519 _stream_passthrough: _stream_passthrough,
23520 _stream_readable: _stream_readable,
23521 _stream_writable: _stream_writable,
23523 string_decoder: string_decoder,
23526 _tls_common: _tls_common,
23527 _tls_legacy: _tls_legacy,
23528 _tls_wrap: _tls_wrap,
23530 trace_events: trace_events,
23534 "v8/tools/arguments": ">= 10 && < 12",
23535 "v8/tools/codemap": [
23539 "v8/tools/consarray": [
23543 "v8/tools/csvparser": [
23547 "v8/tools/logreader": [
23551 "v8/tools/profile_view": [
23555 "v8/tools/splaytree": [
23562 worker_threads: worker_threads,
23566 var core$2 = /*#__PURE__*/Object.freeze({
23569 async_hooks: async_hooks,
23570 buffer_ieee754: buffer_ieee754,
23572 child_process: child_process,
23574 console: console$1,
23575 constants: constants$1,
23577 _debug_agent: _debug_agent,
23578 _debugger: _debugger,
23583 freelist: freelist,
23585 _http_agent: _http_agent,
23586 _http_client: _http_client,
23587 _http_common: _http_common,
23588 _http_incoming: _http_incoming,
23589 _http_outgoing: _http_outgoing,
23590 _http_server: _http_server,
23594 inspector: inspector,
23595 _linklist: _linklist,
23600 perf_hooks: perf_hooks,
23601 process: process$1,
23602 punycode: punycode,
23603 querystring: querystring,
23604 readline: readline,
23607 _stream_duplex: _stream_duplex,
23608 _stream_transform: _stream_transform,
23609 _stream_wrap: _stream_wrap,
23610 _stream_passthrough: _stream_passthrough,
23611 _stream_readable: _stream_readable,
23612 _stream_writable: _stream_writable,
23614 string_decoder: string_decoder,
23617 _tls_common: _tls_common,
23618 _tls_legacy: _tls_legacy,
23619 _tls_wrap: _tls_wrap,
23621 trace_events: trace_events,
23628 worker_threads: worker_threads,
23633 var data = getCjsExportFromNamespace(core$2);
23635 var current = process.versions && process.versions.node && process.versions.node.split('.') || [];
23637 function specifierIncluded(specifier) {
23638 var parts = specifier.split(' ');
23639 var op = parts.length > 1 ? parts[0] : '=';
23640 var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
23642 for (var i = 0; i < 3; ++i) {
23643 var cur = Number(current[i] || 0);
23644 var ver = Number(versionParts[i] || 0);
23647 continue; // eslint-disable-line no-restricted-syntax, no-continue
23652 } else if (op === '>=') {
23659 return op === '>=';
23662 function matchesRange(range) {
23663 var specifiers = range.split(/ ?&& ?/);
23665 if (specifiers.length === 0) {
23669 for (var i = 0; i < specifiers.length; ++i) {
23670 if (!specifierIncluded(specifiers[i])) {
23678 function versionIncluded(specifierValue) {
23679 if (typeof specifierValue === 'boolean') {
23680 return specifierValue;
23683 if (specifierValue && typeof specifierValue === 'object') {
23684 for (var i = 0; i < specifierValue.length; ++i) {
23685 if (matchesRange(specifierValue[i])) {
23693 return matchesRange(specifierValue);
23698 for (var mod in data) {
23699 // eslint-disable-line no-restricted-syntax
23700 if (Object.prototype.hasOwnProperty.call(data, mod)) {
23701 core$3[mod] = versionIncluded(data[mod]);
23705 var core_1 = core$3;
23707 var isCore = function isCore(x) {
23708 return Object.prototype.hasOwnProperty.call(core_1, x);
23711 var realpath = fs$3.realpath && typeof fs$3.realpath.native === 'function' ? fs$3.realpath.native : fs$3.realpath;
23713 var defaultIsFile = function isFile(file, cb) {
23714 fs$3.stat(file, function (err, stat) {
23716 return cb(null, stat.isFile() || stat.isFIFO());
23719 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
23724 var defaultIsDir = function isDirectory(dir, cb) {
23725 fs$3.stat(dir, function (err, stat) {
23727 return cb(null, stat.isDirectory());
23730 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
23735 var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts, cb) {
23736 if (opts && opts.preserveSymlinks === false) {
23737 realpath(x, function (realPathErr, realPath) {
23738 if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);else cb(null, realPathErr ? x : realPath);
23745 var getPackageCandidates = function getPackageCandidates(x, start, opts) {
23746 var dirs = nodeModulesPaths(start, opts, x);
23748 for (var i = 0; i < dirs.length; i++) {
23749 dirs[i] = path$2.join(dirs[i], x);
23755 var async = function resolve(x, options, callback) {
23757 var opts = options;
23759 if (typeof options === 'function') {
23764 if (typeof x !== 'string') {
23765 var err = new TypeError('Path must be a string.');
23766 return process.nextTick(function () {
23771 opts = normalizeOptions$2(x, opts);
23772 var isFile = opts.isFile || defaultIsFile;
23773 var isDirectory = opts.isDirectory || defaultIsDir;
23774 var readFile = opts.readFile || fs$3.readFile;
23775 var packageIterator = opts.packageIterator;
23776 var extensions = opts.extensions || ['.js'];
23777 var basedir = opts.basedir || path$2.dirname(caller());
23778 var parent = opts.filename || basedir;
23779 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
23781 var absoluteStart = path$2.resolve(basedir);
23782 maybeUnwrapSymlink(absoluteStart, opts, function (err, realStart) {
23783 if (err) cb(err);else init(realStart);
23787 function init(basedir) {
23788 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
23789 res = path$2.resolve(basedir, x);
23790 if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
23792 if (/\/$/.test(x) && res === basedir) {
23793 loadAsDirectory(res, opts.package, onfile);
23794 } else loadAsFile(res, opts.package, onfile);
23795 } else if (isCore(x)) {
23796 return cb(null, x);
23797 } else loadNodeModules(x, basedir, function (err, n, pkg) {
23798 if (err) cb(err);else if (n) {
23799 return maybeUnwrapSymlink(n, opts, function (err, realN) {
23803 cb(null, realN, pkg);
23807 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
23808 moduleError.code = 'MODULE_NOT_FOUND';
23814 function onfile(err, m, pkg) {
23815 if (err) cb(err);else if (m) cb(null, m, pkg);else loadAsDirectory(res, function (err, d, pkg) {
23816 if (err) cb(err);else if (d) {
23817 maybeUnwrapSymlink(d, opts, function (err, realD) {
23821 cb(null, realD, pkg);
23825 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
23826 moduleError.code = 'MODULE_NOT_FOUND';
23832 function loadAsFile(x, thePackage, callback) {
23833 var loadAsFilePackage = thePackage;
23836 if (typeof loadAsFilePackage === 'function') {
23837 cb = loadAsFilePackage;
23838 loadAsFilePackage = undefined;
23841 var exts = [''].concat(extensions);
23842 load(exts, x, loadAsFilePackage);
23844 function load(exts, x, loadPackage) {
23845 if (exts.length === 0) return cb(null, undefined, loadPackage);
23846 var file = x + exts[0];
23847 var pkg = loadPackage;
23848 if (pkg) onpkg(null, pkg);else loadpkg(path$2.dirname(file), onpkg);
23850 function onpkg(err, pkg_, dir) {
23852 if (err) return cb(err);
23854 if (dir && pkg && opts.pathFilter) {
23855 var rfile = path$2.relative(dir, file);
23856 var rel = rfile.slice(0, rfile.length - exts[0].length);
23857 var r = opts.pathFilter(pkg, x, rel);
23858 if (r) return load([''].concat(extensions.slice()), path$2.resolve(dir, r), pkg);
23861 isFile(file, onex);
23864 function onex(err, ex) {
23865 if (err) return cb(err);
23866 if (ex) return cb(null, file, pkg);
23867 load(exts.slice(1), x, pkg);
23872 function loadpkg(dir, cb) {
23873 if (dir === '' || dir === '/') return cb(null);
23875 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
23879 if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb(null);
23880 maybeUnwrapSymlink(dir, opts, function (unwrapErr, pkgdir) {
23881 if (unwrapErr) return loadpkg(path$2.dirname(dir), cb);
23882 var pkgfile = path$2.join(pkgdir, 'package.json');
23883 isFile(pkgfile, function (err, ex) {
23884 // on err, ex is false
23885 if (!ex) return loadpkg(path$2.dirname(dir), cb);
23886 readFile(pkgfile, function (err, body) {
23890 var pkg = JSON.parse(body);
23891 } catch (jsonErr) {}
23893 if (pkg && opts.packageFilter) {
23894 pkg = opts.packageFilter(pkg, pkgfile);
23897 cb(null, pkg, dir);
23903 function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
23905 var fpkg = loadAsDirectoryPackage;
23907 if (typeof fpkg === 'function') {
23909 fpkg = opts.package;
23912 maybeUnwrapSymlink(x, opts, function (unwrapErr, pkgdir) {
23913 if (unwrapErr) return cb(unwrapErr);
23914 var pkgfile = path$2.join(pkgdir, 'package.json');
23915 isFile(pkgfile, function (err, ex) {
23916 if (err) return cb(err);
23917 if (!ex) return loadAsFile(path$2.join(x, 'index'), fpkg, cb);
23918 readFile(pkgfile, function (err, body) {
23919 if (err) return cb(err);
23922 var pkg = JSON.parse(body);
23923 } catch (jsonErr) {}
23925 if (pkg && opts.packageFilter) {
23926 pkg = opts.packageFilter(pkg, pkgfile);
23929 if (pkg && pkg.main) {
23930 if (typeof pkg.main !== 'string') {
23931 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
23932 mainError.code = 'INVALID_PACKAGE_MAIN';
23933 return cb(mainError);
23936 if (pkg.main === '.' || pkg.main === './') {
23937 pkg.main = 'index';
23940 loadAsFile(path$2.resolve(x, pkg.main), pkg, function (err, m, pkg) {
23941 if (err) return cb(err);
23942 if (m) return cb(null, m, pkg);
23943 if (!pkg) return loadAsFile(path$2.join(x, 'index'), pkg, cb);
23944 var dir = path$2.resolve(x, pkg.main);
23945 loadAsDirectory(dir, pkg, function (err, n, pkg) {
23946 if (err) return cb(err);
23947 if (n) return cb(null, n, pkg);
23948 loadAsFile(path$2.join(x, 'index'), pkg, cb);
23954 loadAsFile(path$2.join(x, '/index'), pkg, cb);
23960 function processDirs(cb, dirs) {
23961 if (dirs.length === 0) return cb(null, undefined);
23963 isDirectory(path$2.dirname(dir), isdir);
23965 function isdir(err, isdir) {
23966 if (err) return cb(err);
23967 if (!isdir) return processDirs(cb, dirs.slice(1));
23968 loadAsFile(dir, opts.package, onfile);
23971 function onfile(err, m, pkg) {
23972 if (err) return cb(err);
23973 if (m) return cb(null, m, pkg);
23974 loadAsDirectory(dir, opts.package, ondir);
23977 function ondir(err, n, pkg) {
23978 if (err) return cb(err);
23979 if (n) return cb(null, n, pkg);
23980 processDirs(cb, dirs.slice(1));
23984 function loadNodeModules(x, start, cb) {
23985 var thunk = function () {
23986 return getPackageCandidates(x, start, opts);
23989 processDirs(cb, packageIterator ? packageIterator(x, start, thunk, opts) : thunk());
23993 var realpath$1 = fs$3.realpathSync && typeof fs$3.realpathSync.native === 'function' ? fs$3.realpathSync.native : fs$3.realpathSync;
23995 var defaultIsFile$1 = function isFile(file) {
23997 var stat = fs$3.statSync(file);
23999 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
24003 return stat.isFile() || stat.isFIFO();
24006 var defaultIsDir$1 = function isDirectory(dir) {
24008 var stat = fs$3.statSync(dir);
24010 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
24014 return stat.isDirectory();
24017 var maybeUnwrapSymlink$1 = function maybeUnwrapSymlink(x, opts) {
24018 if (opts && opts.preserveSymlinks === false) {
24020 return realpath$1(x);
24021 } catch (realPathErr) {
24022 if (realPathErr.code !== 'ENOENT') {
24031 var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) {
24032 var dirs = nodeModulesPaths(start, opts, x);
24034 for (var i = 0; i < dirs.length; i++) {
24035 dirs[i] = path$2.join(dirs[i], x);
24041 var sync = function resolveSync(x, options) {
24042 if (typeof x !== 'string') {
24043 throw new TypeError('Path must be a string.');
24046 var opts = normalizeOptions$2(x, options);
24047 var isFile = opts.isFile || defaultIsFile$1;
24048 var readFileSync = opts.readFileSync || fs$3.readFileSync;
24049 var isDirectory = opts.isDirectory || defaultIsDir$1;
24050 var packageIterator = opts.packageIterator;
24051 var extensions = opts.extensions || ['.js'];
24052 var basedir = opts.basedir || path$2.dirname(caller());
24053 var parent = opts.filename || basedir;
24054 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
24056 var absoluteStart = maybeUnwrapSymlink$1(path$2.resolve(basedir), opts);
24058 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
24059 var res = path$2.resolve(absoluteStart, x);
24060 if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
24061 var m = loadAsFileSync(res) || loadAsDirectorySync(res);
24062 if (m) return maybeUnwrapSymlink$1(m, opts);
24063 } else if (isCore(x)) {
24066 var n = loadNodeModulesSync(x, absoluteStart);
24067 if (n) return maybeUnwrapSymlink$1(n, opts);
24070 var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
24071 err.code = 'MODULE_NOT_FOUND';
24074 function loadAsFileSync(x) {
24075 var pkg = loadpkg(path$2.dirname(x));
24077 if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
24078 var rfile = path$2.relative(pkg.dir, x);
24079 var r = opts.pathFilter(pkg.pkg, x, rfile);
24082 x = path$2.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
24090 for (var i = 0; i < extensions.length; i++) {
24091 var file = x + extensions[i];
24093 if (isFile(file)) {
24099 function loadpkg(dir) {
24100 if (dir === '' || dir === '/') return;
24102 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
24106 if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
24107 var pkgfile = path$2.join(maybeUnwrapSymlink$1(dir, opts), 'package.json');
24109 if (!isFile(pkgfile)) {
24110 return loadpkg(path$2.dirname(dir));
24113 var body = readFileSync(pkgfile);
24116 var pkg = JSON.parse(body);
24117 } catch (jsonErr) {}
24119 if (pkg && opts.packageFilter) {
24120 // v2 will pass pkgfile
24121 pkg = opts.packageFilter(pkg,
24123 dir); // eslint-disable-line spaced-comment
24132 function loadAsDirectorySync(x) {
24133 var pkgfile = path$2.join(maybeUnwrapSymlink$1(x, opts), '/package.json');
24135 if (isFile(pkgfile)) {
24137 var body = readFileSync(pkgfile, 'UTF8');
24138 var pkg = JSON.parse(body);
24141 if (pkg && opts.packageFilter) {
24142 // v2 will pass pkgfile
24143 pkg = opts.packageFilter(pkg,
24145 x); // eslint-disable-line spaced-comment
24148 if (pkg && pkg.main) {
24149 if (typeof pkg.main !== 'string') {
24150 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
24151 mainError.code = 'INVALID_PACKAGE_MAIN';
24155 if (pkg.main === '.' || pkg.main === './') {
24156 pkg.main = 'index';
24160 var m = loadAsFileSync(path$2.resolve(x, pkg.main));
24162 var n = loadAsDirectorySync(path$2.resolve(x, pkg.main));
24168 return loadAsFileSync(path$2.join(x, '/index'));
24171 function loadNodeModulesSync(x, start) {
24172 var thunk = function () {
24173 return getPackageCandidates$1(x, start, opts);
24176 var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk();
24178 for (var i = 0; i < dirs.length; i++) {
24181 if (isDirectory(path$2.dirname(dir))) {
24182 var m = loadAsFileSync(dir);
24184 var n = loadAsDirectorySync(dir);
24191 async.core = core_1;
24192 async.isCore = isCore;
24194 var resolve = async;
24196 // eslint-disable-next-line prefer-destructuring
24199 let resolve$1 = require.resolve; // In the VS Code and Atom extensions `require` is overridden and `require.resolve` doesn't support the 2nd argument.
24201 if (resolve$1.length === 1 || process.env.PRETTIER_FALLBACK_RESOLVE) {
24202 resolve$1 = (id, options) => {
24205 if (options && options.paths && options.paths.length === 1) {
24206 basedir = options.paths[0];
24209 return resolve.sync(id, {
24215 var resolve_1 = resolve$1;
24217 const getExplorerMemoized = mem_1(opts => {
24218 const cosmiconfig = thirdParty["cosmiconfig" + (opts.sync ? "Sync" : "")];
24219 const explorer = cosmiconfig("prettier", {
24221 transform: result => {
24222 if (result && result.config) {
24223 if (typeof result.config === "string") {
24224 const dir = path$2.dirname(result.filepath);
24227 const modulePath = resolve_1(result.config, {
24230 result.config = require(modulePath);
24232 // Original message contains `__filename`, can't pass tests
24233 error.message = `Cannot find module '${result.config}' from '${dir}'`;
24238 if (typeof result.config !== "object") {
24239 throw new Error("Config is only allowed to be an object, " + `but received ${typeof result.config} in "${result.filepath}"`);
24242 delete result.config.$schema;
24247 searchPlaces: ["package.json", ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.js", "prettier.config.js", ".prettierrc.toml"],
24254 cacheKey: JSON.stringify
24256 /** @param {{ cache: boolean, sync: boolean }} opts */
24258 function getExplorer(opts) {
24259 // Normalize opts before passing to a memoized function
24260 opts = Object.assign({
24264 return getExplorerMemoized(opts);
24267 function _resolveConfig(filePath, opts, sync) {
24268 opts = Object.assign({
24272 cache: !!opts.useCache,
24274 editorconfig: !!opts.editorconfig
24279 } = getExplorer(loadOpts);
24280 const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts);
24281 const arr = [opts.config ? load(opts.config) : search(filePath), loadEditorConfig(filePath)];
24283 const unwrapAndMerge = ([result, editorConfigured]) => {
24284 const merged = Object.assign({}, editorConfigured, {}, mergeOverrides(result, filePath));
24285 ["plugins", "pluginSearchDirs"].forEach(optionName => {
24286 if (Array.isArray(merged[optionName])) {
24287 merged[optionName] = merged[optionName].map(value => typeof value === "string" && value.startsWith(".") // relative path
24288 ? path$2.resolve(path$2.dirname(result.filepath), value) : value);
24292 if (!result && !editorConfigured) {
24299 if (loadOpts.sync) {
24300 return unwrapAndMerge(arr);
24303 return Promise.all(arr).then(unwrapAndMerge);
24306 const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false);
24308 resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true);
24310 function clearCache$1() {
24311 mem_1.clear(getExplorerMemoized);
24312 resolveConfigEditorconfig.clearCache();
24315 async function resolveConfigFile(filePath) {
24321 const result = await search(filePath);
24322 return result ? result.filepath : null;
24325 resolveConfigFile.sync = filePath => {
24331 const result = search(filePath);
24332 return result ? result.filepath : null;
24335 function mergeOverrides(configResult, filePath) {
24338 filepath: configPath
24339 } = configResult || {};
24341 const _ref = config || {},
24345 options = _objectWithoutPropertiesLoose(_ref, ["overrides"]);
24347 if (filePath && overrides) {
24348 const relativeFilePath = path$2.relative(path$2.dirname(configPath), filePath);
24350 for (const override of overrides) {
24351 if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) {
24352 Object.assign(options, override.options);
24358 } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
24361 function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
24362 const patternList = [].concat(patterns);
24363 const excludedPatternList = [].concat(excludedPatterns || []);
24368 return patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts));
24371 var resolveConfig_1 = {
24374 clearCache: clearCache$1
24378 * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions
24379 * @typedef {{ ignored: boolean, inferredParser: string | null }} FileInfoResult
24383 * @param {string} filePath
24384 * @param {FileInfoOptions} opts
24385 * @returns {Promise<FileInfoResult>}
24387 * Please note that prettier.getFileInfo() expects opts.plugins to be an array of paths,
24388 * not an object. A transformation from this array to an object is automatically done
24389 * internally by the method wrapper. See withPlugins() in index.js.
24393 async function getFileInfo(filePath, opts) {
24394 if (typeof filePath !== "string") {
24395 throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
24398 const ignorer = await createIgnorer_1(opts.ignorePath, opts.withNodeModules);
24399 return _getFileInfo({
24401 filePath: normalizeFilePath(filePath, opts.ignorePath),
24402 plugins: opts.plugins,
24403 resolveConfig: opts.resolveConfig,
24408 * @param {string} filePath
24409 * @param {FileInfoOptions} opts
24410 * @returns {FileInfoResult}
24414 getFileInfo.sync = function (filePath, opts) {
24415 if (typeof filePath !== "string") {
24416 throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
24419 const ignorer = createIgnorer_1.sync(opts.ignorePath, opts.withNodeModules);
24420 return _getFileInfo({
24422 filePath: normalizeFilePath(filePath, opts.ignorePath),
24423 plugins: opts.plugins,
24424 resolveConfig: opts.resolveConfig,
24429 function _getFileInfo({
24433 resolveConfig = false,
24437 ignored: ignorer.ignores(filePath),
24438 inferredParser: options$1.inferParser(filePath, plugins) || null
24441 if (!fileInfo.inferredParser && resolveConfig) {
24443 return resolveConfig_1.resolveConfig(filePath).then(resolvedConfig => {
24444 if (resolvedConfig && resolvedConfig.parser) {
24445 fileInfo.inferredParser = resolvedConfig.parser;
24452 const resolvedConfig = resolveConfig_1.resolveConfig.sync(filePath);
24454 if (resolvedConfig && resolvedConfig.parser) {
24455 fileInfo.inferredParser = resolvedConfig.parser;
24462 function normalizeFilePath(filePath, ignorePath) {
24463 return ignorePath ? path$2.relative(path$2.dirname(ignorePath), filePath) : filePath;
24466 var getFileInfo_1 = getFileInfo;
24469 * Removes all key-value entries from the list cache.
24473 * @memberOf ListCache
24475 function listCacheClear() {
24476 this.__data__ = [];
24480 var _listCacheClear = listCacheClear;
24484 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
24485 * comparison between two values to determine if they are equivalent.
24491 * @param {*} value The value to compare.
24492 * @param {*} other The other value to compare.
24493 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
24496 * var object = { 'a': 1 };
24497 * var other = { 'a': 1 };
24499 * _.eq(object, object);
24502 * _.eq(object, other);
24508 * _.eq('a', Object('a'));
24514 function eq(value, other) {
24515 return value === other || value !== value && other !== other;
24521 * Gets the index at which the `key` is found in `array` of key-value pairs.
24524 * @param {Array} array The array to inspect.
24525 * @param {*} key The key to search for.
24526 * @returns {number} Returns the index of the matched value, else `-1`.
24529 function assocIndexOf(array, key) {
24530 var length = array.length;
24533 if (eq_1(array[length][0], key)) {
24541 var _assocIndexOf = assocIndexOf;
24543 /** Used for built-in method references. */
24545 var arrayProto = Array.prototype;
24546 /** Built-in value references. */
24548 var splice = arrayProto.splice;
24550 * Removes `key` and its value from the list cache.
24554 * @memberOf ListCache
24555 * @param {string} key The key of the value to remove.
24556 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
24559 function listCacheDelete(key) {
24560 var data = this.__data__,
24561 index = _assocIndexOf(data, key);
24567 var lastIndex = data.length - 1;
24569 if (index == lastIndex) {
24572 splice.call(data, index, 1);
24579 var _listCacheDelete = listCacheDelete;
24582 * Gets the list cache value for `key`.
24586 * @memberOf ListCache
24587 * @param {string} key The key of the value to get.
24588 * @returns {*} Returns the entry value.
24591 function listCacheGet(key) {
24592 var data = this.__data__,
24593 index = _assocIndexOf(data, key);
24594 return index < 0 ? undefined : data[index][1];
24597 var _listCacheGet = listCacheGet;
24600 * Checks if a list cache value for `key` exists.
24604 * @memberOf ListCache
24605 * @param {string} key The key of the entry to check.
24606 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
24609 function listCacheHas(key) {
24610 return _assocIndexOf(this.__data__, key) > -1;
24613 var _listCacheHas = listCacheHas;
24616 * Sets the list cache `key` to `value`.
24620 * @memberOf ListCache
24621 * @param {string} key The key of the value to set.
24622 * @param {*} value The value to set.
24623 * @returns {Object} Returns the list cache instance.
24626 function listCacheSet(key, value) {
24627 var data = this.__data__,
24628 index = _assocIndexOf(data, key);
24632 data.push([key, value]);
24634 data[index][1] = value;
24640 var _listCacheSet = listCacheSet;
24643 * Creates an list cache object.
24647 * @param {Array} [entries] The key-value pairs to cache.
24650 function ListCache(entries) {
24652 length = entries == null ? 0 : entries.length;
24655 while (++index < length) {
24656 var entry = entries[index];
24657 this.set(entry[0], entry[1]);
24659 } // Add methods to `ListCache`.
24662 ListCache.prototype.clear = _listCacheClear;
24663 ListCache.prototype['delete'] = _listCacheDelete;
24664 ListCache.prototype.get = _listCacheGet;
24665 ListCache.prototype.has = _listCacheHas;
24666 ListCache.prototype.set = _listCacheSet;
24667 var _ListCache = ListCache;
24670 * Removes all key-value entries from the stack.
24677 function stackClear() {
24678 this.__data__ = new _ListCache();
24682 var _stackClear = stackClear;
24685 * Removes `key` and its value from the stack.
24690 * @param {string} key The key of the value to remove.
24691 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
24693 function stackDelete(key) {
24694 var data = this.__data__,
24695 result = data['delete'](key);
24696 this.size = data.size;
24700 var _stackDelete = stackDelete;
24703 * Gets the stack value for `key`.
24708 * @param {string} key The key of the value to get.
24709 * @returns {*} Returns the entry value.
24711 function stackGet(key) {
24712 return this.__data__.get(key);
24715 var _stackGet = stackGet;
24718 * Checks if a stack value for `key` exists.
24723 * @param {string} key The key of the entry to check.
24724 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
24726 function stackHas(key) {
24727 return this.__data__.has(key);
24730 var _stackHas = stackHas;
24732 /** Detect free variable `global` from Node.js. */
24734 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
24735 var _freeGlobal = freeGlobal;
24737 /** Detect free variable `self`. */
24739 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
24740 /** Used as a reference to the global object. */
24742 var root = _freeGlobal || freeSelf || Function('return this')();
24745 /** Built-in value references. */
24747 var Symbol$1 = _root.Symbol;
24748 var _Symbol = Symbol$1;
24750 /** Used for built-in method references. */
24752 var objectProto = Object.prototype;
24753 /** Used to check objects for own properties. */
24755 var hasOwnProperty$2 = objectProto.hasOwnProperty;
24757 * Used to resolve the
24758 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
24762 var nativeObjectToString = objectProto.toString;
24763 /** Built-in value references. */
24765 var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
24767 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
24770 * @param {*} value The value to query.
24771 * @returns {string} Returns the raw `toStringTag`.
24774 function getRawTag(value) {
24775 var isOwn = hasOwnProperty$2.call(value, symToStringTag),
24776 tag = value[symToStringTag];
24779 value[symToStringTag] = undefined;
24780 var unmasked = true;
24783 var result = nativeObjectToString.call(value);
24787 value[symToStringTag] = tag;
24789 delete value[symToStringTag];
24796 var _getRawTag = getRawTag;
24798 /** Used for built-in method references. */
24799 var objectProto$1 = Object.prototype;
24801 * Used to resolve the
24802 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
24806 var nativeObjectToString$1 = objectProto$1.toString;
24808 * Converts `value` to a string using `Object.prototype.toString`.
24811 * @param {*} value The value to convert.
24812 * @returns {string} Returns the converted string.
24815 function objectToString(value) {
24816 return nativeObjectToString$1.call(value);
24819 var _objectToString = objectToString;
24821 /** `Object#toString` result references. */
24823 var nullTag = '[object Null]',
24824 undefinedTag = '[object Undefined]';
24825 /** Built-in value references. */
24827 var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
24829 * The base implementation of `getTag` without fallbacks for buggy environments.
24832 * @param {*} value The value to query.
24833 * @returns {string} Returns the `toStringTag`.
24836 function baseGetTag(value) {
24837 if (value == null) {
24838 return value === undefined ? undefinedTag : nullTag;
24841 return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
24844 var _baseGetTag = baseGetTag;
24847 * Checks if `value` is the
24848 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
24849 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
24855 * @param {*} value The value to check.
24856 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
24862 * _.isObject([1, 2, 3]);
24865 * _.isObject(_.noop);
24868 * _.isObject(null);
24871 function isObject(value) {
24872 var type = typeof value;
24873 return value != null && (type == 'object' || type == 'function');
24876 var isObject_1 = isObject;
24878 /** `Object#toString` result references. */
24880 var asyncTag = '[object AsyncFunction]',
24881 funcTag = '[object Function]',
24882 genTag = '[object GeneratorFunction]',
24883 proxyTag = '[object Proxy]';
24885 * Checks if `value` is classified as a `Function` object.
24891 * @param {*} value The value to check.
24892 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
24898 * _.isFunction(/abc/);
24902 function isFunction(value) {
24903 if (!isObject_1(value)) {
24905 } // The use of `Object#toString` avoids issues with the `typeof` operator
24906 // in Safari 9 which returns 'object' for typed arrays and other constructors.
24909 var tag = _baseGetTag(value);
24910 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
24913 var isFunction_1 = isFunction;
24915 /** Used to detect overreaching core-js shims. */
24917 var coreJsData = _root['__core-js_shared__'];
24918 var _coreJsData = coreJsData;
24920 /** Used to detect methods masquerading as native. */
24922 var maskSrcKey = function () {
24923 var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
24924 return uid ? 'Symbol(src)_1.' + uid : '';
24927 * Checks if `func` has its source masked.
24930 * @param {Function} func The function to check.
24931 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
24935 function isMasked(func) {
24936 return !!maskSrcKey && maskSrcKey in func;
24939 var _isMasked = isMasked;
24941 /** Used for built-in method references. */
24942 var funcProto = Function.prototype;
24943 /** Used to resolve the decompiled source of functions. */
24945 var funcToString = funcProto.toString;
24947 * Converts `func` to its source code.
24950 * @param {Function} func The function to convert.
24951 * @returns {string} Returns the source code.
24954 function toSource(func) {
24955 if (func != null) {
24957 return funcToString.call(func);
24968 var _toSource = toSource;
24971 * Used to match `RegExp`
24972 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
24975 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
24976 /** Used to detect host constructors (Safari). */
24978 var reIsHostCtor = /^\[object .+?Constructor\]$/;
24979 /** Used for built-in method references. */
24981 var funcProto$1 = Function.prototype,
24982 objectProto$2 = Object.prototype;
24983 /** Used to resolve the decompiled source of functions. */
24985 var funcToString$1 = funcProto$1.toString;
24986 /** Used to check objects for own properties. */
24988 var hasOwnProperty$3 = objectProto$2.hasOwnProperty;
24989 /** Used to detect if a method is native. */
24991 var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
24993 * The base implementation of `_.isNative` without bad shim checks.
24996 * @param {*} value The value to check.
24997 * @returns {boolean} Returns `true` if `value` is a native function,
25001 function baseIsNative(value) {
25002 if (!isObject_1(value) || _isMasked(value)) {
25006 var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
25007 return pattern.test(_toSource(value));
25010 var _baseIsNative = baseIsNative;
25013 * Gets the value at `key` of `object`.
25016 * @param {Object} [object] The object to query.
25017 * @param {string} key The key of the property to get.
25018 * @returns {*} Returns the property value.
25020 function getValue(object, key) {
25021 return object == null ? undefined : object[key];
25024 var _getValue = getValue;
25027 * Gets the native function at `key` of `object`.
25030 * @param {Object} object The object to query.
25031 * @param {string} key The key of the method to get.
25032 * @returns {*} Returns the function if it's native, else `undefined`.
25035 function getNative(object, key) {
25036 var value = _getValue(object, key);
25037 return _baseIsNative(value) ? value : undefined;
25040 var _getNative = getNative;
25042 /* Built-in method references that are verified to be native. */
25044 var Map$1 = _getNative(_root, 'Map');
25047 /* Built-in method references that are verified to be native. */
25049 var nativeCreate = _getNative(Object, 'create');
25050 var _nativeCreate = nativeCreate;
25053 * Removes all key-value entries from the hash.
25060 function hashClear() {
25061 this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
25065 var _hashClear = hashClear;
25068 * Removes `key` and its value from the hash.
25073 * @param {Object} hash The hash to modify.
25074 * @param {string} key The key of the value to remove.
25075 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25077 function hashDelete(key) {
25078 var result = this.has(key) && delete this.__data__[key];
25079 this.size -= result ? 1 : 0;
25083 var _hashDelete = hashDelete;
25085 /** Used to stand-in for `undefined` hash values. */
25087 var HASH_UNDEFINED = '__lodash_hash_undefined__';
25088 /** Used for built-in method references. */
25090 var objectProto$3 = Object.prototype;
25091 /** Used to check objects for own properties. */
25093 var hasOwnProperty$4 = objectProto$3.hasOwnProperty;
25095 * Gets the hash value for `key`.
25100 * @param {string} key The key of the value to get.
25101 * @returns {*} Returns the entry value.
25104 function hashGet(key) {
25105 var data = this.__data__;
25107 if (_nativeCreate) {
25108 var result = data[key];
25109 return result === HASH_UNDEFINED ? undefined : result;
25112 return hasOwnProperty$4.call(data, key) ? data[key] : undefined;
25115 var _hashGet = hashGet;
25117 /** Used for built-in method references. */
25119 var objectProto$4 = Object.prototype;
25120 /** Used to check objects for own properties. */
25122 var hasOwnProperty$5 = objectProto$4.hasOwnProperty;
25124 * Checks if a hash value for `key` exists.
25129 * @param {string} key The key of the entry to check.
25130 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25133 function hashHas(key) {
25134 var data = this.__data__;
25135 return _nativeCreate ? data[key] !== undefined : hasOwnProperty$5.call(data, key);
25138 var _hashHas = hashHas;
25140 /** Used to stand-in for `undefined` hash values. */
25142 var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
25144 * Sets the hash `key` to `value`.
25149 * @param {string} key The key of the value to set.
25150 * @param {*} value The value to set.
25151 * @returns {Object} Returns the hash instance.
25154 function hashSet(key, value) {
25155 var data = this.__data__;
25156 this.size += this.has(key) ? 0 : 1;
25157 data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
25161 var _hashSet = hashSet;
25164 * Creates a hash object.
25168 * @param {Array} [entries] The key-value pairs to cache.
25171 function Hash(entries) {
25173 length = entries == null ? 0 : entries.length;
25176 while (++index < length) {
25177 var entry = entries[index];
25178 this.set(entry[0], entry[1]);
25180 } // Add methods to `Hash`.
25183 Hash.prototype.clear = _hashClear;
25184 Hash.prototype['delete'] = _hashDelete;
25185 Hash.prototype.get = _hashGet;
25186 Hash.prototype.has = _hashHas;
25187 Hash.prototype.set = _hashSet;
25191 * Removes all key-value entries from the map.
25195 * @memberOf MapCache
25198 function mapCacheClear() {
25201 'hash': new _Hash(),
25202 'map': new (_Map || _ListCache)(),
25203 'string': new _Hash()
25207 var _mapCacheClear = mapCacheClear;
25210 * Checks if `value` is suitable for use as unique object key.
25213 * @param {*} value The value to check.
25214 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
25216 function isKeyable(value) {
25217 var type = typeof value;
25218 return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
25221 var _isKeyable = isKeyable;
25224 * Gets the data for `map`.
25227 * @param {Object} map The map to query.
25228 * @param {string} key The reference key.
25229 * @returns {*} Returns the map data.
25232 function getMapData(map, key) {
25233 var data = map.__data__;
25234 return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
25237 var _getMapData = getMapData;
25240 * Removes `key` and its value from the map.
25244 * @memberOf MapCache
25245 * @param {string} key The key of the value to remove.
25246 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25249 function mapCacheDelete(key) {
25250 var result = _getMapData(this, key)['delete'](key);
25251 this.size -= result ? 1 : 0;
25255 var _mapCacheDelete = mapCacheDelete;
25258 * Gets the map value for `key`.
25262 * @memberOf MapCache
25263 * @param {string} key The key of the value to get.
25264 * @returns {*} Returns the entry value.
25267 function mapCacheGet(key) {
25268 return _getMapData(this, key).get(key);
25271 var _mapCacheGet = mapCacheGet;
25274 * Checks if a map value for `key` exists.
25278 * @memberOf MapCache
25279 * @param {string} key The key of the entry to check.
25280 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25283 function mapCacheHas(key) {
25284 return _getMapData(this, key).has(key);
25287 var _mapCacheHas = mapCacheHas;
25290 * Sets the map `key` to `value`.
25294 * @memberOf MapCache
25295 * @param {string} key The key of the value to set.
25296 * @param {*} value The value to set.
25297 * @returns {Object} Returns the map cache instance.
25300 function mapCacheSet(key, value) {
25301 var data = _getMapData(this, key),
25303 data.set(key, value);
25304 this.size += data.size == size ? 0 : 1;
25308 var _mapCacheSet = mapCacheSet;
25311 * Creates a map cache object to store key-value pairs.
25315 * @param {Array} [entries] The key-value pairs to cache.
25318 function MapCache(entries) {
25320 length = entries == null ? 0 : entries.length;
25323 while (++index < length) {
25324 var entry = entries[index];
25325 this.set(entry[0], entry[1]);
25327 } // Add methods to `MapCache`.
25330 MapCache.prototype.clear = _mapCacheClear;
25331 MapCache.prototype['delete'] = _mapCacheDelete;
25332 MapCache.prototype.get = _mapCacheGet;
25333 MapCache.prototype.has = _mapCacheHas;
25334 MapCache.prototype.set = _mapCacheSet;
25335 var _MapCache = MapCache;
25337 /** Used as the size to enable large array optimizations. */
25339 var LARGE_ARRAY_SIZE = 200;
25341 * Sets the stack `key` to `value`.
25346 * @param {string} key The key of the value to set.
25347 * @param {*} value The value to set.
25348 * @returns {Object} Returns the stack cache instance.
25351 function stackSet(key, value) {
25352 var data = this.__data__;
25354 if (data instanceof _ListCache) {
25355 var pairs = data.__data__;
25357 if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
25358 pairs.push([key, value]);
25359 this.size = ++data.size;
25363 data = this.__data__ = new _MapCache(pairs);
25366 data.set(key, value);
25367 this.size = data.size;
25371 var _stackSet = stackSet;
25374 * Creates a stack cache object to store key-value pairs.
25378 * @param {Array} [entries] The key-value pairs to cache.
25381 function Stack(entries) {
25382 var data = this.__data__ = new _ListCache(entries);
25383 this.size = data.size;
25384 } // Add methods to `Stack`.
25387 Stack.prototype.clear = _stackClear;
25388 Stack.prototype['delete'] = _stackDelete;
25389 Stack.prototype.get = _stackGet;
25390 Stack.prototype.has = _stackHas;
25391 Stack.prototype.set = _stackSet;
25392 var _Stack = Stack;
25394 /** Used to stand-in for `undefined` hash values. */
25395 var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
25397 * Adds `value` to the array cache.
25401 * @memberOf SetCache
25403 * @param {*} value The value to cache.
25404 * @returns {Object} Returns the cache instance.
25407 function setCacheAdd(value) {
25408 this.__data__.set(value, HASH_UNDEFINED$2);
25413 var _setCacheAdd = setCacheAdd;
25416 * Checks if `value` is in the array cache.
25420 * @memberOf SetCache
25421 * @param {*} value The value to search for.
25422 * @returns {number} Returns `true` if `value` is found, else `false`.
25424 function setCacheHas(value) {
25425 return this.__data__.has(value);
25428 var _setCacheHas = setCacheHas;
25432 * Creates an array cache object to store unique values.
25436 * @param {Array} [values] The values to cache.
25439 function SetCache(values) {
25441 length = values == null ? 0 : values.length;
25442 this.__data__ = new _MapCache();
25444 while (++index < length) {
25445 this.add(values[index]);
25447 } // Add methods to `SetCache`.
25450 SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
25451 SetCache.prototype.has = _setCacheHas;
25452 var _SetCache = SetCache;
25455 * A specialized version of `_.some` for arrays without support for iteratee
25459 * @param {Array} [array] The array to iterate over.
25460 * @param {Function} predicate The function invoked per iteration.
25461 * @returns {boolean} Returns `true` if any element passes the predicate check,
25464 function arraySome(array, predicate) {
25466 length = array == null ? 0 : array.length;
25468 while (++index < length) {
25469 if (predicate(array[index], index, array)) {
25477 var _arraySome = arraySome;
25480 * Checks if a `cache` value for `key` exists.
25483 * @param {Object} cache The cache to query.
25484 * @param {string} key The key of the entry to check.
25485 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25487 function cacheHas(cache, key) {
25488 return cache.has(key);
25491 var _cacheHas = cacheHas;
25493 /** Used to compose bitmasks for value comparisons. */
25495 var COMPARE_PARTIAL_FLAG = 1,
25496 COMPARE_UNORDERED_FLAG = 2;
25498 * A specialized version of `baseIsEqualDeep` for arrays with support for
25499 * partial deep comparisons.
25502 * @param {Array} array The array to compare.
25503 * @param {Array} other The other array to compare.
25504 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
25505 * @param {Function} customizer The function to customize comparisons.
25506 * @param {Function} equalFunc The function to determine equivalents of values.
25507 * @param {Object} stack Tracks traversed `array` and `other` objects.
25508 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
25511 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
25512 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
25513 arrLength = array.length,
25514 othLength = other.length;
25516 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
25518 } // Assume cyclic values are equal.
25521 var stacked = stack.get(array);
25523 if (stacked && stack.get(other)) {
25524 return stacked == other;
25529 seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
25530 stack.set(array, other);
25531 stack.set(other, array); // Ignore non-index properties.
25533 while (++index < arrLength) {
25534 var arrValue = array[index],
25535 othValue = other[index];
25538 var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
25541 if (compared !== undefined) {
25548 } // Recursively compare arrays (susceptible to call stack limits).
25552 if (!_arraySome(other, function (othValue, othIndex) {
25553 if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
25554 return seen.push(othIndex);
25560 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
25566 stack['delete'](array);
25567 stack['delete'](other);
25571 var _equalArrays = equalArrays;
25573 /** Built-in value references. */
25575 var Uint8Array = _root.Uint8Array;
25576 var _Uint8Array = Uint8Array;
25579 * Converts `map` to its key-value pairs.
25582 * @param {Object} map The map to convert.
25583 * @returns {Array} Returns the key-value pairs.
25585 function mapToArray(map) {
25587 result = Array(map.size);
25588 map.forEach(function (value, key) {
25589 result[++index] = [key, value];
25594 var _mapToArray = mapToArray;
25597 * Converts `set` to an array of its values.
25600 * @param {Object} set The set to convert.
25601 * @returns {Array} Returns the values.
25603 function setToArray(set) {
25605 result = Array(set.size);
25606 set.forEach(function (value) {
25607 result[++index] = value;
25612 var _setToArray = setToArray;
25614 /** Used to compose bitmasks for value comparisons. */
25616 var COMPARE_PARTIAL_FLAG$1 = 1,
25617 COMPARE_UNORDERED_FLAG$1 = 2;
25618 /** `Object#toString` result references. */
25620 var boolTag = '[object Boolean]',
25621 dateTag = '[object Date]',
25622 errorTag = '[object Error]',
25623 mapTag = '[object Map]',
25624 numberTag = '[object Number]',
25625 regexpTag = '[object RegExp]',
25626 setTag = '[object Set]',
25627 stringTag = '[object String]',
25628 symbolTag = '[object Symbol]';
25629 var arrayBufferTag = '[object ArrayBuffer]',
25630 dataViewTag = '[object DataView]';
25631 /** Used to convert symbols to primitives and strings. */
25633 var symbolProto = _Symbol ? _Symbol.prototype : undefined,
25634 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
25636 * A specialized version of `baseIsEqualDeep` for comparing objects of
25637 * the same `toStringTag`.
25639 * **Note:** This function only supports comparing values with tags of
25640 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
25643 * @param {Object} object The object to compare.
25644 * @param {Object} other The other object to compare.
25645 * @param {string} tag The `toStringTag` of the objects to compare.
25646 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
25647 * @param {Function} customizer The function to customize comparisons.
25648 * @param {Function} equalFunc The function to determine equivalents of values.
25649 * @param {Object} stack Tracks traversed `object` and `other` objects.
25650 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
25653 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
25656 if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
25660 object = object.buffer;
25661 other = other.buffer;
25663 case arrayBufferTag:
25664 if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
25673 // Coerce booleans to `1` or `0` and dates to milliseconds.
25674 // Invalid dates are coerced to `NaN`.
25675 return eq_1(+object, +other);
25678 return object.name == other.name && object.message == other.message;
25682 // Coerce regexes to strings and treat strings, primitives and objects,
25683 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
25684 // for more details.
25685 return object == other + '';
25688 var convert = _mapToArray;
25691 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
25692 convert || (convert = _setToArray);
25694 if (object.size != other.size && !isPartial) {
25696 } // Assume cyclic values are equal.
25699 var stacked = stack.get(object);
25702 return stacked == other;
25705 bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits).
25707 stack.set(object, other);
25708 var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
25709 stack['delete'](object);
25713 if (symbolValueOf) {
25714 return symbolValueOf.call(object) == symbolValueOf.call(other);
25722 var _equalByTag = equalByTag;
25725 * Appends the elements of `values` to `array`.
25728 * @param {Array} array The array to modify.
25729 * @param {Array} values The values to append.
25730 * @returns {Array} Returns `array`.
25732 function arrayPush(array, values) {
25734 length = values.length,
25735 offset = array.length;
25737 while (++index < length) {
25738 array[offset + index] = values[index];
25744 var _arrayPush = arrayPush;
25747 * Checks if `value` is classified as an `Array` object.
25753 * @param {*} value The value to check.
25754 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
25757 * _.isArray([1, 2, 3]);
25760 * _.isArray(document.body.children);
25763 * _.isArray('abc');
25766 * _.isArray(_.noop);
25769 var isArray$1 = Array.isArray;
25770 var isArray_1 = isArray$1;
25773 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
25774 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
25775 * symbols of `object`.
25778 * @param {Object} object The object to query.
25779 * @param {Function} keysFunc The function to get the keys of `object`.
25780 * @param {Function} symbolsFunc The function to get the symbols of `object`.
25781 * @returns {Array} Returns the array of property names and symbols.
25784 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
25785 var result = keysFunc(object);
25786 return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
25789 var _baseGetAllKeys = baseGetAllKeys;
25792 * A specialized version of `_.filter` for arrays without support for
25793 * iteratee shorthands.
25796 * @param {Array} [array] The array to iterate over.
25797 * @param {Function} predicate The function invoked per iteration.
25798 * @returns {Array} Returns the new filtered array.
25800 function arrayFilter(array, predicate) {
25802 length = array == null ? 0 : array.length,
25806 while (++index < length) {
25807 var value = array[index];
25809 if (predicate(value, index, array)) {
25810 result[resIndex++] = value;
25817 var _arrayFilter = arrayFilter;
25820 * This method returns a new empty array.
25826 * @returns {Array} Returns the new empty array.
25829 * var arrays = _.times(2, _.stubArray);
25831 * console.log(arrays);
25834 * console.log(arrays[0] === arrays[1]);
25837 function stubArray() {
25841 var stubArray_1 = stubArray;
25843 /** Used for built-in method references. */
25845 var objectProto$5 = Object.prototype;
25846 /** Built-in value references. */
25848 var propertyIsEnumerable = objectProto$5.propertyIsEnumerable;
25849 /* Built-in method references for those with the same name as other `lodash` methods. */
25851 var nativeGetSymbols = Object.getOwnPropertySymbols;
25853 * Creates an array of the own enumerable symbols of `object`.
25856 * @param {Object} object The object to query.
25857 * @returns {Array} Returns the array of symbols.
25860 var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) {
25861 if (object == null) {
25865 object = Object(object);
25866 return _arrayFilter(nativeGetSymbols(object), function (symbol) {
25867 return propertyIsEnumerable.call(object, symbol);
25870 var _getSymbols = getSymbols;
25873 * The base implementation of `_.times` without support for iteratee shorthands
25874 * or max array length checks.
25877 * @param {number} n The number of times to invoke `iteratee`.
25878 * @param {Function} iteratee The function invoked per iteration.
25879 * @returns {Array} Returns the array of results.
25881 function baseTimes(n, iteratee) {
25885 while (++index < n) {
25886 result[index] = iteratee(index);
25892 var _baseTimes = baseTimes;
25895 * Checks if `value` is object-like. A value is object-like if it's not `null`
25896 * and has a `typeof` result of "object".
25902 * @param {*} value The value to check.
25903 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
25906 * _.isObjectLike({});
25909 * _.isObjectLike([1, 2, 3]);
25912 * _.isObjectLike(_.noop);
25915 * _.isObjectLike(null);
25918 function isObjectLike(value) {
25919 return value != null && typeof value == 'object';
25922 var isObjectLike_1 = isObjectLike;
25924 /** `Object#toString` result references. */
25926 var argsTag = '[object Arguments]';
25928 * The base implementation of `_.isArguments`.
25931 * @param {*} value The value to check.
25932 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
25935 function baseIsArguments(value) {
25936 return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
25939 var _baseIsArguments = baseIsArguments;
25941 /** Used for built-in method references. */
25943 var objectProto$6 = Object.prototype;
25944 /** Used to check objects for own properties. */
25946 var hasOwnProperty$6 = objectProto$6.hasOwnProperty;
25947 /** Built-in value references. */
25949 var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable;
25951 * Checks if `value` is likely an `arguments` object.
25957 * @param {*} value The value to check.
25958 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
25962 * _.isArguments(function() { return arguments; }());
25965 * _.isArguments([1, 2, 3]);
25969 var isArguments = _baseIsArguments(function () {
25971 }()) ? _baseIsArguments : function (value) {
25972 return isObjectLike_1(value) && hasOwnProperty$6.call(value, 'callee') && !propertyIsEnumerable$1.call(value, 'callee');
25974 var isArguments_1 = isArguments;
25977 * This method returns `false`.
25983 * @returns {boolean} Returns `false`.
25986 * _.times(2, _.stubFalse);
25987 * // => [false, false]
25989 function stubFalse() {
25993 var stubFalse_1 = stubFalse;
25995 var isBuffer_1 = createCommonjsModule(function (module, exports) {
25996 /** Detect free variable `exports`. */
25997 var freeExports = exports && !exports.nodeType && exports;
25998 /** Detect free variable `module`. */
26000 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
26001 /** Detect the popular CommonJS extension `module.exports`. */
26003 var moduleExports = freeModule && freeModule.exports === freeExports;
26004 /** Built-in value references. */
26006 var Buffer = moduleExports ? _root.Buffer : undefined;
26007 /* Built-in method references for those with the same name as other `lodash` methods. */
26009 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
26011 * Checks if `value` is a buffer.
26017 * @param {*} value The value to check.
26018 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
26021 * _.isBuffer(new Buffer(2));
26024 * _.isBuffer(new Uint8Array(2));
26028 var isBuffer = nativeIsBuffer || stubFalse_1;
26029 module.exports = isBuffer;
26032 /** Used as references for various `Number` constants. */
26033 var MAX_SAFE_INTEGER$2 = 9007199254740991;
26034 /** Used to detect unsigned integer values. */
26036 var reIsUint = /^(?:0|[1-9]\d*)$/;
26038 * Checks if `value` is a valid array-like index.
26041 * @param {*} value The value to check.
26042 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
26043 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
26046 function isIndex(value, length) {
26047 var type = typeof value;
26048 length = length == null ? MAX_SAFE_INTEGER$2 : length;
26049 return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
26052 var _isIndex = isIndex;
26054 /** Used as references for various `Number` constants. */
26055 var MAX_SAFE_INTEGER$3 = 9007199254740991;
26057 * Checks if `value` is a valid array-like length.
26059 * **Note:** This method is loosely based on
26060 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
26066 * @param {*} value The value to check.
26067 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
26073 * _.isLength(Number.MIN_VALUE);
26076 * _.isLength(Infinity);
26083 function isLength(value) {
26084 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$3;
26087 var isLength_1 = isLength;
26089 /** `Object#toString` result references. */
26091 var argsTag$1 = '[object Arguments]',
26092 arrayTag = '[object Array]',
26093 boolTag$1 = '[object Boolean]',
26094 dateTag$1 = '[object Date]',
26095 errorTag$1 = '[object Error]',
26096 funcTag$1 = '[object Function]',
26097 mapTag$1 = '[object Map]',
26098 numberTag$1 = '[object Number]',
26099 objectTag = '[object Object]',
26100 regexpTag$1 = '[object RegExp]',
26101 setTag$1 = '[object Set]',
26102 stringTag$1 = '[object String]',
26103 weakMapTag = '[object WeakMap]';
26104 var arrayBufferTag$1 = '[object ArrayBuffer]',
26105 dataViewTag$1 = '[object DataView]',
26106 float32Tag = '[object Float32Array]',
26107 float64Tag = '[object Float64Array]',
26108 int8Tag = '[object Int8Array]',
26109 int16Tag = '[object Int16Array]',
26110 int32Tag = '[object Int32Array]',
26111 uint8Tag = '[object Uint8Array]',
26112 uint8ClampedTag = '[object Uint8ClampedArray]',
26113 uint16Tag = '[object Uint16Array]',
26114 uint32Tag = '[object Uint32Array]';
26115 /** Used to identify `toStringTag` values of typed arrays. */
26117 var typedArrayTags = {};
26118 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
26119 typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag] = false;
26121 * The base implementation of `_.isTypedArray` without Node.js optimizations.
26124 * @param {*} value The value to check.
26125 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
26128 function baseIsTypedArray(value) {
26129 return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
26132 var _baseIsTypedArray = baseIsTypedArray;
26135 * The base implementation of `_.unary` without support for storing metadata.
26138 * @param {Function} func The function to cap arguments for.
26139 * @returns {Function} Returns the new capped function.
26141 function baseUnary(func) {
26142 return function (value) {
26143 return func(value);
26147 var _baseUnary = baseUnary;
26149 var _nodeUtil = createCommonjsModule(function (module, exports) {
26150 /** Detect free variable `exports`. */
26151 var freeExports = exports && !exports.nodeType && exports;
26152 /** Detect free variable `module`. */
26154 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
26155 /** Detect the popular CommonJS extension `module.exports`. */
26157 var moduleExports = freeModule && freeModule.exports === freeExports;
26158 /** Detect free variable `process` from Node.js. */
26160 var freeProcess = moduleExports && _freeGlobal.process;
26161 /** Used to access faster Node.js helpers. */
26163 var nodeUtil = function () {
26165 // Use `util.types` for Node.js 10+.
26166 var types = freeModule && freeModule.require && freeModule.require('util').types;
26170 } // Legacy `process.binding('util')` for Node.js < 10.
26173 return freeProcess && freeProcess.binding && freeProcess.binding('util');
26177 module.exports = nodeUtil;
26180 /* Node.js helper references. */
26182 var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
26184 * Checks if `value` is classified as a typed array.
26190 * @param {*} value The value to check.
26191 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
26194 * _.isTypedArray(new Uint8Array);
26197 * _.isTypedArray([]);
26201 var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
26202 var isTypedArray_1 = isTypedArray;
26204 /** Used for built-in method references. */
26206 var objectProto$7 = Object.prototype;
26207 /** Used to check objects for own properties. */
26209 var hasOwnProperty$7 = objectProto$7.hasOwnProperty;
26211 * Creates an array of the enumerable property names of the array-like `value`.
26214 * @param {*} value The value to query.
26215 * @param {boolean} inherited Specify returning inherited property names.
26216 * @returns {Array} Returns the array of property names.
26219 function arrayLikeKeys(value, inherited) {
26220 var isArr = isArray_1(value),
26221 isArg = !isArr && isArguments_1(value),
26222 isBuff = !isArr && !isArg && isBuffer_1(value),
26223 isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
26224 skipIndexes = isArr || isArg || isBuff || isType,
26225 result = skipIndexes ? _baseTimes(value.length, String) : [],
26226 length = result.length;
26228 for (var key in value) {
26229 if ((inherited || hasOwnProperty$7.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
26230 key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
26231 isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
26232 isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
26233 _isIndex(key, length)))) {
26241 var _arrayLikeKeys = arrayLikeKeys;
26243 /** Used for built-in method references. */
26244 var objectProto$8 = Object.prototype;
26246 * Checks if `value` is likely a prototype object.
26249 * @param {*} value The value to check.
26250 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
26253 function isPrototype(value) {
26254 var Ctor = value && value.constructor,
26255 proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
26256 return value === proto;
26259 var _isPrototype = isPrototype;
26262 * Creates a unary function that invokes `func` with its argument transformed.
26265 * @param {Function} func The function to wrap.
26266 * @param {Function} transform The argument transform.
26267 * @returns {Function} Returns the new function.
26269 function overArg(func, transform) {
26270 return function (arg) {
26271 return func(transform(arg));
26275 var _overArg = overArg;
26277 /* Built-in method references for those with the same name as other `lodash` methods. */
26279 var nativeKeys = _overArg(Object.keys, Object);
26280 var _nativeKeys = nativeKeys;
26282 /** Used for built-in method references. */
26284 var objectProto$9 = Object.prototype;
26285 /** Used to check objects for own properties. */
26287 var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
26289 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
26292 * @param {Object} object The object to query.
26293 * @returns {Array} Returns the array of property names.
26296 function baseKeys(object) {
26297 if (!_isPrototype(object)) {
26298 return _nativeKeys(object);
26303 for (var key in Object(object)) {
26304 if (hasOwnProperty$8.call(object, key) && key != 'constructor') {
26312 var _baseKeys = baseKeys;
26315 * Checks if `value` is array-like. A value is considered array-like if it's
26316 * not a function and has a `value.length` that's an integer greater than or
26317 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
26323 * @param {*} value The value to check.
26324 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
26327 * _.isArrayLike([1, 2, 3]);
26330 * _.isArrayLike(document.body.children);
26333 * _.isArrayLike('abc');
26336 * _.isArrayLike(_.noop);
26340 function isArrayLike(value) {
26341 return value != null && isLength_1(value.length) && !isFunction_1(value);
26344 var isArrayLike_1 = isArrayLike;
26347 * Creates an array of the own enumerable property names of `object`.
26349 * **Note:** Non-object values are coerced to objects. See the
26350 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
26351 * for more details.
26357 * @param {Object} object The object to query.
26358 * @returns {Array} Returns the array of property names.
26366 * Foo.prototype.c = 3;
26369 * // => ['a', 'b'] (iteration order is not guaranteed)
26375 function keys(object) {
26376 return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
26382 * Creates an array of own enumerable property names and symbols of `object`.
26385 * @param {Object} object The object to query.
26386 * @returns {Array} Returns the array of property names and symbols.
26389 function getAllKeys(object) {
26390 return _baseGetAllKeys(object, keys_1, _getSymbols);
26393 var _getAllKeys = getAllKeys;
26395 /** Used to compose bitmasks for value comparisons. */
26397 var COMPARE_PARTIAL_FLAG$2 = 1;
26398 /** Used for built-in method references. */
26400 var objectProto$a = Object.prototype;
26401 /** Used to check objects for own properties. */
26403 var hasOwnProperty$9 = objectProto$a.hasOwnProperty;
26405 * A specialized version of `baseIsEqualDeep` for objects with support for
26406 * partial deep comparisons.
26409 * @param {Object} object The object to compare.
26410 * @param {Object} other The other object to compare.
26411 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
26412 * @param {Function} customizer The function to customize comparisons.
26413 * @param {Function} equalFunc The function to determine equivalents of values.
26414 * @param {Object} stack Tracks traversed `object` and `other` objects.
26415 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
26418 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
26419 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
26420 objProps = _getAllKeys(object),
26421 objLength = objProps.length,
26422 othProps = _getAllKeys(other),
26423 othLength = othProps.length;
26425 if (objLength != othLength && !isPartial) {
26429 var index = objLength;
26432 var key = objProps[index];
26434 if (!(isPartial ? key in other : hasOwnProperty$9.call(other, key))) {
26437 } // Assume cyclic values are equal.
26440 var stacked = stack.get(object);
26442 if (stacked && stack.get(other)) {
26443 return stacked == other;
26447 stack.set(object, other);
26448 stack.set(other, object);
26449 var skipCtor = isPartial;
26451 while (++index < objLength) {
26452 key = objProps[index];
26453 var objValue = object[key],
26454 othValue = other[key];
26457 var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
26458 } // Recursively compare objects (susceptible to call stack limits).
26461 if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
26466 skipCtor || (skipCtor = key == 'constructor');
26469 if (result && !skipCtor) {
26470 var objCtor = object.constructor,
26471 othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
26473 if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
26478 stack['delete'](object);
26479 stack['delete'](other);
26483 var _equalObjects = equalObjects;
26485 /* Built-in method references that are verified to be native. */
26487 var DataView = _getNative(_root, 'DataView');
26488 var _DataView = DataView;
26490 /* Built-in method references that are verified to be native. */
26492 var Promise$1 = _getNative(_root, 'Promise');
26493 var _Promise = Promise$1;
26495 /* Built-in method references that are verified to be native. */
26497 var Set$1 = _getNative(_root, 'Set');
26500 /* Built-in method references that are verified to be native. */
26502 var WeakMap$1 = _getNative(_root, 'WeakMap');
26503 var _WeakMap = WeakMap$1;
26505 /** `Object#toString` result references. */
26507 var mapTag$2 = '[object Map]',
26508 objectTag$1 = '[object Object]',
26509 promiseTag = '[object Promise]',
26510 setTag$2 = '[object Set]',
26511 weakMapTag$1 = '[object WeakMap]';
26512 var dataViewTag$2 = '[object DataView]';
26513 /** Used to detect maps, sets, and weakmaps. */
26515 var dataViewCtorString = _toSource(_DataView),
26516 mapCtorString = _toSource(_Map),
26517 promiseCtorString = _toSource(_Promise),
26518 setCtorString = _toSource(_Set),
26519 weakMapCtorString = _toSource(_WeakMap);
26521 * Gets the `toStringTag` of `value`.
26524 * @param {*} value The value to query.
26525 * @returns {string} Returns the `toStringTag`.
26528 var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
26530 if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) {
26531 getTag = function (value) {
26532 var result = _baseGetTag(value),
26533 Ctor = result == objectTag$1 ? value.constructor : undefined,
26534 ctorString = Ctor ? _toSource(Ctor) : '';
26537 switch (ctorString) {
26538 case dataViewCtorString:
26539 return dataViewTag$2;
26541 case mapCtorString:
26544 case promiseCtorString:
26547 case setCtorString:
26550 case weakMapCtorString:
26551 return weakMapTag$1;
26559 var _getTag = getTag;
26561 /** Used to compose bitmasks for value comparisons. */
26563 var COMPARE_PARTIAL_FLAG$3 = 1;
26564 /** `Object#toString` result references. */
26566 var argsTag$2 = '[object Arguments]',
26567 arrayTag$1 = '[object Array]',
26568 objectTag$2 = '[object Object]';
26569 /** Used for built-in method references. */
26571 var objectProto$b = Object.prototype;
26572 /** Used to check objects for own properties. */
26574 var hasOwnProperty$a = objectProto$b.hasOwnProperty;
26576 * A specialized version of `baseIsEqual` for arrays and objects which performs
26577 * deep comparisons and tracks traversed objects enabling objects with circular
26578 * references to be compared.
26581 * @param {Object} object The object to compare.
26582 * @param {Object} other The other object to compare.
26583 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
26584 * @param {Function} customizer The function to customize comparisons.
26585 * @param {Function} equalFunc The function to determine equivalents of values.
26586 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
26587 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
26590 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
26591 var objIsArr = isArray_1(object),
26592 othIsArr = isArray_1(other),
26593 objTag = objIsArr ? arrayTag$1 : _getTag(object),
26594 othTag = othIsArr ? arrayTag$1 : _getTag(other);
26595 objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
26596 othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
26597 var objIsObj = objTag == objectTag$2,
26598 othIsObj = othTag == objectTag$2,
26599 isSameTag = objTag == othTag;
26601 if (isSameTag && isBuffer_1(object)) {
26602 if (!isBuffer_1(other)) {
26610 if (isSameTag && !objIsObj) {
26611 stack || (stack = new _Stack());
26612 return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
26615 if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
26616 var objIsWrapped = objIsObj && hasOwnProperty$a.call(object, '__wrapped__'),
26617 othIsWrapped = othIsObj && hasOwnProperty$a.call(other, '__wrapped__');
26619 if (objIsWrapped || othIsWrapped) {
26620 var objUnwrapped = objIsWrapped ? object.value() : object,
26621 othUnwrapped = othIsWrapped ? other.value() : other;
26622 stack || (stack = new _Stack());
26623 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
26631 stack || (stack = new _Stack());
26632 return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
26635 var _baseIsEqualDeep = baseIsEqualDeep;
26638 * The base implementation of `_.isEqual` which supports partial comparisons
26639 * and tracks traversed objects.
26642 * @param {*} value The value to compare.
26643 * @param {*} other The other value to compare.
26644 * @param {boolean} bitmask The bitmask flags.
26645 * 1 - Unordered comparison
26646 * 2 - Partial comparison
26647 * @param {Function} [customizer] The function to customize comparisons.
26648 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
26649 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
26652 function baseIsEqual(value, other, bitmask, customizer, stack) {
26653 if (value === other) {
26657 if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
26658 return value !== value && other !== other;
26661 return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
26664 var _baseIsEqual = baseIsEqual;
26666 /** Used to compose bitmasks for value comparisons. */
26668 var COMPARE_PARTIAL_FLAG$4 = 1,
26669 COMPARE_UNORDERED_FLAG$2 = 2;
26671 * The base implementation of `_.isMatch` without support for iteratee shorthands.
26674 * @param {Object} object The object to inspect.
26675 * @param {Object} source The object of property values to match.
26676 * @param {Array} matchData The property names, values, and compare flags to match.
26677 * @param {Function} [customizer] The function to customize comparisons.
26678 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
26681 function baseIsMatch(object, source, matchData, customizer) {
26682 var index = matchData.length,
26684 noCustomizer = !customizer;
26686 if (object == null) {
26690 object = Object(object);
26693 var data = matchData[index];
26695 if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
26700 while (++index < length) {
26701 data = matchData[index];
26703 objValue = object[key],
26704 srcValue = data[1];
26706 if (noCustomizer && data[2]) {
26707 if (objValue === undefined && !(key in object)) {
26711 var stack = new _Stack();
26714 var result = customizer(objValue, srcValue, key, object, source, stack);
26717 if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
26726 var _baseIsMatch = baseIsMatch;
26729 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
26732 * @param {*} value The value to check.
26733 * @returns {boolean} Returns `true` if `value` if suitable for strict
26734 * equality comparisons, else `false`.
26737 function isStrictComparable(value) {
26738 return value === value && !isObject_1(value);
26741 var _isStrictComparable = isStrictComparable;
26744 * Gets the property names, values, and compare flags of `object`.
26747 * @param {Object} object The object to query.
26748 * @returns {Array} Returns the match data of `object`.
26751 function getMatchData(object) {
26752 var result = keys_1(object),
26753 length = result.length;
26756 var key = result[length],
26757 value = object[key];
26758 result[length] = [key, value, _isStrictComparable(value)];
26764 var _getMatchData = getMatchData;
26767 * A specialized version of `matchesProperty` for source values suitable
26768 * for strict equality comparisons, i.e. `===`.
26771 * @param {string} key The key of the property to get.
26772 * @param {*} srcValue The value to match.
26773 * @returns {Function} Returns the new spec function.
26775 function matchesStrictComparable(key, srcValue) {
26776 return function (object) {
26777 if (object == null) {
26781 return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
26785 var _matchesStrictComparable = matchesStrictComparable;
26788 * The base implementation of `_.matches` which doesn't clone `source`.
26791 * @param {Object} source The object of property values to match.
26792 * @returns {Function} Returns the new spec function.
26795 function baseMatches(source) {
26796 var matchData = _getMatchData(source);
26798 if (matchData.length == 1 && matchData[0][2]) {
26799 return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
26802 return function (object) {
26803 return object === source || _baseIsMatch(object, source, matchData);
26807 var _baseMatches = baseMatches;
26809 /** `Object#toString` result references. */
26811 var symbolTag$1 = '[object Symbol]';
26813 * Checks if `value` is classified as a `Symbol` primitive or object.
26819 * @param {*} value The value to check.
26820 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
26823 * _.isSymbol(Symbol.iterator);
26826 * _.isSymbol('abc');
26830 function isSymbol(value) {
26831 return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1;
26834 var isSymbol_1 = isSymbol;
26836 /** Used to match property names within property paths. */
26838 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
26839 reIsPlainProp = /^\w*$/;
26841 * Checks if `value` is a property name and not a property path.
26844 * @param {*} value The value to check.
26845 * @param {Object} [object] The object to query keys on.
26846 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
26849 function isKey(value, object) {
26850 if (isArray_1(value)) {
26854 var type = typeof value;
26856 if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) {
26860 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
26863 var _isKey = isKey;
26865 /** Error message constants. */
26867 var FUNC_ERROR_TEXT = 'Expected a function';
26869 * Creates a function that memoizes the result of `func`. If `resolver` is
26870 * provided, it determines the cache key for storing the result based on the
26871 * arguments provided to the memoized function. By default, the first argument
26872 * provided to the memoized function is used as the map cache key. The `func`
26873 * is invoked with the `this` binding of the memoized function.
26875 * **Note:** The cache is exposed as the `cache` property on the memoized
26876 * function. Its creation may be customized by replacing the `_.memoize.Cache`
26877 * constructor with one whose instances implement the
26878 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
26879 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
26884 * @category Function
26885 * @param {Function} func The function to have its output memoized.
26886 * @param {Function} [resolver] The function to resolve the cache key.
26887 * @returns {Function} Returns the new memoized function.
26890 * var object = { 'a': 1, 'b': 2 };
26891 * var other = { 'c': 3, 'd': 4 };
26893 * var values = _.memoize(_.values);
26904 * // Modify the result cache.
26905 * values.cache.set(object, ['a', 'b']);
26909 * // Replace `_.memoize.Cache`.
26910 * _.memoize.Cache = WeakMap;
26913 function memoize(func, resolver) {
26914 if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
26915 throw new TypeError(FUNC_ERROR_TEXT);
26918 var memoized = function () {
26919 var args = arguments,
26920 key = resolver ? resolver.apply(this, args) : args[0],
26921 cache = memoized.cache;
26923 if (cache.has(key)) {
26924 return cache.get(key);
26927 var result = func.apply(this, args);
26928 memoized.cache = cache.set(key, result) || cache;
26932 memoized.cache = new (memoize.Cache || _MapCache)();
26934 } // Expose `MapCache`.
26937 memoize.Cache = _MapCache;
26938 var memoize_1 = memoize;
26940 /** Used as the maximum memoize cache size. */
26942 var MAX_MEMOIZE_SIZE = 500;
26944 * A specialized version of `_.memoize` which clears the memoized function's
26945 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
26948 * @param {Function} func The function to have its output memoized.
26949 * @returns {Function} Returns the new memoized function.
26952 function memoizeCapped(func) {
26953 var result = memoize_1(func, function (key) {
26954 if (cache.size === MAX_MEMOIZE_SIZE) {
26960 var cache = result.cache;
26964 var _memoizeCapped = memoizeCapped;
26966 /** Used to match property names within property paths. */
26968 var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
26969 /** Used to match backslashes in property paths. */
26971 var reEscapeChar = /\\(\\)?/g;
26973 * Converts `string` to a property path array.
26976 * @param {string} string The string to convert.
26977 * @returns {Array} Returns the property path array.
26980 var stringToPath = _memoizeCapped(function (string) {
26983 if (string.charCodeAt(0) === 46
26989 string.replace(rePropName, function (match, number, quote, subString) {
26990 result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
26994 var _stringToPath = stringToPath;
26997 * A specialized version of `_.map` for arrays without support for iteratee
27001 * @param {Array} [array] The array to iterate over.
27002 * @param {Function} iteratee The function invoked per iteration.
27003 * @returns {Array} Returns the new mapped array.
27005 function arrayMap(array, iteratee) {
27007 length = array == null ? 0 : array.length,
27008 result = Array(length);
27010 while (++index < length) {
27011 result[index] = iteratee(array[index], index, array);
27017 var _arrayMap = arrayMap;
27019 /** Used as references for various `Number` constants. */
27021 var INFINITY = 1 / 0;
27022 /** Used to convert symbols to primitives and strings. */
27024 var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
27025 symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
27027 * The base implementation of `_.toString` which doesn't convert nullish
27028 * values to empty strings.
27031 * @param {*} value The value to process.
27032 * @returns {string} Returns the string.
27035 function baseToString(value) {
27036 // Exit early for strings to avoid a performance hit in some environments.
27037 if (typeof value == 'string') {
27041 if (isArray_1(value)) {
27042 // Recursively convert values (susceptible to call stack limits).
27043 return _arrayMap(value, baseToString) + '';
27046 if (isSymbol_1(value)) {
27047 return symbolToString ? symbolToString.call(value) : '';
27050 var result = value + '';
27051 return result == '0' && 1 / value == -INFINITY ? '-0' : result;
27054 var _baseToString = baseToString;
27057 * Converts `value` to a string. An empty string is returned for `null`
27058 * and `undefined` values. The sign of `-0` is preserved.
27064 * @param {*} value The value to convert.
27065 * @returns {string} Returns the converted string.
27068 * _.toString(null);
27074 * _.toString([1, 2, 3]);
27078 function toString(value) {
27079 return value == null ? '' : _baseToString(value);
27082 var toString_1 = toString;
27085 * Casts `value` to a path array if it's not one.
27088 * @param {*} value The value to inspect.
27089 * @param {Object} [object] The object to query keys on.
27090 * @returns {Array} Returns the cast property path array.
27093 function castPath(value, object) {
27094 if (isArray_1(value)) {
27098 return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
27101 var _castPath = castPath;
27103 /** Used as references for various `Number` constants. */
27105 var INFINITY$1 = 1 / 0;
27107 * Converts `value` to a string key if it's not a string or symbol.
27110 * @param {*} value The value to inspect.
27111 * @returns {string|symbol} Returns the key.
27114 function toKey(value) {
27115 if (typeof value == 'string' || isSymbol_1(value)) {
27119 var result = value + '';
27120 return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
27123 var _toKey = toKey;
27126 * The base implementation of `_.get` without support for default values.
27129 * @param {Object} object The object to query.
27130 * @param {Array|string} path The path of the property to get.
27131 * @returns {*} Returns the resolved value.
27134 function baseGet(object, path) {
27135 path = _castPath(path, object);
27137 length = path.length;
27139 while (object != null && index < length) {
27140 object = object[_toKey(path[index++])];
27143 return index && index == length ? object : undefined;
27146 var _baseGet = baseGet;
27149 * Gets the value at `path` of `object`. If the resolved value is
27150 * `undefined`, the `defaultValue` is returned in its place.
27156 * @param {Object} object The object to query.
27157 * @param {Array|string} path The path of the property to get.
27158 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
27159 * @returns {*} Returns the resolved value.
27162 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
27164 * _.get(object, 'a[0].b.c');
27167 * _.get(object, ['a', '0', 'b', 'c']);
27170 * _.get(object, 'a.b.c', 'default');
27174 function get$1(object, path, defaultValue) {
27175 var result = object == null ? undefined : _baseGet(object, path);
27176 return result === undefined ? defaultValue : result;
27182 * The base implementation of `_.hasIn` without support for deep paths.
27185 * @param {Object} [object] The object to query.
27186 * @param {Array|string} key The key to check.
27187 * @returns {boolean} Returns `true` if `key` exists, else `false`.
27189 function baseHasIn(object, key) {
27190 return object != null && key in Object(object);
27193 var _baseHasIn = baseHasIn;
27196 * Checks if `path` exists on `object`.
27199 * @param {Object} object The object to query.
27200 * @param {Array|string} path The path to check.
27201 * @param {Function} hasFunc The function to check properties.
27202 * @returns {boolean} Returns `true` if `path` exists, else `false`.
27205 function hasPath(object, path, hasFunc) {
27206 path = _castPath(path, object);
27208 length = path.length,
27211 while (++index < length) {
27212 var key = _toKey(path[index]);
27214 if (!(result = object != null && hasFunc(object, key))) {
27218 object = object[key];
27221 if (result || ++index != length) {
27225 length = object == null ? 0 : object.length;
27226 return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
27229 var _hasPath = hasPath;
27232 * Checks if `path` is a direct or inherited property of `object`.
27238 * @param {Object} object The object to query.
27239 * @param {Array|string} path The path to check.
27240 * @returns {boolean} Returns `true` if `path` exists, else `false`.
27243 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
27245 * _.hasIn(object, 'a');
27248 * _.hasIn(object, 'a.b');
27251 * _.hasIn(object, ['a', 'b']);
27254 * _.hasIn(object, 'b');
27258 function hasIn(object, path) {
27259 return object != null && _hasPath(object, path, _baseHasIn);
27262 var hasIn_1 = hasIn;
27264 /** Used to compose bitmasks for value comparisons. */
27266 var COMPARE_PARTIAL_FLAG$5 = 1,
27267 COMPARE_UNORDERED_FLAG$3 = 2;
27269 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
27272 * @param {string} path The path of the property to get.
27273 * @param {*} srcValue The value to match.
27274 * @returns {Function} Returns the new spec function.
27277 function baseMatchesProperty(path, srcValue) {
27278 if (_isKey(path) && _isStrictComparable(srcValue)) {
27279 return _matchesStrictComparable(_toKey(path), srcValue);
27282 return function (object) {
27283 var objValue = get_1(object, path);
27284 return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
27288 var _baseMatchesProperty = baseMatchesProperty;
27291 * This method returns the first argument it receives.
27297 * @param {*} value Any value.
27298 * @returns {*} Returns `value`.
27301 * var object = { 'a': 1 };
27303 * console.log(_.identity(object) === object);
27306 function identity(value) {
27310 var identity_1 = identity;
27313 * The base implementation of `_.property` without support for deep paths.
27316 * @param {string} key The key of the property to get.
27317 * @returns {Function} Returns the new accessor function.
27319 function baseProperty(key) {
27320 return function (object) {
27321 return object == null ? undefined : object[key];
27325 var _baseProperty = baseProperty;
27328 * A specialized version of `baseProperty` which supports deep paths.
27331 * @param {Array|string} path The path of the property to get.
27332 * @returns {Function} Returns the new accessor function.
27335 function basePropertyDeep(path) {
27336 return function (object) {
27337 return _baseGet(object, path);
27341 var _basePropertyDeep = basePropertyDeep;
27344 * Creates a function that returns the value at `path` of a given object.
27350 * @param {Array|string} path The path of the property to get.
27351 * @returns {Function} Returns the new accessor function.
27355 * { 'a': { 'b': 2 } },
27356 * { 'a': { 'b': 1 } }
27359 * _.map(objects, _.property('a.b'));
27362 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
27366 function property(path) {
27367 return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
27370 var property_1 = property;
27373 * The base implementation of `_.iteratee`.
27376 * @param {*} [value=_.identity] The value to convert to an iteratee.
27377 * @returns {Function} Returns the iteratee.
27380 function baseIteratee(value) {
27381 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
27382 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
27383 if (typeof value == 'function') {
27387 if (value == null) {
27391 if (typeof value == 'object') {
27392 return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
27395 return property_1(value);
27398 var _baseIteratee = baseIteratee;
27401 * The base implementation of `_.findIndex` and `_.findLastIndex` without
27402 * support for iteratee shorthands.
27405 * @param {Array} array The array to inspect.
27406 * @param {Function} predicate The function invoked per iteration.
27407 * @param {number} fromIndex The index to search from.
27408 * @param {boolean} [fromRight] Specify iterating from right to left.
27409 * @returns {number} Returns the index of the matched value, else `-1`.
27411 function baseFindIndex(array, predicate, fromIndex, fromRight) {
27412 var length = array.length,
27413 index = fromIndex + (fromRight ? 1 : -1);
27415 while (fromRight ? index-- : ++index < length) {
27416 if (predicate(array[index], index, array)) {
27424 var _baseFindIndex = baseFindIndex;
27427 * The base implementation of `_.isNaN` without support for number objects.
27430 * @param {*} value The value to check.
27431 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
27433 function baseIsNaN(value) {
27434 return value !== value;
27437 var _baseIsNaN = baseIsNaN;
27440 * A specialized version of `_.indexOf` which performs strict equality
27441 * comparisons of values, i.e. `===`.
27444 * @param {Array} array The array to inspect.
27445 * @param {*} value The value to search for.
27446 * @param {number} fromIndex The index to search from.
27447 * @returns {number} Returns the index of the matched value, else `-1`.
27449 function strictIndexOf(array, value, fromIndex) {
27450 var index = fromIndex - 1,
27451 length = array.length;
27453 while (++index < length) {
27454 if (array[index] === value) {
27462 var _strictIndexOf = strictIndexOf;
27465 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
27468 * @param {Array} array The array to inspect.
27469 * @param {*} value The value to search for.
27470 * @param {number} fromIndex The index to search from.
27471 * @returns {number} Returns the index of the matched value, else `-1`.
27474 function baseIndexOf(array, value, fromIndex) {
27475 return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex);
27478 var _baseIndexOf = baseIndexOf;
27481 * A specialized version of `_.includes` for arrays without support for
27482 * specifying an index to search from.
27485 * @param {Array} [array] The array to inspect.
27486 * @param {*} target The value to search for.
27487 * @returns {boolean} Returns `true` if `target` is found, else `false`.
27490 function arrayIncludes(array, value) {
27491 var length = array == null ? 0 : array.length;
27492 return !!length && _baseIndexOf(array, value, 0) > -1;
27495 var _arrayIncludes = arrayIncludes;
27498 * This function is like `arrayIncludes` except that it accepts a comparator.
27501 * @param {Array} [array] The array to inspect.
27502 * @param {*} target The value to search for.
27503 * @param {Function} comparator The comparator invoked per element.
27504 * @returns {boolean} Returns `true` if `target` is found, else `false`.
27506 function arrayIncludesWith(array, value, comparator) {
27508 length = array == null ? 0 : array.length;
27510 while (++index < length) {
27511 if (comparator(value, array[index])) {
27519 var _arrayIncludesWith = arrayIncludesWith;
27522 * This method returns `undefined`.
27530 * _.times(2, _.noop);
27531 * // => [undefined, undefined]
27533 function noop() {// No operation performed.
27538 /** Used as references for various `Number` constants. */
27540 var INFINITY$2 = 1 / 0;
27542 * Creates a set object of `values`.
27545 * @param {Array} values The values to add to the set.
27546 * @returns {Object} Returns the new set.
27549 var createSet = !(_Set && 1 / _setToArray(new _Set([, -0]))[1] == INFINITY$2) ? noop_1 : function (values) {
27550 return new _Set(values);
27552 var _createSet = createSet;
27554 /** Used as the size to enable large array optimizations. */
27556 var LARGE_ARRAY_SIZE$1 = 200;
27558 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
27561 * @param {Array} array The array to inspect.
27562 * @param {Function} [iteratee] The iteratee invoked per element.
27563 * @param {Function} [comparator] The comparator invoked per element.
27564 * @returns {Array} Returns the new duplicate free array.
27567 function baseUniq(array, iteratee, comparator) {
27569 includes = _arrayIncludes,
27570 length = array.length,
27577 includes = _arrayIncludesWith;
27578 } else if (length >= LARGE_ARRAY_SIZE$1) {
27579 var set = iteratee ? null : _createSet(array);
27582 return _setToArray(set);
27586 includes = _cacheHas;
27587 seen = new _SetCache();
27589 seen = iteratee ? [] : result;
27592 outer: while (++index < length) {
27593 var value = array[index],
27594 computed = iteratee ? iteratee(value) : value;
27595 value = comparator || value !== 0 ? value : 0;
27597 if (isCommon && computed === computed) {
27598 var seenIndex = seen.length;
27600 while (seenIndex--) {
27601 if (seen[seenIndex] === computed) {
27607 seen.push(computed);
27610 result.push(value);
27611 } else if (!includes(seen, computed, comparator)) {
27612 if (seen !== result) {
27613 seen.push(computed);
27616 result.push(value);
27623 var _baseUniq = baseUniq;
27626 * This method is like `_.uniq` except that it accepts `iteratee` which is
27627 * invoked for each element in `array` to generate the criterion by which
27628 * uniqueness is computed. The order of result values is determined by the
27629 * order they occur in the array. The iteratee is invoked with one argument:
27636 * @param {Array} array The array to inspect.
27637 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
27638 * @returns {Array} Returns the new duplicate free array.
27641 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
27644 * // The `_.property` iteratee shorthand.
27645 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
27646 * // => [{ 'x': 1 }, { 'x': 2 }]
27649 function uniqBy(array, iteratee) {
27650 return array && array.length ? _baseUniq(array, _baseIteratee(iteratee)) : [];
27653 var uniqBy_1 = uniqBy;
27656 * A specialized version of `baseAggregator` for arrays.
27659 * @param {Array} [array] The array to iterate over.
27660 * @param {Function} setter The function to set `accumulator` values.
27661 * @param {Function} iteratee The iteratee to transform keys.
27662 * @param {Object} accumulator The initial aggregated object.
27663 * @returns {Function} Returns `accumulator`.
27665 function arrayAggregator(array, setter, iteratee, accumulator) {
27667 length = array == null ? 0 : array.length;
27669 while (++index < length) {
27670 var value = array[index];
27671 setter(accumulator, value, iteratee(value), array);
27674 return accumulator;
27677 var _arrayAggregator = arrayAggregator;
27680 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
27683 * @param {boolean} [fromRight] Specify iterating from right to left.
27684 * @returns {Function} Returns the new base function.
27686 function createBaseFor(fromRight) {
27687 return function (object, iteratee, keysFunc) {
27689 iterable = Object(object),
27690 props = keysFunc(object),
27691 length = props.length;
27694 var key = props[fromRight ? length : ++index];
27696 if (iteratee(iterable[key], key, iterable) === false) {
27705 var _createBaseFor = createBaseFor;
27708 * The base implementation of `baseForOwn` which iterates over `object`
27709 * properties returned by `keysFunc` and invokes `iteratee` for each property.
27710 * Iteratee functions may exit iteration early by explicitly returning `false`.
27713 * @param {Object} object The object to iterate over.
27714 * @param {Function} iteratee The function invoked per iteration.
27715 * @param {Function} keysFunc The function to get the keys of `object`.
27716 * @returns {Object} Returns `object`.
27719 var baseFor = _createBaseFor();
27720 var _baseFor = baseFor;
27723 * The base implementation of `_.forOwn` without support for iteratee shorthands.
27726 * @param {Object} object The object to iterate over.
27727 * @param {Function} iteratee The function invoked per iteration.
27728 * @returns {Object} Returns `object`.
27731 function baseForOwn(object, iteratee) {
27732 return object && _baseFor(object, iteratee, keys_1);
27735 var _baseForOwn = baseForOwn;
27738 * Creates a `baseEach` or `baseEachRight` function.
27741 * @param {Function} eachFunc The function to iterate over a collection.
27742 * @param {boolean} [fromRight] Specify iterating from right to left.
27743 * @returns {Function} Returns the new base function.
27746 function createBaseEach(eachFunc, fromRight) {
27747 return function (collection, iteratee) {
27748 if (collection == null) {
27752 if (!isArrayLike_1(collection)) {
27753 return eachFunc(collection, iteratee);
27756 var length = collection.length,
27757 index = fromRight ? length : -1,
27758 iterable = Object(collection);
27760 while (fromRight ? index-- : ++index < length) {
27761 if (iteratee(iterable[index], index, iterable) === false) {
27770 var _createBaseEach = createBaseEach;
27773 * The base implementation of `_.forEach` without support for iteratee shorthands.
27776 * @param {Array|Object} collection The collection to iterate over.
27777 * @param {Function} iteratee The function invoked per iteration.
27778 * @returns {Array|Object} Returns `collection`.
27781 var baseEach = _createBaseEach(_baseForOwn);
27782 var _baseEach = baseEach;
27785 * Aggregates elements of `collection` on `accumulator` with keys transformed
27786 * by `iteratee` and values set by `setter`.
27789 * @param {Array|Object} collection The collection to iterate over.
27790 * @param {Function} setter The function to set `accumulator` values.
27791 * @param {Function} iteratee The iteratee to transform keys.
27792 * @param {Object} accumulator The initial aggregated object.
27793 * @returns {Function} Returns `accumulator`.
27796 function baseAggregator(collection, setter, iteratee, accumulator) {
27797 _baseEach(collection, function (value, key, collection) {
27798 setter(accumulator, value, iteratee(value), collection);
27800 return accumulator;
27803 var _baseAggregator = baseAggregator;
27806 * Creates a function like `_.groupBy`.
27809 * @param {Function} setter The function to set accumulator values.
27810 * @param {Function} [initializer] The accumulator object initializer.
27811 * @returns {Function} Returns the new aggregator function.
27814 function createAggregator(setter, initializer) {
27815 return function (collection, iteratee) {
27816 var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
27817 accumulator = initializer ? initializer() : {};
27818 return func(collection, setter, _baseIteratee(iteratee), accumulator);
27822 var _createAggregator = createAggregator;
27825 * Creates an array of elements split into two groups, the first of which
27826 * contains elements `predicate` returns truthy for, the second of which
27827 * contains elements `predicate` returns falsey for. The predicate is
27828 * invoked with one argument: (value).
27833 * @category Collection
27834 * @param {Array|Object} collection The collection to iterate over.
27835 * @param {Function} [predicate=_.identity] The function invoked per iteration.
27836 * @returns {Array} Returns the array of grouped elements.
27840 * { 'user': 'barney', 'age': 36, 'active': false },
27841 * { 'user': 'fred', 'age': 40, 'active': true },
27842 * { 'user': 'pebbles', 'age': 1, 'active': false }
27845 * _.partition(users, function(o) { return o.active; });
27846 * // => objects for [['fred'], ['barney', 'pebbles']]
27848 * // The `_.matches` iteratee shorthand.
27849 * _.partition(users, { 'age': 1, 'active': false });
27850 * // => objects for [['pebbles'], ['barney', 'fred']]
27852 * // The `_.matchesProperty` iteratee shorthand.
27853 * _.partition(users, ['active', false]);
27854 * // => objects for [['barney', 'pebbles'], ['fred']]
27856 * // The `_.property` iteratee shorthand.
27857 * _.partition(users, 'active');
27858 * // => objects for [['fred'], ['barney', 'pebbles']]
27861 var partition = _createAggregator(function (result, value, key) {
27862 result[key ? 0 : 1].push(value);
27866 var partition_1 = partition;
27868 var arrayUnion = (...arguments_) => {
27869 return [...new Set([].concat(...arguments_))];
27874 * https://github.com/teambition/merge2
27876 * Copyright (c) 2014-2016 Teambition
27877 * Licensed under the MIT license.
27881 const PassThrough = stream$6.PassThrough;
27882 const slice = Array.prototype.slice;
27883 var merge2_1 = merge2;
27885 function merge2() {
27886 const streamsQueue = [];
27887 let merging = false;
27888 const args = slice.call(arguments);
27889 let options = args[args.length - 1];
27890 if (options && !Array.isArray(options) && options.pipe == null) args.pop();else options = {};
27891 const doEnd = options.end !== false;
27892 if (options.objectMode == null) options.objectMode = true;
27893 if (options.highWaterMark == null) options.highWaterMark = 64 * 1024;
27894 const mergedStream = PassThrough(options);
27896 function addStream() {
27897 for (let i = 0, len = arguments.length; i < len; i++) {
27898 streamsQueue.push(pauseStreams(arguments[i], options));
27905 function mergeStream() {
27906 if (merging) return;
27908 let streams = streamsQueue.shift();
27911 process.nextTick(endStream);
27915 if (!Array.isArray(streams)) streams = [streams];
27916 let pipesCount = streams.length + 1;
27919 if (--pipesCount > 0) return;
27924 function pipe(stream) {
27926 stream.removeListener('merge2UnpipeEnd', onend);
27927 stream.removeListener('end', onend);
27929 } // skip ended stream
27932 if (stream._readableState.endEmitted) return next();
27933 stream.on('merge2UnpipeEnd', onend);
27934 stream.on('end', onend);
27935 stream.pipe(mergedStream, {
27937 }); // compatible for old stream
27942 for (let i = 0; i < streams.length; i++) pipe(streams[i]);
27947 function endStream() {
27948 merging = false; // emit 'queueDrain' when all streams merged.
27950 mergedStream.emit('queueDrain');
27951 return doEnd && mergedStream.end();
27954 mergedStream.setMaxListeners(0);
27955 mergedStream.add = addStream;
27956 mergedStream.on('unpipe', function (stream) {
27957 stream.emit('merge2UnpipeEnd');
27959 if (args.length) addStream.apply(null, args);
27960 return mergedStream;
27961 } // check and pause streams for pipe.
27964 function pauseStreams(streams, options) {
27965 if (!Array.isArray(streams)) {
27966 // Backwards-compat with old-style streams
27967 if (!streams._readableState && streams.pipe) streams = streams.pipe(PassThrough(options));
27969 if (!streams._readableState || !streams.pause || !streams.pipe) {
27970 throw new Error('Only readable stream can be merged.');
27975 for (let i = 0, len = streams.length; i < len; i++) streams[i] = pauseStreams(streams[i], options);
27981 var array$2 = createCommonjsModule(function (module, exports) {
27983 Object.defineProperty(exports, "__esModule", {
27987 function flatten(items) {
27988 return items.reduce((collection, item) => [].concat(collection, item), []);
27991 exports.flatten = flatten;
27993 function splitWhen(items, predicate) {
27994 const result = [[]];
27995 let groupIndex = 0;
27997 for (const item of items) {
27998 if (predicate(item)) {
28000 result[groupIndex] = [];
28002 result[groupIndex].push(item);
28009 exports.splitWhen = splitWhen;
28011 unwrapExports(array$2);
28012 var array_1$1 = array$2.flatten;
28013 var array_2 = array$2.splitWhen;
28015 var errno = createCommonjsModule(function (module, exports) {
28017 Object.defineProperty(exports, "__esModule", {
28021 function isEnoentCodeError(error) {
28022 return error.code === 'ENOENT';
28025 exports.isEnoentCodeError = isEnoentCodeError;
28027 unwrapExports(errno);
28028 var errno_1 = errno.isEnoentCodeError;
28030 var fs$1 = createCommonjsModule(function (module, exports) {
28032 Object.defineProperty(exports, "__esModule", {
28036 class DirentFromStats {
28037 constructor(name, stats) {
28039 this.isBlockDevice = stats.isBlockDevice.bind(stats);
28040 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
28041 this.isDirectory = stats.isDirectory.bind(stats);
28042 this.isFIFO = stats.isFIFO.bind(stats);
28043 this.isFile = stats.isFile.bind(stats);
28044 this.isSocket = stats.isSocket.bind(stats);
28045 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
28050 function createDirentFromStats(name, stats) {
28051 return new DirentFromStats(name, stats);
28054 exports.createDirentFromStats = createDirentFromStats;
28056 unwrapExports(fs$1);
28057 var fs_1 = fs$1.createDirentFromStats;
28059 var path_1 = createCommonjsModule(function (module, exports) {
28061 Object.defineProperty(exports, "__esModule", {
28064 const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
28066 const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
28068 * Designed to work only with simple paths: `dir\\file`.
\r
28071 function unixify(filepath) {
28072 return filepath.replace(/\\/g, '/');
28075 exports.unixify = unixify;
28077 function makeAbsolute(cwd, filepath) {
28078 return path$2.resolve(cwd, filepath);
28081 exports.makeAbsolute = makeAbsolute;
28083 function escape(pattern) {
28084 return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
28087 exports.escape = escape;
28089 function removeLeadingDotSegment(entry) {
28090 // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
28091 // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
28092 if (entry.charAt(0) === '.') {
28093 const secondCharactery = entry.charAt(1);
28095 if (secondCharactery === '/' || secondCharactery === '\\') {
28096 return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
28103 exports.removeLeadingDotSegment = removeLeadingDotSegment;
28105 unwrapExports(path_1);
28106 var path_2 = path_1.unixify;
28107 var path_3 = path_1.makeAbsolute;
28108 var path_4 = path_1.escape;
28109 var path_5 = path_1.removeLeadingDotSegment;
28112 * is-extglob <https://github.com/jonschlinkert/is-extglob>
28114 * Copyright (c) 2014-2016, Jon Schlinkert.
28115 * Licensed under the MIT License.
28117 var isExtglob = function isExtglob(str) {
28118 if (typeof str !== 'string' || str === '') {
28124 while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
28125 if (match[2]) return true;
28126 str = str.slice(match.index + match[0].length);
28133 * is-glob <https://github.com/jonschlinkert/is-glob>
28135 * Copyright (c) 2014-2017, Jon Schlinkert.
28136 * Released under the MIT License.
28144 var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
28145 var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
28147 var isGlob = function isGlob(str, options) {
28148 if (typeof str !== 'string' || str === '') {
28152 if (isExtglob(str)) {
28156 var regex = strictRegex;
28157 var match; // optionally relax regex
28159 if (options && options.strict === false) {
28160 regex = relaxedRegex;
28163 while (match = regex.exec(str)) {
28164 if (match[2]) return true;
28165 var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
28166 // set the index to the next closing character
28168 var open = match[1];
28169 var close = open ? chars[open] : null;
28171 if (open && close) {
28172 var n = str.indexOf(close, idx);
28179 str = str.slice(idx);
28185 var pathPosixDirname = path$2.posix.dirname;
28186 var isWin32 = os$1.platform() === 'win32';
28188 var backslash = /\\/g;
28189 var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
28190 var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
28191 var escaped = /\\([\*\?\|\[\]\(\)\{\}])/g;
28193 * @param {string} str
28194 * @param {Object} opts
28195 * @param {boolean} [opts.flipBackslashes=true]
28198 var globParent = function globParent(str, opts) {
28199 var options = Object.assign({
28200 flipBackslashes: true
28201 }, opts); // flip windows path separators
28203 if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
28204 str = str.replace(backslash, slash);
28205 } // special case for strings ending in enclosure containing path separator
28208 if (enclosure.test(str)) {
28210 } // preserves full path in case of trailing path separator
28213 str += 'a'; // remove path parts that are globby
28216 str = pathPosixDirname(str);
28217 } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
28220 return str.replace(escaped, '$1');
28223 var utils$2 = createCommonjsModule(function (module, exports) {
28225 exports.isInteger = num => {
28226 if (typeof num === 'number') {
28227 return Number.isInteger(num);
28230 if (typeof num === 'string' && num.trim() !== '') {
28231 return Number.isInteger(Number(num));
28237 * Find a node of the given type
28241 exports.find = (node, type) => node.nodes.find(node => node.type === type);
28243 * Find a node of the given type
28247 exports.exceedsLimit = (min, max, step = 1, limit) => {
28248 if (limit === false) return false;
28249 if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
28250 return (Number(max) - Number(min)) / Number(step) >= limit;
28253 * Escape the given node with '\\' before node.value
28257 exports.escapeNode = (block, n = 0, type) => {
28258 let node = block.nodes[n];
28261 if (type && node.type === type || node.type === 'open' || node.type === 'close') {
28262 if (node.escaped !== true) {
28263 node.value = '\\' + node.value;
28264 node.escaped = true;
28269 * Returns true if the given brace node should be enclosed in literal braces
28273 exports.encloseBrace = node => {
28274 if (node.type !== 'brace') return false;
28276 if (node.commas >> 0 + node.ranges >> 0 === 0) {
28277 node.invalid = true;
28284 * Returns true if a brace node is invalid.
28288 exports.isInvalidBrace = block => {
28289 if (block.type !== 'brace') return false;
28290 if (block.invalid === true || block.dollar) return true;
28292 if (block.commas >> 0 + block.ranges >> 0 === 0) {
28293 block.invalid = true;
28297 if (block.open !== true || block.close !== true) {
28298 block.invalid = true;
28305 * Returns true if a node is an open or close node
28309 exports.isOpenOrClose = node => {
28310 if (node.type === 'open' || node.type === 'close') {
28314 return node.open === true || node.close === true;
28317 * Reduce an array of text nodes.
28321 exports.reduce = nodes => nodes.reduce((acc, node) => {
28322 if (node.type === 'text') acc.push(node.value);
28323 if (node.type === 'range') node.type = 'text';
28331 exports.flatten = (...args) => {
28334 const flat = arr => {
28335 for (let i = 0; i < arr.length; i++) {
28337 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
28347 var utils_1$2 = utils$2.isInteger;
28348 var utils_2$2 = utils$2.find;
28349 var utils_3$2 = utils$2.exceedsLimit;
28350 var utils_4$1 = utils$2.escapeNode;
28351 var utils_5$1 = utils$2.encloseBrace;
28352 var utils_6$1 = utils$2.isInvalidBrace;
28353 var utils_7$1 = utils$2.isOpenOrClose;
28354 var utils_8$1 = utils$2.reduce;
28355 var utils_9$1 = utils$2.flatten;
28357 var stringify = (ast, options = {}) => {
28358 let stringify = (node, parent = {}) => {
28359 let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);
28360 let invalidNode = node.invalid === true && options.escapeInvalid === true;
28364 if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {
28365 return '\\' + node.value;
28376 for (let child of node.nodes) {
28377 output += stringify(child);
28384 return stringify(ast);
28388 * is-number <https://github.com/jonschlinkert/is-number>
28390 * Copyright (c) 2014-present, Jon Schlinkert.
28391 * Released under the MIT License.
28394 var isNumber = function (num) {
28395 if (typeof num === 'number') {
28396 return num - num === 0;
28399 if (typeof num === 'string' && num.trim() !== '') {
28400 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
28406 const toRegexRange = (min, max, options) => {
28407 if (isNumber(min) === false) {
28408 throw new TypeError('toRegexRange: expected the first argument to be a number');
28411 if (max === void 0 || min === max) {
28412 return String(min);
28415 if (isNumber(max) === false) {
28416 throw new TypeError('toRegexRange: expected the second argument to be a number.');
28419 let opts = Object.assign({
28423 if (typeof opts.strictZeros === 'boolean') {
28424 opts.relaxZeros = opts.strictZeros === false;
28427 let relax = String(opts.relaxZeros);
28428 let shorthand = String(opts.shorthand);
28429 let capture = String(opts.capture);
28430 let wrap = String(opts.wrap);
28431 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
28433 if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
28434 return toRegexRange.cache[cacheKey].result;
28437 let a = Math.min(min, max);
28438 let b = Math.max(min, max);
28440 if (Math.abs(a - b) === 1) {
28441 let result = min + '|' + max;
28443 if (opts.capture) {
28444 return `(${result})`;
28447 if (opts.wrap === false) {
28451 return `(?:${result})`;
28454 let isPadded = hasPadding(min) || hasPadding(max);
28461 let positives = [];
28462 let negatives = [];
28465 state.isPadded = isPadded;
28466 state.maxLen = String(state.max).length;
28470 let newMin = b < 0 ? Math.abs(b) : 1;
28471 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
28476 positives = splitToPatterns(a, b, state, opts);
28479 state.negatives = negatives;
28480 state.positives = positives;
28481 state.result = collatePatterns(negatives, positives);
28483 if (opts.capture === true) {
28484 state.result = `(${state.result})`;
28485 } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
28486 state.result = `(?:${state.result})`;
28489 toRegexRange.cache[cacheKey] = state;
28490 return state.result;
28493 function collatePatterns(neg, pos, options) {
28494 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
28495 let onlyPositive = filterPatterns(pos, neg, '', false) || [];
28496 let intersected = filterPatterns(neg, pos, '-?', true) || [];
28497 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
28498 return subpatterns.join('|');
28501 function splitToRanges(min, max) {
28504 let stop = countNines(min, nines);
28505 let stops = new Set([max]);
28507 while (min <= stop && stop <= max) {
28510 stop = countNines(min, nines);
28513 stop = countZeros(max + 1, zeros) - 1;
28515 while (min < stop && stop <= max) {
28518 stop = countZeros(max + 1, zeros) - 1;
28521 stops = [...stops];
28522 stops.sort(compare$1);
28526 * Convert a range to a regex pattern
28527 * @param {Number} `start`
28528 * @param {Number} `stop`
28533 function rangeToPattern(start, stop, options) {
28534 if (start === stop) {
28542 let zipped = zip(start, stop);
28543 let digits = zipped.length;
28547 for (let i = 0; i < digits; i++) {
28548 let [startDigit, stopDigit] = zipped[i];
28550 if (startDigit === stopDigit) {
28551 pattern += startDigit;
28552 } else if (startDigit !== '0' || stopDigit !== '9') {
28553 pattern += toCharacterClass(startDigit, stopDigit);
28560 pattern += options.shorthand === true ? '\\d' : '[0-9]';
28570 function splitToPatterns(min, max, tok, options) {
28571 let ranges = splitToRanges(min, max);
28576 for (let i = 0; i < ranges.length; i++) {
28577 let max = ranges[i];
28578 let obj = rangeToPattern(String(start), String(max), options);
28581 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
28582 if (prev.count.length > 1) {
28586 prev.count.push(obj.count[0]);
28587 prev.string = prev.pattern + toQuantifier(prev.count);
28592 if (tok.isPadded) {
28593 zeros = padZeros(max, tok, options);
28596 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
28605 function filterPatterns(arr, comparison, prefix, intersection, options) {
28608 for (let ele of arr) {
28611 } = ele; // only push if _both_ are negative...
28613 if (!intersection && !contains(comparison, 'string', string)) {
28614 result.push(prefix + string);
28615 } // or _both_ are positive
28618 if (intersection && contains(comparison, 'string', string)) {
28619 result.push(prefix + string);
28630 function zip(a, b) {
28633 for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
28638 function compare$1(a, b) {
28639 return a > b ? 1 : b > a ? -1 : 0;
28642 function contains(arr, key, val) {
28643 return arr.some(ele => ele[key] === val);
28646 function countNines(min, len) {
28647 return Number(String(min).slice(0, -len) + '9'.repeat(len));
28650 function countZeros(integer, zeros) {
28651 return integer - integer % Math.pow(10, zeros);
28654 function toQuantifier(digits) {
28655 let [start = 0, stop = ''] = digits;
28657 if (stop || start > 1) {
28658 return `{${start + (stop ? ',' + stop : '')}}`;
28664 function toCharacterClass(a, b, options) {
28665 return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
28668 function hasPadding(str) {
28669 return /^-?(0+)\d/.test(str);
28672 function padZeros(value, tok, options) {
28673 if (!tok.isPadded) {
28677 let diff = Math.abs(tok.maxLen - String(value).length);
28678 let relax = options.relaxZeros !== false;
28685 return relax ? '0?' : '0';
28688 return relax ? '0{0,2}' : '00';
28692 return relax ? `0{0,${diff}}` : `0{${diff}}`;
28701 toRegexRange.cache = {};
28703 toRegexRange.clearCache = () => toRegexRange.cache = {};
28705 * Expose `toRegexRange`
28709 var toRegexRange_1 = toRegexRange;
28711 const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
28713 const transform = toNumber => {
28714 return value => toNumber === true ? Number(value) : String(value);
28717 const isValidValue = value => {
28718 return typeof value === 'number' || typeof value === 'string' && value !== '';
28721 const isNumber$1 = num => Number.isInteger(+num);
28723 const zeros = input => {
28724 let value = `${input}`;
28726 if (value[0] === '-') value = value.slice(1);
28727 if (value === '0') return false;
28729 while (value[++index] === '0');
28734 const stringify$1 = (start, end, options) => {
28735 if (typeof start === 'string' || typeof end === 'string') {
28739 return options.stringify === true;
28742 const pad = (input, maxLength, toNumber) => {
28743 if (maxLength > 0) {
28744 let dash = input[0] === '-' ? '-' : '';
28745 if (dash) input = input.slice(1);
28746 input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
28749 if (toNumber === false) {
28750 return String(input);
28756 const toMaxLen = (input, maxLength) => {
28757 let negative = input[0] === '-' ? '-' : '';
28760 input = input.slice(1);
28764 while (input.length < maxLength) input = '0' + input;
28766 return negative ? '-' + input : input;
28769 const toSequence = (parts, options) => {
28770 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
28771 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
28772 let prefix = options.capture ? '' : '?:';
28773 let positives = '';
28774 let negatives = '';
28777 if (parts.positives.length) {
28778 positives = parts.positives.join('|');
28781 if (parts.negatives.length) {
28782 negatives = `-(${prefix}${parts.negatives.join('|')})`;
28785 if (positives && negatives) {
28786 result = `${positives}|${negatives}`;
28788 result = positives || negatives;
28791 if (options.wrap) {
28792 return `(${prefix}${result})`;
28798 const toRange = (a, b, isNumbers, options) => {
28800 return toRegexRange_1(a, b, Object.assign({
28805 let start = String.fromCharCode(a);
28806 if (a === b) return start;
28807 let stop = String.fromCharCode(b);
28808 return `[${start}-${stop}]`;
28811 const toRegex = (start, end, options) => {
28812 if (Array.isArray(start)) {
28813 let wrap = options.wrap === true;
28814 let prefix = options.capture ? '' : '?:';
28815 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
28818 return toRegexRange_1(start, end, options);
28821 const rangeError = (...args) => {
28822 return new RangeError('Invalid range arguments: ' + util$3.inspect(...args));
28825 const invalidRange = (start, end, options) => {
28826 if (options.strictRanges === true) throw rangeError([start, end]);
28830 const invalidStep = (step, options) => {
28831 if (options.strictRanges === true) {
28832 throw new TypeError(`Expected step "${step}" to be a number`);
28838 const fillNumbers = (start, end, step = 1, options = {}) => {
28839 let a = Number(start);
28840 let b = Number(end);
28842 if (!Number.isInteger(a) || !Number.isInteger(b)) {
28843 if (options.strictRanges === true) throw rangeError([start, end]);
28845 } // fix negative zero
28848 if (a === 0) a = 0;
28849 if (b === 0) b = 0;
28850 let descending = a > b;
28851 let startString = String(start);
28852 let endString = String(end);
28853 let stepString = String(step);
28854 step = Math.max(Math.abs(step), 1);
28855 let padded = zeros(startString) || zeros(endString) || zeros(stepString);
28856 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
28857 let toNumber = padded === false && stringify$1(start, end, options) === false;
28858 let format = options.transform || transform(toNumber);
28860 if (options.toRegex && step === 1) {
28861 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
28869 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
28874 while (descending ? a >= b : a <= b) {
28875 if (options.toRegex === true && step > 1) {
28878 range.push(pad(format(a, index), maxLen, toNumber));
28881 a = descending ? a - step : a + step;
28885 if (options.toRegex === true) {
28886 return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
28894 const fillLetters = (start, end, step = 1, options = {}) => {
28895 if (!isNumber$1(start) && start.length > 1 || !isNumber$1(end) && end.length > 1) {
28896 return invalidRange(start, end, options);
28899 let format = options.transform || (val => String.fromCharCode(val));
28901 let a = `${start}`.charCodeAt(0);
28902 let b = `${end}`.charCodeAt(0);
28903 let descending = a > b;
28904 let min = Math.min(a, b);
28905 let max = Math.max(a, b);
28907 if (options.toRegex && step === 1) {
28908 return toRange(min, max, false, options);
28914 while (descending ? a >= b : a <= b) {
28915 range.push(format(a, index));
28916 a = descending ? a - step : a + step;
28920 if (options.toRegex === true) {
28921 return toRegex(range, null, {
28930 const fill$2 = (start, end, step, options = {}) => {
28931 if (end == null && isValidValue(start)) {
28935 if (!isValidValue(start) || !isValidValue(end)) {
28936 return invalidRange(start, end, options);
28939 if (typeof step === 'function') {
28940 return fill$2(start, end, 1, {
28945 if (isObject$1(step)) {
28946 return fill$2(start, end, 0, step);
28949 let opts = Object.assign({}, options);
28950 if (opts.capture === true) opts.wrap = true;
28951 step = step || opts.step || 1;
28953 if (!isNumber$1(step)) {
28954 if (step != null && !isObject$1(step)) return invalidStep(step, opts);
28955 return fill$2(start, end, 1, step);
28958 if (isNumber$1(start) && isNumber$1(end)) {
28959 return fillNumbers(start, end, step, opts);
28962 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
28965 var fillRange = fill$2;
28967 const compile = (ast, options = {}) => {
28968 let walk = (node, parent = {}) => {
28969 let invalidBlock = utils$2.isInvalidBrace(parent);
28970 let invalidNode = node.invalid === true && options.escapeInvalid === true;
28971 let invalid = invalidBlock === true || invalidNode === true;
28972 let prefix = options.escapeInvalid === true ? '\\' : '';
28975 if (node.isOpen === true) {
28976 return prefix + node.value;
28979 if (node.isClose === true) {
28980 return prefix + node.value;
28983 if (node.type === 'open') {
28984 return invalid ? prefix + node.value : '(';
28987 if (node.type === 'close') {
28988 return invalid ? prefix + node.value : ')';
28991 if (node.type === 'comma') {
28992 return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
28999 if (node.nodes && node.ranges > 0) {
29000 let args = utils$2.reduce(node.nodes);
29001 let range = fillRange(...args, Object.assign({}, options, {
29006 if (range.length !== 0) {
29007 return args.length > 1 && range.length > 1 ? `(${range})` : range;
29012 for (let child of node.nodes) {
29013 output += walk(child, node);
29023 var compile_1 = compile;
29025 const append = (queue = '', stash = '', enclose = false) => {
29027 queue = [].concat(queue);
29028 stash = [].concat(stash);
29029 if (!stash.length) return queue;
29031 if (!queue.length) {
29032 return enclose ? utils$2.flatten(stash).map(ele => `{${ele}}`) : stash;
29035 for (let item of queue) {
29036 if (Array.isArray(item)) {
29037 for (let value of item) {
29038 result.push(append(value, stash, enclose));
29041 for (let ele of stash) {
29042 if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
29043 result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
29048 return utils$2.flatten(result);
29051 const expand$1 = (ast, options = {}) => {
29052 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
29054 let walk = (node, parent = {}) => {
29057 let q = parent.queue;
29059 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
29064 if (node.invalid || node.dollar) {
29065 q.push(append(q.pop(), stringify(node, options)));
29069 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
29070 q.push(append(q.pop(), ['{}']));
29074 if (node.nodes && node.ranges > 0) {
29075 let args = utils$2.reduce(node.nodes);
29077 if (utils$2.exceedsLimit(...args, options.step, rangeLimit)) {
29078 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
29081 let range = fillRange(...args, options);
29083 if (range.length === 0) {
29084 range = stringify(node, options);
29087 q.push(append(q.pop(), range));
29092 let enclose = utils$2.encloseBrace(node);
29093 let queue = node.queue;
29096 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
29097 block = block.parent;
29098 queue = block.queue;
29101 for (let i = 0; i < node.nodes.length; i++) {
29102 let child = node.nodes[i];
29104 if (child.type === 'comma' && node.type === 'brace') {
29105 if (i === 1) queue.push('');
29110 if (child.type === 'close') {
29111 q.push(append(q.pop(), queue, enclose));
29115 if (child.value && child.type !== 'open') {
29116 queue.push(append(queue.pop(), child.value));
29128 return utils$2.flatten(walk(ast));
29131 var expand_1 = expand$1;
29133 var constants$2 = {
29134 MAX_LENGTH: 1024 * 64,
29143 CHAR_UPPERCASE_A: 'A',
29146 CHAR_LOWERCASE_A: 'a',
29149 CHAR_UPPERCASE_Z: 'Z',
29152 CHAR_LOWERCASE_Z: 'z',
29155 CHAR_LEFT_PARENTHESES: '(',
29158 CHAR_RIGHT_PARENTHESES: ')',
29161 CHAR_ASTERISK: '*',
29164 // Non-alphabetic chars.
29165 CHAR_AMPERSAND: '&',
29171 CHAR_BACKSLASH: '\\',
29174 CHAR_BACKTICK: '`',
29177 CHAR_CARRIAGE_RETURN: '\r',
29180 CHAR_CIRCUMFLEX_ACCENT: '^',
29195 CHAR_DOUBLE_QUOTE: '"',
29201 CHAR_EXCLAMATION_MARK: '!',
29204 CHAR_FORM_FEED: '\f',
29207 CHAR_FORWARD_SLASH: '/',
29213 CHAR_HYPHEN_MINUS: '-',
29216 CHAR_LEFT_ANGLE_BRACKET: '<',
29219 CHAR_LEFT_CURLY_BRACE: '{',
29222 CHAR_LEFT_SQUARE_BRACKET: '[',
29225 CHAR_LINE_FEED: '\n',
29228 CHAR_NO_BREAK_SPACE: '\u00A0',
29237 CHAR_QUESTION_MARK: '?',
29240 CHAR_RIGHT_ANGLE_BRACKET: '>',
29243 CHAR_RIGHT_CURLY_BRACE: '}',
29246 CHAR_RIGHT_SQUARE_BRACKET: ']',
29249 CHAR_SEMICOLON: ';',
29252 CHAR_SINGLE_QUOTE: '\'',
29261 CHAR_UNDERSCORE: '_',
29264 CHAR_VERTICAL_LINE: '|',
29267 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
29278 MAX_LENGTH: MAX_LENGTH$2,
29285 CHAR_COMMA: CHAR_COMMA$1,
29291 CHAR_LEFT_PARENTHESES,
29294 CHAR_RIGHT_PARENTHESES,
29297 CHAR_LEFT_CURLY_BRACE,
29300 CHAR_RIGHT_CURLY_BRACE,
29303 CHAR_LEFT_SQUARE_BRACKET,
29306 CHAR_RIGHT_SQUARE_BRACKET,
29315 CHAR_NO_BREAK_SPACE,
29316 CHAR_ZERO_WIDTH_NOBREAK_SPACE
29322 const parse$3 = (input, options = {}) => {
29323 if (typeof input !== 'string') {
29324 throw new TypeError('Expected a string');
29327 let opts = options || {};
29328 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2;
29330 if (input.length > max) {
29331 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
29343 let length = input.length;
29351 const advance = () => input[index++];
29353 const push = node => {
29354 if (node.type === 'text' && prev.type === 'dot') {
29355 prev.type = 'text';
29358 if (prev && prev.type === 'text' && node.type === 'text') {
29359 prev.value += node.value;
29363 block.nodes.push(node);
29364 node.parent = block;
29374 while (index < length) {
29375 block = stack[stack.length - 1];
29381 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
29389 if (value === CHAR_BACKSLASH) {
29392 value: (options.keepEscaping ? value : '') + advance()
29397 * Right square bracket (literal): ']'
29401 if (value === CHAR_RIGHT_SQUARE_BRACKET) {
29404 value: '\\' + value
29409 * Left square bracket: '['
29413 if (value === CHAR_LEFT_SQUARE_BRACKET) {
29417 while (index < length && (next = advance())) {
29420 if (next === CHAR_LEFT_SQUARE_BRACKET) {
29425 if (next === CHAR_BACKSLASH) {
29426 value += advance();
29430 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
29433 if (brackets === 0) {
29450 if (value === CHAR_LEFT_PARENTHESES) {
29463 if (value === CHAR_RIGHT_PARENTHESES) {
29464 if (block.type !== 'paren') {
29472 block = stack.pop();
29477 block = stack[stack.length - 1];
29485 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
29489 if (options.keepQuotes !== true) {
29493 while (index < length && (next = advance())) {
29494 if (next === CHAR_BACKSLASH) {
29495 value += next + advance();
29499 if (next === open) {
29500 if (options.keepQuotes === true) value += next;
29514 * Left curly brace: '{'
29518 if (value === CHAR_LEFT_CURLY_BRACE) {
29520 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
29531 block = push(brace);
29540 * Right curly brace: '}'
29544 if (value === CHAR_RIGHT_CURLY_BRACE) {
29545 if (block.type !== 'brace') {
29553 let type = 'close';
29554 block = stack.pop();
29555 block.close = true;
29561 block = stack[stack.length - 1];
29569 if (value === CHAR_COMMA$1 && depth > 0) {
29570 if (block.ranges > 0) {
29572 let open = block.nodes.shift();
29573 block.nodes = [open, {
29575 value: stringify(block)
29591 if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
29592 let siblings = block.nodes;
29594 if (depth === 0 || siblings.length === 0) {
29602 if (prev.type === 'dot') {
29604 prev.value += value;
29605 prev.type = 'range';
29607 if (block.nodes.length !== 3 && block.nodes.length !== 5) {
29608 block.invalid = true;
29610 prev.type = 'text';
29619 if (prev.type === 'range') {
29621 let before = siblings[siblings.length - 1];
29622 before.value += prev.value + value;
29643 } // Mark imbalanced braces and brackets as invalid
29647 block = stack.pop();
29649 if (block.type !== 'root') {
29650 block.nodes.forEach(node => {
29652 if (node.type === 'open') node.isOpen = true;
29653 if (node.type === 'close') node.isClose = true;
29654 if (!node.nodes) node.type = 'text';
29655 node.invalid = true;
29657 }); // get the location of the block on parent.nodes (block's siblings)
29659 let parent = stack[stack.length - 1];
29660 let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
29662 parent.nodes.splice(index, 1, ...block.nodes);
29664 } while (stack.length > 0);
29672 var parse_1 = parse$3;
29675 * Expand the given pattern or create a regex-compatible string.
29678 * const braces = require('braces');
29679 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
29680 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
29682 * @param {String} `str`
29683 * @param {Object} `options`
29689 const braces = (input, options = {}) => {
29692 if (Array.isArray(input)) {
29693 for (let pattern of input) {
29694 let result = braces.create(pattern, options);
29696 if (Array.isArray(result)) {
29697 output.push(...result);
29699 output.push(result);
29703 output = [].concat(braces.create(input, options));
29706 if (options && options.expand === true && options.nodupes === true) {
29707 output = [...new Set(output)];
29713 * Parse the given `str` with the given `options`.
29716 * // braces.parse(pattern, [, options]);
29717 * const ast = braces.parse('a/{b,c}/d');
29718 * console.log(ast);
29720 * @param {String} pattern Brace pattern to parse
29721 * @param {Object} options
29722 * @return {Object} Returns an AST
29727 braces.parse = (input, options = {}) => parse_1(input, options);
29729 * Creates a braces string from an AST, or an AST node.
29732 * const braces = require('braces');
29733 * let ast = braces.parse('foo/{a,b}/bar');
29734 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
29736 * @param {String} `input` Brace pattern or AST.
29737 * @param {Object} `options`
29738 * @return {Array} Returns an array of expanded values.
29743 braces.stringify = (input, options = {}) => {
29744 if (typeof input === 'string') {
29745 return stringify(braces.parse(input, options), options);
29748 return stringify(input, options);
29751 * Compiles a brace pattern into a regex-compatible, optimized string.
29752 * This method is called by the main [braces](#braces) function by default.
29755 * const braces = require('braces');
29756 * console.log(braces.compile('a/{b,c}/d'));
29757 * //=> ['a/(b|c)/d']
29759 * @param {String} `input` Brace pattern or AST.
29760 * @param {Object} `options`
29761 * @return {Array} Returns an array of expanded values.
29766 braces.compile = (input, options = {}) => {
29767 if (typeof input === 'string') {
29768 input = braces.parse(input, options);
29771 return compile_1(input, options);
29774 * Expands a brace pattern into an array. This method is called by the
29775 * main [braces](#braces) function when `options.expand` is true. Before
29776 * using this method it's recommended that you read the [performance notes](#performance))
29777 * and advantages of using [.compile](#compile) instead.
29780 * const braces = require('braces');
29781 * console.log(braces.expand('a/{b,c}/d'));
29782 * //=> ['a/b/d', 'a/c/d'];
29784 * @param {String} `pattern` Brace pattern
29785 * @param {Object} `options`
29786 * @return {Array} Returns an array of expanded values.
29791 braces.expand = (input, options = {}) => {
29792 if (typeof input === 'string') {
29793 input = braces.parse(input, options);
29796 let result = expand_1(input, options); // filter out empty strings if specified
29798 if (options.noempty === true) {
29799 result = result.filter(Boolean);
29800 } // filter out duplicates if specified
29803 if (options.nodupes === true) {
29804 result = [...new Set(result)];
29810 * Processes a brace pattern and returns either an expanded array
29811 * (if `options.expand` is true), a highly optimized regex-compatible string.
29812 * This method is called by the main [braces](#braces) function.
29815 * const braces = require('braces');
29816 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
29817 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
29819 * @param {String} `pattern` Brace pattern
29820 * @param {Object} `options`
29821 * @return {Array} Returns an array of expanded values.
29826 braces.create = (input, options = {}) => {
29827 if (input === '' || input.length < 3) {
29831 return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
29838 var braces_1 = braces;
29840 const WIN_SLASH = '\\\\/';
29841 const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
29846 const DOT_LITERAL = '\\.';
29847 const PLUS_LITERAL = '\\+';
29848 const QMARK_LITERAL = '\\?';
29849 const SLASH_LITERAL = '\\/';
29850 const ONE_CHAR = '(?=.)';
29851 const QMARK = '[^/]';
29852 const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
29853 const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
29854 const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
29855 const NO_DOT = `(?!${DOT_LITERAL})`;
29856 const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
29857 const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
29858 const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
29859 const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
29860 const STAR = `${QMARK}*?`;
29861 const POSIX_CHARS = {
29879 * Windows glob regex
29882 const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, {
29883 SLASH_LITERAL: `[${WIN_SLASH}]`,
29884 QMARK: WIN_NO_SLASH,
29885 STAR: `${WIN_NO_SLASH}*?`,
29886 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
29887 NO_DOT: `(?!${DOT_LITERAL})`,
29888 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
29889 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
29890 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
29891 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
29892 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
29893 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
29896 * POSIX Bracket Regex
29899 const POSIX_REGEX_SOURCE = {
29900 alnum: 'a-zA-Z0-9',
29902 ascii: '\\x00-\\x7F',
29904 cntrl: '\\x00-\\x1F\\x7F',
29906 graph: '\\x21-\\x7E',
29908 print: '\\x20-\\x7E ',
29909 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
29910 space: ' \\t\\r\\n\\v\\f',
29912 word: 'A-Za-z0-9_',
29913 xdigit: 'A-Fa-f0-9'
29915 var constants$3 = {
29916 MAX_LENGTH: 1024 * 64,
29917 POSIX_REGEX_SOURCE,
29918 // regular expressions
29919 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
29920 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
29921 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
29922 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
29923 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
29924 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
29925 // Replace globs with equivalent patterns to reduce parsing time.
29939 CHAR_UPPERCASE_A: 65,
29942 CHAR_LOWERCASE_A: 97,
29945 CHAR_UPPERCASE_Z: 90,
29948 CHAR_LOWERCASE_Z: 122,
29951 CHAR_LEFT_PARENTHESES: 40,
29954 CHAR_RIGHT_PARENTHESES: 41,
29960 // Non-alphabetic chars.
29961 CHAR_AMPERSAND: 38,
29967 CHAR_BACKWARD_SLASH: 92,
29970 CHAR_CARRIAGE_RETURN: 13,
29973 CHAR_CIRCUMFLEX_ACCENT: 94,
29985 CHAR_DOUBLE_QUOTE: 34,
29991 CHAR_EXCLAMATION_MARK: 33,
29994 CHAR_FORM_FEED: 12,
29997 CHAR_FORWARD_SLASH: 47,
30000 CHAR_GRAVE_ACCENT: 96,
30006 CHAR_HYPHEN_MINUS: 45,
30009 CHAR_LEFT_ANGLE_BRACKET: 60,
30012 CHAR_LEFT_CURLY_BRACE: 123,
30015 CHAR_LEFT_SQUARE_BRACKET: 91,
30018 CHAR_LINE_FEED: 10,
30021 CHAR_NO_BREAK_SPACE: 160,
30030 CHAR_QUESTION_MARK: 63,
30033 CHAR_RIGHT_ANGLE_BRACKET: 62,
30036 CHAR_RIGHT_CURLY_BRACE: 125,
30039 CHAR_RIGHT_SQUARE_BRACKET: 93,
30042 CHAR_SEMICOLON: 59,
30045 CHAR_SINGLE_QUOTE: 39,
30054 CHAR_UNDERSCORE: 95,
30057 CHAR_VERTICAL_LINE: 124,
30060 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
30066 * Create EXTGLOB_CHARS
30068 extglobChars(chars) {
30073 close: `))${chars.STAR})`
30099 * Create GLOB_CHARS
30102 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
30107 var utils$3 = createCommonjsModule(function (module, exports) {
30109 const win32 = process.platform === 'win32';
30112 REGEX_REMOVE_BACKSLASH,
30113 REGEX_SPECIAL_CHARS,
30114 REGEX_SPECIAL_CHARS_GLOBAL
30117 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
30119 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
30121 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
30123 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
30125 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
30127 exports.removeBackslashes = str => {
30128 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
30129 return match === '\\' ? '' : match;
30133 exports.supportsLookbehinds = () => {
30134 const segs = process.version.slice(1).split('.').map(Number);
30136 if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
30143 exports.isWindows = options => {
30144 if (options && typeof options.windows === 'boolean') {
30145 return options.windows;
30148 return win32 === true || path$2.sep === '\\';
30151 exports.escapeLast = (input, char, lastIdx) => {
30152 const idx = input.lastIndexOf(char, lastIdx);
30153 if (idx === -1) return input;
30154 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
30155 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
30158 exports.removePrefix = (input, state = {}) => {
30159 let output = input;
30161 if (output.startsWith('./')) {
30162 output = output.slice(2);
30163 state.prefix = './';
30169 exports.wrapOutput = (input, state = {}, options = {}) => {
30170 const prepend = options.contains ? '' : '^';
30171 const append = options.contains ? '' : '$';
30172 let output = `${prepend}(?:${input})${append}`;
30174 if (state.negated === true) {
30175 output = `(?:^(?!${output}).*$)`;
30181 var utils_1$3 = utils$3.isObject;
30182 var utils_2$3 = utils$3.hasRegexChars;
30183 var utils_3$3 = utils$3.isRegexChar;
30184 var utils_4$2 = utils$3.escapeRegex;
30185 var utils_5$2 = utils$3.toPosixSlashes;
30186 var utils_6$2 = utils$3.removeBackslashes;
30187 var utils_7$2 = utils$3.supportsLookbehinds;
30188 var utils_8$2 = utils$3.isWindows;
30189 var utils_9$2 = utils$3.escapeLast;
30190 var utils_10$1 = utils$3.removePrefix;
30191 var utils_11$1 = utils$3.wrapOutput;
30200 CHAR_BACKWARD_SLASH,
30203 CHAR_COMMA: CHAR_COMMA$2,
30206 CHAR_DOT: CHAR_DOT$1,
30209 CHAR_EXCLAMATION_MARK,
30212 CHAR_FORWARD_SLASH,
30215 CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
30218 CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
30221 CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
30224 CHAR_PLUS: CHAR_PLUS$1,
30227 CHAR_QUESTION_MARK,
30230 CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
30233 CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
30236 CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
30241 const isPathSeparator = code => {
30242 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
30245 const depth = token => {
30246 if (token.isPrefix !== true) {
30247 token.depth = token.isGlobstar ? Infinity : 1;
30251 * Quickly scans a glob pattern and returns an object with a handful of
30252 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
30253 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
30256 * const pm = require('picomatch');
30257 * console.log(pm.scan('foo/bar/*.js'));
30258 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
30260 * @param {String} `str`
30261 * @param {Object} `options`
30262 * @return {Object} Returns an object with tokens and regex source string.
30267 const scan = (input, options) => {
30268 const opts = options || {};
30269 const length = input.length - 1;
30270 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
30271 const slashes = [];
30278 let isBrace = false;
30279 let isBracket = false;
30280 let isGlob = false;
30281 let isExtglob = false;
30282 let isGlobstar = false;
30283 let braceEscaped = false;
30284 let backslashes = false;
30285 let negated = false;
30286 let finished = false;
30296 const eos = () => index >= length;
30298 const peek = () => str.charCodeAt(index + 1);
30300 const advance = () => {
30302 return str.charCodeAt(++index);
30305 while (index < length) {
30309 if (code === CHAR_BACKWARD_SLASH) {
30310 backslashes = token.backslashes = true;
30313 if (code === CHAR_LEFT_CURLY_BRACE$1) {
30314 braceEscaped = true;
30320 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
30323 while (eos() !== true && (code = advance())) {
30324 if (code === CHAR_BACKWARD_SLASH) {
30325 backslashes = token.backslashes = true;
30330 if (code === CHAR_LEFT_CURLY_BRACE$1) {
30335 if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
30336 isBrace = token.isBrace = true;
30337 isGlob = token.isGlob = true;
30340 if (scanToEnd === true) {
30347 if (braceEscaped !== true && code === CHAR_COMMA$2) {
30348 isBrace = token.isBrace = true;
30349 isGlob = token.isGlob = true;
30352 if (scanToEnd === true) {
30359 if (code === CHAR_RIGHT_CURLY_BRACE$1) {
30362 if (braces === 0) {
30363 braceEscaped = false;
30364 isBrace = token.isBrace = true;
30371 if (scanToEnd === true) {
30378 if (code === CHAR_FORWARD_SLASH) {
30379 slashes.push(index);
30380 tokens.push(token);
30386 if (finished === true) continue;
30388 if (prev === CHAR_DOT$1 && index === start + 1) {
30393 lastIndex = index + 1;
30397 if (opts.noext !== true) {
30398 const isExtglobChar = code === CHAR_PLUS$1 || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
30400 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
30401 isGlob = token.isGlob = true;
30402 isExtglob = token.isExtglob = true;
30405 if (scanToEnd === true) {
30406 while (eos() !== true && (code = advance())) {
30407 if (code === CHAR_BACKWARD_SLASH) {
30408 backslashes = token.backslashes = true;
30413 if (code === CHAR_RIGHT_PARENTHESES$1) {
30414 isGlob = token.isGlob = true;
30427 if (code === CHAR_ASTERISK) {
30428 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
30429 isGlob = token.isGlob = true;
30432 if (scanToEnd === true) {
30439 if (code === CHAR_QUESTION_MARK) {
30440 isGlob = token.isGlob = true;
30443 if (scanToEnd === true) {
30450 if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
30451 while (eos() !== true && (next = advance())) {
30452 if (next === CHAR_BACKWARD_SLASH) {
30453 backslashes = token.backslashes = true;
30458 if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
30459 isBracket = token.isBracket = true;
30460 isGlob = token.isGlob = true;
30463 if (scanToEnd === true) {
30472 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
30473 negated = token.negated = true;
30478 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
30479 while (eos() !== true && (code = advance())) {
30480 if (code === CHAR_BACKWARD_SLASH) {
30481 backslashes = token.backslashes = true;
30486 if (code === CHAR_RIGHT_PARENTHESES$1) {
30487 isGlob = token.isGlob = true;
30490 if (scanToEnd === true) {
30499 if (isGlob === true) {
30502 if (scanToEnd === true) {
30510 if (opts.noext === true) {
30520 prefix = str.slice(0, start);
30521 str = str.slice(start);
30522 lastIndex -= start;
30525 if (base && isGlob === true && lastIndex > 0) {
30526 base = str.slice(0, lastIndex);
30527 glob = str.slice(lastIndex);
30528 } else if (isGlob === true) {
30535 if (base && base !== '' && base !== '/' && base !== str) {
30536 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
30537 base = base.slice(0, -1);
30541 if (opts.unescape === true) {
30542 if (glob) glob = utils$3.removeBackslashes(glob);
30544 if (base && backslashes === true) {
30545 base = utils$3.removeBackslashes(base);
30563 if (opts.tokens === true) {
30564 state.maxDepth = 0;
30566 if (!isPathSeparator(code)) {
30567 tokens.push(token);
30570 state.tokens = tokens;
30573 if (opts.parts === true || opts.tokens === true) {
30576 for (let idx = 0; idx < slashes.length; idx++) {
30577 const n = prevIndex ? prevIndex + 1 : start;
30578 const i = slashes[idx];
30579 const value = input.slice(n, i);
30582 if (idx === 0 && start !== 0) {
30583 tokens[idx].isPrefix = true;
30584 tokens[idx].value = prefix;
30586 tokens[idx].value = value;
30589 depth(tokens[idx]);
30590 state.maxDepth += tokens[idx].depth;
30593 if (idx !== 0 || value !== '') {
30600 if (prevIndex && prevIndex + 1 < input.length) {
30601 const value = input.slice(prevIndex + 1);
30605 tokens[tokens.length - 1].value = value;
30606 depth(tokens[tokens.length - 1]);
30607 state.maxDepth += tokens[tokens.length - 1].depth;
30611 state.slashes = slashes;
30612 state.parts = parts;
30626 MAX_LENGTH: MAX_LENGTH$3,
30627 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
30628 REGEX_NON_SPECIAL_CHARS,
30629 REGEX_SPECIAL_CHARS_BACKREF,
30636 const expandRange = (args, options) => {
30637 if (typeof options.expandRange === 'function') {
30638 return options.expandRange(...args, options);
30642 const value = `[${args.join('-')}]`;
30645 /* eslint-disable-next-line no-new */
30648 return args.map(v => utils$3.escapeRegex(v)).join('..');
30654 * Create the message for a syntax error
30658 const syntaxError = (type, char) => {
30659 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
30662 * Parse the given input string.
30663 * @param {String} input
30664 * @param {Object} options
30669 const parse$4 = (input, options) => {
30670 if (typeof input !== 'string') {
30671 throw new TypeError('Expected a string');
30674 input = REPLACEMENTS[input] || input;
30675 const opts = Object.assign({}, options);
30676 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
30677 let len = input.length;
30680 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
30686 output: opts.prepend || ''
30688 const tokens = [bos];
30689 const capture = opts.capture ? '' : '?:';
30690 const win32 = utils$3.isWindows(options); // create constants based on platform, for windows or posix
30692 const PLATFORM_CHARS = constants$3.globChars(win32);
30693 const EXTGLOB_CHARS = constants$3.extglobChars(PLATFORM_CHARS);
30707 } = PLATFORM_CHARS;
30709 const globstar = opts => {
30710 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
30713 const nodot = opts.dot ? '' : NO_DOT;
30714 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
30715 let star = opts.bash === true ? globstar(opts) : STAR;
30717 if (opts.capture) {
30718 star = `(${star})`;
30719 } // minimatch options support
30722 if (typeof opts.noext === 'boolean') {
30723 opts.noextglob = opts.noext;
30730 dot: opts.dot === true,
30743 input = utils$3.removePrefix(input, state);
30744 len = input.length;
30745 const extglobs = [];
30751 * Tokenizing helpers
30754 const eos = () => state.index === len - 1;
30756 const peek = state.peek = (n = 1) => input[state.index + n];
30758 const advance = state.advance = () => input[++state.index];
30760 const remaining = () => input.slice(state.index + 1);
30762 const consume = (value = '', num = 0) => {
30763 state.consumed += value;
30764 state.index += num;
30767 const append = token => {
30768 state.output += token.output != null ? token.output : token.value;
30769 consume(token.value);
30772 const negate = () => {
30775 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
30781 if (count % 2 === 0) {
30785 state.negated = true;
30790 const increment = type => {
30795 const decrement = type => {
30800 * Push tokens onto the tokens array. This helper speeds up
30801 * tokenizing by 1) helping us avoid backtracking as much as possible,
30802 * and 2) helping us avoid creating extra tokens when consecutive
30803 * characters are plain text. This improves performance and simplifies
30808 const push = tok => {
30809 if (prev.type === 'globstar') {
30810 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
30811 const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
30813 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
30814 state.output = state.output.slice(0, -prev.output.length);
30815 prev.type = 'star';
30817 prev.output = star;
30818 state.output += prev.output;
30822 if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
30823 extglobs[extglobs.length - 1].inner += tok.value;
30826 if (tok.value || tok.output) append(tok);
30828 if (prev && prev.type === 'text' && tok.type === 'text') {
30829 prev.value += tok.value;
30830 prev.output = (prev.output || '') + tok.value;
30839 const extglobOpen = (type, value) => {
30840 const token = Object.assign({}, EXTGLOB_CHARS[value], {
30845 token.parens = state.parens;
30846 token.output = state.output;
30847 const output = (opts.capture ? '(' : '') + token.open;
30848 increment('parens');
30852 output: state.output ? '' : ONE_CHAR
30860 extglobs.push(token);
30863 const extglobClose = token => {
30864 let output = token.close + (opts.capture ? ')' : '');
30866 if (token.type === 'negate') {
30867 let extglobStar = star;
30869 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
30870 extglobStar = globstar(opts);
30873 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
30874 output = token.close = `)$))${extglobStar}`;
30877 if (token.prev.type === 'bos' && eos()) {
30878 state.negatedExtglob = true;
30888 decrement('parens');
30895 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
30896 let backslashes = false;
30897 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
30898 if (first === '\\') {
30899 backslashes = true;
30903 if (first === '?') {
30905 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
30909 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
30912 return QMARK.repeat(chars.length);
30915 if (first === '.') {
30916 return DOT_LITERAL.repeat(chars.length);
30919 if (first === '*') {
30921 return esc + first + (rest ? star : '');
30927 return esc ? m : `\\${m}`;
30930 if (backslashes === true) {
30931 if (opts.unescape === true) {
30932 output = output.replace(/\\/g, '');
30934 output = output.replace(/\\+/g, m => {
30935 return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
30940 if (output === input && opts.contains === true) {
30941 state.output = input;
30945 state.output = utils$3.wrapOutput(output, state, options);
30949 * Tokenize input until we reach end-of-string
30956 if (value === '\u0000') {
30960 * Escaped characters
30964 if (value === '\\') {
30965 const next = peek();
30967 if (next === '/' && opts.bash !== true) {
30971 if (next === '.' || next === ';') {
30982 } // collapse slashes to reduce potential for exploits
30985 const match = /^\\+/.exec(remaining());
30988 if (match && match[0].length > 2) {
30989 slashes = match[0].length;
30990 state.index += slashes;
30992 if (slashes % 2 !== 0) {
30997 if (opts.unescape === true) {
30998 value = advance() || '';
31000 value += advance() || '';
31003 if (state.brackets === 0) {
31012 * If we're inside a regex character class, continue
31013 * until we reach the closing bracket.
31017 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
31018 if (opts.posix !== false && value === ':') {
31019 const inner = prev.value.slice(1);
31021 if (inner.includes('[')) {
31024 if (inner.includes(':')) {
31025 const idx = prev.value.lastIndexOf('[');
31026 const pre = prev.value.slice(0, idx);
31027 const rest = prev.value.slice(idx + 2);
31028 const posix = POSIX_REGEX_SOURCE$1[rest];
31031 prev.value = pre + posix;
31032 state.backtrack = true;
31035 if (!bos.output && tokens.indexOf(prev) === 1) {
31036 bos.output = ONE_CHAR;
31045 if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
31046 value = `\\${value}`;
31049 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
31050 value = `\\${value}`;
31053 if (opts.posix === true && value === '!' && prev.value === '[') {
31057 prev.value += value;
31064 * If we're inside a quoted string, continue
31065 * until we reach the closing double quote.
31069 if (state.quotes === 1 && value !== '"') {
31070 value = utils$3.escapeRegex(value);
31071 prev.value += value;
31082 if (value === '"') {
31083 state.quotes = state.quotes === 1 ? 0 : 1;
31085 if (opts.keepQuotes === true) {
31099 if (value === '(') {
31100 increment('parens');
31108 if (value === ')') {
31109 if (state.parens === 0 && opts.strictBrackets === true) {
31110 throw new SyntaxError(syntaxError('opening', '('));
31113 const extglob = extglobs[extglobs.length - 1];
31115 if (extglob && state.parens === extglob.parens + 1) {
31116 extglobClose(extglobs.pop());
31123 output: state.parens ? ')' : '\\)'
31125 decrement('parens');
31133 if (value === '[') {
31134 if (opts.nobracket === true || !remaining().includes(']')) {
31135 if (opts.nobracket !== true && opts.strictBrackets === true) {
31136 throw new SyntaxError(syntaxError('closing', ']'));
31139 value = `\\${value}`;
31141 increment('brackets');
31151 if (value === ']') {
31152 if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
31156 output: `\\${value}`
31161 if (state.brackets === 0) {
31162 if (opts.strictBrackets === true) {
31163 throw new SyntaxError(syntaxError('opening', '['));
31169 output: `\\${value}`
31174 decrement('brackets');
31175 const prevValue = prev.value.slice(1);
31177 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
31178 value = `/${value}`;
31181 prev.value += value;
31184 }); // when literal brackets are explicitly disabled
31185 // assume we should match with a regex character class
31187 if (opts.literalBrackets === false || utils$3.hasRegexChars(prevValue)) {
31191 const escaped = utils$3.escapeRegex(prev.value);
31192 state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
31193 // assume we should escape the brackets to match literal characters
31195 if (opts.literalBrackets === true) {
31196 state.output += escaped;
31197 prev.value = escaped;
31199 } // when the user specifies nothing, try to match both
31202 prev.value = `(${capture}${escaped}|${prev.value})`;
31203 state.output += prev.value;
31211 if (value === '{' && opts.nobrace !== true) {
31212 increment('braces');
31217 outputIndex: state.output.length,
31218 tokensIndex: state.tokens.length
31225 if (value === '}') {
31226 const brace = braces[braces.length - 1];
31228 if (opts.nobrace === true || !brace) {
31239 if (brace.dots === true) {
31240 const arr = tokens.slice();
31243 for (let i = arr.length - 1; i >= 0; i--) {
31246 if (arr[i].type === 'brace') {
31250 if (arr[i].type !== 'dots') {
31251 range.unshift(arr[i].value);
31255 output = expandRange(range, opts);
31256 state.backtrack = true;
31259 if (brace.comma !== true && brace.dots !== true) {
31260 const out = state.output.slice(0, brace.outputIndex);
31261 const toks = state.tokens.slice(brace.tokensIndex);
31262 brace.value = brace.output = '\\{';
31263 value = output = `\\}`;
31264 state.output = out;
31266 for (const t of toks) {
31267 state.output += t.output || t.value;
31276 decrement('braces');
31285 if (value === '|') {
31286 if (extglobs.length > 0) {
31287 extglobs[extglobs.length - 1].conditions++;
31301 if (value === ',') {
31302 let output = value;
31303 const brace = braces[braces.length - 1];
31305 if (brace && stack[stack.length - 1] === 'braces') {
31306 brace.comma = true;
31322 if (value === '/') {
31323 // if the beginning of the glob is "./", advance the start
31324 // to the current index, and don't add the "./" characters
31325 // to the state. This greatly simplifies lookbehinds when
31326 // checking for BOS characters like "!" and "." (not "./")
31327 if (prev.type === 'dot' && state.index === state.start + 1) {
31328 state.start = state.index + 1;
31329 state.consumed = '';
31332 prev = bos; // reset "prev" to the first token
31340 output: SLASH_LITERAL
31349 if (value === '.') {
31350 if (state.braces > 0 && prev.type === 'dot') {
31351 if (prev.value === '.') prev.output = DOT_LITERAL;
31352 const brace = braces[braces.length - 1];
31353 prev.type = 'dots';
31354 prev.output += value;
31355 prev.value += value;
31360 if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
31364 output: DOT_LITERAL
31372 output: DOT_LITERAL
31381 if (value === '?') {
31382 const isGroup = prev && prev.value === '(';
31384 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
31385 extglobOpen('qmark', value);
31389 if (prev && prev.type === 'paren') {
31390 const next = peek();
31391 let output = value;
31393 if (next === '<' && !utils$3.supportsLookbehinds()) {
31394 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
31397 if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
31398 output = `\\${value}`;
31409 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
31413 output: QMARK_NO_DOT
31430 if (value === '!') {
31431 if (opts.noextglob !== true && peek() === '(') {
31432 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
31433 extglobOpen('negate', value);
31438 if (opts.nonegate !== true && state.index === 0) {
31448 if (value === '+') {
31449 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
31450 extglobOpen('plus', value);
31454 if (prev && prev.value === '(' || opts.regex === false) {
31458 output: PLUS_LITERAL
31463 if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
31473 value: PLUS_LITERAL
31482 if (value === '@') {
31483 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
31504 if (value !== '*') {
31505 if (value === '$' || value === '^') {
31506 value = `\\${value}`;
31509 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
31513 state.index += match[0].length;
31527 if (prev && (prev.type === 'globstar' || prev.star === true)) {
31528 prev.type = 'star';
31530 prev.value += value;
31531 prev.output = star;
31532 state.backtrack = true;
31533 state.globstar = true;
31538 let rest = remaining();
31540 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
31541 extglobOpen('star', value);
31545 if (prev.type === 'star') {
31546 if (opts.noglobstar === true) {
31551 const prior = prev.prev;
31552 const before = prior.prev;
31553 const isStart = prior.type === 'slash' || prior.type === 'bos';
31554 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
31556 if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
31565 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
31566 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
31568 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
31575 } // strip consecutive `/**/`
31578 while (rest.slice(0, 3) === '/**') {
31579 const after = input[state.index + 4];
31581 if (after && after !== '/') {
31585 rest = rest.slice(3);
31589 if (prior.type === 'bos' && eos()) {
31590 prev.type = 'globstar';
31591 prev.value += value;
31592 prev.output = globstar(opts);
31593 state.output = prev.output;
31594 state.globstar = true;
31599 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
31600 state.output = state.output.slice(0, -(prior.output + prev.output).length);
31601 prior.output = `(?:${prior.output}`;
31602 prev.type = 'globstar';
31603 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
31604 prev.value += value;
31605 state.globstar = true;
31606 state.output += prior.output + prev.output;
31611 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
31612 const end = rest[1] !== void 0 ? '|$' : '';
31613 state.output = state.output.slice(0, -(prior.output + prev.output).length);
31614 prior.output = `(?:${prior.output}`;
31615 prev.type = 'globstar';
31616 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
31617 prev.value += value;
31618 state.output += prior.output + prev.output;
31619 state.globstar = true;
31620 consume(value + advance());
31629 if (prior.type === 'bos' && rest[0] === '/') {
31630 prev.type = 'globstar';
31631 prev.value += value;
31632 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
31633 state.output = prev.output;
31634 state.globstar = true;
31635 consume(value + advance());
31642 } // remove single star from output
31645 state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
31647 prev.type = 'globstar';
31648 prev.output = globstar(opts);
31649 prev.value += value; // reset output with globstar
31651 state.output += prev.output;
31652 state.globstar = true;
31663 if (opts.bash === true) {
31664 token.output = '.*?';
31666 if (prev.type === 'bos' || prev.type === 'slash') {
31667 token.output = nodot + token.output;
31674 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
31675 token.output = value;
31680 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
31681 if (prev.type === 'dot') {
31682 state.output += NO_DOT_SLASH;
31683 prev.output += NO_DOT_SLASH;
31684 } else if (opts.dot === true) {
31685 state.output += NO_DOTS_SLASH;
31686 prev.output += NO_DOTS_SLASH;
31688 state.output += nodot;
31689 prev.output += nodot;
31692 if (peek() !== '*') {
31693 state.output += ONE_CHAR;
31694 prev.output += ONE_CHAR;
31701 while (state.brackets > 0) {
31702 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
31703 state.output = utils$3.escapeLast(state.output, '[');
31704 decrement('brackets');
31707 while (state.parens > 0) {
31708 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
31709 state.output = utils$3.escapeLast(state.output, '(');
31710 decrement('parens');
31713 while (state.braces > 0) {
31714 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
31715 state.output = utils$3.escapeLast(state.output, '{');
31716 decrement('braces');
31719 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
31721 type: 'maybe_slash',
31723 output: `${SLASH_LITERAL}?`
31725 } // rebuild the output if we had to backtrack at any point
31728 if (state.backtrack === true) {
31731 for (const token of state.tokens) {
31732 state.output += token.output != null ? token.output : token.value;
31734 if (token.suffix) {
31735 state.output += token.suffix;
31743 * Fast paths for creating regular expressions for common glob patterns.
31744 * This can significantly speed up processing and has very little downside
31745 * impact when none of the fast paths match.
31749 parse$4.fastpaths = (input, options) => {
31750 const opts = Object.assign({}, options);
31751 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
31752 const len = input.length;
31755 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
31758 input = REPLACEMENTS[input] || input;
31759 const win32 = utils$3.isWindows(options); // create constants based on platform, for windows or posix
31771 } = constants$3.globChars(win32);
31772 const nodot = opts.dot ? NO_DOTS : NO_DOT;
31773 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
31774 const capture = opts.capture ? '' : '?:';
31779 let star = opts.bash === true ? '.*?' : STAR;
31781 if (opts.capture) {
31782 star = `(${star})`;
31785 const globstar = opts => {
31786 if (opts.noglobstar === true) return star;
31787 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
31790 const create = str => {
31793 return `${nodot}${ONE_CHAR}${star}`;
31796 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
31799 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
31802 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
31805 return nodot + globstar(opts);
31808 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
31811 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
31814 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
31818 const match = /^(.*?)\.(\w+)$/.exec(str);
31819 if (!match) return;
31820 const source = create(match[1]);
31821 if (!source) return;
31822 return source + DOT_LITERAL + match[2];
31827 const output = utils$3.removePrefix(input, state);
31828 let source = create(output);
31830 if (source && opts.strictSlashes !== true) {
31831 source += `${SLASH_LITERAL}?`;
31837 var parse_1$1 = parse$4;
31839 const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
31841 * Creates a matcher function from one or more glob patterns. The
31842 * returned function takes a string to match as its first argument,
31843 * and returns true if the string is a match. The returned matcher
31844 * function also takes a boolean as the second argument that, when true,
31845 * returns an object with additional information.
31848 * const picomatch = require('picomatch');
31849 * // picomatch(glob[, options]);
31851 * const isMatch = picomatch('*.!(*a)');
31852 * console.log(isMatch('a.a')); //=> false
31853 * console.log(isMatch('a.b')); //=> true
31856 * @param {String|Array} `globs` One or more glob patterns.
31857 * @param {Object=} `options`
31858 * @return {Function=} Returns a matcher function.
31863 const picomatch = (glob, options, returnState = false) => {
31864 if (Array.isArray(glob)) {
31865 const fns = glob.map(input => picomatch(input, options, returnState));
31867 const arrayMatcher = str => {
31868 for (const isMatch of fns) {
31869 const state = isMatch(str);
31870 if (state) return state;
31876 return arrayMatcher;
31879 const isState = isObject$2(glob) && glob.tokens && glob.input;
31881 if (glob === '' || typeof glob !== 'string' && !isState) {
31882 throw new TypeError('Expected pattern to be a non-empty string');
31885 const opts = options || {};
31886 const posix = utils$3.isWindows(options);
31887 const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
31888 const state = regex.state;
31889 delete regex.state;
31891 let isIgnored = () => false;
31894 const ignoreOpts = Object.assign({}, options, {
31899 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
31902 const matcher = (input, returnObject = false) => {
31907 } = picomatch.test(input, regex, options, {
31922 if (typeof opts.onResult === 'function') {
31923 opts.onResult(result);
31926 if (isMatch === false) {
31927 result.isMatch = false;
31928 return returnObject ? result : false;
31931 if (isIgnored(input)) {
31932 if (typeof opts.onIgnore === 'function') {
31933 opts.onIgnore(result);
31936 result.isMatch = false;
31937 return returnObject ? result : false;
31940 if (typeof opts.onMatch === 'function') {
31941 opts.onMatch(result);
31944 return returnObject ? result : true;
31948 matcher.state = state;
31954 * Test `input` with the given `regex`. This is used by the main
31955 * `picomatch()` function to test the input string.
31958 * const picomatch = require('picomatch');
31959 * // picomatch.test(input, regex[, options]);
31961 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
31962 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
31964 * @param {String} `input` String to test.
31965 * @param {RegExp} `regex`
31966 * @return {Object} Returns an object with matching info.
31971 picomatch.test = (input, regex, options, {
31975 if (typeof input !== 'string') {
31976 throw new TypeError('Expected input to be a string');
31979 if (input === '') {
31986 const opts = options || {};
31987 const format = opts.format || (posix ? utils$3.toPosixSlashes : null);
31988 let match = input === glob;
31989 let output = match && format ? format(input) : input;
31991 if (match === false) {
31992 output = format ? format(input) : input;
31993 match = output === glob;
31996 if (match === false || opts.capture === true) {
31997 if (opts.matchBase === true || opts.basename === true) {
31998 match = picomatch.matchBase(input, regex, options, posix);
32000 match = regex.exec(output);
32005 isMatch: Boolean(match),
32011 * Match the basename of a filepath.
32014 * const picomatch = require('picomatch');
32015 * // picomatch.matchBase(input, glob[, options]);
32016 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
32018 * @param {String} `input` String to test.
32019 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
32020 * @return {Boolean}
32025 picomatch.matchBase = (input, glob, options, posix = utils$3.isWindows(options)) => {
32026 const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
32027 return regex.test(path$2.basename(input));
32030 * Returns true if **any** of the given glob `patterns` match the specified `string`.
32033 * const picomatch = require('picomatch');
32034 * // picomatch.isMatch(string, patterns[, options]);
32036 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
32037 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
32039 * @param {String|Array} str The string to test.
32040 * @param {String|Array} patterns One or more glob patterns to use for matching.
32041 * @param {Object} [options] See available [options](#options).
32042 * @return {Boolean} Returns true if any patterns match `str`
32047 picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
32049 * Parse a glob pattern to create the source string for a regular
32053 * const picomatch = require('picomatch');
32054 * const result = picomatch.parse(pattern[, options]);
32056 * @param {String} `pattern`
32057 * @param {Object} `options`
32058 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
32063 picomatch.parse = (pattern, options) => {
32064 if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
32065 return parse_1$1(pattern, Object.assign({}, options, {
32070 * Scan a glob pattern to separate the pattern into segments.
32073 * const picomatch = require('picomatch');
32074 * // picomatch.scan(input[, options]);
32076 * const result = picomatch.scan('!./foo/*.js');
32077 * console.log(result);
32079 * input: '!./foo/*.js',
32084 * isBracket: false,
32086 * isExtglob: false,
32087 * isGlobstar: false,
32090 * @param {String} `input` Glob pattern to scan.
32091 * @param {Object} `options`
32092 * @return {Object} Returns an object with
32097 picomatch.scan = (input, options) => scan_1(input, options);
32099 * Create a regular expression from a glob pattern.
32102 * const picomatch = require('picomatch');
32103 * // picomatch.makeRe(input[, options]);
32105 * console.log(picomatch.makeRe('*.js'));
32106 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
32108 * @param {String} `input` A glob pattern to convert to regex.
32109 * @param {Object} `options`
32110 * @return {RegExp} Returns a regex created from the given pattern.
32115 picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
32116 if (returnOutput === true) {
32117 return parsed.output;
32120 const opts = options || {};
32121 const prepend = opts.contains ? '' : '^';
32122 const append = opts.contains ? '' : '$';
32123 let source = `${prepend}(?:${parsed.output})${append}`;
32125 if (parsed && parsed.negated === true) {
32126 source = `^(?!${source}).*$`;
32129 const regex = picomatch.toRegex(source, options);
32131 if (returnState === true) {
32132 regex.state = parsed;
32138 picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
32139 if (!input || typeof input !== 'string') {
32140 throw new TypeError('Expected a non-empty string');
32143 const opts = options || {};
32151 if (input.startsWith('./')) {
32152 input = input.slice(2);
32153 prefix = parsed.prefix = './';
32156 if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
32157 output = parse_1$1.fastpaths(input, options);
32160 if (output === undefined) {
32161 parsed = parse_1$1(input, options);
32162 parsed.prefix = prefix + (parsed.prefix || '');
32164 parsed.output = output;
32167 return picomatch.compileRe(parsed, options, returnOutput, returnState);
32170 * Create a regular expression from the given regex source string.
32173 * const picomatch = require('picomatch');
32174 * // picomatch.toRegex(source[, options]);
32176 * const { output } = picomatch.parse('*.js');
32177 * console.log(picomatch.toRegex(output));
32178 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
32180 * @param {String} `source` Regular expression source string.
32181 * @param {Object} `options`
32187 picomatch.toRegex = (source, options) => {
32189 const opts = options || {};
32190 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
32192 if (options && options.debug === true) throw err;
32197 * Picomatch constants.
32202 picomatch.constants = constants$3;
32204 * Expose "picomatch"
32207 var picomatch_1 = picomatch;
32209 var picomatch$1 = picomatch_1;
32211 const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
32213 * Returns an array of strings that match one or more glob patterns.
32216 * const mm = require('micromatch');
32217 * // mm(list, patterns[, options]);
32219 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
32222 * @param {String|Array<string>} list List of strings to match.
32223 * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
32224 * @param {Object} options See available [options](#options)
32225 * @return {Array} Returns an array of matches
32231 const micromatch = (list, patterns, options) => {
32232 patterns = [].concat(patterns);
32233 list = [].concat(list);
32234 let omit = new Set();
32235 let keep = new Set();
32236 let items = new Set();
32239 let onResult = state => {
32240 items.add(state.output);
32242 if (options && options.onResult) {
32243 options.onResult(state);
32247 for (let i = 0; i < patterns.length; i++) {
32248 let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, {
32251 let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
32252 if (negated) negatives++;
32254 for (let item of list) {
32255 let matched = isMatch(item, true);
32256 let match = negated ? !matched.isMatch : matched.isMatch;
32257 if (!match) continue;
32260 omit.add(matched.output);
32262 omit.delete(matched.output);
32263 keep.add(matched.output);
32268 let result = negatives === patterns.length ? [...items] : [...keep];
32269 let matches = result.filter(item => !omit.has(item));
32271 if (options && matches.length === 0) {
32272 if (options.failglob === true) {
32273 throw new Error(`No matches found for "${patterns.join(', ')}"`);
32276 if (options.nonull === true || options.nullglob === true) {
32277 return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
32284 * Backwards compatibility
32288 micromatch.match = micromatch;
32290 * Returns a matcher function from the given glob `pattern` and `options`.
32291 * The returned function takes a string to match as its only argument and returns
32292 * true if the string is a match.
32295 * const mm = require('micromatch');
32296 * // mm.matcher(pattern[, options]);
32298 * const isMatch = mm.matcher('*.!(*a)');
32299 * console.log(isMatch('a.a')); //=> false
32300 * console.log(isMatch('a.b')); //=> true
32302 * @param {String} `pattern` Glob pattern
32303 * @param {Object} `options`
32304 * @return {Function} Returns a matcher function.
32308 micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
32310 * Returns true if **any** of the given glob `patterns` match the specified `string`.
32313 * const mm = require('micromatch');
32314 * // mm.isMatch(string, patterns[, options]);
32316 * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
32317 * console.log(mm.isMatch('a.a', 'b.*')); //=> false
32319 * @param {String} str The string to test.
32320 * @param {String|Array} patterns One or more glob patterns to use for matching.
32321 * @param {Object} [options] See available [options](#options).
32322 * @return {Boolean} Returns true if any patterns match `str`
32327 micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
32329 * Backwards compatibility
32333 micromatch.any = micromatch.isMatch;
32335 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
32338 * const mm = require('micromatch');
32339 * // mm.not(list, patterns[, options]);
32341 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
32342 * //=> ['b.b', 'c.c']
32344 * @param {Array} `list` Array of strings to match.
32345 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
32346 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32347 * @return {Array} Returns an array of strings that **do not match** the given patterns.
32351 micromatch.not = (list, patterns, options = {}) => {
32352 patterns = [].concat(patterns).map(String);
32353 let result = new Set();
32356 let onResult = state => {
32357 if (options.onResult) options.onResult(state);
32358 items.push(state.output);
32361 let matches = micromatch(list, patterns, Object.assign({}, options, {
32365 for (let item of items) {
32366 if (!matches.includes(item)) {
32371 return [...result];
32374 * Returns true if the given `string` contains the given pattern. Similar
32375 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
32378 * var mm = require('micromatch');
32379 * // mm.contains(string, pattern[, options]);
32381 * console.log(mm.contains('aa/bb/cc', '*b'));
32383 * console.log(mm.contains('aa/bb/cc', '*d'));
32386 * @param {String} `str` The string to match.
32387 * @param {String|Array} `patterns` Glob pattern to use for matching.
32388 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32389 * @return {Boolean} Returns true if the patter matches any part of `str`.
32394 micromatch.contains = (str, pattern, options) => {
32395 if (typeof str !== 'string') {
32396 throw new TypeError(`Expected a string: "${util$3.inspect(str)}"`);
32399 if (Array.isArray(pattern)) {
32400 return pattern.some(p => micromatch.contains(str, p, options));
32403 if (typeof pattern === 'string') {
32404 if (isEmptyString(str) || isEmptyString(pattern)) {
32408 if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
32413 return micromatch.isMatch(str, pattern, Object.assign({}, options, {
32418 * Filter the keys of the given object with the given `glob` pattern
32419 * and `options`. Does not attempt to match nested keys. If you need this feature,
32420 * use [glob-object][] instead.
32423 * const mm = require('micromatch');
32424 * // mm.matchKeys(object, patterns[, options]);
32426 * const obj = { aa: 'a', ab: 'b', ac: 'c' };
32427 * console.log(mm.matchKeys(obj, '*b'));
32430 * @param {Object} `object` The object with keys to filter.
32431 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
32432 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32433 * @return {Object} Returns an object with only keys that match the given patterns.
32438 micromatch.matchKeys = (obj, patterns, options) => {
32439 if (!utils$3.isObject(obj)) {
32440 throw new TypeError('Expected the first argument to be an object');
32443 let keys = micromatch(Object.keys(obj), patterns, options);
32446 for (let key of keys) res[key] = obj[key];
32451 * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
32454 * const mm = require('micromatch');
32455 * // mm.some(list, patterns[, options]);
32457 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
32459 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
32462 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
32463 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
32464 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32465 * @return {Boolean} Returns true if any patterns match `str`
32470 micromatch.some = (list, patterns, options) => {
32471 let items = [].concat(list);
32473 for (let pattern of [].concat(patterns)) {
32474 let isMatch = picomatch$1(String(pattern), options);
32476 if (items.some(item => isMatch(item))) {
32484 * Returns true if every string in the given `list` matches
32485 * any of the given glob `patterns`.
32488 * const mm = require('micromatch');
32489 * // mm.every(list, patterns[, options]);
32491 * console.log(mm.every('foo.js', ['foo.js']));
32493 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
32495 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
32497 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
32500 * @param {String|Array} `list` The string or array of strings to test.
32501 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
32502 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32503 * @return {Boolean} Returns true if any patterns match `str`
32508 micromatch.every = (list, patterns, options) => {
32509 let items = [].concat(list);
32511 for (let pattern of [].concat(patterns)) {
32512 let isMatch = picomatch$1(String(pattern), options);
32514 if (!items.every(item => isMatch(item))) {
32522 * Returns true if **all** of the given `patterns` match
32523 * the specified string.
32526 * const mm = require('micromatch');
32527 * // mm.all(string, patterns[, options]);
32529 * console.log(mm.all('foo.js', ['foo.js']));
32532 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
32535 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
32538 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
32541 * @param {String|Array} `str` The string to test.
32542 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
32543 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32544 * @return {Boolean} Returns true if any patterns match `str`
32549 micromatch.all = (str, patterns, options) => {
32550 if (typeof str !== 'string') {
32551 throw new TypeError(`Expected a string: "${util$3.inspect(str)}"`);
32554 return [].concat(patterns).every(p => picomatch$1(p, options)(str));
32557 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
32560 * const mm = require('micromatch');
32561 * // mm.capture(pattern, string[, options]);
32563 * console.log(mm.capture('test/*.js', 'test/foo.js'));
32565 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
32568 * @param {String} `glob` Glob pattern to use for matching.
32569 * @param {String} `input` String to match
32570 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32571 * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
32576 micromatch.capture = (glob, input, options) => {
32577 let posix = utils$3.isWindows(options);
32578 let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, {
32581 let match = regex.exec(posix ? utils$3.toPosixSlashes(input) : input);
32584 return match.slice(1).map(v => v === void 0 ? '' : v);
32588 * Create a regular expression from the given glob `pattern`.
32591 * const mm = require('micromatch');
32592 * // mm.makeRe(pattern[, options]);
32594 * console.log(mm.makeRe('*.js'));
32595 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
32597 * @param {String} `pattern` A glob pattern to convert to regex.
32598 * @param {Object} `options`
32599 * @return {RegExp} Returns a regex created from the given pattern.
32604 micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
32606 * Scan a glob pattern to separate the pattern into segments. Used
32607 * by the [split](#split) method.
32610 * const mm = require('micromatch');
32611 * const state = mm.scan(pattern[, options]);
32613 * @param {String} `pattern`
32614 * @param {Object} `options`
32615 * @return {Object} Returns an object with
32620 micromatch.scan = (...args) => picomatch$1.scan(...args);
32622 * Parse a glob pattern to create the source string for a regular
32626 * const mm = require('micromatch');
32627 * const state = mm(pattern[, options]);
32629 * @param {String} `glob`
32630 * @param {Object} `options`
32631 * @return {Object} Returns an object with useful properties and output to be used as regex source string.
32636 micromatch.parse = (patterns, options) => {
32639 for (let pattern of [].concat(patterns || [])) {
32640 for (let str of braces_1(String(pattern), options)) {
32641 res.push(picomatch$1.parse(str, options));
32648 * Process the given brace `pattern`.
32651 * const { braces } = require('micromatch');
32652 * console.log(braces('foo/{a,b,c}/bar'));
32653 * //=> [ 'foo/(a|b|c)/bar' ]
32655 * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
32656 * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
32658 * @param {String} `pattern` String with brace pattern to process.
32659 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
32665 micromatch.braces = (pattern, options) => {
32666 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
32668 if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
32672 return braces_1(pattern, options);
32679 micromatch.braceExpand = (pattern, options) => {
32680 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
32681 return micromatch.braces(pattern, Object.assign({}, options, {
32686 * Expose micromatch
32690 var micromatch_1 = micromatch;
32692 var pattern = createCommonjsModule(function (module, exports) {
32694 Object.defineProperty(exports, "__esModule", {
32697 const GLOBSTAR = '**';
32698 const ESCAPE_SYMBOL = '\\';
32699 const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
32700 const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
32701 const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
32702 const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
32703 const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
32705 function isStaticPattern(pattern, options = {}) {
32706 return !isDynamicPattern(pattern, options);
32709 exports.isStaticPattern = isStaticPattern;
32711 function isDynamicPattern(pattern, options = {}) {
32713 * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
\r
32714 * filepath directly (without read directory).
\r
32716 if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
32720 if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
32724 if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
32728 if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
32735 exports.isDynamicPattern = isDynamicPattern;
32737 function convertToPositivePattern(pattern) {
32738 return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
32741 exports.convertToPositivePattern = convertToPositivePattern;
32743 function convertToNegativePattern(pattern) {
32744 return '!' + pattern;
32747 exports.convertToNegativePattern = convertToNegativePattern;
32749 function isNegativePattern(pattern) {
32750 return pattern.startsWith('!') && pattern[1] !== '(';
32753 exports.isNegativePattern = isNegativePattern;
32755 function isPositivePattern(pattern) {
32756 return !isNegativePattern(pattern);
32759 exports.isPositivePattern = isPositivePattern;
32761 function getNegativePatterns(patterns) {
32762 return patterns.filter(isNegativePattern);
32765 exports.getNegativePatterns = getNegativePatterns;
32767 function getPositivePatterns(patterns) {
32768 return patterns.filter(isPositivePattern);
32771 exports.getPositivePatterns = getPositivePatterns;
32773 function getBaseDirectory(pattern) {
32774 return globParent(pattern, {
32775 flipBackslashes: false
32779 exports.getBaseDirectory = getBaseDirectory;
32781 function hasGlobStar(pattern) {
32782 return pattern.includes(GLOBSTAR);
32785 exports.hasGlobStar = hasGlobStar;
32787 function endsWithSlashGlobStar(pattern) {
32788 return pattern.endsWith('/' + GLOBSTAR);
32791 exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
32793 function isAffectDepthOfReadingPattern(pattern) {
32794 const basename = path$2.basename(pattern);
32795 return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
32798 exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
32800 function expandPatternsWithBraceExpansion(patterns) {
32801 return patterns.reduce((collection, pattern) => {
32802 return collection.concat(expandBraceExpansion(pattern));
32806 exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
32808 function expandBraceExpansion(pattern) {
32809 return micromatch_1.braces(pattern, {
32815 exports.expandBraceExpansion = expandBraceExpansion;
32817 function getPatternParts(pattern, options) {
32818 const info = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), {
32820 })); // See micromatch/picomatch#58 for more details
32822 if (info.parts.length === 0) {
32829 exports.getPatternParts = getPatternParts;
32831 function makeRe(pattern, options) {
32832 return micromatch_1.makeRe(pattern, options);
32835 exports.makeRe = makeRe;
32837 function convertPatternsToRe(patterns, options) {
32838 return patterns.map(pattern => makeRe(pattern, options));
32841 exports.convertPatternsToRe = convertPatternsToRe;
32843 function matchAny(entry, patternsRe) {
32844 return patternsRe.some(patternRe => patternRe.test(entry));
32847 exports.matchAny = matchAny;
32849 unwrapExports(pattern);
32850 var pattern_1 = pattern.isStaticPattern;
32851 var pattern_2 = pattern.isDynamicPattern;
32852 var pattern_3 = pattern.convertToPositivePattern;
32853 var pattern_4 = pattern.convertToNegativePattern;
32854 var pattern_5 = pattern.isNegativePattern;
32855 var pattern_6 = pattern.isPositivePattern;
32856 var pattern_7 = pattern.getNegativePatterns;
32857 var pattern_8 = pattern.getPositivePatterns;
32858 var pattern_9 = pattern.getBaseDirectory;
32859 var pattern_10 = pattern.hasGlobStar;
32860 var pattern_11 = pattern.endsWithSlashGlobStar;
32861 var pattern_12 = pattern.isAffectDepthOfReadingPattern;
32862 var pattern_13 = pattern.expandPatternsWithBraceExpansion;
32863 var pattern_14 = pattern.expandBraceExpansion;
32864 var pattern_15 = pattern.getPatternParts;
32865 var pattern_16 = pattern.makeRe;
32866 var pattern_17 = pattern.convertPatternsToRe;
32867 var pattern_18 = pattern.matchAny;
32869 var stream$1 = createCommonjsModule(function (module, exports) {
32871 Object.defineProperty(exports, "__esModule", {
32875 function merge(streams) {
32876 const mergedStream = merge2_1(streams);
32877 streams.forEach(stream => {
32878 stream.once('error', error => mergedStream.emit('error', error));
32880 mergedStream.once('close', () => propagateCloseEventToSources(streams));
32881 mergedStream.once('end', () => propagateCloseEventToSources(streams));
32882 return mergedStream;
32885 exports.merge = merge;
32887 function propagateCloseEventToSources(streams) {
32888 streams.forEach(stream => stream.emit('close'));
32891 unwrapExports(stream$1);
32892 var stream_1 = stream$1.merge;
32894 var string$1 = createCommonjsModule(function (module, exports) {
32896 Object.defineProperty(exports, "__esModule", {
32900 function isString(input) {
32901 return typeof input === 'string';
32904 exports.isString = isString;
32906 function isEmpty(input) {
32907 return input === '';
32910 exports.isEmpty = isEmpty;
32912 unwrapExports(string$1);
32913 var string_1$1 = string$1.isString;
32914 var string_2 = string$1.isEmpty;
32916 var utils$4 = createCommonjsModule(function (module, exports) {
32918 Object.defineProperty(exports, "__esModule", {
32921 exports.array = array$2;
32922 exports.errno = errno;
32924 exports.path = path_1;
32925 exports.pattern = pattern;
32926 exports.stream = stream$1;
32927 exports.string = string$1;
32929 unwrapExports(utils$4);
32930 var utils_1$4 = utils$4.array;
32931 var utils_2$4 = utils$4.errno;
32932 var utils_3$4 = utils$4.fs;
32933 var utils_4$3 = utils$4.path;
32934 var utils_5$3 = utils$4.pattern;
32935 var utils_6$3 = utils$4.stream;
32936 var utils_7$3 = utils$4.string;
32938 var tasks = createCommonjsModule(function (module, exports) {
32940 Object.defineProperty(exports, "__esModule", {
32944 function generate(patterns, settings) {
32945 const positivePatterns = getPositivePatterns(patterns);
32946 const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
32947 const staticPatterns = positivePatterns.filter(pattern => utils$4.pattern.isStaticPattern(pattern, settings));
32948 const dynamicPatterns = positivePatterns.filter(pattern => utils$4.pattern.isDynamicPattern(pattern, settings));
32949 const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
32952 const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
32955 return staticTasks.concat(dynamicTasks);
32958 exports.generate = generate;
32960 function convertPatternsToTasks(positive, negative, dynamic) {
32961 const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks.
32962 // In this case, the global task covers the rest.
32964 if ('.' in positivePatternsGroup) {
32965 const task = convertPatternGroupToTask('.', positive, negative, dynamic);
32969 return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
32972 exports.convertPatternsToTasks = convertPatternsToTasks;
32974 function getPositivePatterns(patterns) {
32975 return utils$4.pattern.getPositivePatterns(patterns);
32978 exports.getPositivePatterns = getPositivePatterns;
32980 function getNegativePatternsAsPositive(patterns, ignore) {
32981 const negative = utils$4.pattern.getNegativePatterns(patterns).concat(ignore);
32982 const positive = negative.map(utils$4.pattern.convertToPositivePattern);
32986 exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
32988 function groupPatternsByBaseDirectory(patterns) {
32990 return patterns.reduce((collection, pattern) => {
32991 const base = utils$4.pattern.getBaseDirectory(pattern);
32993 if (base in collection) {
32994 collection[base].push(pattern);
32996 collection[base] = [pattern];
33003 exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
33005 function convertPatternGroupsToTasks(positive, negative, dynamic) {
33006 return Object.keys(positive).map(base => {
33007 return convertPatternGroupToTask(base, positive[base], negative, dynamic);
33011 exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
33013 function convertPatternGroupToTask(base, positive, negative, dynamic) {
33019 patterns: [].concat(positive, negative.map(utils$4.pattern.convertToNegativePattern))
33023 exports.convertPatternGroupToTask = convertPatternGroupToTask;
33025 unwrapExports(tasks);
33026 var tasks_1 = tasks.generate;
33027 var tasks_2 = tasks.convertPatternsToTasks;
33028 var tasks_3 = tasks.getPositivePatterns;
33029 var tasks_4 = tasks.getNegativePatternsAsPositive;
33030 var tasks_5 = tasks.groupPatternsByBaseDirectory;
33031 var tasks_6 = tasks.convertPatternGroupsToTasks;
33032 var tasks_7 = tasks.convertPatternGroupToTask;
33034 var async$1 = createCommonjsModule(function (module, exports) {
33036 Object.defineProperty(exports, "__esModule", {
33040 function read(path, settings, callback) {
33041 settings.fs.lstat(path, (lstatError, lstat) => {
33042 if (lstatError !== null) {
33043 return callFailureCallback(callback, lstatError);
33046 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
33047 return callSuccessCallback(callback, lstat);
33050 settings.fs.stat(path, (statError, stat) => {
33051 if (statError !== null) {
33052 if (settings.throwErrorOnBrokenSymbolicLink) {
33053 return callFailureCallback(callback, statError);
33056 return callSuccessCallback(callback, lstat);
33059 if (settings.markSymbolicLink) {
33060 stat.isSymbolicLink = () => true;
33063 callSuccessCallback(callback, stat);
33068 exports.read = read;
33070 function callFailureCallback(callback, error) {
33074 function callSuccessCallback(callback, result) {
33075 callback(null, result);
33078 unwrapExports(async$1);
33079 var async_1 = async$1.read;
33081 var sync$1 = createCommonjsModule(function (module, exports) {
33083 Object.defineProperty(exports, "__esModule", {
33087 function read(path, settings) {
33088 const lstat = settings.fs.lstatSync(path);
33090 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
33095 const stat = settings.fs.statSync(path);
33097 if (settings.markSymbolicLink) {
33098 stat.isSymbolicLink = () => true;
33103 if (!settings.throwErrorOnBrokenSymbolicLink) {
33111 exports.read = read;
33113 unwrapExports(sync$1);
33114 var sync_1 = sync$1.read;
33116 var fs_1$1 = createCommonjsModule(function (module, exports) {
33118 Object.defineProperty(exports, "__esModule", {
33121 exports.FILE_SYSTEM_ADAPTER = {
33124 lstatSync: fs$3.lstatSync,
33125 statSync: fs$3.statSync
33128 function createFileSystemAdapter(fsMethods) {
33129 if (fsMethods === undefined) {
33130 return exports.FILE_SYSTEM_ADAPTER;
33133 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
33136 exports.createFileSystemAdapter = createFileSystemAdapter;
33138 unwrapExports(fs_1$1);
33139 var fs_2 = fs_1$1.FILE_SYSTEM_ADAPTER;
33140 var fs_3 = fs_1$1.createFileSystemAdapter;
33142 var settings = createCommonjsModule(function (module, exports) {
33144 Object.defineProperty(exports, "__esModule", {
33149 constructor(_options = {}) {
33150 this._options = _options;
33151 this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
33152 this.fs = fs_1$1.createFileSystemAdapter(this._options.fs);
33153 this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
33154 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
33157 _getValue(option, value) {
33158 return option === undefined ? value : option;
33163 exports.default = Settings;
33165 unwrapExports(settings);
33167 var out = createCommonjsModule(function (module, exports) {
33169 Object.defineProperty(exports, "__esModule", {
33172 exports.Settings = settings.default;
33174 function stat(path, optionsOrSettingsOrCallback, callback) {
33175 if (typeof optionsOrSettingsOrCallback === 'function') {
33176 return async$1.read(path, getSettings(), optionsOrSettingsOrCallback);
33179 async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback);
33182 exports.stat = stat;
33184 function statSync(path, optionsOrSettings) {
33185 const settings = getSettings(optionsOrSettings);
33186 return sync$1.read(path, settings);
33189 exports.statSync = statSync;
33191 function getSettings(settingsOrOptions = {}) {
33192 if (settingsOrOptions instanceof settings.default) {
33193 return settingsOrOptions;
33196 return new settings.default(settingsOrOptions);
33199 unwrapExports(out);
33200 var out_1 = out.Settings;
33201 var out_2 = out.stat;
33202 var out_3 = out.statSync;
33204 var runParallel_1 = runParallel;
33206 function runParallel(tasks, cb) {
33207 var results, pending, keys;
33210 if (Array.isArray(tasks)) {
33212 pending = tasks.length;
33214 keys = Object.keys(tasks);
33216 pending = keys.length;
33219 function done(err) {
33221 if (cb) cb(err, results);
33225 if (isSync) process.nextTick(end);else end();
33228 function each(i, err, result) {
33229 results[i] = result;
33231 if (--pending === 0 || err) {
33241 keys.forEach(function (key) {
33242 tasks[key](function (err, result) {
33243 each(key, err, result);
33248 tasks.forEach(function (task, i) {
33249 task(function (err, result) {
33250 each(i, err, result);
33258 var constants$4 = createCommonjsModule(function (module, exports) {
33260 Object.defineProperty(exports, "__esModule", {
33263 const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
33264 const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
33265 const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
33266 const SUPPORTED_MAJOR_VERSION = 10;
33267 const SUPPORTED_MINOR_VERSION = 10;
33268 const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
33269 const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
33271 * IS `true` for Node.js 10.10 and greater.
\r
33274 exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
33276 unwrapExports(constants$4);
33277 var constants_1 = constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES;
33279 var fs$2 = createCommonjsModule(function (module, exports) {
33281 Object.defineProperty(exports, "__esModule", {
33285 class DirentFromStats {
33286 constructor(name, stats) {
33288 this.isBlockDevice = stats.isBlockDevice.bind(stats);
33289 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
33290 this.isDirectory = stats.isDirectory.bind(stats);
33291 this.isFIFO = stats.isFIFO.bind(stats);
33292 this.isFile = stats.isFile.bind(stats);
33293 this.isSocket = stats.isSocket.bind(stats);
33294 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
33299 function createDirentFromStats(name, stats) {
33300 return new DirentFromStats(name, stats);
33303 exports.createDirentFromStats = createDirentFromStats;
33305 unwrapExports(fs$2);
33306 var fs_1$2 = fs$2.createDirentFromStats;
33308 var utils$5 = createCommonjsModule(function (module, exports) {
33310 Object.defineProperty(exports, "__esModule", {
33315 unwrapExports(utils$5);
33316 var utils_1$5 = utils$5.fs;
33318 var async$2 = createCommonjsModule(function (module, exports) {
33320 Object.defineProperty(exports, "__esModule", {
33324 function read(directory, settings, callback) {
33325 if (!settings.stats && constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
33326 return readdirWithFileTypes(directory, settings, callback);
33329 return readdir(directory, settings, callback);
33332 exports.read = read;
33334 function readdirWithFileTypes(directory, settings, callback) {
33335 settings.fs.readdir(directory, {
33336 withFileTypes: true
33337 }, (readdirError, dirents) => {
33338 if (readdirError !== null) {
33339 return callFailureCallback(callback, readdirError);
33342 const entries = dirents.map(dirent => ({
33345 path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
33348 if (!settings.followSymbolicLinks) {
33349 return callSuccessCallback(callback, entries);
33352 const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
33353 runParallel_1(tasks, (rplError, rplEntries) => {
33354 if (rplError !== null) {
33355 return callFailureCallback(callback, rplError);
33358 callSuccessCallback(callback, rplEntries);
33363 exports.readdirWithFileTypes = readdirWithFileTypes;
33365 function makeRplTaskEntry(entry, settings) {
33367 if (!entry.dirent.isSymbolicLink()) {
33368 return done(null, entry);
33371 settings.fs.stat(entry.path, (statError, stats) => {
33372 if (statError !== null) {
33373 if (settings.throwErrorOnBrokenSymbolicLink) {
33374 return done(statError);
33377 return done(null, entry);
33380 entry.dirent = utils$5.fs.createDirentFromStats(entry.name, stats);
33381 return done(null, entry);
33386 function readdir(directory, settings, callback) {
33387 settings.fs.readdir(directory, (readdirError, names) => {
33388 if (readdirError !== null) {
33389 return callFailureCallback(callback, readdirError);
33392 const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`);
33393 const tasks = filepaths.map(filepath => {
33394 return done => out.stat(filepath, settings.fsStatSettings, done);
33396 runParallel_1(tasks, (rplError, results) => {
33397 if (rplError !== null) {
33398 return callFailureCallback(callback, rplError);
33401 const entries = [];
33402 names.forEach((name, index) => {
33403 const stats = results[index];
33406 path: filepaths[index],
33407 dirent: utils$5.fs.createDirentFromStats(name, stats)
33410 if (settings.stats) {
33411 entry.stats = stats;
33414 entries.push(entry);
33416 callSuccessCallback(callback, entries);
33421 exports.readdir = readdir;
33423 function callFailureCallback(callback, error) {
33427 function callSuccessCallback(callback, result) {
33428 callback(null, result);
33431 unwrapExports(async$2);
33432 var async_1$1 = async$2.read;
33433 var async_2 = async$2.readdirWithFileTypes;
33434 var async_3 = async$2.readdir;
33436 var sync$2 = createCommonjsModule(function (module, exports) {
33438 Object.defineProperty(exports, "__esModule", {
33442 function read(directory, settings) {
33443 if (!settings.stats && constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
33444 return readdirWithFileTypes(directory, settings);
33447 return readdir(directory, settings);
33450 exports.read = read;
33452 function readdirWithFileTypes(directory, settings) {
33453 const dirents = settings.fs.readdirSync(directory, {
33454 withFileTypes: true
33456 return dirents.map(dirent => {
33460 path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
33463 if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
33465 const stats = settings.fs.statSync(entry.path);
33466 entry.dirent = utils$5.fs.createDirentFromStats(entry.name, stats);
33468 if (settings.throwErrorOnBrokenSymbolicLink) {
33478 exports.readdirWithFileTypes = readdirWithFileTypes;
33480 function readdir(directory, settings) {
33481 const names = settings.fs.readdirSync(directory);
33482 return names.map(name => {
33483 const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`;
33484 const stats = out.statSync(entryPath, settings.fsStatSettings);
33488 dirent: utils$5.fs.createDirentFromStats(name, stats)
33491 if (settings.stats) {
33492 entry.stats = stats;
33499 exports.readdir = readdir;
33501 unwrapExports(sync$2);
33502 var sync_1$1 = sync$2.read;
33503 var sync_2 = sync$2.readdirWithFileTypes;
33504 var sync_3 = sync$2.readdir;
33506 var fs_1$3 = createCommonjsModule(function (module, exports) {
33508 Object.defineProperty(exports, "__esModule", {
33511 exports.FILE_SYSTEM_ADAPTER = {
33514 lstatSync: fs$3.lstatSync,
33515 statSync: fs$3.statSync,
33516 readdir: fs$3.readdir,
33517 readdirSync: fs$3.readdirSync
33520 function createFileSystemAdapter(fsMethods) {
33521 if (fsMethods === undefined) {
33522 return exports.FILE_SYSTEM_ADAPTER;
33525 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
33528 exports.createFileSystemAdapter = createFileSystemAdapter;
33530 unwrapExports(fs_1$3);
33531 var fs_2$1 = fs_1$3.FILE_SYSTEM_ADAPTER;
33532 var fs_3$1 = fs_1$3.createFileSystemAdapter;
33534 var settings$1 = createCommonjsModule(function (module, exports) {
33536 Object.defineProperty(exports, "__esModule", {
33541 constructor(_options = {}) {
33542 this._options = _options;
33543 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
33544 this.fs = fs_1$3.createFileSystemAdapter(this._options.fs);
33545 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$2.sep);
33546 this.stats = this._getValue(this._options.stats, false);
33547 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
33548 this.fsStatSettings = new out.Settings({
33549 followSymbolicLink: this.followSymbolicLinks,
33551 throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
33555 _getValue(option, value) {
33556 return option === undefined ? value : option;
33561 exports.default = Settings;
33563 unwrapExports(settings$1);
33565 var out$1 = createCommonjsModule(function (module, exports) {
33567 Object.defineProperty(exports, "__esModule", {
33570 exports.Settings = settings$1.default;
33572 function scandir(path, optionsOrSettingsOrCallback, callback) {
33573 if (typeof optionsOrSettingsOrCallback === 'function') {
33574 return async$2.read(path, getSettings(), optionsOrSettingsOrCallback);
33577 async$2.read(path, getSettings(optionsOrSettingsOrCallback), callback);
33580 exports.scandir = scandir;
33582 function scandirSync(path, optionsOrSettings) {
33583 const settings = getSettings(optionsOrSettings);
33584 return sync$2.read(path, settings);
33587 exports.scandirSync = scandirSync;
33589 function getSettings(settingsOrOptions = {}) {
33590 if (settingsOrOptions instanceof settings$1.default) {
33591 return settingsOrOptions;
33594 return new settings$1.default(settingsOrOptions);
33597 unwrapExports(out$1);
33598 var out_1$1 = out$1.Settings;
33599 var out_2$1 = out$1.scandir;
33600 var out_3$1 = out$1.scandirSync;
33602 function reusify(Constructor) {
33603 var head = new Constructor();
33607 var current = head;
33609 if (current.next) {
33610 head = current.next;
33612 head = new Constructor();
33616 current.next = null;
33620 function release(obj) {
33631 var reusify_1 = reusify;
33633 function fastqueue(context, worker, concurrency) {
33634 if (typeof context === 'function') {
33635 concurrency = worker;
33640 var cache = reusify_1(Task);
33641 var queueHead = null;
33642 var queueTail = null;
33650 concurrency: concurrency,
33658 killAndDrain: killAndDrain
33662 function running() {
33667 self.paused = true;
33670 function length() {
33671 var current = queueHead;
33675 current = current.next;
33682 function resume() {
33683 if (!self.paused) return;
33684 self.paused = false;
33686 for (var i = 0; i < self.concurrency; i++) {
33693 return _running === 0 && self.length() === 0;
33696 function push(value, done) {
33697 var current = cache.get();
33698 current.context = context;
33699 current.release = release;
33700 current.value = value;
33701 current.callback = done || noop$1;
33703 if (_running === self.concurrency || self.paused) {
33705 queueTail.next = current;
33706 queueTail = current;
33708 queueHead = current;
33709 queueTail = current;
33714 worker.call(context, current.value, current.worked);
33718 function unshift(value, done) {
33719 var current = cache.get();
33720 current.context = context;
33721 current.release = release;
33722 current.value = value;
33723 current.callback = done || noop$1;
33725 if (_running === self.concurrency || self.paused) {
33727 current.next = queueHead;
33728 queueHead = current;
33730 queueHead = current;
33731 queueTail = current;
33736 worker.call(context, current.value, current.worked);
33740 function release(holder) {
33742 cache.release(holder);
33745 var next = queueHead;
33748 if (!self.paused) {
33749 if (queueTail === queueHead) {
33753 queueHead = next.next;
33755 worker.call(context, next.value, next.worked);
33757 if (queueTail === null) {
33763 } else if (--_running === 0) {
33771 self.drain = noop$1;
33774 function killAndDrain() {
33778 self.drain = noop$1;
33782 function noop$1() {}
33786 this.callback = noop$1;
33788 this.release = noop$1;
33789 this.context = null;
33792 this.worked = function worked(err, result) {
33793 var callback = self.callback;
33795 self.callback = noop$1;
33796 callback.call(self.context, err, result);
33797 self.release(self);
33801 var queue = fastqueue;
33803 var common$2 = createCommonjsModule(function (module, exports) {
33805 Object.defineProperty(exports, "__esModule", {
33809 function isFatalError(settings, error) {
33810 if (settings.errorFilter === null) {
33814 return !settings.errorFilter(error);
33817 exports.isFatalError = isFatalError;
33819 function isAppliedFilter(filter, value) {
33820 return filter === null || filter(value);
33823 exports.isAppliedFilter = isAppliedFilter;
33825 function replacePathSegmentSeparator(filepath, separator) {
33826 return filepath.split(/[\\/]/).join(separator);
33829 exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
33831 function joinPathSegments(a, b, separator) {
33836 return a + separator + b;
33839 exports.joinPathSegments = joinPathSegments;
33841 unwrapExports(common$2);
33842 var common_1$2 = common$2.isFatalError;
33843 var common_2 = common$2.isAppliedFilter;
33844 var common_3 = common$2.replacePathSegmentSeparator;
33845 var common_4 = common$2.joinPathSegments;
33847 var reader = createCommonjsModule(function (module, exports) {
33849 Object.defineProperty(exports, "__esModule", {
33854 constructor(_root, _settings) {
33855 this._root = _root;
33856 this._settings = _settings;
33857 this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
33862 exports.default = Reader;
33864 unwrapExports(reader);
33866 var async$3 = createCommonjsModule(function (module, exports) {
33868 Object.defineProperty(exports, "__esModule", {
33872 class AsyncReader extends reader.default {
33873 constructor(_root, _settings) {
33874 super(_root, _settings);
33875 this._settings = _settings;
33876 this._scandir = out$1.scandir;
33877 this._emitter = new events$1.EventEmitter();
33878 this._queue = queue(this._worker.bind(this), this._settings.concurrency);
33879 this._isFatalError = false;
33880 this._isDestroyed = false;
33882 this._queue.drain = () => {
33883 if (!this._isFatalError) {
33884 this._emitter.emit('end');
33890 this._isFatalError = false;
33891 this._isDestroyed = false;
33892 setImmediate(() => {
33893 this._pushToQueue(this._root, this._settings.basePath);
33895 return this._emitter;
33899 if (this._isDestroyed) {
33900 throw new Error('The reader is already destroyed');
33903 this._isDestroyed = true;
33905 this._queue.killAndDrain();
33908 onEntry(callback) {
33909 this._emitter.on('entry', callback);
33912 onError(callback) {
33913 this._emitter.once('error', callback);
33917 this._emitter.once('end', callback);
33920 _pushToQueue(directory, base) {
33921 const queueItem = {
33926 this._queue.push(queueItem, error => {
33927 if (error !== null) {
33928 this._handleError(error);
33933 _worker(item, done) {
33934 this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
33935 if (error !== null) {
33936 return done(error, undefined);
33939 for (const entry of entries) {
33940 this._handleEntry(entry, item.base);
33943 done(null, undefined);
33947 _handleError(error) {
33948 if (!common$2.isFatalError(this._settings, error)) {
33952 this._isFatalError = true;
33953 this._isDestroyed = true;
33955 this._emitter.emit('error', error);
33958 _handleEntry(entry, base) {
33959 if (this._isDestroyed || this._isFatalError) {
33963 const fullpath = entry.path;
33965 if (base !== undefined) {
33966 entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
33969 if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) {
33970 this._emitEntry(entry);
33973 if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) {
33974 this._pushToQueue(fullpath, entry.path);
33978 _emitEntry(entry) {
33979 this._emitter.emit('entry', entry);
33984 exports.default = AsyncReader;
33986 unwrapExports(async$3);
33988 var async$4 = createCommonjsModule(function (module, exports) {
33990 Object.defineProperty(exports, "__esModule", {
33994 class AsyncProvider {
33995 constructor(_root, _settings) {
33996 this._root = _root;
33997 this._settings = _settings;
33998 this._reader = new async$3.default(this._root, this._settings);
33999 this._storage = new Set();
34003 this._reader.onError(error => {
34004 callFailureCallback(callback, error);
34007 this._reader.onEntry(entry => {
34008 this._storage.add(entry);
34011 this._reader.onEnd(() => {
34012 callSuccessCallback(callback, [...this._storage]);
34015 this._reader.read();
34020 exports.default = AsyncProvider;
34022 function callFailureCallback(callback, error) {
34026 function callSuccessCallback(callback, entries) {
34027 callback(null, entries);
34030 unwrapExports(async$4);
34032 var stream$2 = createCommonjsModule(function (module, exports) {
34034 Object.defineProperty(exports, "__esModule", {
34038 class StreamProvider {
34039 constructor(_root, _settings) {
34040 this._root = _root;
34041 this._settings = _settings;
34042 this._reader = new async$3.default(this._root, this._settings);
34043 this._stream = new stream$6.Readable({
34046 destroy: this._reader.destroy.bind(this._reader)
34051 this._reader.onError(error => {
34052 this._stream.emit('error', error);
34055 this._reader.onEntry(entry => {
34056 this._stream.push(entry);
34059 this._reader.onEnd(() => {
34060 this._stream.push(null);
34063 this._reader.read();
34065 return this._stream;
34070 exports.default = StreamProvider;
34072 unwrapExports(stream$2);
34074 var sync$3 = createCommonjsModule(function (module, exports) {
34076 Object.defineProperty(exports, "__esModule", {
34080 class SyncReader extends reader.default {
34082 super(...arguments);
34083 this._scandir = out$1.scandirSync;
34084 this._storage = new Set();
34085 this._queue = new Set();
34089 this._pushToQueue(this._root, this._settings.basePath);
34091 this._handleQueue();
34093 return [...this._storage];
34096 _pushToQueue(directory, base) {
34104 for (const item of this._queue.values()) {
34105 this._handleDirectory(item.directory, item.base);
34109 _handleDirectory(directory, base) {
34111 const entries = this._scandir(directory, this._settings.fsScandirSettings);
34113 for (const entry of entries) {
34114 this._handleEntry(entry, base);
34117 this._handleError(error);
34121 _handleError(error) {
34122 if (!common$2.isFatalError(this._settings, error)) {
34129 _handleEntry(entry, base) {
34130 const fullpath = entry.path;
34132 if (base !== undefined) {
34133 entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
34136 if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) {
34137 this._pushToStorage(entry);
34140 if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) {
34141 this._pushToQueue(fullpath, entry.path);
34145 _pushToStorage(entry) {
34146 this._storage.add(entry);
34151 exports.default = SyncReader;
34153 unwrapExports(sync$3);
34155 var sync$4 = createCommonjsModule(function (module, exports) {
34157 Object.defineProperty(exports, "__esModule", {
34161 class SyncProvider {
34162 constructor(_root, _settings) {
34163 this._root = _root;
34164 this._settings = _settings;
34165 this._reader = new sync$3.default(this._root, this._settings);
34169 return this._reader.read();
34174 exports.default = SyncProvider;
34176 unwrapExports(sync$4);
34178 var settings$2 = createCommonjsModule(function (module, exports) {
34180 Object.defineProperty(exports, "__esModule", {
34185 constructor(_options = {}) {
34186 this._options = _options;
34187 this.basePath = this._getValue(this._options.basePath, undefined);
34188 this.concurrency = this._getValue(this._options.concurrency, Infinity);
34189 this.deepFilter = this._getValue(this._options.deepFilter, null);
34190 this.entryFilter = this._getValue(this._options.entryFilter, null);
34191 this.errorFilter = this._getValue(this._options.errorFilter, null);
34192 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$2.sep);
34193 this.fsScandirSettings = new out$1.Settings({
34194 followSymbolicLinks: this._options.followSymbolicLinks,
34195 fs: this._options.fs,
34196 pathSegmentSeparator: this._options.pathSegmentSeparator,
34197 stats: this._options.stats,
34198 throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
34202 _getValue(option, value) {
34203 return option === undefined ? value : option;
34208 exports.default = Settings;
34210 unwrapExports(settings$2);
34212 var out$2 = createCommonjsModule(function (module, exports) {
34214 Object.defineProperty(exports, "__esModule", {
34217 exports.Settings = settings$2.default;
34219 function walk(directory, optionsOrSettingsOrCallback, callback) {
34220 if (typeof optionsOrSettingsOrCallback === 'function') {
34221 return new async$4.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
34224 new async$4.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
34227 exports.walk = walk;
34229 function walkSync(directory, optionsOrSettings) {
34230 const settings = getSettings(optionsOrSettings);
34231 const provider = new sync$4.default(directory, settings);
34232 return provider.read();
34235 exports.walkSync = walkSync;
34237 function walkStream(directory, optionsOrSettings) {
34238 const settings = getSettings(optionsOrSettings);
34239 const provider = new stream$2.default(directory, settings);
34240 return provider.read();
34243 exports.walkStream = walkStream;
34245 function getSettings(settingsOrOptions = {}) {
34246 if (settingsOrOptions instanceof settings$2.default) {
34247 return settingsOrOptions;
34250 return new settings$2.default(settingsOrOptions);
34253 unwrapExports(out$2);
34254 var out_1$2 = out$2.Settings;
34255 var out_2$2 = out$2.walk;
34256 var out_3$2 = out$2.walkSync;
34257 var out_4 = out$2.walkStream;
34259 var reader$1 = createCommonjsModule(function (module, exports) {
34261 Object.defineProperty(exports, "__esModule", {
34266 constructor(_settings) {
34267 this._settings = _settings;
34268 this._fsStatSettings = new out.Settings({
34269 followSymbolicLink: this._settings.followSymbolicLinks,
34270 fs: this._settings.fs,
34271 throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
34275 _getFullEntryPath(filepath) {
34276 return path$2.resolve(this._settings.cwd, filepath);
34279 _makeEntry(stats, pattern) {
34283 dirent: utils$4.fs.createDirentFromStats(pattern, stats)
34286 if (this._settings.stats) {
34287 entry.stats = stats;
34293 _isFatalError(error) {
34294 return !utils$4.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
34299 exports.default = Reader;
34301 unwrapExports(reader$1);
34303 var stream$3 = createCommonjsModule(function (module, exports) {
34305 Object.defineProperty(exports, "__esModule", {
34309 class ReaderStream extends reader$1.default {
34311 super(...arguments);
34312 this._walkStream = out$2.walkStream;
34313 this._stat = out.stat;
34316 dynamic(root, options) {
34317 return this._walkStream(root, options);
34320 static(patterns, options) {
34321 const filepaths = patterns.map(this._getFullEntryPath, this);
34322 const stream = new stream$6.PassThrough({
34326 stream._write = (index, _enc, done) => {
34327 return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
34328 if (entry !== null && options.entryFilter(entry)) {
34329 stream.push(entry);
34332 if (index === filepaths.length - 1) {
34340 for (let i = 0; i < filepaths.length; i++) {
34347 _getEntry(filepath, pattern, options) {
34348 return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
34349 if (options.errorFilter(error)) {
34357 _getStat(filepath) {
34358 return new Promise((resolve, reject) => {
34359 this._stat(filepath, this._fsStatSettings, (error, stats) => {
34360 return error === null ? resolve(stats) : reject(error);
34367 exports.default = ReaderStream;
34369 unwrapExports(stream$3);
34371 var matcher = createCommonjsModule(function (module, exports) {
34373 Object.defineProperty(exports, "__esModule", {
34378 constructor(_patterns, _settings, _micromatchOptions) {
34379 this._patterns = _patterns;
34380 this._settings = _settings;
34381 this._micromatchOptions = _micromatchOptions;
34382 this._storage = [];
34384 this._fillStorage();
34389 * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
\r
34390 * So, before expand patterns with brace expansion into separated patterns.
\r
34392 const patterns = utils$4.pattern.expandPatternsWithBraceExpansion(this._patterns);
34394 for (const pattern of patterns) {
34395 const segments = this._getPatternSegments(pattern);
34397 const sections = this._splitSegmentsIntoSections(segments);
34399 this._storage.push({
34400 complete: sections.length <= 1,
34408 _getPatternSegments(pattern) {
34409 const parts = utils$4.pattern.getPatternParts(pattern, this._micromatchOptions);
34410 return parts.map(part => {
34411 const dynamic = utils$4.pattern.isDynamicPattern(part, this._settings);
34423 patternRe: utils$4.pattern.makeRe(part, this._micromatchOptions)
34428 _splitSegmentsIntoSections(segments) {
34429 return utils$4.array.splitWhen(segments, segment => segment.dynamic && utils$4.pattern.hasGlobStar(segment.pattern));
34434 exports.default = Matcher;
34436 unwrapExports(matcher);
34438 var partial = createCommonjsModule(function (module, exports) {
34440 Object.defineProperty(exports, "__esModule", {
34444 class PartialMatcher extends matcher.default {
34446 const parts = filepath.split('/');
34447 const levels = parts.length;
34449 const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
34451 for (const pattern of patterns) {
34452 const section = pattern.sections[0];
34454 * In this case, the pattern has a globstar and we must read all directories unconditionally,
\r
34455 * but only if the level has reached the end of the first group.
\r
34457 * fixtures/{a,b}/**
\r
34458 * ^ true/false ^ always true
\r
34461 if (!pattern.complete && levels > section.length) {
34465 const match = parts.every((part, index) => {
34466 const segment = pattern.segments[index];
34468 if (segment.dynamic && segment.patternRe.test(part)) {
34472 if (!segment.dynamic && segment.pattern === part) {
34489 exports.default = PartialMatcher;
34491 unwrapExports(partial);
34493 var deep = createCommonjsModule(function (module, exports) {
34495 Object.defineProperty(exports, "__esModule", {
34500 constructor(_settings, _micromatchOptions) {
34501 this._settings = _settings;
34502 this._micromatchOptions = _micromatchOptions;
34505 getFilter(basePath, positive, negative) {
34506 const matcher = this._getMatcher(positive);
34508 const negativeRe = this._getNegativePatternsRe(negative);
34510 return entry => this._filter(basePath, entry, matcher, negativeRe);
34513 _getMatcher(patterns) {
34514 return new partial.default(patterns, this._settings, this._micromatchOptions);
34517 _getNegativePatternsRe(patterns) {
34518 const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
34519 return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
34522 _filter(basePath, entry, matcher, negativeRe) {
34523 const depth = this._getEntryLevel(basePath, entry.path);
34525 if (this._isSkippedByDeep(depth)) {
34529 if (this._isSkippedSymbolicLink(entry)) {
34533 const filepath = utils$4.path.removeLeadingDotSegment(entry.path);
34535 if (this._isSkippedByPositivePatterns(filepath, matcher)) {
34539 return this._isSkippedByNegativePatterns(filepath, negativeRe);
34542 _isSkippedByDeep(entryDepth) {
34543 return entryDepth >= this._settings.deep;
34546 _isSkippedSymbolicLink(entry) {
34547 return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
34550 _getEntryLevel(basePath, entryPath) {
34551 const basePathDepth = basePath.split('/').length;
34552 const entryPathDepth = entryPath.split('/').length;
34553 return entryPathDepth - (basePath === '' ? 0 : basePathDepth);
34556 _isSkippedByPositivePatterns(entryPath, matcher) {
34557 return !this._settings.baseNameMatch && !matcher.match(entryPath);
34560 _isSkippedByNegativePatterns(entryPath, negativeRe) {
34561 return !utils$4.pattern.matchAny(entryPath, negativeRe);
34566 exports.default = DeepFilter;
34568 unwrapExports(deep);
34570 var entry = createCommonjsModule(function (module, exports) {
34572 Object.defineProperty(exports, "__esModule", {
34576 class EntryFilter {
34577 constructor(_settings, _micromatchOptions) {
34578 this._settings = _settings;
34579 this._micromatchOptions = _micromatchOptions;
34580 this.index = new Map();
34583 getFilter(positive, negative) {
34584 const positiveRe = utils$4.pattern.convertPatternsToRe(positive, this._micromatchOptions);
34585 const negativeRe = utils$4.pattern.convertPatternsToRe(negative, this._micromatchOptions);
34586 return entry => this._filter(entry, positiveRe, negativeRe);
34589 _filter(entry, positiveRe, negativeRe) {
34590 if (this._settings.unique) {
34591 if (this._isDuplicateEntry(entry)) {
34595 this._createIndexRecord(entry);
34598 if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
34602 if (this._isSkippedByAbsoluteNegativePatterns(entry, negativeRe)) {
34606 const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
34607 return this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
34610 _isDuplicateEntry(entry) {
34611 return this.index.has(entry.path);
34614 _createIndexRecord(entry) {
34615 this.index.set(entry.path, undefined);
34618 _onlyFileFilter(entry) {
34619 return this._settings.onlyFiles && !entry.dirent.isFile();
34622 _onlyDirectoryFilter(entry) {
34623 return this._settings.onlyDirectories && !entry.dirent.isDirectory();
34626 _isSkippedByAbsoluteNegativePatterns(entry, negativeRe) {
34627 if (!this._settings.absolute) {
34631 const fullpath = utils$4.path.makeAbsolute(this._settings.cwd, entry.path);
34632 return this._isMatchToPatterns(fullpath, negativeRe);
34635 _isMatchToPatterns(entryPath, patternsRe) {
34636 const filepath = utils$4.path.removeLeadingDotSegment(entryPath);
34637 return utils$4.pattern.matchAny(filepath, patternsRe);
34642 exports.default = EntryFilter;
34644 unwrapExports(entry);
34646 var error = createCommonjsModule(function (module, exports) {
34648 Object.defineProperty(exports, "__esModule", {
34652 class ErrorFilter {
34653 constructor(_settings) {
34654 this._settings = _settings;
34658 return error => this._isNonFatalError(error);
34661 _isNonFatalError(error) {
34662 return utils$4.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
34667 exports.default = ErrorFilter;
34669 unwrapExports(error);
34671 var entry$1 = createCommonjsModule(function (module, exports) {
34673 Object.defineProperty(exports, "__esModule", {
34677 class EntryTransformer {
34678 constructor(_settings) {
34679 this._settings = _settings;
34683 return entry => this._transform(entry);
34686 _transform(entry) {
34687 let filepath = entry.path;
34689 if (this._settings.absolute) {
34690 filepath = utils$4.path.makeAbsolute(this._settings.cwd, filepath);
34691 filepath = utils$4.path.unixify(filepath);
34694 if (this._settings.markDirectories && entry.dirent.isDirectory()) {
34698 if (!this._settings.objectMode) {
34702 return Object.assign(Object.assign({}, entry), {
34709 exports.default = EntryTransformer;
34711 unwrapExports(entry$1);
34713 var provider = createCommonjsModule(function (module, exports) {
34715 Object.defineProperty(exports, "__esModule", {
34720 constructor(_settings) {
34721 this._settings = _settings;
34722 this.errorFilter = new error.default(this._settings);
34723 this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions());
34724 this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions());
34725 this.entryTransformer = new entry$1.default(this._settings);
34728 _getRootDirectory(task) {
34729 return path$2.resolve(this._settings.cwd, task.base);
34732 _getReaderOptions(task) {
34733 const basePath = task.base === '.' ? '' : task.base;
34736 pathSegmentSeparator: '/',
34737 concurrency: this._settings.concurrency,
34738 deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
34739 entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
34740 errorFilter: this.errorFilter.getFilter(),
34741 followSymbolicLinks: this._settings.followSymbolicLinks,
34742 fs: this._settings.fs,
34743 stats: this._settings.stats,
34744 throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
34745 transform: this.entryTransformer.getTransformer()
34749 _getMicromatchOptions() {
34751 dot: this._settings.dot,
34752 matchBase: this._settings.baseNameMatch,
34753 nobrace: !this._settings.braceExpansion,
34754 nocase: !this._settings.caseSensitiveMatch,
34755 noext: !this._settings.extglob,
34756 noglobstar: !this._settings.globstar,
34758 strictSlashes: false
34764 exports.default = Provider;
34766 unwrapExports(provider);
34768 var async$5 = createCommonjsModule(function (module, exports) {
34770 Object.defineProperty(exports, "__esModule", {
34774 class ProviderAsync extends provider.default {
34776 super(...arguments);
34777 this._reader = new stream$3.default(this._settings);
34781 const root = this._getRootDirectory(task);
34783 const options = this._getReaderOptions(task);
34785 const entries = [];
34786 return new Promise((resolve, reject) => {
34787 const stream = this.api(root, task, options);
34788 stream.once('error', reject);
34789 stream.on('data', entry => entries.push(options.transform(entry)));
34790 stream.once('end', () => resolve(entries));
34794 api(root, task, options) {
34795 if (task.dynamic) {
34796 return this._reader.dynamic(root, options);
34799 return this._reader.static(task.patterns, options);
34804 exports.default = ProviderAsync;
34806 unwrapExports(async$5);
34808 var stream$4 = createCommonjsModule(function (module, exports) {
34810 Object.defineProperty(exports, "__esModule", {
34814 class ProviderStream extends provider.default {
34816 super(...arguments);
34817 this._reader = new stream$3.default(this._settings);
34821 const root = this._getRootDirectory(task);
34823 const options = this._getReaderOptions(task);
34825 const source = this.api(root, task, options);
34826 const destination = new stream$6.Readable({
34830 source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
34831 destination.once('close', () => source.destroy());
34832 return destination;
34835 api(root, task, options) {
34836 if (task.dynamic) {
34837 return this._reader.dynamic(root, options);
34840 return this._reader.static(task.patterns, options);
34845 exports.default = ProviderStream;
34847 unwrapExports(stream$4);
34849 var sync$5 = createCommonjsModule(function (module, exports) {
34851 Object.defineProperty(exports, "__esModule", {
34855 class ReaderSync extends reader$1.default {
34857 super(...arguments);
34858 this._walkSync = out$2.walkSync;
34859 this._statSync = out.statSync;
34862 dynamic(root, options) {
34863 return this._walkSync(root, options);
34866 static(patterns, options) {
34867 const entries = [];
34869 for (const pattern of patterns) {
34870 const filepath = this._getFullEntryPath(pattern);
34872 const entry = this._getEntry(filepath, pattern, options);
34874 if (entry === null || !options.entryFilter(entry)) {
34878 entries.push(entry);
34884 _getEntry(filepath, pattern, options) {
34886 const stats = this._getStat(filepath);
34888 return this._makeEntry(stats, pattern);
34890 if (options.errorFilter(error)) {
34898 _getStat(filepath) {
34899 return this._statSync(filepath, this._fsStatSettings);
34904 exports.default = ReaderSync;
34906 unwrapExports(sync$5);
34908 var sync$6 = createCommonjsModule(function (module, exports) {
34910 Object.defineProperty(exports, "__esModule", {
34914 class ProviderSync extends provider.default {
34916 super(...arguments);
34917 this._reader = new sync$5.default(this._settings);
34921 const root = this._getRootDirectory(task);
34923 const options = this._getReaderOptions(task);
34925 const entries = this.api(root, task, options);
34926 return entries.map(options.transform);
34929 api(root, task, options) {
34930 if (task.dynamic) {
34931 return this._reader.dynamic(root, options);
34934 return this._reader.static(task.patterns, options);
34939 exports.default = ProviderSync;
34941 unwrapExports(sync$6);
34943 var settings$3 = createCommonjsModule(function (module, exports) {
34945 Object.defineProperty(exports, "__esModule", {
34948 const CPU_COUNT = os$1.cpus().length;
34949 exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
34951 lstatSync: fs$3.lstatSync,
34953 statSync: fs$3.statSync,
34954 readdir: fs$3.readdir,
34955 readdirSync: fs$3.readdirSync
34959 constructor(_options = {}) {
34960 this._options = _options;
34961 this.absolute = this._getValue(this._options.absolute, false);
34962 this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
34963 this.braceExpansion = this._getValue(this._options.braceExpansion, true);
34964 this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
34965 this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
34966 this.cwd = this._getValue(this._options.cwd, process.cwd());
34967 this.deep = this._getValue(this._options.deep, Infinity);
34968 this.dot = this._getValue(this._options.dot, false);
34969 this.extglob = this._getValue(this._options.extglob, true);
34970 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
34971 this.fs = this._getFileSystemMethods(this._options.fs);
34972 this.globstar = this._getValue(this._options.globstar, true);
34973 this.ignore = this._getValue(this._options.ignore, []);
34974 this.markDirectories = this._getValue(this._options.markDirectories, false);
34975 this.objectMode = this._getValue(this._options.objectMode, false);
34976 this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
34977 this.onlyFiles = this._getValue(this._options.onlyFiles, true);
34978 this.stats = this._getValue(this._options.stats, false);
34979 this.suppressErrors = this._getValue(this._options.suppressErrors, false);
34980 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
34981 this.unique = this._getValue(this._options.unique, true);
34983 if (this.onlyDirectories) {
34984 this.onlyFiles = false;
34988 this.objectMode = true;
34992 _getValue(option, value) {
34993 return option === undefined ? value : option;
34996 _getFileSystemMethods(methods = {}) {
34997 return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
35002 exports.default = Settings;
35004 unwrapExports(settings$3);
35005 var settings_1 = settings$3.DEFAULT_FILE_SYSTEM_ADAPTER;
35007 async function FastGlob(source, options) {
35008 assertPatternsInput(source);
35009 const works = getWorks(source, async$5.default, options);
35010 const result = await Promise.all(works);
35011 return utils$4.array.flatten(result);
35012 } // https://github.com/typescript-eslint/typescript-eslint/issues/60
35013 // eslint-disable-next-line no-redeclare
35016 (function (FastGlob) {
35017 function sync(source, options) {
35018 assertPatternsInput(source);
35019 const works = getWorks(source, sync$6.default, options);
35020 return utils$4.array.flatten(works);
35023 FastGlob.sync = sync;
35025 function stream(source, options) {
35026 assertPatternsInput(source);
35027 const works = getWorks(source, stream$4.default, options);
35029 * The stream returned by the provider cannot work with an asynchronous iterator.
\r
35030 * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
\r
35031 * This affects performance (+25%). I don't see best solution right now.
\r
35034 return utils$4.stream.merge(works);
35037 FastGlob.stream = stream;
35039 function generateTasks(source, options) {
35040 assertPatternsInput(source);
35041 const patterns = [].concat(source);
35042 const settings = new settings$3.default(options);
35043 return tasks.generate(patterns, settings);
35046 FastGlob.generateTasks = generateTasks;
35048 function isDynamicPattern(source, options) {
35049 assertPatternsInput(source);
35050 const settings = new settings$3.default(options);
35051 return utils$4.pattern.isDynamicPattern(source, settings);
35054 FastGlob.isDynamicPattern = isDynamicPattern;
35056 function escapePath(source) {
35057 assertPatternsInput(source);
35058 return utils$4.path.escape(source);
35061 FastGlob.escapePath = escapePath;
35062 })(FastGlob || (FastGlob = {}));
35064 function getWorks(source, _Provider, options) {
35065 const patterns = [].concat(source);
35066 const settings = new settings$3.default(options);
35067 const tasks$1 = tasks.generate(patterns, settings);
35068 const provider = new _Provider(settings);
35069 return tasks$1.map(provider.read, provider);
35072 function assertPatternsInput(input) {
35073 const source = [].concat(input);
35074 const isValidSource = source.every(item => utils$4.string.isString(item) && !utils$4.string.isEmpty(item));
35076 if (!isValidSource) {
35077 throw new TypeError('Patterns must be a string (non empty) or an array of strings');
35081 var out$3 = FastGlob;
35087 async function isType(fsStatType, statsMethodName, filePath) {
35088 if (typeof filePath !== 'string') {
35089 throw new TypeError(`Expected a string, got ${typeof filePath}`);
35093 const stats = await promisify(fs$3[fsStatType])(filePath);
35094 return stats[statsMethodName]();
35096 if (error.code === 'ENOENT') {
35104 function isTypeSync(fsStatType, statsMethodName, filePath) {
35105 if (typeof filePath !== 'string') {
35106 throw new TypeError(`Expected a string, got ${typeof filePath}`);
35110 return fs$3[fsStatType](filePath)[statsMethodName]();
35112 if (error.code === 'ENOENT') {
35120 var isFile = isType.bind(null, 'stat', 'isFile');
35121 var isDirectory = isType.bind(null, 'stat', 'isDirectory');
35122 var isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
35123 var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
35124 var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
35125 var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
35128 isDirectory: isDirectory,
35129 isSymlink: isSymlink,
35130 isFileSync: isFileSync,
35131 isDirectorySync: isDirectorySync,
35132 isSymlinkSync: isSymlinkSync
35135 const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];
35137 const getPath = (filepath, cwd) => {
35138 const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;
35139 return path$2.isAbsolute(pth) ? pth : path$2.join(cwd, pth);
35142 const addExtensions = (file, extensions) => {
35143 if (path$2.extname(file)) {
35144 return `**/${file}`;
35147 return `**/${file}.${getExtensions(extensions)}`;
35150 const getGlob = (directory, options) => {
35151 if (options.files && !Array.isArray(options.files)) {
35152 throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);
35155 if (options.extensions && !Array.isArray(options.extensions)) {
35156 throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);
35159 if (options.files && options.extensions) {
35160 return options.files.map(x => path$2.posix.join(directory, addExtensions(x, options.extensions)));
35163 if (options.files) {
35164 return options.files.map(x => path$2.posix.join(directory, `**/${x}`));
35167 if (options.extensions) {
35168 return [path$2.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];
35171 return [path$2.posix.join(directory, '**')];
35174 var dirGlob = async (input, options) => {
35175 options = Object.assign({
35179 if (typeof options.cwd !== 'string') {
35180 throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
35183 const globs = await Promise.all([].concat(input).map(async x => {
35184 const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));
35185 return isDirectory ? getGlob(x, options) : x;
35187 return [].concat.apply([], globs); // eslint-disable-line prefer-spread
35190 var sync$7 = (input, options) => {
35191 options = Object.assign({
35195 if (typeof options.cwd !== 'string') {
35196 throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
35199 const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);
35200 return [].concat.apply([], globs); // eslint-disable-line prefer-spread
35202 dirGlob.sync = sync$7;
35204 // A simple implementation of make-array
35205 function makeArray(subject) {
35206 return Array.isArray(subject) ? subject : [subject];
35209 const REGEX_TEST_BLANK_LINE = /^\s+$/;
35210 const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
35211 const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
35212 const REGEX_SPLITALL_CRLF = /\r?\n/g; // /foo,
35218 const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
35219 const SLASH$1 = '/';
35220 const KEY_IGNORE$1 = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
35221 /* istanbul ignore next */
35224 const define$1 = (object, key, value) => Object.defineProperty(object, key, {
35228 const REGEX_REGEXP_RANGE$1 = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
35229 // The cases are complicated, see test cases for details
35231 const sanitizeRange$1 = range => range.replace(REGEX_REGEXP_RANGE$1, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
35232 // fatal for JavaScript regular expression, so eliminate it.
35233 : ''); // > If the pattern ends with a slash,
35234 // > it is removed for the purpose of the following description,
35235 // > but it would only find a match with a directory.
35236 // > In other words, foo/ will match a directory foo and paths underneath it,
35237 // > but will not match a regular file or a symbolic link foo
35238 // > (this is consistent with the way how pathspec works in general in Git).
35239 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
35240 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
35241 // you could use option `mark: true` with `glob`
35242 // '`foo/`' should not continue with the '`..`'
35245 const REPLACERS = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
35249 /\\?\s+$/, match => match.indexOf('\\') === 0 ? ' ' : ''], // replace (\ ) with ' '
35250 [/\\\s/g, () => ' '], // Escape metacharacters
35251 // which is written down by users but means special for regular expressions.
35252 // > There are 12 characters with special meanings:
35253 // > - the backslash \,
35254 // > - the caret ^,
35255 // > - the dollar sign $,
35256 // > - the period or dot .,
35257 // > - the vertical bar or pipe symbol |,
35258 // > - the question mark ?,
35259 // > - the asterisk or star *,
35260 // > - the plus sign +,
35261 // > - the opening parenthesis (,
35262 // > - the closing parenthesis ),
35263 // > - and the opening square bracket [,
35264 // > - the opening curly brace {,
35265 // > These special characters are often called "metacharacters".
35266 [/[\\^$.|*+(){]/g, match => `\\${match}`], [// > [abc] matches any character inside the brackets
35267 // > (in this case a, b, or c);
35268 /\[([^\]/]*)($|\])/g, (match, p1, p2) => p2 === ']' ? `[${sanitizeRange$1(p1)}]` : `\\${match}`], [// > a question mark (?) matches a single character
35269 /(?!\\)\?/g, () => '[^/]'], // leading slash
35270 [// > A leading slash matches the beginning of the pathname.
35271 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
35272 // A leading slash matches the beginning of the pathname
35273 /^\//, () => '^'], // replace special metacharacter slash after the leading slash
35274 [/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
35275 // > For example, "**/foo" matches file or directory "foo" anywhere,
35276 // > the same as pattern "foo".
35277 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
35278 // > under directory "foo".
35279 // Notice that the '*'s have been replaced as '\\*'
35280 /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
35281 () => '^(?:.*\\/)?'], // ending
35282 [// 'js' will not match 'js.'
35283 // 'ab' will not match 'abc'
35284 /(?:[^*])$/, // WTF!
35285 // https://git-scm.com/docs/gitignore
35286 // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
35287 // which re-fixes #24, #38
35288 // > If there is a separator at the end of the pattern then the pattern
35289 // > will only match directories, otherwise the pattern can match both
35290 // > files and directories.
35291 // 'js*' will not match 'a.js'
35292 // 'js/' will not match 'a.js'
35293 // 'js' will match 'a.js' and 'a.js/'
35294 match => /\/$/.test(match) // foo/ will not match 'foo'
35295 ? `${match}$` // foo matches 'foo' and 'foo/'
35296 : `${match}(?=$|\\/$)`], // starting
35297 [// there will be no leading '/'
35298 // (which has been replaced by section "leading slash")
35299 // If starts with '**', adding a '^' to the regular expression also works
35300 /^(?=[^^])/, function startingReplacer() {
35301 // If has a slash `/` at the beginning or middle
35302 return !/\/(?!$)/.test(this) // > Prior to 2.22.1
35303 // > If the pattern does not contain a slash /,
35304 // > Git treats it as a shell glob pattern
35305 // Actually, if there is only a trailing slash,
35306 // git also treats it as a shell glob pattern
35307 // After 2.22.1 (compatible but clearer)
35308 // > If there is a separator at the beginning or middle (or both)
35309 // > of the pattern, then the pattern is relative to the directory
35310 // > level of the particular .gitignore file itself.
35311 // > Otherwise the pattern may also match at any level below
35312 // > the .gitignore level.
35313 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
35314 // > consumption by fnmatch(3)
35316 }], // two globstars
35317 [// Use lookahead assertions so that we could match more than one `'/**'`
35318 /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
35319 // should not use '*', or it will be replaced by the next replacer
35320 // Check if it is not the last `'/**'`
35321 (_, index, str) => index + 6 < str.length // case: /**/
35322 // > A slash followed by two consecutive asterisks then a slash matches
35323 // > zero or more directories.
35324 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
35326 ? '(?:\\/[^\\/]+)*' // case: /**
35327 // > A trailing `"/**"` matches everything inside.
35328 // #21: everything inside but it should not include the current folder
35329 : '\\/.+'], // intermediate wildcards
35330 [// Never replace escaped '*'
35331 // ignore rule '\*' will match the path '*'
35333 // 'abc.*' -> skip this rule
35334 /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
35335 // '*.js' doesn't match 'abc'
35336 (_, p1) => `${p1}[^\\/]*`], // trailing wildcard
35337 [/(\^|\\\/)?\\\*$/, (_, p1) => {
35338 const prefix = p1 // '\^':
35339 // '/*' does not match ''
35340 // '/*' does not match everything
35342 // 'abc/*' does not match 'abc/'
35343 ? `${p1}[^/]+` // 'a*' matches 'a'
35344 // 'a*' matches 'aa'
35346 return `${prefix}(?=$|\\/$)`;
35348 /\\\\\\/g, () => '\\']]; // A simple cache, because an ignore rule only has only one certain meaning
35350 const regexCache = Object.create(null); // @param {pattern}
35352 const makeRegex = (pattern, negative, ignorecase) => {
35353 const r = regexCache[pattern];
35357 } // const replacers = negative
35358 // ? NEGATIVE_REPLACERS
35359 // : POSITIVE_REPLACERS
35362 const source = REPLACERS.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
35363 return regexCache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
35366 const isString = subject => typeof subject === 'string'; // > A blank line matches no files, so it can serve as a separator for readability.
35369 const checkPattern$1 = pattern => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
35370 && pattern.indexOf('#') !== 0;
35372 const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);
35375 constructor(origin, pattern, negative, regex) {
35376 this.origin = origin;
35377 this.pattern = pattern;
35378 this.negative = negative;
35379 this.regex = regex;
35384 const createRule$1 = (pattern, ignorecase) => {
35385 const origin = pattern;
35386 let negative = false; // > An optional prefix "!" which negates the pattern;
35388 if (pattern.indexOf('!') === 0) {
35390 pattern = pattern.substr(1);
35393 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
35394 // > begin with a literal "!", for example, `"\!important!.txt"`.
35395 .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
35396 // > begin with a hash.
35397 .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
35398 const regex = makeRegex(pattern, negative, ignorecase);
35399 return new IgnoreRule(origin, pattern, negative, regex);
35402 const throwError = (message, Ctor) => {
35403 throw new Ctor(message);
35406 const checkPath = (path, originalPath, doThrow) => {
35407 if (!isString(path)) {
35408 return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
35409 } // We don't know if we should ignore '', so throw
35413 return doThrow(`path must not be empty`, TypeError);
35414 } // Check if it is a relative path
35417 if (checkPath.isNotRelative(path)) {
35418 const r = '`path.relative()`d';
35419 return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
35425 const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);
35427 checkPath.isNotRelative = isNotRelative;
35429 checkPath.convert = p => p;
35436 this._ignorecase = ignorecase;
35437 define$1(this, KEY_IGNORE$1, true);
35443 this._ignoreCache = Object.create(null);
35444 this._testCache = Object.create(null);
35447 _addPattern(pattern) {
35449 if (pattern && pattern[KEY_IGNORE$1]) {
35450 this._rules = this._rules.concat(pattern._rules);
35451 this._added = true;
35455 if (checkPattern$1(pattern)) {
35456 const rule = createRule$1(pattern, this._ignorecase);
35457 this._added = true;
35459 this._rules.push(rule);
35461 } // @param {Array<string> | string | Ignore} pattern
35465 this._added = false;
35466 makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
35467 // making the behavior changed.
35477 addPattern(pattern) {
35478 return this.add(pattern);
35479 } // | ignored : unignored
35480 // negative | 0:0 | 0:1 | 1:0 | 1:1
35481 // -------- | ------- | ------- | ------- | --------
35482 // 0 | TEST | TEST | SKIP | X
35483 // 1 | TESTIF | SKIP | TEST | X
35484 // - SKIP: always skip
35485 // - TEST: always test
35486 // - TESTIF: only test if checkUnignored
35487 // - X: that never happen
35488 // @param {boolean} whether should check if the path is unignored,
35489 // setting `checkUnignored` to `false` could reduce additional
35491 // @returns {TestResult} true if a file is ignored
35494 _testOne(path, checkUnignored) {
35495 let ignored = false;
35496 let unignored = false;
35498 this._rules.forEach(rule => {
35503 if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
35507 const matched = rule.regex.test(path);
35510 ignored = !negative;
35511 unignored = negative;
35519 } // @returns {TestResult}
35522 _test(originalPath, cache, checkUnignored, slices) {
35523 const path = originalPath // Supports nullable path
35524 && checkPath.convert(originalPath);
35525 checkPath(path, originalPath, throwError);
35526 return this._t(path, cache, checkUnignored, slices);
35529 _t(path, cache, checkUnignored, slices) {
35530 if (path in cache) {
35531 return cache[path];
35536 // ['path', 'to', 'a.js']
35537 slices = path.split(SLASH$1);
35540 slices.pop(); // If the path has no parent directory, just test it
35542 if (!slices.length) {
35543 return cache[path] = this._testOne(path, checkUnignored);
35546 const parent = this._t(slices.join(SLASH$1) + SLASH$1, cache, checkUnignored, slices); // If the path contains a parent directory, check the parent first
35549 return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of
35550 // > that file is excluded.
35551 ? parent : this._testOne(path, checkUnignored);
35555 return this._test(path, this._ignoreCache, false).ignored;
35559 return path => !this.ignores(path);
35563 return makeArray(paths).filter(this.createFilter());
35564 } // @returns {TestResult}
35568 return this._test(path, this._testCache, true);
35573 const factory = options => new Ignore(options);
35575 const returnFalse = () => false;
35577 const isPathValid = path => checkPath(path && checkPath.convert(path), path, returnFalse);
35579 factory.isPathValid = isPathValid; // Fixes typescript
35581 factory.default = factory;
35582 var ignore$1 = factory; // Windows
35583 // --------------------------------------------------------------
35585 /* istanbul ignore if */
35587 if ( // Detect `process` so that it can run in browsers.
35588 typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
35589 /* eslint no-control-regex: "off" */
35590 const makePosix = str => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, '/');
35592 checkPath.convert = makePosix; // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
35595 const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
35597 checkPath.isNotRelative = path => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
35600 var slash$1 = path => {
35601 const isExtendedLengthPath = /^\\\\\?\\/.test(path);
35602 const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
35604 if (isExtendedLengthPath || hasNonAscii) {
35608 return path.replace(/\\/g, '/');
35612 promisify: promisify$1
35614 const DEFAULT_IGNORE = ['**/node_modules/**', '**/flow-typed/**', '**/coverage/**', '**/.git'];
35615 const readFileP = promisify$1(fs$3.readFile);
35617 const mapGitIgnorePatternTo = base => ignore => {
35618 if (ignore.startsWith('!')) {
35619 return '!' + path$2.posix.join(base, ignore.slice(1));
35622 return path$2.posix.join(base, ignore);
35625 const parseGitIgnore = (content, options) => {
35626 const base = slash$1(path$2.relative(options.cwd, path$2.dirname(options.fileName)));
35627 return content.split(/\r?\n/).filter(Boolean).filter(line => !line.startsWith('#')).map(mapGitIgnorePatternTo(base));
35630 const reduceIgnore = files => {
35631 return files.reduce((ignores, file) => {
35632 ignores.add(parseGitIgnore(file.content, {
35634 fileName: file.filePath
35640 const ensureAbsolutePathForCwd = (cwd, p) => {
35641 if (path$2.isAbsolute(p)) {
35642 if (p.startsWith(cwd)) {
35646 throw new Error(`Path ${p} is not in cwd ${cwd}`);
35649 return path$2.join(cwd, p);
35652 const getIsIgnoredPredecate = (ignores, cwd) => {
35653 return p => ignores.ignores(slash$1(path$2.relative(cwd, ensureAbsolutePathForCwd(cwd, p))));
35656 const getFile = async (file, cwd) => {
35657 const filePath = path$2.join(cwd, file);
35658 const content = await readFileP(filePath, 'utf8');
35666 const getFileSync = (file, cwd) => {
35667 const filePath = path$2.join(cwd, file);
35668 const content = fs$3.readFileSync(filePath, 'utf8');
35676 const normalizeOptions$3 = ({
35678 cwd = slash$1(process.cwd())
35686 var gitignore = async options => {
35687 options = normalizeOptions$3(options);
35688 const paths = await out$3('**/.gitignore', {
35689 ignore: DEFAULT_IGNORE.concat(options.ignore),
35692 const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
35693 const ignores = reduceIgnore(files);
35694 return getIsIgnoredPredecate(ignores, options.cwd);
35697 var sync$8 = options => {
35698 options = normalizeOptions$3(options);
35699 const paths = out$3.sync('**/.gitignore', {
35700 ignore: DEFAULT_IGNORE.concat(options.ignore),
35703 const files = paths.map(file => getFileSync(file, options.cwd));
35704 const ignores = reduceIgnore(files);
35705 return getIsIgnoredPredecate(ignores, options.cwd);
35707 gitignore.sync = sync$8;
35713 class ObjectTransform extends Transform {
35722 class FilterStream extends ObjectTransform {
35723 constructor(filter) {
35725 this._filter = filter;
35728 _transform(data, encoding, callback) {
35729 if (this._filter(data)) {
35738 class UniqueStream extends ObjectTransform {
35741 this._pushed = new Set();
35744 _transform(data, encoding, callback) {
35745 if (!this._pushed.has(data)) {
35748 this._pushed.add(data);
35756 var streamUtils = {
35762 FilterStream: FilterStream$1,
35763 UniqueStream: UniqueStream$1
35766 const DEFAULT_FILTER = () => false;
35768 const isNegative = pattern => pattern[0] === '!';
35770 const assertPatternsInput$1 = patterns => {
35771 if (!patterns.every(pattern => typeof pattern === 'string')) {
35772 throw new TypeError('Patterns must be a string or an array of strings');
35776 const checkCwdOption = (options = {}) => {
35777 if (!options.cwd) {
35784 stat = fs$3.statSync(options.cwd);
35789 if (!stat.isDirectory()) {
35790 throw new Error('The `cwd` option must be a path to a directory');
35794 const getPathString = p => p.stats instanceof fs$3.Stats ? p.path : p;
35796 const generateGlobTasks = (patterns, taskOptions) => {
35797 patterns = arrayUnion([].concat(patterns));
35798 assertPatternsInput$1(patterns);
35799 checkCwdOption(taskOptions);
35800 const globTasks = [];
35801 taskOptions = Object.assign({
35803 expandDirectories: true
35806 for (const [index, pattern] of patterns.entries()) {
35807 if (isNegative(pattern)) {
35811 const ignore = patterns.slice(index).filter(isNegative).map(pattern => pattern.slice(1));
35812 const options = Object.assign({}, taskOptions, {
35813 ignore: taskOptions.ignore.concat(ignore)
35824 const globDirs = (task, fn) => {
35827 if (task.options.cwd) {
35828 options.cwd = task.options.cwd;
35831 if (Array.isArray(task.options.expandDirectories)) {
35832 options = Object.assign({}, options, {
35833 files: task.options.expandDirectories
35835 } else if (typeof task.options.expandDirectories === 'object') {
35836 options = Object.assign({}, options, {}, task.options.expandDirectories);
35839 return fn(task.pattern, options);
35842 const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
35844 const getFilterSync = options => {
35845 return options && options.gitignore ? gitignore.sync({
35847 ignore: options.ignore
35848 }) : DEFAULT_FILTER;
35851 const globToTask = task => glob => {
35856 if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
35857 options.ignore = dirGlob.sync(options.ignore);
35866 var globby$1 = async (patterns, options) => {
35867 const globTasks = generateGlobTasks(patterns, options);
35869 const getFilter = async () => {
35870 return options && options.gitignore ? gitignore({
35872 ignore: options.ignore
35873 }) : DEFAULT_FILTER;
35876 const getTasks = async () => {
35877 const tasks = await Promise.all(globTasks.map(async task => {
35878 const globs = await getPattern(task, dirGlob);
35879 return Promise.all(globs.map(globToTask(task)));
35881 return arrayUnion(...tasks);
35884 const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
35885 const paths = await Promise.all(tasks.map(task => out$3(task.pattern, task.options)));
35886 return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
35889 var sync$9 = (patterns, options) => {
35890 const globTasks = generateGlobTasks(patterns, options);
35891 const tasks = globTasks.reduce((tasks, task) => {
35892 const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
35893 return tasks.concat(newTask);
35895 const filter = getFilterSync(options);
35896 return tasks.reduce((matches, task) => arrayUnion(matches, out$3.sync(task.pattern, task.options)), []).filter(path_ => !filter(path_));
35899 var stream$5 = (patterns, options) => {
35900 const globTasks = generateGlobTasks(patterns, options);
35901 const tasks = globTasks.reduce((tasks, task) => {
35902 const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
35903 return tasks.concat(newTask);
35905 const filter = getFilterSync(options);
35906 const filterStream = new FilterStream$1(p => !filter(p));
35907 const uniqueStream = new UniqueStream$1();
35908 return merge2_1(tasks.map(task => out$3.stream(task.pattern, task.options))).pipe(filterStream).pipe(uniqueStream);
35911 var generateGlobTasks_1 = generateGlobTasks;
35913 var hasMagic = (patterns, options) => [].concat(patterns).some(pattern => out$3.isDynamicPattern(pattern, options));
35915 var gitignore_1 = gitignore;
35916 globby$1.sync = sync$9;
35917 globby$1.stream = stream$5;
35918 globby$1.generateGlobTasks = generateGlobTasks_1;
35919 globby$1.hasMagic = hasMagic;
35920 globby$1.gitignore = gitignore_1;
35923 addLeadingComment: addLeadingComment$3,
35924 addTrailingComment: addTrailingComment$3,
35925 addDanglingComment: addDanglingComment$3,
35926 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$2
35929 function handleOwnLineComment(comment, text, options, ast, isLastComment) {
35935 return handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleLabeledStatementComments(enclosingNode, comment);
35938 function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
35944 return handleClosureTypeCastComments(followingNode, comment) || handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment);
35947 function handleRemainingComment(comment, text, options, ast, isLastComment) {
35954 if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment) || handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options)) {
35961 function addBlockStatementFirstComment(node, comment) {
35962 const body = node.body.filter(n => n.type !== "EmptyStatement");
35964 if (body.length === 0) {
35965 addDanglingComment$3(node, comment);
35967 addLeadingComment$3(body[0], comment);
35971 function addBlockOrNotComment(node, comment) {
35972 if (node.type === "BlockStatement") {
35973 addBlockStatementFirstComment(node, comment);
35975 addLeadingComment$3(node, comment);
35979 function handleClosureTypeCastComments(followingNode, comment) {
35980 if (followingNode && isTypeCastComment(comment)) {
35981 addLeadingComment$3(followingNode, comment);
35986 } // There are often comments before the else clause of if statements like
35992 // They are being attached as leading comments of the BlockExpression which
35993 // is not well printed. What we want is to instead move the comment inside
35994 // of the block and make it leadingComment of the first element of the block
35995 // or dangling comment of the block if there is nothing inside
36004 function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
36005 if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
36007 } // We unfortunately have no way using the AST or location of nodes to know
36008 // if the comment is positioned before the condition parenthesis:
36009 // if (a /* comment */) {}
36010 // The only workaround I found is to look at the next character to see if
36014 const nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
36016 if (nextCharacter === ")") {
36017 addTrailingComment$3(precedingNode, comment);
36019 } // Comments before `else`:
36020 // - treat as trailing comments of the consequent, if it's a BlockStatement
36021 // - treat as a dangling comment otherwise
36024 if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
36025 if (precedingNode.type === "BlockStatement") {
36026 addTrailingComment$3(precedingNode, comment);
36028 addDanglingComment$3(enclosingNode, comment);
36034 if (followingNode.type === "BlockStatement") {
36035 addBlockStatementFirstComment(followingNode, comment);
36039 if (followingNode.type === "IfStatement") {
36040 addBlockOrNotComment(followingNode.consequent, comment);
36042 } // For comments positioned after the condition parenthesis in an if statement
36043 // before the consequent without brackets on, such as
36044 // if (a) /* comment */ true,
36045 // we look at the next character to see if the following node
36046 // is the consequent for the if statement
36049 if (enclosingNode.consequent === followingNode) {
36050 addLeadingComment$3(followingNode, comment);
36057 function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
36058 if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
36060 } // We unfortunately have no way using the AST or location of nodes to know
36061 // if the comment is positioned before the condition parenthesis:
36062 // while (a /* comment */) {}
36063 // The only workaround I found is to look at the next character to see if
36067 const nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
36069 if (nextCharacter === ")") {
36070 addTrailingComment$3(precedingNode, comment);
36074 if (followingNode.type === "BlockStatement") {
36075 addBlockStatementFirstComment(followingNode, comment);
36080 } // Same as IfStatement but for TryStatement
36083 function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) {
36084 if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
36088 if (enclosingNode.type === "CatchClause" && precedingNode) {
36089 addTrailingComment$3(precedingNode, comment);
36093 if (followingNode.type === "BlockStatement") {
36094 addBlockStatementFirstComment(followingNode, comment);
36098 if (followingNode.type === "TryStatement") {
36099 addBlockOrNotComment(followingNode.finalizer, comment);
36103 if (followingNode.type === "CatchClause") {
36104 addBlockOrNotComment(followingNode.body, comment);
36111 function handleMemberExpressionComments(enclosingNode, followingNode, comment) {
36112 if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") {
36113 addLeadingComment$3(enclosingNode, comment);
36120 function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) {
36121 const isSameLineAsPrecedingNode = precedingNode && !util$1.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment));
36123 if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) {
36124 addLeadingComment$3(followingNode, comment);
36131 function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
36132 if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
36133 addTrailingComment$3(enclosingNode.value.left, comment);
36140 function handleClassComments(enclosingNode, precedingNode, followingNode, comment) {
36141 if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
36142 if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) {
36143 addLeadingComment$3(enclosingNode, comment);
36145 addTrailingComment$3(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
36154 function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) {
36155 // This is only needed for estree parsers (flow, typescript) to attach
36156 // after a method name:
36157 // obj = { fn /*comment*/() {} };
36158 if (enclosingNode && precedingNode && ( // "MethodDefinition" is handled in getCommentChildNodes
36159 enclosingNode.type === "Property" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "TSAbstractMethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
36160 // comment should be attached to value instead of key
36161 util$1.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") {
36162 addTrailingComment$3(precedingNode, comment);
36164 } // Print comments between decorators and class methods as a trailing comment
36165 // on the decorator node instead of the method node
36168 if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "MethodDefinition")) {
36169 addTrailingComment$3(precedingNode, comment);
36176 function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) {
36177 if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") {
36181 if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
36182 addTrailingComment$3(precedingNode, comment);
36189 function handleCommentAfterArrowParams(text, enclosingNode, comment, options) {
36190 if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
36194 const index = getNextNonSpaceNonCommentCharacterIndex$2(text, comment, options.locEnd);
36196 if (text.slice(index, index + 2) === "=>") {
36197 addDanglingComment$3(enclosingNode, comment);
36204 function handleCommentInEmptyParens(text, enclosingNode, comment, options) {
36205 if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") {
36207 } // Only add dangling comments to fix the case when no params are present,
36208 // i.e. a function without any argument.
36211 if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && // `params` vs `parameters` - see https://github.com/babel/babel/issues/9231
36212 (enclosingNode.params || enclosingNode.parameters).length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) {
36213 addDanglingComment$3(enclosingNode, comment);
36217 if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) {
36218 addDanglingComment$3(enclosingNode.value, comment);
36225 function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
36226 // Flow function type definitions
36227 if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
36228 addTrailingComment$3(precedingNode, comment);
36230 } // Real functions and TypeScript function type definitions
36233 if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && isRealFunctionLikeNode(enclosingNode) && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ")") {
36234 addTrailingComment$3(precedingNode, comment);
36238 if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
36239 const functionParamRightParenIndex = (() => {
36240 if ((enclosingNode.params || enclosingNode.parameters).length !== 0) {
36241 return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(util$1.getLast(enclosingNode.params || enclosingNode.parameters)));
36244 const functionParamLeftParenIndex = util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(enclosingNode.id));
36245 return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
36248 if (options.locStart(comment) > functionParamRightParenIndex) {
36249 addBlockStatementFirstComment(followingNode, comment);
36257 function handleImportSpecifierComments(enclosingNode, comment) {
36258 if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
36259 addLeadingComment$3(enclosingNode, comment);
36266 function handleLabeledStatementComments(enclosingNode, comment) {
36267 if (enclosingNode && enclosingNode.type === "LabeledStatement") {
36268 addLeadingComment$3(enclosingNode, comment);
36275 function handleBreakAndContinueStatementComments(enclosingNode, comment) {
36276 if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
36277 addTrailingComment$3(enclosingNode, comment);
36284 function handleCallExpressionComments(precedingNode, enclosingNode, comment) {
36285 if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
36286 addLeadingComment$3(enclosingNode.arguments[0], comment);
36293 function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) {
36294 if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
36295 if (util$1.isNodeIgnoreComment(comment)) {
36296 followingNode.prettierIgnore = true;
36297 comment.unignore = true;
36300 if (precedingNode) {
36301 addTrailingComment$3(precedingNode, comment);
36308 if (followingNode && (followingNode.type === "UnionTypeAnnotation" || followingNode.type === "TSUnionType") && util$1.isNodeIgnoreComment(comment)) {
36309 followingNode.types[0].prettierIgnore = true;
36310 comment.unignore = true;
36316 function handlePropertyComments(enclosingNode, comment) {
36317 if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
36318 addLeadingComment$3(enclosingNode, comment);
36325 function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
36326 // With Flow the enclosingNode is undefined so use the AST instead.
36327 if (ast && ast.body && ast.body.length === 0) {
36328 if (isLastComment) {
36329 addDanglingComment$3(ast, comment);
36331 addLeadingComment$3(ast, comment);
36335 } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
36336 if (isLastComment) {
36337 addDanglingComment$3(enclosingNode, comment);
36339 addLeadingComment$3(enclosingNode, comment);
36348 function handleForComments(enclosingNode, precedingNode, comment) {
36349 if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
36350 addLeadingComment$3(enclosingNode, comment);
36357 function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) {
36358 if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && util$1.hasNewline(text, options.locEnd(comment))) {
36359 addTrailingComment$3(precedingNode, comment);
36366 function handleAssignmentPatternComments(enclosingNode, comment) {
36367 if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
36368 addLeadingComment$3(enclosingNode, comment);
36375 function handleTypeAliasComments(enclosingNode, followingNode, comment) {
36376 if (enclosingNode && enclosingNode.type === "TypeAlias") {
36377 addLeadingComment$3(enclosingNode, comment);
36384 function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) {
36385 if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression" || isBlockComment(comment))) {
36386 addLeadingComment$3(followingNode, comment);
36393 function handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options) {
36394 if (!followingNode && enclosingNode && (enclosingNode.type === "TSMethodSignature" || enclosingNode.type === "TSDeclareFunction" || enclosingNode.type === "TSAbstractMethodDefinition") && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ";") {
36395 addTrailingComment$3(enclosingNode, comment);
36402 function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) {
36403 if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
36407 if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
36408 addLeadingComment$3(followingNode.name, comment);
36412 if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
36413 addTrailingComment$3(precedingNode.constraint, comment);
36420 function isBlockComment(comment) {
36421 return comment.type === "Block" || comment.type === "CommentBlock";
36424 function hasLeadingComment(node, fn = () => true) {
36425 if (node.leadingComments) {
36426 return node.leadingComments.some(fn);
36429 if (node.comments) {
36430 return node.comments.some(comment => comment.leading && fn(comment));
36436 function isRealFunctionLikeNode(node) {
36437 return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration" || node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "TSDeclareFunction" || node.type === "TSCallSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSMethodSignature" || node.type === "TSConstructorType" || node.type === "TSFunctionType" || node.type === "TSDeclareMethod";
36440 function getGapRegex(enclosingNode) {
36441 if (enclosingNode && enclosingNode.type !== "BinaryExpression" && enclosingNode.type !== "LogicalExpression") {
36442 // Support degenerate single-element unions and intersections.
36443 // E.g.: `type A = /* 1 */ & B`
36444 return /^[\s(&|]*$/;
36448 function getCommentChildNodes(node, options) {
36449 // Prevent attaching comments to FunctionExpression in this case:
36451 // bar() // comment
36456 if ((options.parser === "typescript" || options.parser === "flow") && node.type === "MethodDefinition" && node.value && node.value.type === "FunctionExpression" && node.value.params.length === 0 && !node.value.returnType && (!node.value.typeParameters || node.value.typeParameters.length === 0) && node.value.body) {
36457 return [...(node.decorators || []), node.key, node.value.body];
36461 function isTypeCastComment(comment) {
36462 return isBlockComment(comment) && comment.value[0] === "*" && // TypeScript expects the type to be enclosed in curly brackets, however
36463 // Closure Compiler accepts types in parens and even without any delimiters at all.
36464 // That's why we just search for "@type".
36465 /@type\b/.test(comment.value);
36469 handleOwnLineComment,
36470 handleEndOfLineComment,
36471 handleRemainingComment,
36476 getCommentChildNodes
36480 isBlockComment: isBlockComment$1,
36481 hasLeadingComment: hasLeadingComment$1
36488 hardline: hardline$3,
36489 softline: softline$1,
36490 literalline: literalline$1,
36493 dedentToRoot: dedentToRoot$1
36497 stripTrailingHardline: stripTrailingHardline$1
36501 function embed(path, print, textToDoc, options) {
36502 const node = path.getValue();
36503 const parent = path.getParentNode();
36504 const parentParent = path.getParentNode(1);
36506 switch (node.type) {
36507 case "TemplateLiteral":
36509 const isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(isIt => isIt(path));
36512 // Get full template literal with expressions replaced by placeholders
36513 const rawQuasis = node.quasis.map(q => q.value.raw);
36514 let placeholderID = 0;
36515 const text = rawQuasis.reduce((prevVal, currVal, idx) => {
36516 return idx === 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
36518 const doc = textToDoc(text, {
36521 return transformCssDoc(doc, path, print);
36524 * react-relay and graphql-tag
36526 * graphql.experimental`...`
36529 * This intentionally excludes Relay Classic tags, as Prettier does not
36530 * support Relay Classic formatting.
36534 if (isGraphQL(path)) {
36535 const expressionDocs = node.expressions ? path.map(print, "expressions") : [];
36536 const numQuasis = node.quasis.length;
36538 if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
36544 for (let i = 0; i < numQuasis; i++) {
36545 const templateElement = node.quasis[i];
36546 const isFirst = i === 0;
36547 const isLast = i === numQuasis - 1;
36548 const text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence
36549 // (which would make the `cooked` value be `null` or `undefined`)
36551 if (typeof text !== "string") {
36555 const lines = text.split("\n");
36556 const numLines = lines.length;
36557 const expressionDoc = expressionDocs[i];
36558 const startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
36559 const endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
36560 const commentsAndWhitespaceOnly = lines.every(line => /^\s*(?:#[^\r\n]*)?$/.test(line)); // Bail out if an interpolation occurs within a comment.
36562 if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) {
36568 if (commentsAndWhitespaceOnly) {
36569 doc = printGraphqlComments(lines);
36571 doc = stripTrailingHardline$1(textToDoc(text, {
36577 doc = escapeTemplateCharacters(doc, false);
36579 if (!isFirst && startsWithBlankLine) {
36585 if (!isLast && endsWithBlankLine) {
36588 } else if (!isFirst && !isLast && startsWithBlankLine) {
36592 if (expressionDoc) {
36593 parts.push(concat$4(["${", expressionDoc, "}"]));
36597 return concat$4(["`", indent$2(concat$4([hardline$3, join$2(hardline$3, parts)])), hardline$3, "`"]);
36600 const htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined;
36603 return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options);
36609 case "TemplateElement":
36615 if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) {
36616 const text = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`");
36617 const indentation = getIndentation(text);
36618 const hasIndent = indentation !== "";
36619 return concat$4([hasIndent ? indent$2(concat$4([softline$1, printMarkdown(text.replace(new RegExp(`^${indentation}`, "gm"), ""))])) : concat$4([literalline$1, dedentToRoot$1(printMarkdown(text))]), softline$1]);
36626 function printMarkdown(text) {
36627 const doc = textToDoc(text, {
36628 parser: "markdown",
36629 __inJsTemplate: true
36631 return stripTrailingHardline$1(escapeTemplateCharacters(doc, true));
36635 function getIndentation(str) {
36636 const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
36637 return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
36640 function uncook(cookedValue) {
36641 return cookedValue.replace(/([\\`]|\$\{)/g, "\\$1");
36644 function escapeTemplateCharacters(doc, raw) {
36645 return mapDoc$1(doc, currentDoc => {
36646 if (!currentDoc.parts) {
36651 currentDoc.parts.forEach(part => {
36652 if (typeof part === "string") {
36653 parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part));
36658 return Object.assign({}, currentDoc, {
36664 function transformCssDoc(quasisDoc, path, print) {
36665 const parentNode = path.getValue();
36666 const isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
36672 const expressionDocs = parentNode.expressions ? path.map(print, "expressions") : [];
36673 const newDoc = replacePlaceholders(quasisDoc, expressionDocs);
36674 /* istanbul ignore if */
36677 throw new Error("Couldn't insert all the expressions");
36680 return concat$4(["`", indent$2(concat$4([hardline$3, stripTrailingHardline$1(newDoc)])), softline$1, "`"]);
36681 } // Search all the placeholders in the quasisDoc tree
36682 // and replace them with the expression docs one by one
36683 // returns a new doc with all the placeholders replaced,
36684 // or null if it couldn't replace any expression
36687 function replacePlaceholders(quasisDoc, expressionDocs) {
36688 if (!expressionDocs || !expressionDocs.length) {
36692 const expressions = expressionDocs.slice();
36693 let replaceCounter = 0;
36694 const newDoc = mapDoc$1(quasisDoc, doc => {
36695 if (!doc || !doc.parts || !doc.parts.length) {
36702 const atIndex = parts.indexOf("@");
36703 const placeholderIndex = atIndex + 1;
36705 if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
36706 // If placeholder is split, join it
36707 const at = parts[atIndex];
36708 const placeholder = parts[placeholderIndex];
36709 const rest = parts.slice(placeholderIndex + 1);
36710 parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
36713 const atPlaceholderIndex = parts.findIndex(part => typeof part === "string" && part.startsWith("@prettier-placeholder"));
36715 if (atPlaceholderIndex > -1) {
36716 const placeholder = parts[atPlaceholderIndex];
36717 const rest = parts.slice(atPlaceholderIndex + 1);
36718 const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/);
36719 const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:
36720 // animation: linear ${time}s ease-out;
36722 const suffix = placeholderMatch[2];
36723 const expression = expressions[placeholderID];
36725 parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(rest);
36728 return Object.assign({}, doc, {
36732 return expressions.length === replaceCounter ? newDoc : null;
36735 function printGraphqlComments(lines) {
36737 let seenComment = false;
36738 lines.map(textLine => textLine.trim()).forEach((textLine, i, array) => {
36739 // Lines are either whitespace only, or a comment (with potential whitespace
36740 // around it). Drop whitespace-only lines.
36741 if (textLine === "") {
36745 if (array[i - 1] === "" && seenComment) {
36746 // If a non-first comment is preceded by a blank (whitespace only) line,
36747 // add in a blank line.
36748 parts.push(concat$4([hardline$3, textLine]));
36750 parts.push(textLine);
36753 seenComment = true;
36754 }); // If `lines` was whitespace only, return `null`.
36756 return parts.length === 0 ? null : join$2(hardline$3, parts);
36759 * Template literal in these contexts:
36760 * <style jsx>{`div{color:red}`}</style>
36767 function isStyledJsx(path) {
36768 const node = path.getValue();
36769 const parent = path.getParentNode();
36770 const parentParent = path.getParentNode(1);
36771 return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(attribute => attribute.name.name === "jsx") || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "Identifier" && parent.tag.name === "css" || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "MemberExpression" && parent.tag.object.name === "css" && (parent.tag.property.name === "global" || parent.tag.property.name === "resolve");
36774 * Angular Components can have:
36775 * - Inline HTML template
36776 * - Inline CSS styles
36778 * ...which are both within template literals somewhere
36779 * inside of the Component decorator factory.
36783 * template: `<div>...</div>`,
36784 * styles: [`h1 { color: blue; }`]
36789 function isAngularComponentStyles(path) {
36790 return path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "ArrayExpression" && name === "elements", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "styles" && name === "value", ...angularComponentObjectExpressionPredicates);
36793 function isAngularComponentTemplate(path) {
36794 return path.match(node => node.type === "TemplateLiteral", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "template" && name === "value", ...angularComponentObjectExpressionPredicates);
36797 const angularComponentObjectExpressionPredicates = [(node, name) => node.type === "ObjectExpression" && name === "properties", (node, name) => node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments", (node, name) => node.type === "Decorator" && name === "expression"];
36799 * styled-components template literals
36802 function isStyledComponents(path) {
36803 const parent = path.getParentNode();
36805 if (!parent || parent.type !== "TaggedTemplateExpression") {
36813 switch (tag.type) {
36814 case "MemberExpression":
36815 return (// styled.foo``
36816 isStyledIdentifier(tag.object) || // Component.extend``
36817 isStyledExtend(tag)
36820 case "CallExpression":
36821 return (// styled(Component)``
36822 isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})``
36823 isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})``
36824 isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})``
36825 tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
36830 return tag.name === "css";
36837 * JSX element with CSS prop
36841 function isCssProp(path) {
36842 const parent = path.getParentNode();
36843 const parentParent = path.getParentNode(1);
36844 return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
36847 function isStyledIdentifier(node) {
36848 return node.type === "Identifier" && node.name === "styled";
36851 function isStyledExtend(node) {
36852 return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
36855 * react-relay and graphql-tag
36857 * graphql.experimental`...`
36859 * GraphQL comment block
36861 * This intentionally excludes Relay Classic tags, as Prettier does not
36862 * support Relay Classic formatting.
36866 function isGraphQL(path) {
36867 const node = path.getValue();
36868 const parent = path.getParentNode();
36869 return hasLanguageComment(node, "GraphQL") || parent && (parent.type === "TaggedTemplateExpression" && (parent.tag.type === "MemberExpression" && parent.tag.object.name === "graphql" && parent.tag.property.name === "experimental" || parent.tag.type === "Identifier" && (parent.tag.name === "gql" || parent.tag.name === "graphql")) || parent.type === "CallExpression" && parent.callee.type === "Identifier" && parent.callee.name === "graphql");
36872 function hasLanguageComment(node, languageName) {
36873 // This checks for a leading comment that is exactly `/* GraphQL */`
36874 // In order to be in line with other implementations of this comment tag
36875 // we will not trim the comment value and we will expect exactly one space on
36876 // either side of the GraphQL string
36877 // Also see ./clean.js
36878 return hasLeadingComment$1(node, comment => isBlockComment$1(comment) && comment.value === ` ${languageName} `);
36882 * - HTML comment block
36886 function isHtml(path) {
36887 return hasLanguageComment(path.getValue(), "HTML") || path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi");
36888 } // The counter is needed to distinguish nested embeds.
36891 let htmlTemplateLiteralCounter = 0;
36893 function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) {
36894 const node = path.getValue();
36895 const counter = htmlTemplateLiteralCounter;
36896 htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0;
36898 const composePlaceholder = index => `PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
36900 const text = node.quasis.map((quasi, index, quasis) => index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index)).join("");
36901 const expressionDocs = path.map(print, "expressions");
36903 if (expressionDocs.length === 0 && text.trim().length === 0) {
36907 const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g");
36908 let topLevelCount = 0;
36909 const contentDoc = mapDoc$1(stripTrailingHardline$1(textToDoc(text, {
36912 __onHtmlRoot(root) {
36913 topLevelCount = root.children.length;
36917 if (typeof doc !== "string") {
36922 const components = doc.split(placeholderRegex);
36924 for (let i = 0; i < components.length; i++) {
36925 let component = components[i];
36929 component = uncook(component);
36931 if (options.embeddedInHtml) {
36932 component = component.replace(/<\/(script)\b/gi, "<\\/$1");
36935 parts.push(component);
36941 const placeholderIndex = +component;
36942 parts.push(concat$4(["${", group$1(expressionDocs[placeholderIndex]), "}"]));
36945 return concat$4(parts);
36947 const leadingWhitespace = /^\s/.test(text) ? " " : "";
36948 const trailingWhitespace = /\s$/.test(text) ? " " : "";
36949 const linebreak = options.htmlWhitespaceSensitivity === "ignore" ? hardline$3 : leadingWhitespace && trailingWhitespace ? line$2 : null;
36952 return group$1(concat$4(["`", indent$2(concat$4([linebreak, group$1(contentDoc)])), linebreak, "`"]));
36955 return group$1(concat$4(["`", leadingWhitespace, topLevelCount > 1 ? indent$2(group$1(contentDoc)) : group$1(contentDoc), trailingWhitespace, "`"]));
36958 var embed_1 = embed;
36960 function clean(ast, newObj, parent) {
36961 ["range", "raw", "comments", "leadingComments", "trailingComments", "innerComments", "extra", "start", "end", "flags", "errors"].forEach(name => {
36962 delete newObj[name];
36965 if (ast.loc && ast.loc.source === null) {
36966 delete newObj.loc.source;
36969 if (ast.type === "BigIntLiteral") {
36970 newObj.value = newObj.value.toLowerCase();
36971 } // We remove extra `;` and add them when needed
36974 if (ast.type === "EmptyStatement") {
36976 } // We move text around, including whitespaces and add {" "}
36979 if (ast.type === "JSXText") {
36983 if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") {
36985 } // (TypeScript) Ignore `static` in `constructor(static p) {}`
36986 // and `export` in `constructor(export p) {}`
36989 if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) {
36991 type: "Identifier",
36992 name: ast.parameter.name,
36993 typeAnnotation: newObj.parameter.typeAnnotation,
36994 decorators: newObj.decorators
36996 } // (TypeScript) ignore empty `specifiers` array
36999 if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) {
37000 delete newObj.specifiers;
37001 } // We convert <div></div> to <div />
37004 if (ast.type === "JSXOpeningElement") {
37005 delete newObj.selfClosing;
37008 if (ast.type === "JSXElement") {
37009 delete newObj.closingElement;
37010 } // We change {'key': value} into {key: value}
37013 if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && typeof ast.key === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) {
37017 if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
37018 newObj.type = "MemberExpression";
37019 delete newObj.optional;
37020 } // Remove raw and cooked values from TemplateElement when it's CSS
37024 if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(attr => attr.name.name === "jsx")) {
37025 const templateLiterals = newObj.children.filter(child => child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral").map(container => container.expression);
37026 const quasis = templateLiterals.reduce((quasis, templateLiteral) => quasis.concat(templateLiteral.quasis), []);
37027 quasis.forEach(q => delete q.value);
37028 } // CSS template literals in css prop
37031 if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
37032 newObj.value.expression.quasis.forEach(q => delete q.value);
37033 } // Angular Components: Inline HTML template and Inline CSS styles
37036 const expression = ast.expression || ast.callee;
37038 if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
37039 const astProps = ast.expression.arguments[0].properties;
37040 newObj.expression.arguments[0].properties.forEach((prop, index) => {
37041 let templateLiteral = null;
37043 switch (astProps[index].key.name) {
37045 if (prop.value.type === "ArrayExpression") {
37046 templateLiteral = prop.value.elements[0];
37052 if (prop.value.type === "TemplateLiteral") {
37053 templateLiteral = prop.value;
37059 if (templateLiteral) {
37060 templateLiteral.quasis.forEach(q => delete q.value);
37063 } // styled-components, graphql, markdown
37066 if (ast.type === "TaggedTemplateExpression" && (ast.tag.type === "MemberExpression" || ast.tag.type === "Identifier" && (ast.tag.name === "gql" || ast.tag.name === "graphql" || ast.tag.name === "css" || ast.tag.name === "md" || ast.tag.name === "markdown" || ast.tag.name === "html") || ast.tag.type === "CallExpression")) {
37067 newObj.quasi.quasis.forEach(quasi => delete quasi.value);
37070 if (ast.type === "TemplateLiteral") {
37071 // This checks for a leading comment that is exactly `/* GraphQL */`
37072 // In order to be in line with other implementations of this comment tag
37073 // we will not trim the comment value and we will expect exactly one space on
37074 // either side of the GraphQL string
37075 // Also see ./embed.js
37076 const hasLanguageComment = ast.leadingComments && ast.leadingComments.some(comment => comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(languageName => comment.value === ` ${languageName} `));
37078 if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
37079 newObj.quasis.forEach(quasi => delete quasi.value);
37084 var clean_1 = clean;
37086 const detectNewline = string => {
37087 if (typeof string !== 'string') {
37088 throw new TypeError('Expected a string');
37091 const newlines = string.match(/(?:\r?\n)/g) || [];
37093 if (newlines.length === 0) {
37097 const crlf = newlines.filter(newline => newline === '\r\n').length;
37098 const lf = newlines.length - crlf;
37099 return crlf > lf ? '\r\n' : '\n';
37102 var detectNewline_1 = detectNewline;
37104 var graceful = string => typeof string === 'string' && detectNewline(string) || '\n';
37105 detectNewline_1.graceful = graceful;
37107 var build = createCommonjsModule(function (module, exports) {
37109 Object.defineProperty(exports, '__esModule', {
37112 exports.extract = extract;
37113 exports.strip = strip;
37114 exports.parse = parse;
37115 exports.parseWithComments = parseWithComments;
37116 exports.print = print;
37121 _os = function () {
37128 function _detectNewline() {
37129 const data = _interopRequireDefault(detectNewline_1);
37131 _detectNewline = function () {
37138 function _interopRequireDefault(obj) {
37139 return obj && obj.__esModule ? obj : {
37144 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
37146 * This source code is licensed under the MIT license found in the
37147 * LICENSE file in the root directory of this source tree.
37151 const commentEndRe = /\*\/$/;
37152 const commentStartRe = /^\/\*\*/;
37153 const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
37154 const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
37155 const ltrimNewlineRe = /^(\r?\n)+/;
37156 const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
37157 const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
37158 const stringStartRe = /(\r?\n|^) *\* ?/g;
37160 function extract(contents) {
37161 const match = contents.match(docblockRe);
37162 return match ? match[0].trimLeft() : '';
37165 function strip(contents) {
37166 const match = contents.match(docblockRe);
37167 return match && match[0] ? contents.substring(match[0].length) : contents;
37170 function parse(docblock) {
37171 return parseWithComments(docblock).pragmas;
37174 function parseWithComments(docblock) {
37175 const line = (0, _detectNewline().default)(docblock) || _os().EOL;
37177 docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
37181 while (prev !== docblock) {
37183 docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`);
37186 docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
37187 const result = Object.create(null);
37188 const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
37191 while (match = propertyRe.exec(docblock)) {
37192 // strip linecomments from pragmas
37193 const nextPragma = match[2].replace(lineCommentRe, '');
37195 if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
37196 result[match[1]] = [].concat(result[match[1]], nextPragma);
37198 result[match[1]] = nextPragma;
37212 const line = (0, _detectNewline().default)(comments) || _os().EOL;
37214 const head = '/**';
37215 const start = ' *';
37216 const tail = ' */';
37217 const keys = Object.keys(pragmas);
37218 const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join('');
37221 if (keys.length === 0) {
37225 if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
37226 const value = pragmas[keys[0]];
37227 return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`;
37231 const printedComments = comments.split(line).map(textLine => `${start} ${textLine}`).join(line) + line;
37232 return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
37235 function printKeyValues(key, valueOrArray) {
37236 return [].concat(valueOrArray).map(value => `@${key} ${value}`.trim());
37239 unwrapExports(build);
37240 var build_1 = build.extract;
37241 var build_2 = build.strip;
37242 var build_3 = build.parse;
37243 var build_4 = build.parseWithComments;
37244 var build_5 = build.print;
37246 function hasPragma(text) {
37247 const pragmas = Object.keys(build.parse(build.extract(text)));
37248 return pragmas.includes("prettier") || pragmas.includes("format");
37251 function insertPragma(text) {
37252 const parsedDocblock = build.parseWithComments(build.extract(text));
37253 const pragmas = Object.assign({
37255 }, parsedDocblock.pragmas);
37256 const newDocblock = build.print({
37258 comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines
37260 }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock)
37262 const strippedText = build.strip(text);
37263 const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n";
37264 return newDocblock + separatingNewlines + strippedText;
37273 getLast: getLast$1,
37274 hasNewline: hasNewline$3,
37275 hasNewlineInRange: hasNewlineInRange$2,
37276 hasIgnoreComment: hasIgnoreComment$1,
37277 hasNodeIgnoreComment: hasNodeIgnoreComment$1,
37278 skipWhitespace: skipWhitespace$2
37280 const isIdentifierName = utils$1.keyword.isIdentifierNameES5; // We match any whitespace except line terminators because
37281 // Flow annotation comments cannot be split across lines. For example:
37284 // : any */).foo = 5;
37286 // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
37287 // removing the newline would create a type annotation that the user did not intend
37290 const NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
37291 const FLOW_SHORTHAND_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*:`);
37292 const FLOW_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*::`);
37294 function hasFlowShorthandAnnotationComment(node) {
37295 // https://flow.org/en/docs/types/comments/
37296 // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
37297 return node.extra && node.extra.parenthesized && node.trailingComments && node.trailingComments[0].value.match(FLOW_SHORTHAND_ANNOTATION);
37300 function hasFlowAnnotationComment(comments) {
37301 return comments && comments[0].value.match(FLOW_ANNOTATION);
37304 function hasNode(node, fn) {
37305 if (!node || typeof node !== "object") {
37309 if (Array.isArray(node)) {
37310 return node.some(value => hasNode(value, fn));
37313 const result = fn(node);
37314 return typeof result === "boolean" ? result : Object.keys(node).some(key => hasNode(node[key], fn));
37317 function hasNakedLeftSide(node) {
37318 return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" || node.type === "UpdateExpression" && !node.prefix || node.type === "TSAsExpression" || node.type === "TSNonNullExpression";
37321 function getLeftSide(node) {
37322 if (node.expressions) {
37323 return node.expressions[0];
37326 return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
37329 function getLeftSidePathName(path, node) {
37330 if (node.expressions) {
37331 return ["expressions", 0];
37354 if (node.argument) {
37355 return ["argument"];
37358 if (node.expression) {
37359 return ["expression"];
37362 throw new Error("Unexpected node has no left side", node);
37365 const exportDeclarationTypes = new Set(["ExportDefaultDeclaration", "ExportDefaultSpecifier", "DeclareExportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"]);
37367 function isExportDeclaration(node) {
37368 return node && exportDeclarationTypes.has(node.type);
37371 function getParentExportDeclaration(path) {
37372 const parentNode = path.getParentNode();
37374 if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
37381 function isLiteral(node) {
37382 return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText";
37385 function isNumericLiteral(node) {
37386 return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
37389 function isStringLiteral(node) {
37390 return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
37393 function isObjectType(n) {
37394 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
37397 function isFunctionOrArrowExpression(node) {
37398 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
37401 function isFunctionOrArrowExpressionWithBody(node) {
37402 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
37405 function isTemplateLiteral(node) {
37406 return node.type === "TemplateLiteral";
37407 } // `inject` is used in AngularJS 1.x, `async` in Angular 2+
37408 // example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
37411 function isAngularTestWrapper(node) {
37412 return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
37415 function isJSXNode(node) {
37416 return node.type === "JSXElement" || node.type === "JSXFragment";
37419 function isTheOnlyJSXElementInMarkdown(options, path) {
37420 if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
37424 const node = path.getNode();
37426 if (!node.expression || !isJSXNode(node.expression)) {
37430 const parent = path.getParentNode();
37431 return parent.type === "Program" && parent.body.length === 1;
37432 } // Detect an expression node representing `{" "}`
37435 function isJSXWhitespaceExpression(node) {
37436 return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
37439 function isMemberExpressionChain(node) {
37440 if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
37444 if (node.object.type === "Identifier") {
37448 return isMemberExpressionChain(node.object);
37451 function isGetterOrSetter(node) {
37452 return node.kind === "get" || node.kind === "set";
37455 function sameLocStart(nodeA, nodeB, options) {
37456 return options.locStart(nodeA) === options.locStart(nodeB);
37457 } // TODO: This is a bad hack and we need a better way to distinguish between
37458 // arrow functions and otherwise
37461 function isFunctionNotation(node, options) {
37462 return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
37463 } // Hack to differentiate between the following two which have the same ast
37464 // type T = { method: () => void };
37465 // type T = { method(): void };
37468 function isObjectTypePropertyAFunction(node, options) {
37469 return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
37470 } // Hack to differentiate between the following two which have the same ast
37471 // declare function f(a): void;
37472 // var f: (a) => void;
37475 function isTypeAnnotationAFunction(node, options) {
37476 return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
37479 const binaryishNodeTypes = new Set(["BinaryExpression", "LogicalExpression", "NGPipeExpression"]);
37481 function isBinaryish(node) {
37482 return binaryishNodeTypes.has(node.type);
37485 function isMemberish(node) {
37486 return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
37489 function isSimpleFlowType(node) {
37490 const flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
37491 return node && flowTypeAnnotations.includes(node.type) && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
37494 const unitTestRe = /^(skip|[fx]?(it|describe|test))$/;
37496 function isSkipOrOnlyBlock(node) {
37497 return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip");
37500 function isUnitTestSetUp(n) {
37501 const unitTestSetUpRe = /^(before|after)(Each|All)$/;
37502 return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
37503 } // eg; `describe("some string", (done) => {})`
37506 function isTestCall(n, parent) {
37507 if (n.type !== "CallExpression") {
37511 if (n.arguments.length === 1) {
37512 if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
37513 return isFunctionOrArrowExpression(n.arguments[0]);
37516 if (isUnitTestSetUp(n)) {
37517 return isAngularTestWrapper(n.arguments[0]);
37519 } else if (n.arguments.length === 2 || n.arguments.length === 3) {
37520 if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
37521 // it("name", () => { ... }, 2500)
37522 if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
37526 return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
37533 function hasLeadingComment$2(node) {
37534 return node.comments && node.comments.some(comment => comment.leading);
37537 function hasTrailingComment(node) {
37538 return node.comments && node.comments.some(comment => comment.trailing);
37541 function isCallOrOptionalCallExpression(node) {
37542 return node.type === "CallExpression" || node.type === "OptionalCallExpression";
37545 function hasDanglingComments(node) {
37546 return node.comments && node.comments.some(comment => !comment.leading && !comment.trailing);
37548 /** identify if an angular expression seems to have side effects */
37551 function hasNgSideEffect(path) {
37552 return hasNode(path.getValue(), node => {
37553 switch (node.type) {
37557 case "CallExpression":
37558 case "OptionalCallExpression":
37559 case "AssignmentExpression":
37565 function isNgForOf(node, index, parentNode) {
37566 return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
37568 /** @param node {import("estree").TemplateLiteral} */
37571 function isSimpleTemplateLiteral(node) {
37572 if (node.expressions.length === 0) {
37576 return node.expressions.every(expr => {
37577 // Disallow comments since printDocToString can't print them here
37578 if (expr.comments) {
37580 } // Allow `x` and `this`
37583 if (expr.type === "Identifier" || expr.type === "ThisExpression") {
37585 } // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
37588 if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") {
37591 while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") {
37592 if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") {
37596 head = head.object;
37598 if (head.comments) {
37603 if (head.type === "Identifier" || head.type === "ThisExpression") {
37614 function getFlowVariance(path) {
37615 if (!path.variance) {
37617 } // Babel 7.0 currently uses variance node type, and flow should
37618 // follow suit soon:
37619 // https://github.com/babel/babel/issues/4722
37622 const variance = path.variance.kind || path.variance;
37624 switch (variance) {
37632 /* istanbul ignore next */
37637 function classPropMayCauseASIProblems(path) {
37638 const node = path.getNode();
37640 if (node.type !== "ClassProperty") {
37644 const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
37645 // so isn't properly tested yet.
37647 if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
37652 function classChildNeedsASIProtection(node) {
37657 if (node.static || node.accessibility // TypeScript
37662 if (!node.computed) {
37663 const name = node.key && node.key.name;
37665 if (name === "in" || name === "instanceof") {
37670 switch (node.type) {
37671 case "ClassProperty":
37672 case "TSAbstractClassProperty":
37673 return node.computed;
37675 case "MethodDefinition": // Flow
37677 case "TSAbstractMethodDefinition": // TypeScript
37679 case "ClassMethod":
37680 case "ClassPrivateMethod":
37683 const isAsync = node.value ? node.value.async : node.async;
37684 const isGenerator = node.value ? node.value.generator : node.generator;
37686 if (isAsync || node.kind === "get" || node.kind === "set") {
37690 if (node.computed || isGenerator) {
37697 case "TSIndexSignature":
37701 /* istanbul ignore next */
37706 function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
37707 if (tokenNode === "+") {
37708 return "+" + keyword;
37709 } else if (tokenNode === "-") {
37710 return "-" + keyword;
37716 function hasNewlineBetweenOrAfterDecorators(node, options) {
37717 return hasNewlineInRange$2(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$1(node.decorators))) || hasNewline$3(options.originalText, options.locEnd(getLast$1(node.decorators)));
37718 } // Only space, newline, carriage return, and tab are treated as whitespace
37722 const jsxWhitespaceChars = " \n\r\t";
37723 const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
37724 const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters,
37725 // or it contains whitespace without a new line.
37727 function isMeaningfulJSXText(node) {
37728 return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
37731 function hasJsxIgnoreComment(path) {
37732 const node = path.getValue();
37733 const parent = path.getParentNode();
37735 if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
37737 } // Lookup the previous sibling, ignoring any empty JSXText elements
37740 const index = parent.children.indexOf(node);
37741 let prevSibling = null;
37743 for (let i = index; i > 0; i--) {
37744 const candidate = parent.children[i - 1];
37746 if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
37750 prevSibling = candidate;
37754 return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(comment => comment.value.trim() === "prettier-ignore");
37757 function isEmptyJSXElement(node) {
37758 if (node.children.length === 0) {
37762 if (node.children.length > 1) {
37764 } // if there is one text child and does not contain any meaningful text
37765 // we can treat the element as empty.
37768 const child = node.children[0];
37769 return isLiteral(child) && !isMeaningfulJSXText(child);
37772 function hasPrettierIgnore(path) {
37773 return hasIgnoreComment$1(path) || hasJsxIgnoreComment(path);
37776 function isLastStatement(path) {
37777 const parent = path.getParentNode();
37783 const node = path.getValue();
37784 const body = (parent.body || parent.consequent).filter(stmt => stmt.type !== "EmptyStatement");
37785 return body && body[body.length - 1] === node;
37788 function isFlowAnnotationComment(text, typeAnnotation, options) {
37789 const start = options.locStart(typeAnnotation);
37790 const end = skipWhitespace$2(text, options.locEnd(typeAnnotation));
37791 return text.slice(start, start + 2) === "/*" && text.slice(end, end + 2) === "*/";
37794 function hasLeadingOwnLineComment(text, node, options) {
37795 if (isJSXNode(node)) {
37796 return hasNodeIgnoreComment$1(node);
37799 const res = node.comments && node.comments.some(comment => comment.leading && hasNewline$3(text, options.locEnd(comment)));
37801 } // This recurses the return argument, looking for the first token
37802 // (the leftmost leaf node) and, if it (or its parents) has any
37803 // leadingComments, returns true (so it can be wrapped in parens).
37806 function returnArgumentHasLeadingComment(options, argument) {
37807 if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
37811 if (hasNakedLeftSide(argument)) {
37812 let leftMost = argument;
37815 while (newLeftMost = getLeftSide(leftMost)) {
37816 leftMost = newLeftMost;
37818 if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
37827 function isStringPropSafeToCoerceToIdentifier(node, options) {
37828 return isStringLiteral(node.key) && isIdentifierName(node.key.value) && options.parser !== "json" && // With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones.
37829 // See https://github.com/microsoft/TypeScript/pull/20075
37830 !((options.parser === "typescript" || options.parser === "babel-ts") && node.type === "ClassProperty");
37833 function isJestEachTemplateLiteral(node, parentNode) {
37835 * describe.each`table`(name, fn)
37836 * describe.only.each`table`(name, fn)
37837 * describe.skip.each`table`(name, fn)
37838 * test.each`table`(name, fn)
37839 * test.only.each`table`(name, fn)
37840 * test.skip.each`table`(name, fn)
37842 * Ref: https://github.com/facebook/jest/pull/6102
37844 const jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
37845 return parentNode.type === "TaggedTemplateExpression" && parentNode.quasi === node && parentNode.tag.type === "MemberExpression" && parentNode.tag.property.type === "Identifier" && parentNode.tag.property.name === "each" && (parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.name) || parentNode.tag.object.type === "MemberExpression" && parentNode.tag.object.property.type === "Identifier" && (parentNode.tag.object.property.name === "only" || parentNode.tag.object.property.name === "skip") && parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.object.name));
37848 function templateLiteralHasNewLines(template) {
37849 return template.quasis.some(quasi => quasi.value.raw.includes("\n"));
37852 function isTemplateOnItsOwnLine(n, text, options) {
37853 return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$3(text, options.locStart(n), {
37858 function needsHardlineAfterDanglingComment(node) {
37859 if (!node.comments) {
37863 const lastDanglingComment = getLast$1(node.comments.filter(comment => !comment.leading && !comment.trailing));
37864 return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment);
37865 } // If we have nested conditional expressions, we want to print them in JSX mode
37866 // if there's at least one JSXElement somewhere in the tree.
37868 // A conditional expression chain like this should be printed in normal mode,
37869 // because there aren't JSXElements anywhere in it:
37871 // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
37873 // But a conditional expression chain like this should be printed in JSX mode,
37874 // because there is a JSXElement in the last ConditionalExpression:
37876 // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
37878 // This type of ConditionalExpression chain is structured like this in the AST:
37880 // ConditionalExpression {
37882 // consequent: ...,
37883 // alternate: ConditionalExpression {
37885 // consequent: ...,
37886 // alternate: ConditionalExpression {
37888 // consequent: ...,
37894 // We want to traverse over that shape and convert it into a flat structure so
37895 // that we can find if there's a JSXElement somewhere inside.
37898 function getConditionalChainContents(node) {
37899 // Given this code:
37901 // // Using a ConditionalExpression as the consequent is uncommon, but should
37903 // A ? B : C ? D : E ? F ? G : H : I
37905 // which has this AST:
37907 // ConditionalExpression {
37908 // test: Identifier(A),
37909 // consequent: Identifier(B),
37910 // alternate: ConditionalExpression {
37911 // test: Identifier(C),
37912 // consequent: Identifier(D),
37913 // alternate: ConditionalExpression {
37914 // test: Identifier(E),
37915 // consequent: ConditionalExpression {
37916 // test: Identifier(F),
37917 // consequent: Identifier(G),
37918 // alternate: Identifier(H),
37920 // alternate: Identifier(I),
37925 // we should return this Array:
37939 // This loses the information about whether each node was the test,
37940 // consequent, or alternate, but we don't care about that here- we are only
37941 // flattening this structure to find if there's any JSXElements inside.
37942 const nonConditionalExpressions = [];
37944 function recurse(node) {
37945 if (node.type === "ConditionalExpression") {
37946 recurse(node.test);
37947 recurse(node.consequent);
37948 recurse(node.alternate);
37950 nonConditionalExpressions.push(node);
37955 return nonConditionalExpressions;
37958 function conditionalExpressionChainContainsJSX(node) {
37959 return Boolean(getConditionalChainContents(node).find(isJSXNode));
37960 } // Logic to check for args with multiple anonymous functions. For instance,
37961 // the following call should be split on multiple lines for readability:
37962 // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0))
37965 function isFunctionCompositionArgs(args) {
37966 if (args.length <= 1) {
37972 for (const arg of args) {
37973 if (isFunctionOrArrowExpression(arg)) {
37979 } else if (isCallOrOptionalCallExpression(arg)) {
37980 for (const childArg of arg.arguments) {
37981 if (isFunctionOrArrowExpression(childArg)) {
37989 } // Logic to determine if a call is a “long curried function call”.
37990 // See https://github.com/prettier/prettier/issues/1420.
37992 // `connect(a, b, c)(d)`
37993 // In the above call expression, the second call is the parent node and the
37994 // first call is the current node.
37997 function isLongCurriedCallExpression(path) {
37998 const node = path.getValue();
37999 const parent = path.getParentNode();
38000 return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
38003 * @param {import('estree').Node} node
38004 * @param {number} depth
38005 * @returns {boolean}
38009 function isSimpleCallArgument(node, depth) {
38014 const isChildSimple = child => isSimpleCallArgument(child, depth + 1);
38016 const regexpPattern = node.type === "Literal" && node.regex && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern;
38018 if (regexpPattern && regexpPattern.length > 5) {
38022 if (node.type === "Literal" || node.type === "BooleanLiteral" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "StringLiteral" || node.type === "Identifier" || node.type === "ThisExpression" || node.type === "Super" || node.type === "BigIntLiteral" || node.type === "PrivateName" || node.type === "ArgumentPlaceholder" || node.type === "RegExpLiteral" || node.type === "Import") {
38026 if (node.type === "TemplateLiteral") {
38027 return node.expressions.every(isChildSimple);
38030 if (node.type === "ObjectExpression") {
38031 return node.properties.every(p => !p.computed && (p.shorthand || p.value && isChildSimple(p.value)));
38034 if (node.type === "ArrayExpression") {
38035 return node.elements.every(x => x == null || isChildSimple(x));
38038 if (node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "NewExpression") {
38039 return isSimpleCallArgument(node.callee, depth) && node.arguments.every(isChildSimple);
38042 if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
38043 return isSimpleCallArgument(node.object, depth) && isSimpleCallArgument(node.property, depth);
38046 if (node.type === "UnaryExpression" && (node.operator === "!" || node.operator === "-")) {
38047 return isSimpleCallArgument(node.argument, depth);
38050 if (node.type === "TSNonNullExpression") {
38051 return isSimpleCallArgument(node.expression, depth);
38057 function rawText(node) {
38058 return node.extra ? node.extra.raw : node.raw;
38061 function identity$1(x) {
38065 function isTSXFile(options) {
38066 return options.filepath && /\.tsx$/i.test(options.filepath);
38070 classChildNeedsASIProtection,
38071 classPropMayCauseASIProblems,
38072 conditionalExpressionChainContainsJSX,
38074 getLeftSidePathName,
38075 getParentExportDeclaration,
38076 getTypeScriptMappedTypeModifier,
38077 hasDanglingComments,
38078 hasFlowAnnotationComment,
38079 hasFlowShorthandAnnotationComment,
38080 hasLeadingComment: hasLeadingComment$2,
38081 hasLeadingOwnLineComment,
38083 hasNewlineBetweenOrAfterDecorators,
38087 hasTrailingComment,
38088 identity: identity$1,
38090 isCallOrOptionalCallExpression,
38092 isExportDeclaration,
38093 isFlowAnnotationComment,
38094 isFunctionCompositionArgs,
38095 isFunctionNotation,
38096 isFunctionOrArrowExpression,
38098 isJestEachTemplateLiteral,
38100 isJSXWhitespaceExpression,
38103 isLongCurriedCallExpression,
38104 isSimpleCallArgument,
38105 isMeaningfulJSXText,
38106 isMemberExpressionChain,
38111 isObjectTypePropertyAFunction,
38113 isSimpleTemplateLiteral,
38115 isStringPropSafeToCoerceToIdentifier,
38116 isTemplateOnItsOwnLine,
38118 isTheOnlyJSXElementInMarkdown,
38120 isTypeAnnotationAFunction,
38121 matchJsxWhitespaceRegex,
38122 needsHardlineAfterDanglingComment,
38124 returnArgumentHasLeadingComment
38128 getLeftSidePathName: getLeftSidePathName$1,
38129 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$1,
38130 hasNakedLeftSide: hasNakedLeftSide$1,
38134 function needsParens(path, options) {
38135 const parent = path.getParentNode();
38141 const name = path.getName();
38142 const node = path.getNode(); // If the value of this path is some child of a Node and not a Node
38143 // itself, then it doesn't need parentheses. Only Node objects (in
38144 // fact, only Expression nodes) need parentheses.
38146 if (path.getValue() !== node) {
38148 } // to avoid unexpected `}}` in HTML interpolations
38151 if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) {
38153 } // Only statements don't need parentheses.
38156 if (isStatement(node)) {
38160 if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
38161 // parser. The Flow parser turns Flow comments into type annotation nodes in its
38162 // AST, which we handle separately.
38163 options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) {
38165 } // Identifiers never need parentheses.
38168 if (node.type === "Identifier") {
38169 // ...unless those identifiers are embed placeholders. They might be substituted by complex
38170 // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS):
38171 // let tpl = html`<script> f((${expr}) / 2); </script>`;
38172 // If the inner JS formatter removes the parens, the expression might change its meaning:
38173 // f((a + b) / 2) vs f(a + b / 2)
38174 if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) {
38181 if (parent.type === "ParenthesizedExpression") {
38183 } // Add parens around the extends clause of a class. It is needed for almost
38184 // all expressions.
38187 if ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression")) {
38191 if (parent.type === "ExportDefaultDeclaration") {
38192 return (// `export default function` or `export default class` can't be followed by
38193 // anything after. So an expression like `export default (function(){}).toString()`
38194 // needs to be followed by a parentheses
38195 shouldWrapFunctionForExportDefault(path, options) || // `export default (foo, bar)` also needs parentheses
38196 node.type === "SequenceExpression"
38200 if (parent.type === "Decorator" && parent.expression === node) {
38201 let hasCallExpression = false;
38202 let hasMemberExpression = false;
38203 let current = node;
38206 switch (current.type) {
38207 case "MemberExpression":
38208 hasMemberExpression = true;
38209 current = current.object;
38212 case "CallExpression":
38215 hasMemberExpression ||
38217 hasCallExpression) {
38221 hasCallExpression = true;
38222 current = current.callee;
38236 if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway
38237 util$1.startsWithNoLookaheadToken(node,
38238 /* forbidFunctionClassAndDoExpr */
38239 false) || parent.type === "ExpressionStatement" && util$1.startsWithNoLookaheadToken(node,
38240 /* forbidFunctionClassAndDoExpr */
38245 switch (node.type) {
38246 case "SpreadElement":
38247 case "SpreadProperty":
38248 return parent.type === "MemberExpression" && name === "object" && parent.object === node;
38250 case "UpdateExpression":
38251 if (parent.type === "UnaryExpression") {
38252 return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
38255 // else fallthrough
38257 case "UnaryExpression":
38258 switch (parent.type) {
38259 case "UnaryExpression":
38260 return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
38262 case "BindExpression":
38265 case "MemberExpression":
38266 case "OptionalMemberExpression":
38267 return name === "object";
38269 case "TaggedTemplateExpression":
38272 case "NewExpression":
38273 case "CallExpression":
38274 case "OptionalCallExpression":
38275 return name === "callee";
38277 case "BinaryExpression":
38278 return parent.operator === "**" && name === "left";
38280 case "TSNonNullExpression":
38287 case "BinaryExpression":
38289 if (parent.type === "UpdateExpression") {
38293 const isLeftOfAForStatement = node => {
38297 const parent = path.getParentNode(i++);
38303 if (parent.type === "ForStatement" && parent.init === node) {
38313 if (node.operator === "in" && isLeftOfAForStatement(node)) {
38319 case "TSTypeAssertion":
38320 case "TSAsExpression":
38321 case "LogicalExpression":
38322 switch (parent.type) {
38323 case "ConditionalExpression":
38324 return node.type === "TSAsExpression";
38326 case "CallExpression":
38327 case "NewExpression":
38328 case "OptionalCallExpression":
38329 return name === "callee";
38331 case "ClassExpression":
38332 case "ClassDeclaration":
38333 return name === "superClass" && parent.superClass === node;
38335 case "TSTypeAssertion":
38336 case "TaggedTemplateExpression":
38337 case "UnaryExpression":
38338 case "JSXSpreadAttribute":
38339 case "SpreadElement":
38340 case "SpreadProperty":
38341 case "BindExpression":
38342 case "AwaitExpression":
38343 case "TSAsExpression":
38344 case "TSNonNullExpression":
38345 case "UpdateExpression":
38348 case "MemberExpression":
38349 case "OptionalMemberExpression":
38350 return name === "object";
38352 case "AssignmentExpression":
38353 return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
38355 case "LogicalExpression":
38356 if (node.type === "LogicalExpression") {
38357 return parent.operator !== node.operator;
38360 // else fallthrough
38362 case "BinaryExpression":
38364 if (!node.operator && node.type !== "TSTypeAssertion") {
38368 const po = parent.operator;
38369 const pp = util$1.getPrecedence(po);
38370 const no = node.operator;
38371 const np = util$1.getPrecedence(no);
38377 if (pp === np && name === "right") {
38378 assert$1.strictEqual(parent.right, node);
38382 if (pp === np && !util$1.shouldFlatten(po, no)) {
38386 if (pp < np && no === "%") {
38387 return po === "+" || po === "-";
38388 } // Add parenthesis when working with bitwise operators
38389 // It's not strictly needed but helps with code understanding
38392 if (util$1.isBitwiseOperator(po)) {
38403 case "SequenceExpression":
38404 switch (parent.type) {
38405 case "ReturnStatement":
38408 case "ForStatement":
38409 // Although parentheses wouldn't hurt around sequence
38410 // expressions in the head of for loops, traditional style
38411 // dictates that e.g. i++, j++ should not be wrapped with
38415 case "ExpressionStatement":
38416 return name !== "expression";
38418 case "ArrowFunctionExpression":
38419 // We do need parentheses, but SequenceExpressions are handled
38420 // specially when printing bodies of arrow functions.
38421 return name !== "body";
38424 // Otherwise err on the side of overparenthesization, adding
38425 // explicit exceptions above if this proves overzealous.
38429 case "YieldExpression":
38430 if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
38434 // else fallthrough
38436 case "AwaitExpression":
38437 switch (parent.type) {
38438 case "TaggedTemplateExpression":
38439 case "UnaryExpression":
38440 case "BinaryExpression":
38441 case "LogicalExpression":
38442 case "SpreadElement":
38443 case "SpreadProperty":
38444 case "TSAsExpression":
38445 case "TSNonNullExpression":
38446 case "BindExpression":
38449 case "MemberExpression":
38450 case "OptionalMemberExpression":
38451 return name === "object";
38453 case "NewExpression":
38454 case "CallExpression":
38455 case "OptionalCallExpression":
38456 return name === "callee";
38458 case "ConditionalExpression":
38459 return parent.test === node;
38465 case "TSJSDocFunctionType":
38466 case "TSConditionalType":
38467 if (parent.type === "TSConditionalType" && node === parent.extendsType) {
38473 case "TSFunctionType":
38474 case "TSConstructorType":
38475 if (parent.type === "TSConditionalType" && node === parent.checkType) {
38481 case "TSUnionType":
38482 case "TSIntersectionType":
38483 if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") {
38489 case "TSTypeOperator":
38490 case "TSInferType":
38491 return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator" || parent.type === "TSTypeAnnotation" && /^TSJSDoc/.test(path.getParentNode(1).type);
38493 case "ArrayTypeAnnotation":
38494 return parent.type === "NullableTypeAnnotation";
38496 case "IntersectionTypeAnnotation":
38497 case "UnionTypeAnnotation":
38498 return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
38500 case "NullableTypeAnnotation":
38501 return parent.type === "ArrayTypeAnnotation";
38503 case "FunctionTypeAnnotation":
38505 const ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent;
38506 return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
38507 // are really needed, but since ??T doesn't make sense this check
38508 // will almost never be true.
38509 ancestor.type === "NullableTypeAnnotation";
38512 case "StringLiteral":
38513 case "NumericLiteral":
38515 if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
38516 // See corresponding workaround in printer.js case: "Literal"
38517 options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.charAt(options.locStart(node) - 1) === "(")) {
38518 // To avoid becoming a directive
38519 const grandParent = path.getParentNode(1);
38520 return grandParent.type === "Program" || grandParent.type === "BlockStatement";
38523 return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node;
38525 case "AssignmentExpression":
38527 const grandParent = path.getParentNode(1);
38529 if (parent.type === "ArrowFunctionExpression" && parent.body === node) {
38531 } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) {
38533 } else if (parent.type === "TSPropertySignature" && parent.name === node) {
38535 } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) {
38537 } else if (parent.type === "ExpressionStatement") {
38538 return node.left.type === "ObjectPattern";
38539 } else if (parent.type === "TSPropertySignature" && parent.key === node) {
38541 } else if (parent.type === "AssignmentExpression") {
38543 } else if (parent.type === "SequenceExpression" && grandParent && grandParent.type === "ForStatement" && (grandParent.init === parent || grandParent.update === parent)) {
38545 } else if (parent.type === "Property" && parent.value === node) {
38547 } else if (parent.type === "NGChainedExpression") {
38554 case "ConditionalExpression":
38555 switch (parent.type) {
38556 case "TaggedTemplateExpression":
38557 case "UnaryExpression":
38558 case "SpreadElement":
38559 case "SpreadProperty":
38560 case "BinaryExpression":
38561 case "LogicalExpression":
38562 case "NGPipeExpression":
38563 case "ExportDefaultDeclaration":
38564 case "AwaitExpression":
38565 case "JSXSpreadAttribute":
38566 case "TSTypeAssertion":
38567 case "TypeCastExpression":
38568 case "TSAsExpression":
38569 case "TSNonNullExpression":
38572 case "NewExpression":
38573 case "CallExpression":
38574 case "OptionalCallExpression":
38575 return name === "callee";
38577 case "ConditionalExpression":
38578 return name === "test" && parent.test === node;
38580 case "MemberExpression":
38581 case "OptionalMemberExpression":
38582 return name === "object";
38588 case "FunctionExpression":
38589 switch (parent.type) {
38590 case "NewExpression":
38591 case "CallExpression":
38592 case "OptionalCallExpression":
38593 // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
38594 // Is necessary if it is `expression` of `ExpressionStatement`.
38595 return name === "callee";
38597 case "TaggedTemplateExpression":
38599 // This is basically a kind of IIFE.
38605 case "ArrowFunctionExpression":
38606 switch (parent.type) {
38607 case "NewExpression":
38608 case "CallExpression":
38609 case "OptionalCallExpression":
38610 return name === "callee";
38612 case "MemberExpression":
38613 case "OptionalMemberExpression":
38614 return name === "object";
38616 case "TSAsExpression":
38617 case "BindExpression":
38618 case "TaggedTemplateExpression":
38619 case "UnaryExpression":
38620 case "LogicalExpression":
38621 case "BinaryExpression":
38622 case "AwaitExpression":
38623 case "TSTypeAssertion":
38626 case "ConditionalExpression":
38627 return name === "test";
38633 case "ClassExpression":
38634 switch (parent.type) {
38635 case "NewExpression":
38636 return name === "callee" && parent.callee === node;
38642 case "OptionalMemberExpression":
38643 case "OptionalCallExpression":
38644 if (parent.type === "MemberExpression" && name === "object" || (parent.type === "CallExpression" || parent.type === "NewExpression") && name === "callee") {
38650 case "CallExpression":
38651 case "MemberExpression":
38652 case "TaggedTemplateExpression":
38653 case "TSNonNullExpression":
38654 if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") {
38658 switch (object.type) {
38659 case "CallExpression":
38660 case "OptionalCallExpression":
38663 case "MemberExpression":
38664 case "OptionalMemberExpression":
38665 case "BindExpression":
38666 object = object.object;
38668 // tagged templates are basically member expressions from a grammar perspective
38669 // see https://tc39.github.io/ecma262/#prod-MemberExpression
38671 case "TaggedTemplateExpression":
38672 object = object.tag;
38675 case "TSNonNullExpression":
38676 object = object.expression;
38687 case "BindExpression":
38688 return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object";
38690 case "NGPipeExpression":
38691 if (parent.type === "NGRoot" || parent.type === "NGMicrosyntaxExpression" || parent.type === "ObjectProperty" || parent.type === "ArrayExpression" || (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.arguments[name] === node || parent.type === "NGPipeExpression" && name === "right" || parent.type === "MemberExpression" && name === "property" || parent.type === "AssignmentExpression") {
38697 case "JSXFragment":
38699 return name === "callee" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "ConditionalExpression" && parent.type !== "ExpressionStatement" && parent.type !== "JsExpressionRoot" && parent.type !== "JSXAttribute" && parent.type !== "JSXElement" && parent.type !== "JSXExpressionContainer" && parent.type !== "JSXFragment" && parent.type !== "LogicalExpression" && parent.type !== "ObjectProperty" && parent.type !== "OptionalCallExpression" && parent.type !== "Property" && parent.type !== "ReturnStatement" && parent.type !== "ThrowStatement" && parent.type !== "TypeCastExpression" && parent.type !== "VariableDeclarator" && parent.type !== "YieldExpression";
38701 case "TypeAnnotation":
38702 return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node);
38708 function isStatement(node) {
38709 return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "EnumDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSDeclareFunction" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement";
38712 function includesFunctionTypeInObjectType(node) {
38713 return hasNode$1(node, n1 => n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined) || undefined);
38716 function endsWithRightBracket(node) {
38717 switch (node.type) {
38718 case "ObjectExpression":
38726 function isFollowedByRightBracket(path) {
38727 const node = path.getValue();
38728 const parent = path.getParentNode();
38729 const name = path.getName();
38731 switch (parent.type) {
38732 case "NGPipeExpression":
38733 if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
38734 return path.callParent(isFollowedByRightBracket);
38739 case "ObjectProperty":
38740 if (name === "value") {
38741 const parentParent = path.getParentNode(1);
38742 return parentParent.properties[parentParent.properties.length - 1] === parent;
38747 case "BinaryExpression":
38748 case "LogicalExpression":
38749 if (name === "right") {
38750 return path.callParent(isFollowedByRightBracket);
38755 case "ConditionalExpression":
38756 if (name === "alternate") {
38757 return path.callParent(isFollowedByRightBracket);
38762 case "UnaryExpression":
38763 if (parent.prefix) {
38764 return path.callParent(isFollowedByRightBracket);
38773 function shouldWrapFunctionForExportDefault(path, options) {
38774 const node = path.getValue();
38775 const parent = path.getParentNode();
38777 if (node.type === "FunctionExpression" || node.type === "ClassExpression") {
38778 return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped
38779 // (e.g. `export default (function() {})();`)
38780 // in this case we don't need to add extra parens
38781 !needsParens(path, options);
38784 if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) {
38788 return path.call(childPath => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName$1(path, node));
38791 var needsParens_1 = needsParens;
38801 function printHtmlBinding(path, options, print) {
38802 const node = path.getValue();
38804 if (options.__onHtmlBindingRoot && path.getName() === null) {
38805 options.__onHtmlBindingRoot(node, options);
38808 if (node.type !== "File") {
38812 if (options.__isVueForBindingLeft) {
38813 return path.call(functionDeclarationPath => {
38816 } = functionDeclarationPath.getValue();
38817 return concat$5([params.length > 1 ? "(" : "", join$3(concat$5([",", line$3]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]);
38818 }, "program", "body", 0);
38821 if (options.__isVueSlotScope) {
38822 return path.call(functionDeclarationPath => join$3(concat$5([",", line$3]), functionDeclarationPath.map(print, "params")), "program", "body", 0);
38824 } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
38827 function isVueEventBindingExpression(node) {
38828 switch (node.type) {
38829 case "MemberExpression":
38830 switch (node.property.type) {
38832 case "NumericLiteral":
38833 case "StringLiteral":
38834 return isVueEventBindingExpression(node.object);
38847 var htmlBinding = {
38848 isVueEventBindingExpression,
38852 function preprocess(ast, options) {
38853 switch (options.parser) {
38856 case "json-stringify":
38857 case "__js_expression":
38858 case "__vue_expression":
38859 return Object.assign({}, ast, {
38860 type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
38863 rootMarker: options.rootMarker
38871 var preprocess_1 = preprocess;
38874 shouldFlatten: shouldFlatten$1,
38875 getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$1,
38876 hasNewline: hasNewline$4,
38877 hasNewlineInRange: hasNewlineInRange$3,
38878 getLast: getLast$2,
38879 getStringWidth: getStringWidth$3,
38880 printString: printString$1,
38881 printNumber: printNumber$1,
38882 hasIgnoreComment: hasIgnoreComment$2,
38883 hasNodeIgnoreComment: hasNodeIgnoreComment$2,
38884 getPenultimate: getPenultimate$1,
38885 startsWithNoLookaheadToken: startsWithNoLookaheadToken$1,
38886 getIndentSize: getIndentSize$2,
38887 getPreferredQuote: getPreferredQuote$1
38890 isNextLineEmpty: isNextLineEmpty$2,
38891 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$2,
38892 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$3
38895 insertPragma: insertPragma$1
38898 printHtmlBinding: printHtmlBinding$1,
38899 isVueEventBindingExpression: isVueEventBindingExpression$1
38902 classChildNeedsASIProtection: classChildNeedsASIProtection$1,
38903 classPropMayCauseASIProblems: classPropMayCauseASIProblems$1,
38904 conditionalExpressionChainContainsJSX: conditionalExpressionChainContainsJSX$1,
38905 getFlowVariance: getFlowVariance$1,
38906 getLeftSidePathName: getLeftSidePathName$2,
38907 getParentExportDeclaration: getParentExportDeclaration$1,
38908 getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier$1,
38909 hasDanglingComments: hasDanglingComments$1,
38910 hasFlowAnnotationComment: hasFlowAnnotationComment$1,
38911 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$2,
38912 hasLeadingComment: hasLeadingComment$3,
38913 hasLeadingOwnLineComment: hasLeadingOwnLineComment$1,
38914 hasNakedLeftSide: hasNakedLeftSide$2,
38915 hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$1,
38916 hasNgSideEffect: hasNgSideEffect$1,
38917 hasPrettierIgnore: hasPrettierIgnore$1,
38918 hasTrailingComment: hasTrailingComment$1,
38919 identity: identity$2,
38920 isBinaryish: isBinaryish$1,
38921 isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$1,
38922 isEmptyJSXElement: isEmptyJSXElement$1,
38923 isExportDeclaration: isExportDeclaration$1,
38924 isFlowAnnotationComment: isFlowAnnotationComment$1,
38925 isFunctionCompositionArgs: isFunctionCompositionArgs$1,
38926 isFunctionNotation: isFunctionNotation$1,
38927 isFunctionOrArrowExpression: isFunctionOrArrowExpression$1,
38928 isGetterOrSetter: isGetterOrSetter$1,
38929 isJestEachTemplateLiteral: isJestEachTemplateLiteral$1,
38930 isJSXNode: isJSXNode$1,
38931 isJSXWhitespaceExpression: isJSXWhitespaceExpression$1,
38932 isLastStatement: isLastStatement$1,
38933 isLiteral: isLiteral$1,
38934 isLongCurriedCallExpression: isLongCurriedCallExpression$1,
38935 isMeaningfulJSXText: isMeaningfulJSXText$1,
38936 isMemberExpressionChain: isMemberExpressionChain$1,
38937 isMemberish: isMemberish$1,
38938 isNgForOf: isNgForOf$1,
38939 isNumericLiteral: isNumericLiteral$1,
38940 isObjectType: isObjectType$1,
38941 isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1,
38942 isSimpleCallArgument: isSimpleCallArgument$1,
38943 isSimpleFlowType: isSimpleFlowType$1,
38944 isSimpleTemplateLiteral: isSimpleTemplateLiteral$1,
38945 isStringLiteral: isStringLiteral$1,
38946 isStringPropSafeToCoerceToIdentifier: isStringPropSafeToCoerceToIdentifier$1,
38947 isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1,
38948 isTestCall: isTestCall$1,
38949 isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$1,
38950 isTSXFile: isTSXFile$1,
38951 isTypeAnnotationAFunction: isTypeAnnotationAFunction$1,
38952 matchJsxWhitespaceRegex: matchJsxWhitespaceRegex$1,
38953 needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1,
38954 rawText: rawText$1,
38955 returnArgumentHasLeadingComment: returnArgumentHasLeadingComment$1
38957 const needsQuoteProps = new WeakMap();
38963 hardline: hardline$4,
38964 softline: softline$2,
38965 literalline: literalline$2,
38969 conditionalGroup: conditionalGroup$1,
38971 ifBreak: ifBreak$1,
38972 breakParent: breakParent$2,
38973 lineSuffixBoundary: lineSuffixBoundary$1,
38974 addAlignmentToDoc: addAlignmentToDoc$2,
38978 willBreak: willBreak$1,
38979 isLineNext: isLineNext$1,
38980 isEmpty: isEmpty$1,
38981 removeLines: removeLines$1
38984 printDocToString: printDocToString$2
38989 function shouldPrintComma(options, level) {
38990 level = level || "es5";
38992 switch (options.trailingComma) {
38994 if (level === "all") {
39001 if (level === "es5") {
39013 function genericPrint(path, options, printPath, args) {
39014 const node = path.getValue();
39015 let needsParens = false;
39016 const linesWithoutParens = printPathNoParens(path, options, printPath, args);
39018 if (!node || isEmpty$1(linesWithoutParens)) {
39019 return linesWithoutParens;
39022 const parentExportDecl = getParentExportDeclaration$1(path);
39023 const decorators = [];
39025 if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition" || node.type === "TSDeclareMethod") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator
39026 // was written before the export, the export will be responsible
39027 // for printing the decorators.
39028 !(parentExportDecl && options.locStart(parentExportDecl, {
39029 ignoreDecorators: true
39030 }) > options.locStart(node.decorators[0]))) {
39031 const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options);
39032 const separator = shouldBreak ? hardline$4 : line$4;
39033 path.each(decoratorPath => {
39034 let decorator = decoratorPath.getValue();
39036 if (decorator.expression) {
39037 decorator = decorator.expression;
39039 decorator = decorator.callee;
39042 decorators.push(printPath(decoratorPath), separator);
39045 if (parentExportDecl) {
39046 decorators.unshift(hardline$4);
39048 } else if (isExportDeclaration$1(node) && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0 && // Only print decorators here if they were written before the export,
39049 // otherwise they are printed by the node.declaration
39050 options.locStart(node, {
39051 ignoreDecorators: true
39052 }) > options.locStart(node.declaration.decorators[0])) {
39053 // Export declarations are responsible for printing any decorators
39054 // that logically apply to node.declaration.
39055 path.each(decoratorPath => {
39056 const decorator = decoratorPath.getValue();
39057 const prefix = decorator.type === "Decorator" ? "" : "@";
39058 decorators.push(prefix, printPath(decoratorPath), hardline$4);
39059 }, "declaration", "decorators");
39061 // Nodes with decorators can't have parentheses, so we can avoid
39062 // computing pathNeedsParens() except in this case.
39063 needsParens = needsParens_1(path, options);
39069 parts.unshift("(");
39072 parts.push(linesWithoutParens);
39075 const node = path.getValue();
39077 if (hasFlowShorthandAnnotationComment$2(node)) {
39079 parts.push(node.trailingComments[0].value.trimStart());
39081 node.trailingComments[0].printed = true;
39087 if (decorators.length > 0) {
39088 return group$2(concat$6(decorators.concat(parts)));
39091 return concat$6(parts);
39094 function printDecorators(path, options, print) {
39095 const node = path.getValue();
39096 return group$2(concat$6([join$4(line$4, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$4 : line$4]));
39099 * The following is the shared logic for
39100 * ternary operators, namely ConditionalExpression
39101 * and TSConditionalType
39102 * @typedef {Object} OperatorOptions
39103 * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
39104 * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
39105 * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
39106 * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
39107 * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
39108 * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
39109 * @property {string[]} testNodePropertyNames - The properties at which the test nodes can be found on the main node, eg "test".
39110 * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
39111 * @param {Options} options - Prettier options
39112 * @param {Function} print - Print function to call recursively
39113 * @param {OperatorOptions} operatorOptions
39118 function printTernaryOperator(path, options, print, operatorOptions) {
39119 const node = path.getValue();
39120 const consequentNode = node[operatorOptions.consequentNodePropertyName];
39121 const alternateNode = node[operatorOptions.alternateNodePropertyName];
39122 const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
39123 // See tests/jsx/conditional-expression.js for more info.
39125 let jsxMode = false;
39126 const parent = path.getParentNode();
39127 const isParentTest = parent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.some(prop => parent[prop] === node);
39128 let forceNoIndent = parent.type === operatorOptions.conditionalNodeType && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost
39129 // ConditionalExpression parent. We'll use these to determine if we should
39130 // print in JSX mode.
39133 let previousParent;
39137 previousParent = currentParent || node;
39138 currentParent = path.getParentNode(i);
39140 } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.every(prop => currentParent[prop] !== previousParent));
39142 const firstNonConditionalParent = currentParent || parent;
39143 const lastConditionalParent = previousParent;
39145 if (operatorOptions.shouldCheckJsx && (isJSXNode$1(node[operatorOptions.testNodePropertyNames[0]]) || isJSXNode$1(consequentNode) || isJSXNode$1(alternateNode) || conditionalExpressionChainContainsJSX$1(lastConditionalParent))) {
39147 forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
39148 // parens when using ?: within JSX, because the parens are analogous to
39149 // curly braces in an if statement.
39151 const wrap = doc => concat$6([ifBreak$1("(", ""), indent$3(concat$6([softline$2, doc])), softline$2, ifBreak$1(")", "")]); // The only things we don't wrap are:
39152 // * Nested conditional expressions in alternates
39157 const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined";
39159 parts.push(" ? ", isNil(consequentNode) ? path.call(print, operatorOptions.consequentNodePropertyName) : wrap(path.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNil(alternateNode) ? path.call(print, operatorOptions.alternateNodePropertyName) : wrap(path.call(print, operatorOptions.alternateNodePropertyName)));
39162 const part = concat$6([line$4, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$1("", "(") : "", align$1(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$1("", ")") : "", line$4, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path.call(print, operatorOptions.alternateNodePropertyName))]);
39163 parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$1(indent$3(part)) : align$1(Math.max(0, options.tabWidth - 2), part));
39164 } // We want a whole chain of ConditionalExpressions to all
39165 // break if any of them break. That means we should only group around the
39166 // outer-most ConditionalExpression.
39169 const maybeGroup = doc => parent === firstNonConditionalParent ? group$2(doc) : doc; // Break the closing paren to keep the chain right after it:
39176 const breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed;
39177 const result = maybeGroup(concat$6([].concat((testDoc =>
39188 parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc)(concat$6(operatorOptions.beforeParts())), forceNoIndent ? concat$6(parts) : indent$3(concat$6(parts)), operatorOptions.afterParts(breakClosingParen))));
39189 return isParentTest ? group$2(concat$6([indent$3(concat$6([softline$2, result])), softline$2])) : result;
39192 function printPathNoParens(path, options, print, args) {
39193 const n = path.getValue();
39194 const semi = options.semi ? ";" : "";
39200 if (typeof n === "string") {
39204 const htmlBinding = printHtmlBinding$1(path, options, print);
39207 return htmlBinding;
39213 case "JsExpressionRoot":
39214 return path.call(print, "node");
39217 return concat$6([path.call(print, "node"), hardline$4]);
39220 // Print @babel/parser's InterpreterDirective here so that
39221 // leading comments on the `Program` node get printed after the hashbang.
39222 if (n.program && n.program.interpreter) {
39223 parts.push(path.call(programPath => programPath.call(print, "interpreter"), "program"));
39226 parts.push(path.call(print, "program"));
39227 return concat$6(parts);
39231 if (n.directives) {
39232 path.each(childPath => {
39233 parts.push(print(childPath), semi, hardline$4);
39235 if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options.locEnd)) {
39236 parts.push(hardline$4);
39241 parts.push(path.call(bodyPath => {
39242 return printStatementSequence(bodyPath, options, print);
39244 parts.push(comments.printDanglingComments(path, options,
39246 true)); // Only force a trailing newline if there were any contents.
39248 if (!n.body.every(({
39250 }) => type === "EmptyStatement") || n.comments) {
39251 parts.push(hardline$4);
39254 return concat$6(parts);
39255 // Babel extension.
39257 case "EmptyStatement":
39260 case "ExpressionStatement":
39261 // Detect Flow-parsed directives
39263 return concat$6([nodeStr(n.expression, options, true), semi]);
39266 if (options.parser === "__vue_event_binding") {
39267 const parent = path.getParentNode();
39269 if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
39270 return concat$6([path.call(print, "expression"), isVueEventBindingExpression$1(n.expression) ? ";" : ""]);
39272 } // Do not append semicolon after the only JSX element in a program
39275 return concat$6([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]);
39276 // Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
39278 case "ParenthesizedExpression":
39280 const shouldHug = !n.expression.comments;
39283 return concat$6(["(", path.call(print, "expression"), ")"]);
39286 return group$2(concat$6(["(", indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, ")"]));
39289 case "AssignmentExpression":
39290 return printAssignment(n.left, path.call(print, "left"), concat$6([" ", n.operator]), n.right, path.call(print, "right"), options);
39292 case "BinaryExpression":
39293 case "LogicalExpression":
39294 case "NGPipeExpression":
39296 const parent = path.getParentNode();
39297 const parentParent = path.getParentNode(1);
39298 const isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement");
39299 const parts = printBinaryishExpressions(path, print, options,
39301 false, isInsideParenthesis); // if (
39302 // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
39305 // looks super weird, we want to break the children if the parent breaks
39308 // this.hasPlugin("dynamicImports") &&
39309 // this.lookahead().type === tt.parenLeft
39312 if (isInsideParenthesis) {
39313 return concat$6(parts);
39314 } // Break between the parens in
39315 // unaries or in a member or specific call expression, i.e.
39324 if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) {
39325 return group$2(concat$6([indent$3(concat$6([softline$2, concat$6(parts)])), softline$2]));
39326 } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
39327 // indented accordingly. We should indent sub-expressions where the first case isn't indented.
39330 const shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "ThrowStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n.operator !== "|" && parent.type === "JsExpressionRoot" || n.type !== "NGPipeExpression" && (parent.type === "NGRoot" && options.parser === "__ng_binding" || parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || n === parent.body && parent.type === "ArrowFunctionExpression" || n !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "ThrowStatement" && parentParent.type !== "CallExpression" && parentParent.type !== "OptionalCallExpression" || parent.type === "TemplateLiteral";
39331 const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property";
39332 const samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$1(n.operator, n.left.operator);
39334 if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
39335 return group$2(concat$6(parts));
39338 if (parts.length === 0) {
39340 } // If the right part is a JSX node, we include it in a separate group to
39341 // prevent it breaking the whole chain, so we can print the expression like:
39350 const hasJSX = isJSXNode$1(n.right);
39351 const rest = concat$6(hasJSX ? parts.slice(1, -1) : parts.slice(1));
39352 const groupId = Symbol("logicalChain-" + ++uid);
39353 const chain = group$2(concat$6([// Don't include the initial expression in the indentation
39354 // level. The first item is guaranteed to be the first
39355 // left-most expression.
39356 parts.length > 0 ? parts[0] : "", indent$3(rest)]), {
39364 const jsxPart = getLast$2(parts);
39365 return group$2(concat$6([chain, ifBreak$1(indent$3(jsxPart), jsxPart, {
39370 case "AssignmentPattern":
39371 return concat$6([path.call(print, "left"), " = ", path.call(print, "right")]);
39373 case "TSTypeAssertion":
39375 const shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
39376 const castGroup = group$2(concat$6(["<", indent$3(concat$6([softline$2, path.call(print, "typeAnnotation")])), softline$2, ">"]));
39377 const exprContents = concat$6([ifBreak$1("("), indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, ifBreak$1(")")]);
39379 if (shouldBreakAfterCast) {
39380 return conditionalGroup$1([concat$6([castGroup, path.call(print, "expression")]), concat$6([castGroup, group$2(exprContents, {
39382 })]), concat$6([castGroup, path.call(print, "expression")])]);
39385 return group$2(concat$6([castGroup, path.call(print, "expression")]));
39388 case "OptionalMemberExpression":
39389 case "MemberExpression":
39391 const parent = path.getParentNode();
39392 let firstNonMemberParent;
39396 firstNonMemberParent = path.getParentNode(i);
39398 } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
39400 const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression";
39401 return concat$6([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$2(indent$3(concat$6([softline$2, printMemberLookup(path, options, print)])))]);
39404 case "MetaProperty":
39405 return concat$6([path.call(print, "meta"), ".", path.call(print, "property")]);
39407 case "BindExpression":
39409 parts.push(path.call(print, "object"));
39412 parts.push(group$2(indent$3(concat$6([softline$2, printBindExpressionCallee(path, options, print)]))));
39413 return concat$6(parts);
39417 return concat$6([n.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]);
39420 case "V8IntrinsicIdentifier":
39421 return concat$6(["%", n.name]);
39423 case "SpreadElement":
39424 case "SpreadElementPattern":
39425 case "SpreadProperty":
39426 case "SpreadPropertyPattern":
39427 case "RestElement":
39428 case "ObjectTypeSpreadProperty":
39429 return concat$6(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]);
39431 case "FunctionDeclaration":
39432 case "FunctionExpression":
39433 parts.push(printFunctionDeclaration(path, print, options));
39439 return concat$6(parts);
39441 case "ArrowFunctionExpression":
39444 parts.push("async ");
39447 if (shouldPrintParamsWithoutParens(path, options)) {
39448 parts.push(path.call(print, "params", 0));
39450 parts.push(group$2(concat$6([printFunctionParams(path, print, options,
39452 args && (args.expandLastArg || args.expandFirstArg),
39453 /* printTypeParams */
39454 true), printReturnType(path, print, options)])));
39457 const dangling = comments.printDanglingComments(path, options,
39460 const nextCharacter = getNextNonSpaceNonCommentCharacterIndex$3(options.originalText, comment, options.locEnd);
39461 return options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>";
39465 parts.push(" ", dangling);
39469 const body = path.call(bodyPath => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line
39472 if (!hasLeadingOwnLineComment$1(options.originalText, n.body, options) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode$1(n.body) || isTemplateOnItsOwnLine$1(n.body, options.originalText, options) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) {
39473 return group$2(concat$6([concat$6(parts), " ", body]));
39474 } // We handle sequence expressions as the body of arrows specially,
39475 // so that the required parentheses end up on their own lines.
39478 if (n.body.type === "SequenceExpression") {
39479 return group$2(concat$6([concat$6(parts), group$2(concat$6([" (", indent$3(concat$6([softline$2, body])), softline$2, ")"]))]));
39480 } // if the arrow function is expanded as last argument, we are adding a
39481 // level of indentation and need to add a softline to align the closing )
39482 // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
39483 // we should align the expression's closing } with the line with the opening {.
39486 const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
39487 const printTrailingComma = args && args.expandLastArg && shouldPrintComma(options, "all"); // In order to avoid confusion between
39491 const shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body,
39492 /* forbidFunctionAndClass */
39494 return group$2(concat$6([concat$6(parts), group$2(concat$6([indent$3(concat$6([line$4, shouldAddParens ? ifBreak$1("", "(") : "", body, shouldAddParens ? ifBreak$1("", ")") : ""])), shouldAddSoftLine ? concat$6([ifBreak$1(printTrailingComma ? "," : ""), softline$2]) : ""]))]));
39497 case "YieldExpression":
39498 parts.push("yield");
39505 parts.push(" ", path.call(print, "argument"));
39508 return concat$6(parts);
39510 case "AwaitExpression":
39512 parts.push("await ", path.call(print, "argument"));
39513 const parent = path.getParentNode();
39515 if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && parent.object === n) {
39516 return group$2(concat$6([indent$3(concat$6([softline$2, concat$6(parts)])), softline$2]));
39519 return concat$6(parts);
39522 case "ImportSpecifier":
39523 if (n.importKind) {
39524 parts.push(path.call(print, "importKind"), " ");
39527 parts.push(path.call(print, "imported"));
39529 if (n.local && n.local.name !== n.imported.name) {
39530 parts.push(" as ", path.call(print, "local"));
39533 return concat$6(parts);
39535 case "ExportSpecifier":
39536 parts.push(path.call(print, "local"));
39538 if (n.exported && n.exported.name !== n.local.name) {
39539 parts.push(" as ", path.call(print, "exported"));
39542 return concat$6(parts);
39544 case "ImportNamespaceSpecifier":
39545 parts.push("* as ");
39546 parts.push(path.call(print, "local"));
39547 return concat$6(parts);
39549 case "ImportDefaultSpecifier":
39550 return path.call(print, "local");
39552 case "TSExportAssignment":
39553 return concat$6(["export = ", path.call(print, "expression"), semi]);
39555 case "ExportDefaultDeclaration":
39556 case "ExportNamedDeclaration":
39557 return printExportDeclaration(path, options, print);
39559 case "ExportAllDeclaration":
39560 parts.push("export ");
39562 if (n.exportKind === "type") {
39563 parts.push("type ");
39569 parts.push("as ", path.call(print, "exported"), " ");
39572 parts.push("from ", path.call(print, "source"), semi);
39573 return concat$6(parts);
39575 case "ExportNamespaceSpecifier":
39576 case "ExportDefaultSpecifier":
39577 return path.call(print, "exported");
39579 case "ImportDeclaration":
39581 parts.push("import ");
39583 if (n.importKind && n.importKind !== "value") {
39584 parts.push(n.importKind + " ");
39587 const standalones = [];
39588 const grouped = [];
39590 if (n.specifiers && n.specifiers.length > 0) {
39591 path.each(specifierPath => {
39592 const value = specifierPath.getValue();
39594 if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") {
39595 standalones.push(print(specifierPath));
39597 grouped.push(print(specifierPath));
39601 if (standalones.length > 0) {
39602 parts.push(join$4(", ", standalones));
39605 if (standalones.length > 0 && grouped.length > 0) {
39609 if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(node => node.comments)) {
39610 parts.push(concat$6(["{", options.bracketSpacing ? " " : "", concat$6(grouped), options.bracketSpacing ? " " : "", "}"]));
39611 } else if (grouped.length >= 1) {
39612 parts.push(group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$4 : softline$2, join$4(concat$6([",", line$4]), grouped)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$4 : softline$2, "}"])));
39615 parts.push(" from ");
39616 } else if (n.importKind && n.importKind === "type" || // import {} from 'x'
39617 /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) {
39618 parts.push("{} from ");
39621 parts.push(path.call(print, "source"), semi);
39622 return concat$6(parts);
39628 case "TSModuleBlock":
39629 case "BlockStatement":
39631 const naked = path.call(bodyPath => {
39632 return printStatementSequence(bodyPath, options, print);
39634 const hasContent = n.body.find(node => node.type !== "EmptyStatement");
39635 const hasDirectives = n.directives && n.directives.length > 0;
39636 const parent = path.getParentNode();
39637 const parentParent = path.getParentNode(1);
39639 if (!hasContent && !hasDirectives && !hasDanglingComments$1(n) && (parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration")) {
39643 parts.push("{"); // Babel 6
39645 if (hasDirectives) {
39646 path.each(childPath => {
39647 parts.push(indent$3(concat$6([hardline$4, print(childPath), semi])));
39649 if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options.locEnd)) {
39650 parts.push(hardline$4);
39656 parts.push(indent$3(concat$6([hardline$4, naked])));
39659 parts.push(comments.printDanglingComments(path, options));
39660 parts.push(hardline$4, "}");
39661 return concat$6(parts);
39664 case "ReturnStatement":
39665 return concat$6(["return", printReturnAndThrowArgument(path, options, print)]);
39667 case "NewExpression":
39668 case "OptionalCallExpression":
39669 case "CallExpression":
39671 const isNew = n.type === "NewExpression";
39672 const optional = printOptionalToken(path);
39674 if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
39675 // define calls, as a unit.
39676 // e.g. `define(["some/lib", (lib) => {`
39677 !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
39678 n.arguments.length === 1 && isTemplateOnItsOwnLine$1(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line
39679 // e.g. `it('long name', () => {`
39680 !isNew && isTestCall$1(n, path.getParentNode())) {
39681 return concat$6([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), concat$6(["(", join$4(", ", path.map(print, "arguments")), ")"])]);
39682 } // Inline Flow annotation comments following Identifiers in Call nodes need to
39683 // stay with the Identifier. For example:
39685 // foo /*:: <SomeGeneric> */(bar);
39687 // Here, we ensure that such comments stay between the Identifier and the Callee.
39690 const isIdentifierWithFlowAnnotation = n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments);
39692 if (isIdentifierWithFlowAnnotation) {
39693 n.callee.trailingComments[0].printed = true;
39694 } // We detect calls on member lookups and possibly print them in a
39695 // special chain format. See `printMemberChain` for more info.
39698 if (!isNew && isMemberish$1(n.callee) && !path.call(path => needsParens_1(path, options), "callee")) {
39699 return printMemberChain(path, options, print);
39702 const contents = concat$6([isNew ? "new " : "", path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${n.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]); // We group here when the callee is itself a call expression.
39703 // See `isLongCurriedCallExpression` for more info.
39705 if (isCallOrOptionalCallExpression$1(n.callee)) {
39706 return group$2(contents);
39712 case "TSInterfaceDeclaration":
39714 parts.push("declare ");
39717 parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print), "interface ", path.call(print, "id"), n.typeParameters ? path.call(print, "typeParameters") : "", " ");
39719 if (n.extends && n.extends.length) {
39720 parts.push(group$2(indent$3(concat$6([softline$2, "extends ", (n.extends.length === 1 ? identity$2 : indent$3)(join$4(concat$6([",", line$4]), path.map(print, "extends"))), " "]))));
39723 parts.push(path.call(print, "body"));
39724 return concat$6(parts);
39726 case "ObjectTypeInternalSlot":
39727 return concat$6([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken(path), n.method ? "" : ": ", path.call(print, "value")]);
39729 case "ObjectExpression":
39730 case "ObjectPattern":
39731 case "ObjectTypeAnnotation":
39732 case "TSInterfaceBody":
39733 case "TSTypeLiteral":
39735 let propertiesField;
39737 if (n.type === "TSTypeLiteral") {
39738 propertiesField = "members";
39739 } else if (n.type === "TSInterfaceBody") {
39740 propertiesField = "body";
39742 propertiesField = "properties";
39745 const isTypeAnnotation = n.type === "ObjectTypeAnnotation";
39748 if (isTypeAnnotation) {
39749 fields.push("indexers", "callProperties", "internalSlots");
39752 fields.push(propertiesField);
39753 const firstProperty = fields.map(field => n[field][0]).sort((a, b) => options.locStart(a) - options.locStart(b))[0];
39754 const parent = path.getParentNode(0);
39755 const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body";
39756 const shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && n.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$3(options.originalText, options.locStart(n), options.locStart(firstProperty));
39757 const separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$1(semi, ";") : ",";
39758 const leftBrace = n.exact ? "{|" : "{";
39759 const rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
39760 // interleaved in the source code. So we need to reorder them before
39763 const propsAndLoc = [];
39764 fields.forEach(field => {
39765 path.each(childPath => {
39766 const node = childPath.getValue();
39769 printed: print(childPath),
39770 loc: options.locStart(node)
39774 let separatorParts = [];
39775 const props = propsAndLoc.sort((a, b) => a.loc - b.loc).map(prop => {
39776 const result = concat$6(separatorParts.concat(group$2(prop.printed)));
39777 separatorParts = [separator, line$4];
39779 if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) {
39780 separatorParts.shift();
39783 if (isNextLineEmpty$2(options.originalText, prop.node, options.locEnd)) {
39784 separatorParts.push(hardline$4);
39793 if (hasDanglingComments$1(n)) {
39794 const hasLineComments = !n.comments.every(comments$1.isBlockComment);
39795 const printedDanglingComments = comments.printDanglingComments(path, options,
39798 printed = concat$6([printedDanglingComments, hasLineComments || hasNewline$4(options.originalText, options.locEnd(n.comments[n.comments.length - 1])) ? hardline$4 : line$4, "..."]);
39803 props.push(concat$6(separatorParts.concat(printed)));
39806 const lastElem = getLast$2(n[propertiesField]);
39807 const canHaveTrailingSeparator = !(n.inexact || lastElem && (lastElem.type === "RestElement" || hasNodeIgnoreComment$2(lastElem)));
39810 if (props.length === 0) {
39811 if (!hasDanglingComments$1(n)) {
39812 return concat$6([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]);
39815 content = group$2(concat$6([leftBrace, comments.printDanglingComments(path, options), softline$2, rightBrace, printOptionalToken(path), printTypeAnnotation(path, options, print)]));
39817 content = concat$6([leftBrace, indent$3(concat$6([options.bracketSpacing ? line$4 : softline$2, concat$6(props)])), ifBreak$1(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma(options)) ? separator : ""), concat$6([options.bracketSpacing ? line$4 : softline$2, rightBrace]), printOptionalToken(path), printTypeAnnotation(path, options, print)]);
39818 } // If we inline the object as first argument of the parent, we don't want
39819 // to create another group so that the object breaks before the return
39823 if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0)) {
39827 return group$2(content, {
39833 case "ObjectProperty": // Non-standard AST node type.
39836 if (n.method || n.kind === "get" || n.kind === "set") {
39837 return printMethod(path, options, print);
39841 parts.push(path.call(print, "value"));
39843 parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options));
39846 return concat$6(parts);
39849 case "ClassMethod":
39850 case "ClassPrivateMethod":
39851 case "MethodDefinition":
39852 case "TSAbstractMethodDefinition":
39853 case "TSDeclareMethod":
39854 if (n.decorators && n.decorators.length !== 0) {
39855 parts.push(printDecorators(path, options, print));
39858 if (n.accessibility) {
39859 parts.push(n.accessibility + " ");
39863 parts.push("static ");
39866 if (n.type === "TSAbstractMethodDefinition" || n.abstract) {
39867 parts.push("abstract ");
39870 parts.push(printMethod(path, options, print));
39871 return concat$6(parts);
39873 case "ObjectMethod":
39874 return printMethod(path, options, print);
39877 return concat$6(["@", path.call(print, "expression"), path.call(print, "callee")]);
39879 case "ArrayExpression":
39880 case "ArrayPattern":
39881 if (n.elements.length === 0) {
39882 if (!hasDanglingComments$1(n)) {
39885 parts.push(group$2(concat$6(["[", comments.printDanglingComments(path, options), softline$2, "]"])));
39888 const lastElem = getLast$2(n.elements);
39889 const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
39890 // changes its length based on the number of commas. The algorithm
39891 // is that if the last argument is null, we need to force insert
39892 // a comma to ensure JavaScript recognizes it.
39893 // [,].length === 1
39894 // [1,].length === 1
39895 // [1,,].length === 2
39897 // Note that getLast returns null if the array is empty, but
39898 // we already check for an empty array just above so we are safe
39900 const needsForcedTrailingComma = canHaveTrailingComma && lastElem === null;
39901 const shouldBreak = n.elements.length > 1 && n.elements.every((element, i, elements) => {
39902 const elementType = element && element.type;
39904 if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
39908 const nextElement = elements[i + 1];
39910 if (nextElement && elementType !== nextElement.type) {
39914 const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
39915 return element[itemsKey] && element[itemsKey].length > 1;
39917 parts.push(group$2(concat$6(["[", indent$3(concat$6([softline$2, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$1(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path, options,
39919 true), softline$2, "]"]), {
39924 parts.push(printOptionalToken(path), printTypeAnnotation(path, options, print));
39925 return concat$6(parts);
39927 case "SequenceExpression":
39929 const parent = path.getParentNode(0);
39931 if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") {
39932 // For ExpressionStatements and for-loop heads, which are among
39933 // the few places a SequenceExpression appears unparenthesized, we want
39934 // to indent expressions after the first.
39937 if (p.getName() === 0) {
39938 parts.push(print(p));
39940 parts.push(",", indent$3(concat$6([line$4, print(p)])));
39943 return group$2(concat$6(parts));
39946 return group$2(concat$6([join$4(concat$6([",", line$4]), path.map(print, "expressions"))]));
39949 case "ThisExpression":
39955 case "NullLiteral":
39956 // Babel 6 Literal split
39959 case "RegExpLiteral":
39960 // Babel 6 Literal split
39961 return printRegex(n);
39963 case "NumericLiteral":
39964 // Babel 6 Literal split
39965 return printNumber$1(n.extra.raw);
39967 case "BigIntLiteral":
39968 // babel: n.extra.raw, typescript: n.raw, flow: n.bigint
39969 return (n.bigint || (n.extra ? n.extra.raw : n.raw)).toLowerCase();
39971 case "BooleanLiteral": // Babel 6 Literal split
39973 case "StringLiteral": // Babel 6 Literal split
39978 return printRegex(n.regex);
39981 if (typeof n.value === "number") {
39982 return printNumber$1(n.raw);
39985 if (typeof n.value !== "string") {
39986 return "" + n.value;
39987 } // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
39988 // See corresponding workaround in needs-parens.js
39991 const grandParent = path.getParentNode(1);
39992 const isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement");
39993 return nodeStr(n, options, isTypeScriptDirective);
39997 return path.call(print, "value");
40000 case "DirectiveLiteral":
40001 return nodeStr(n, options);
40003 case "UnaryExpression":
40004 parts.push(n.operator);
40006 if (/[a-z]$/.test(n.operator)) {
40010 if (n.argument.comments && n.argument.comments.length > 0) {
40011 parts.push(group$2(concat$6(["(", indent$3(concat$6([softline$2, path.call(print, "argument")])), softline$2, ")"])));
40013 parts.push(path.call(print, "argument"));
40016 return concat$6(parts);
40018 case "UpdateExpression":
40019 parts.push(path.call(print, "argument"), n.operator);
40025 return concat$6(parts);
40027 case "ConditionalExpression":
40028 return printTernaryOperator(path, options, print, {
40029 beforeParts: () => [path.call(print, "test")],
40030 afterParts: breakClosingParen => [breakClosingParen ? softline$2 : ""],
40031 shouldCheckJsx: true,
40032 conditionalNodeType: "ConditionalExpression",
40033 consequentNodePropertyName: "consequent",
40034 alternateNodePropertyName: "alternate",
40035 testNodePropertyNames: ["test"]
40038 case "VariableDeclaration":
40040 const printed = path.map(childPath => {
40041 return print(childPath);
40042 }, "declarations"); // We generally want to terminate all variable declarations with a
40043 // semicolon, except when they in the () part of for loops.
40045 const parentNode = path.getParentNode();
40046 const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement";
40047 const hasValue = n.declarations.some(decl => decl.init);
40050 if (printed.length === 1 && !n.declarations[0].comments) {
40051 firstVariable = printed[0];
40052 } else if (printed.length > 0) {
40053 // Indent first var to comply with eslint one-var rule
40054 firstVariable = indent$3(printed[0]);
40057 parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$6([" ", firstVariable]) : "", indent$3(concat$6(printed.slice(1).map(p => concat$6([",", hasValue && !isParentForLoop ? hardline$4 : line$4, p]))))];
40059 if (!(isParentForLoop && parentNode.body !== n)) {
40063 return group$2(concat$6(parts));
40066 case "TSTypeAliasDeclaration":
40069 parts.push("declare ");
40072 const printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
40073 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
40074 return group$2(concat$6(parts));
40077 case "VariableDeclarator":
40078 return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
40080 case "WithStatement":
40081 return group$2(concat$6(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))]));
40083 case "IfStatement":
40085 const con = adjustClause(n.consequent, path.call(print, "consequent"));
40086 const opening = group$2(concat$6(["if (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", con]));
40087 parts.push(opening);
40090 const commentOnOwnLine = hasTrailingComment$1(n.consequent) && n.consequent.comments.some(comment => comment.trailing && !comments$1.isBlockComment(comment)) || needsHardlineAfterDanglingComment$1(n);
40091 const elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
40092 parts.push(elseOnSameLine ? " " : hardline$4);
40094 if (hasDanglingComments$1(n)) {
40095 parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$4 : " ");
40098 parts.push("else", group$2(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
40101 return concat$6(parts);
40104 case "ForStatement":
40106 const body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
40107 // Any comment positioned between the for statement and the parentheses
40108 // is going to be printed before the statement.
40110 const dangling = comments.printDanglingComments(path, options,
40113 const printedComments = dangling ? concat$6([dangling, softline$2]) : "";
40115 if (!n.init && !n.test && !n.update) {
40116 return concat$6([printedComments, group$2(concat$6(["for (;;)", body]))]);
40119 return concat$6([printedComments, group$2(concat$6(["for (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "init"), ";", line$4, path.call(print, "test"), ";", line$4, path.call(print, "update")])), softline$2])), ")", body]))]);
40122 case "WhileStatement":
40123 return group$2(concat$6(["while (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", adjustClause(n.body, path.call(print, "body"))]));
40125 case "ForInStatement":
40126 // Note: esprima can't actually parse "for each (".
40127 return group$2(concat$6([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
40129 case "ForOfStatement":
40130 return group$2(concat$6(["for", n.await ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
40132 case "DoWhileStatement":
40134 const clause = adjustClause(n.body, path.call(print, "body"));
40135 const doBody = group$2(concat$6(["do", clause]));
40138 if (n.body.type === "BlockStatement") {
40141 parts.push(hardline$4);
40144 parts.push("while (");
40145 parts.push(group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", semi);
40146 return concat$6(parts);
40149 case "DoExpression":
40150 return concat$6(["do ", path.call(print, "body")]);
40152 case "BreakStatement":
40153 parts.push("break");
40156 parts.push(" ", path.call(print, "label"));
40160 return concat$6(parts);
40162 case "ContinueStatement":
40163 parts.push("continue");
40166 parts.push(" ", path.call(print, "label"));
40170 return concat$6(parts);
40172 case "LabeledStatement":
40173 if (n.body.type === "EmptyStatement") {
40174 return concat$6([path.call(print, "label"), ":;"]);
40177 return concat$6([path.call(print, "label"), ": ", path.call(print, "body")]);
40179 case "TryStatement":
40180 return concat$6(["try ", path.call(print, "block"), n.handler ? concat$6([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$6([" finally ", path.call(print, "finalizer")]) : ""]);
40182 case "CatchClause":
40184 const hasComments = n.param.comments && n.param.comments.some(comment => !comments$1.isBlockComment(comment) || comment.leading && hasNewline$4(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$4(options.originalText, options.locStart(comment), {
40187 const param = path.call(print, "param");
40188 return concat$6(["catch ", hasComments ? concat$6(["(", indent$3(concat$6([softline$2, param])), softline$2, ") "]) : concat$6(["(", param, ") "]), path.call(print, "body")]);
40191 return concat$6(["catch ", path.call(print, "body")]);
40193 case "ThrowStatement":
40194 return concat$6(["throw", printReturnAndThrowArgument(path, options, print)]);
40195 // Note: ignoring n.lexical because it has no printing consequences.
40197 case "SwitchStatement":
40198 return concat$6([group$2(concat$6(["switch (", indent$3(concat$6([softline$2, path.call(print, "discriminant")])), softline$2, ")"])), " {", n.cases.length > 0 ? indent$3(concat$6([hardline$4, join$4(hardline$4, path.map(casePath => {
40199 const caseNode = casePath.getValue();
40200 return concat$6([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$2(options.originalText, caseNode, options.locEnd) ? hardline$4 : ""]);
40201 }, "cases"))])) : "", hardline$4, "}"]);
40206 parts.push("case ", path.call(print, "test"), ":");
40208 parts.push("default:");
40211 const consequent = n.consequent.filter(node => node.type !== "EmptyStatement");
40213 if (consequent.length > 0) {
40214 const cons = path.call(consequentPath => {
40215 return printStatementSequence(consequentPath, options, print);
40217 parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$6([" ", cons]) : indent$3(concat$6([hardline$4, cons])));
40220 return concat$6(parts);
40222 // JSX extensions below.
40224 case "DebuggerStatement":
40225 return concat$6(["debugger", semi]);
40227 case "JSXAttribute":
40228 parts.push(path.call(print, "name"));
40233 if (isStringLiteral$1(n.value)) {
40234 const raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote
40236 let final = raw.replace(/'/g, "'").replace(/"/g, '"');
40237 const quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
40238 const escape = quote === "'" ? "'" : """;
40239 final = final.slice(1, -1).replace(new RegExp(quote, "g"), escape);
40240 res = concat$6([quote, final, quote]);
40242 res = path.call(print, "value");
40245 parts.push("=", res);
40248 return concat$6(parts);
40250 case "JSXIdentifier":
40251 return "" + n.name;
40253 case "JSXNamespacedName":
40254 return join$4(":", [path.call(print, "namespace"), path.call(print, "name")]);
40256 case "JSXMemberExpression":
40257 return join$4(".", [path.call(print, "object"), path.call(print, "property")]);
40259 case "TSQualifiedName":
40260 return join$4(".", [path.call(print, "left"), path.call(print, "right")]);
40262 case "JSXSpreadAttribute":
40263 case "JSXSpreadChild":
40265 return concat$6(["{", path.call(p => {
40266 const printed = concat$6(["...", print(p)]);
40267 const n = p.getValue();
40269 if (!n.comments || !n.comments.length) {
40273 return concat$6([indent$3(concat$6([softline$2, comments.printComments(p, () => printed, options)])), softline$2]);
40274 }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
40277 case "JSXExpressionContainer":
40279 const parent = path.getParentNode(0);
40280 const hasComments = n.expression.comments && n.expression.comments.length > 0;
40281 const shouldInline = n.expression.type === "JSXEmptyExpression" || !hasComments && (n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression" || n.expression.type === "ArrowFunctionExpression" || n.expression.type === "CallExpression" || n.expression.type === "OptionalCallExpression" || n.expression.type === "FunctionExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode$1(parent) && (n.expression.type === "ConditionalExpression" || isBinaryish$1(n.expression)));
40283 if (shouldInline) {
40284 return group$2(concat$6(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"]));
40287 return group$2(concat$6(["{", indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, lineSuffixBoundary$1, "}"]));
40290 case "JSXFragment":
40293 const elem = comments.printComments(path, () => printJSXElement(path, options, print), options);
40294 return maybeWrapJSXElementInParens(path, elem, options);
40297 case "JSXOpeningElement":
40299 const n = path.getValue();
40300 const nameHasComments = n.name && n.name.comments && n.name.comments.length > 0 || n.typeParameters && n.typeParameters.comments && n.typeParameters.comments.length > 0; // Don't break self-closing elements with no attributes and no comments
40302 if (n.selfClosing && !n.attributes.length && !nameHasComments) {
40303 return concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]);
40304 } // don't break up opening elements with a single long text attribute
40307 if (n.attributes && n.attributes.length === 1 && n.attributes[0].value && isStringLiteral$1(n.attributes[0].value) && !n.attributes[0].value.value.includes("\n") && // We should break for the following cases:
40316 !nameHasComments && (!n.attributes[0].comments || !n.attributes[0].comments.length)) {
40317 return group$2(concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$6(path.map(print, "attributes")), n.selfClosing ? " />" : ">"]));
40320 const lastAttrHasTrailingComments = n.attributes.length && hasTrailingComment$1(getLast$2(n.attributes));
40321 const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
40322 // kept unbroken regardless of `jsxBracketSameLine`
40323 !n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
40330 !nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
40331 // string literal with newlines
40333 const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n"));
40334 return group$2(concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$6([indent$3(concat$6(path.map(attr => concat$6([line$4, print(attr)]), "attributes"))), n.selfClosing ? line$4 : bracketSameLine ? ">" : softline$2]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
40339 case "JSXClosingElement":
40340 return concat$6(["</", path.call(print, "name"), ">"]);
40342 case "JSXOpeningFragment":
40343 case "JSXClosingFragment":
40345 const hasComment = n.comments && n.comments.length;
40346 const hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
40347 const isOpeningFragment = n.type === "JSXOpeningFragment";
40348 return concat$6([isOpeningFragment ? "<" : "</", indent$3(concat$6([hasOwnLineComment ? hardline$4 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$4 : "", ">"]);
40352 /* istanbul ignore next */
40353 throw new Error("JSXTest should be handled by JSXElement");
40355 case "JSXEmptyExpression":
40357 const requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
40358 return concat$6([comments.printDanglingComments(path, options,
40360 !requiresHardline), requiresHardline ? hardline$4 : ""]);
40364 if (!n.comments && n.body.length === 0) {
40368 return concat$6(["{", n.body.length > 0 ? indent$3(concat$6([hardline$4, path.call(bodyPath => {
40369 return printStatementSequence(bodyPath, options, print);
40370 }, "body")])) : comments.printDanglingComments(path, options), hardline$4, "}"]);
40372 case "ClassProperty":
40373 case "TSAbstractClassProperty":
40374 case "ClassPrivateProperty":
40376 if (n.decorators && n.decorators.length !== 0) {
40377 parts.push(printDecorators(path, options, print));
40380 if (n.accessibility) {
40381 parts.push(n.accessibility + " ");
40385 parts.push("declare ");
40389 parts.push("static ");
40392 if (n.type === "TSAbstractClassProperty" || n.abstract) {
40393 parts.push("abstract ");
40397 parts.push("readonly ");
40400 const variance = getFlowVariance$1(n);
40403 parts.push(variance);
40406 parts.push(printPropertyKey(path, options, print), printOptionalToken(path), printTypeAnnotation(path, options, print));
40409 parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
40413 return group$2(concat$6(parts));
40416 case "ClassDeclaration":
40417 case "ClassExpression":
40419 parts.push("declare ");
40422 parts.push(concat$6(printClass(path, options, print)));
40423 return concat$6(parts);
40425 case "TSInterfaceHeritage":
40426 case "TSExpressionWithTypeArguments":
40428 parts.push(path.call(print, "expression"));
40430 if (n.typeParameters) {
40431 parts.push(path.call(print, "typeParameters"));
40434 return concat$6(parts);
40436 case "TemplateElement":
40437 return join$4(literalline$2, n.value.raw.split(/\r?\n/g));
40439 case "TemplateLiteral":
40441 let expressions = path.map(print, "expressions");
40442 const parentNode = path.getParentNode();
40444 if (isJestEachTemplateLiteral$1(n, parentNode)) {
40445 const printed = printJestEachTemplateLiteral(n, expressions, options);
40452 const isSimple = isSimpleTemplateLiteral$1(n);
40455 expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, {
40456 printWidth: Infinity
40460 parts.push(lineSuffixBoundary$1, "`");
40461 path.each(childPath => {
40462 const i = childPath.getName();
40463 parts.push(print(childPath));
40465 if (i < expressions.length) {
40466 // For a template literal of the following form:
40473 // the expression is on its own line (there is a \n in the previous
40474 // quasi literal), therefore we want to indent the JavaScript
40475 // expression inside at the beginning of ${ instead of the beginning
40480 const quasi = childPath.getValue();
40481 const indentSize = getIndentSize$2(quasi.value.raw, tabWidth);
40482 let printed = expressions[i];
40485 // Breaks at the template element boundaries (${ and }) are preferred to breaking
40486 // in the middle of a MemberExpression
40487 if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression" || n.expressions[i].type === "SequenceExpression" || n.expressions[i].type === "TSAsExpression" || isBinaryish$1(n.expressions[i])) {
40488 printed = concat$6([indent$3(concat$6([softline$2, printed])), softline$2]);
40492 const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth);
40493 parts.push(group$2(concat$6(["${", aligned, lineSuffixBoundary$1, "}"])));
40497 return concat$6(parts);
40499 // These types are unprintable because they serve as abstract
40500 // supertypes for other (printable) types.
40502 case "TaggedTemplateExpression":
40503 return concat$6([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
40507 case "SourceLocation":
40513 case "Declaration":
40515 case "NamedSpecifier":
40517 case "MemberTypeAnnotation": // Flow
40520 /* istanbul ignore next */
40521 throw new Error("unprintable type: " + JSON.stringify(n.type));
40522 // Type Annotations for Facebook Flow, typically stripped out or
40523 // transformed away before printing.
40525 case "TypeAnnotation":
40526 case "TSTypeAnnotation":
40527 if (n.typeAnnotation) {
40528 return path.call(print, "typeAnnotation");
40530 /* istanbul ignore next */
40535 case "TSTupleType":
40536 case "TupleTypeAnnotation":
40538 const typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
40539 const hasRest = n[typesField].length > 0 && getLast$2(n[typesField]).type === "TSRestType";
40540 return group$2(concat$6(["[", indent$3(concat$6([softline$2, printArrayItems(path, options, typesField, print)])), ifBreak$1(shouldPrintComma(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options,
40542 true), softline$2, "]"]));
40545 case "ExistsTypeAnnotation":
40548 case "EmptyTypeAnnotation":
40551 case "AnyTypeAnnotation":
40554 case "MixedTypeAnnotation":
40557 case "ArrayTypeAnnotation":
40558 return concat$6([path.call(print, "elementType"), "[]"]);
40560 case "BooleanTypeAnnotation":
40563 case "BooleanLiteralTypeAnnotation":
40564 return "" + n.value;
40566 case "DeclareClass":
40567 return printFlowDeclaration(path, printClass(path, options, print));
40569 case "TSDeclareFunction":
40570 // For TypeScript the TSDeclareFunction node shares the AST
40571 // structure with FunctionDeclaration
40572 return concat$6([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
40574 case "DeclareFunction":
40575 return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
40577 case "DeclareModule":
40578 return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
40580 case "DeclareModuleExports":
40581 return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
40583 case "DeclareVariable":
40584 return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
40586 case "DeclareExportAllDeclaration":
40587 return concat$6(["declare export * from ", path.call(print, "source")]);
40589 case "DeclareExportDeclaration":
40590 return concat$6(["declare ", printExportDeclaration(path, options, print)]);
40592 case "DeclareOpaqueType":
40595 parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
40598 parts.push(": ", path.call(print, "supertype"));
40602 parts.push(" = ", path.call(print, "impltype"));
40607 if (n.type === "DeclareOpaqueType") {
40608 return printFlowDeclaration(path, parts);
40611 return concat$6(parts);
40614 case "EnumDeclaration":
40615 return concat$6(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
40617 case "EnumBooleanBody":
40618 case "EnumNumberBody":
40619 case "EnumStringBody":
40620 case "EnumSymbolBody":
40622 if (n.type === "EnumSymbolBody" || n.explicitType) {
40626 case "EnumBooleanBody":
40630 case "EnumNumberBody":
40634 case "EnumStringBody":
40638 case "EnumSymbolBody":
40643 parts.push("of ", type, " ");
40646 if (n.members.length === 0) {
40647 parts.push(group$2(concat$6(["{", comments.printDanglingComments(path, options), softline$2, "}"])));
40649 parts.push(group$2(concat$6(["{", indent$3(concat$6([hardline$4, printArrayItems(path, options, "members", print), shouldPrintComma(options) ? "," : ""])), comments.printDanglingComments(path, options,
40651 true), hardline$4, "}"])));
40654 return concat$6(parts);
40657 case "EnumBooleanMember":
40658 case "EnumNumberMember":
40659 case "EnumStringMember":
40660 return concat$6([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
40662 case "EnumDefaultedMember":
40663 return path.call(print, "id");
40665 case "FunctionTypeAnnotation":
40666 case "TSFunctionType":
40668 // FunctionTypeAnnotation is ambiguous:
40669 // declare function foo(a: B): void; OR
40670 // var A: (a: B) => void;
40671 const parent = path.getParentNode(0);
40672 const parentParent = path.getParentNode(1);
40673 const parentParentParent = path.getParentNode(2);
40674 let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(parent) && !parent.optional && options.locStart(parent) === options.locStart(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
40675 let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
40676 // printing ":" as part of the expression and it would put parenthesis
40679 const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression";
40681 if (isObjectTypePropertyAFunction$1(parent, options)) {
40682 isArrowFunctionTypeAnnotation = true;
40690 parts.push(printFunctionParams(path, print, options,
40693 /* printTypeParams */
40694 true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
40695 // needs to be added separately.
40697 if (n.returnType || n.predicate || n.typeAnnotation) {
40698 parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
40705 return group$2(concat$6(parts));
40709 return concat$6(["...", path.call(print, "typeAnnotation")]);
40711 case "TSOptionalType":
40712 return concat$6([path.call(print, "typeAnnotation"), "?"]);
40714 case "FunctionTypeParam":
40715 return concat$6([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
40717 case "GenericTypeAnnotation":
40718 return concat$6([path.call(print, "id"), path.call(print, "typeParameters")]);
40720 case "DeclareInterface":
40721 case "InterfaceDeclaration":
40722 case "InterfaceTypeAnnotation":
40724 if (n.type === "DeclareInterface" || n.declare) {
40725 parts.push("declare ");
40728 parts.push("interface");
40730 if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
40731 parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
40734 if (n.extends.length > 0) {
40735 parts.push(group$2(indent$3(concat$6([line$4, "extends ", (n.extends.length === 1 ? identity$2 : indent$3)(join$4(concat$6([",", line$4]), path.map(print, "extends")))]))));
40738 parts.push(" ", path.call(print, "body"));
40739 return group$2(concat$6(parts));
40742 case "ClassImplements":
40743 case "InterfaceExtends":
40744 return concat$6([path.call(print, "id"), path.call(print, "typeParameters")]);
40746 case "TSClassImplements":
40747 return concat$6([path.call(print, "expression"), path.call(print, "typeParameters")]);
40749 case "TSIntersectionType":
40750 case "IntersectionTypeAnnotation":
40752 const types = path.map(print, "types");
40754 let wasIndented = false;
40756 for (let i = 0; i < types.length; ++i) {
40758 result.push(types[i]);
40759 } else if (isObjectType$1(n.types[i - 1]) && isObjectType$1(n.types[i])) {
40760 // If both are objects, don't indent
40761 result.push(concat$6([" & ", wasIndented ? indent$3(types[i]) : types[i]]));
40762 } else if (!isObjectType$1(n.types[i - 1]) && !isObjectType$1(n.types[i])) {
40763 // If no object is involved, go to the next line if it breaks
40764 result.push(indent$3(concat$6([" &", line$4, types[i]])));
40766 // If you go from object to non-object or vis-versa, then inline it
40768 wasIndented = true;
40771 result.push(" & ", i > 1 ? indent$3(types[i]) : types[i]);
40775 return group$2(concat$6(result));
40778 case "TSUnionType":
40779 case "UnionTypeAnnotation":
40781 // single-line variation
40783 // multi-line variation
40787 const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
40789 const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // {
40792 // should be inlined and not be printed in the multi-line variant
40794 const shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
40799 const printed = path.map(typePath => {
40800 let printedType = typePath.call(print);
40803 printedType = align$1(2, printedType);
40806 return comments.printComments(typePath, () => printedType, options);
40810 return join$4(" | ", printed);
40813 const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
40814 const code = concat$6([ifBreak$1(concat$6([shouldAddStartLine ? line$4 : "", "| "])), join$4(concat$6([line$4, "| "]), printed)]);
40816 if (needsParens_1(path, options)) {
40817 return group$2(concat$6([indent$3(code), softline$2]));
40820 if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
40821 return group$2(concat$6([indent$3(concat$6([ifBreak$1(concat$6(["(", softline$2])), code])), softline$2, ifBreak$1(")")]));
40824 return group$2(shouldIndent ? indent$3(code) : code);
40827 case "NullableTypeAnnotation":
40828 return concat$6(["?", path.call(print, "typeAnnotation")]);
40830 case "TSNullKeyword":
40831 case "NullLiteralTypeAnnotation":
40834 case "ThisTypeAnnotation":
40837 case "NumberTypeAnnotation":
40840 case "SymbolTypeAnnotation":
40843 case "ObjectTypeCallProperty":
40845 parts.push("static ");
40848 parts.push(path.call(print, "value"));
40849 return concat$6(parts);
40851 case "ObjectTypeIndexer":
40853 const variance = getFlowVariance$1(n);
40854 return concat$6([variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
40857 case "ObjectTypeProperty":
40859 const variance = getFlowVariance$1(n);
40863 modifier = "proto ";
40864 } else if (n.static) {
40865 modifier = "static ";
40868 return concat$6([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", variance || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
40871 case "QualifiedTypeIdentifier":
40872 return concat$6([path.call(print, "qualification"), ".", path.call(print, "id")]);
40874 case "StringLiteralTypeAnnotation":
40875 return nodeStr(n, options);
40877 case "NumberLiteralTypeAnnotation":
40878 assert$1.strictEqual(typeof n.value, "number");
40880 if (n.extra != null) {
40881 return printNumber$1(n.extra.raw);
40884 return printNumber$1(n.raw);
40886 case "StringTypeAnnotation":
40889 case "DeclareTypeAlias":
40892 if (n.type === "DeclareTypeAlias" || n.declare) {
40893 parts.push("declare ");
40896 const printed = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
40897 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
40898 return group$2(concat$6(parts));
40901 case "TypeCastExpression":
40903 return concat$6(["(", path.call(print, "expression"), printTypeAnnotation(path, options, print), ")"]);
40906 case "TypeParameterDeclaration":
40907 case "TypeParameterInstantiation":
40909 const value = path.getValue();
40910 const commentStart = value.range ? options.originalText.slice(0, value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
40911 // because we know for sure that this is a type definition.
40913 const commentSyntax = commentStart >= 0 && options.originalText.slice(commentStart).match(/^\/\*\s*::/);
40915 if (commentSyntax) {
40916 return concat$6(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
40919 return printTypeParameters(path, options, print, "params");
40922 case "TSTypeParameterDeclaration":
40923 case "TSTypeParameterInstantiation":
40924 return printTypeParameters(path, options, print, "params");
40926 case "TSTypeParameter":
40927 case "TypeParameter":
40929 const parent = path.getParentNode();
40931 if (parent.type === "TSMappedType") {
40932 parts.push("[", path.call(print, "name"));
40934 if (n.constraint) {
40935 parts.push(" in ", path.call(print, "constraint"));
40939 return concat$6(parts);
40942 const variance = getFlowVariance$1(n);
40945 parts.push(variance);
40948 parts.push(path.call(print, "name"));
40952 parts.push(path.call(print, "bound"));
40955 if (n.constraint) {
40956 parts.push(" extends ", path.call(print, "constraint"));
40960 parts.push(" = ", path.call(print, "default"));
40961 } // Keep comma if the file extension is .tsx and
40962 // has one type parameter that isn't extend with any types.
40963 // Because, otherwise formatted result will be invalid as tsx.
40966 const grandParent = path.getNode(2);
40968 if (parent.params && parent.params.length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") {
40972 return concat$6(parts);
40975 case "TypeofTypeAnnotation":
40976 return concat$6(["typeof ", path.call(print, "argument")]);
40978 case "VoidTypeAnnotation":
40981 case "InferredPredicate":
40983 // Unhandled types below. If encountered, nodes of these types should
40984 // be either left alone or desugared into AST types that are fully
40985 // supported by the pretty-printer.
40987 case "DeclaredPredicate":
40988 return concat$6(["%checks(", path.call(print, "value"), ")"]);
40990 case "TSAbstractKeyword":
40993 case "TSAnyKeyword":
40996 case "TSAsyncKeyword":
40999 case "TSBooleanKeyword":
41002 case "TSBigIntKeyword":
41005 case "TSConstKeyword":
41008 case "TSDeclareKeyword":
41011 case "TSExportKeyword":
41014 case "TSNeverKeyword":
41017 case "TSNumberKeyword":
41020 case "TSObjectKeyword":
41023 case "TSProtectedKeyword":
41024 return "protected";
41026 case "TSPrivateKeyword":
41029 case "TSPublicKeyword":
41032 case "TSReadonlyKeyword":
41035 case "TSSymbolKeyword":
41038 case "TSStaticKeyword":
41041 case "TSStringKeyword":
41044 case "TSUndefinedKeyword":
41045 return "undefined";
41047 case "TSUnknownKeyword":
41050 case "TSVoidKeyword":
41053 case "TSAsExpression":
41054 return concat$6([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
41056 case "TSArrayType":
41057 return concat$6([path.call(print, "elementType"), "[]"]);
41059 case "TSPropertySignature":
41062 parts.push("export ");
41065 if (n.accessibility) {
41066 parts.push(n.accessibility + " ");
41070 parts.push("static ");
41074 parts.push("readonly ");
41077 parts.push(printPropertyKey(path, options, print), printOptionalToken(path));
41079 if (n.typeAnnotation) {
41081 parts.push(path.call(print, "typeAnnotation"));
41082 } // This isn't valid semantically, but it's in the AST so we can print it.
41085 if (n.initializer) {
41086 parts.push(" = ", path.call(print, "initializer"));
41089 return concat$6(parts);
41092 case "TSParameterProperty":
41093 if (n.accessibility) {
41094 parts.push(n.accessibility + " ");
41098 parts.push("export ");
41102 parts.push("static ");
41106 parts.push("readonly ");
41109 parts.push(path.call(print, "parameter"));
41110 return concat$6(parts);
41112 case "TSTypeReference":
41113 return concat$6([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
41115 case "TSTypeQuery":
41116 return concat$6(["typeof ", path.call(print, "exprName")]);
41118 case "TSIndexSignature":
41120 const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
41121 // using them, it makes sense to have a trailing comma. But if you
41122 // aren't, this is more like a computed property name than an array.
41123 // So we leave off the trailing comma when there's just one parameter.
41125 const trailingComma = n.parameters.length > 1 ? ifBreak$1(shouldPrintComma(options) ? "," : "") : "";
41126 const parametersGroup = group$2(concat$6([indent$3(concat$6([softline$2, join$4(concat$6([", ", softline$2]), path.map(print, "parameters"))])), trailingComma, softline$2]));
41127 return concat$6([n.export ? "export " : "", n.accessibility ? concat$6([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]);
41130 case "TSTypePredicate":
41131 return concat$6([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$6([" is ", path.call(print, "typeAnnotation")]) : ""]);
41133 case "TSNonNullExpression":
41134 return concat$6([path.call(print, "expression"), "!"]);
41139 case "TSImportType":
41140 return concat$6([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$6([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
41142 case "TSLiteralType":
41143 return path.call(print, "literal");
41145 case "TSIndexedAccessType":
41146 return concat$6([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
41148 case "TSConstructSignatureDeclaration":
41149 case "TSCallSignatureDeclaration":
41150 case "TSConstructorType":
41152 if (n.type !== "TSCallSignatureDeclaration") {
41153 parts.push("new ");
41156 parts.push(group$2(printFunctionParams(path, print, options,
41159 /* printTypeParams */
41162 if (n.returnType || n.typeAnnotation) {
41163 const isType = n.type === "TSConstructorType";
41164 parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
41167 return concat$6(parts);
41170 case "TSTypeOperator":
41171 return concat$6([n.operator, " ", path.call(print, "typeAnnotation")]);
41173 case "TSMappedType":
41175 const shouldBreak = hasNewlineInRange$3(options.originalText, options.locStart(n), options.locEnd(n));
41176 return group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$4 : softline$2, n.readonly ? concat$6([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$1(semi, "")])), comments.printDanglingComments(path, options,
41178 true), options.bracketSpacing ? line$4 : softline$2, "}"]), {
41183 case "TSMethodSignature":
41184 parts.push(n.accessibility ? concat$6([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path), printFunctionParams(path, print, options,
41187 /* printTypeParams */
41190 if (n.returnType || n.typeAnnotation) {
41191 parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
41194 return group$2(concat$6(parts));
41196 case "TSNamespaceExportDeclaration":
41197 parts.push("export as namespace ", path.call(print, "id"));
41199 if (options.semi) {
41203 return group$2(concat$6(parts));
41205 case "TSEnumDeclaration":
41207 parts.push("declare ");
41211 parts.push(printTypeScriptModifiers(path, options, print));
41215 parts.push("const ");
41218 parts.push("enum ", path.call(print, "id"), " ");
41220 if (n.members.length === 0) {
41221 parts.push(group$2(concat$6(["{", comments.printDanglingComments(path, options), softline$2, "}"])));
41223 parts.push(group$2(concat$6(["{", indent$3(concat$6([hardline$4, printArrayItems(path, options, "members", print), shouldPrintComma(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
41225 true), hardline$4, "}"])));
41228 return concat$6(parts);
41230 case "TSEnumMember":
41231 parts.push(path.call(print, "id"));
41233 if (n.initializer) {
41234 parts.push(" = ", path.call(print, "initializer"));
41237 return concat$6(parts);
41239 case "TSImportEqualsDeclaration":
41241 parts.push("export ");
41244 parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
41246 if (options.semi) {
41250 return group$2(concat$6(parts));
41252 case "TSExternalModuleReference":
41253 return concat$6(["require(", path.call(print, "expression"), ")"]);
41255 case "TSModuleDeclaration":
41257 const parent = path.getParentNode();
41258 const isExternalModule = isLiteral$1(n.id);
41259 const parentIsDeclaration = parent.type === "TSModuleDeclaration";
41260 const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
41262 if (parentIsDeclaration) {
41266 parts.push("declare ");
41269 parts.push(printTypeScriptModifiers(path, options, print));
41270 const textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
41271 // (declare)? global { ... }
41273 const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
41275 if (!isGlobalDeclaration) {
41276 parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
41280 parts.push(path.call(print, "id"));
41282 if (bodyIsDeclaration) {
41283 parts.push(path.call(print, "body"));
41284 } else if (n.body) {
41285 parts.push(" ", group$2(path.call(print, "body")));
41290 return concat$6(parts);
41293 case "PrivateName":
41294 return concat$6(["#", path.call(print, "id")]);
41295 // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
41297 case "TSPrivateIdentifier":
41298 return n.escapedText;
41300 case "TSConditionalType":
41301 return printTernaryOperator(path, options, print, {
41302 beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")],
41303 afterParts: () => [],
41304 shouldCheckJsx: false,
41305 conditionalNodeType: "TSConditionalType",
41306 consequentNodePropertyName: "trueType",
41307 alternateNodePropertyName: "falseType",
41308 testNodePropertyNames: ["checkType", "extendsType"]
41311 case "TSInferType":
41312 return concat$6(["infer", " ", path.call(print, "typeParameter")]);
41314 case "InterpreterDirective":
41315 parts.push("#!", n.value, hardline$4);
41317 if (isNextLineEmpty$2(options.originalText, n, options.locEnd)) {
41318 parts.push(hardline$4);
41321 return concat$6(parts);
41324 return concat$6([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$6([" //", n.node.comments[0].value.trimEnd()])));
41326 case "NGChainedExpression":
41327 return group$2(join$4(concat$6([";", line$4]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$6(["(", print(childPath), ")"]), "expressions")));
41329 case "NGEmptyExpression":
41332 case "NGQuotedExpression":
41333 return concat$6([n.prefix, ": ", n.value.trim()]);
41335 case "NGMicrosyntax":
41336 return concat$6(path.map((childPath, index) => concat$6([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$6([";", line$4]), print(childPath)]), "body"));
41338 case "NGMicrosyntaxKey":
41339 return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
41341 case "NGMicrosyntaxExpression":
41342 return concat$6([path.call(print, "expression"), n.alias === null ? "" : concat$6([" as ", path.call(print, "alias")])]);
41344 case "NGMicrosyntaxKeyedExpression":
41346 const index = path.getName();
41347 const parentNode = path.getParentNode();
41348 const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression";
41349 return concat$6([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
41352 case "NGMicrosyntaxLet":
41353 return concat$6(["let ", path.call(print, "key"), n.value === null ? "" : concat$6([" = ", path.call(print, "value")])]);
41355 case "NGMicrosyntaxAs":
41356 return concat$6([path.call(print, "key"), " as ", path.call(print, "alias")]);
41358 case "ArgumentPlaceholder":
41360 // These are not valid TypeScript. Printing them just for the sake of error recovery.
41362 case "TSJSDocAllType":
41365 case "TSJSDocUnknownType":
41368 case "TSJSDocNullableType":
41369 return concat$6(["?", path.call(print, "typeAnnotation")]);
41371 case "TSJSDocNonNullableType":
41372 return concat$6(["!", path.call(print, "typeAnnotation")]);
41374 case "TSJSDocFunctionType":
41375 return concat$6(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error).
41376 "): ", path.call(print, "typeAnnotation")]);
41379 /* istanbul ignore next */
41380 throw new Error("unknown type: " + JSON.stringify(n.type));
41384 function printStatementSequence(path, options, print) {
41385 const printed = [];
41386 const bodyNode = path.getNode();
41387 const isClass = bodyNode.type === "ClassBody";
41388 path.map((stmtPath, i) => {
41389 const stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
41390 // "statements," it's safer simply to skip them.
41392 /* istanbul ignore if */
41396 } // Skip printing EmptyStatement nodes to avoid leaving stray
41397 // semicolons lying around.
41400 if (stmt.type === "EmptyStatement") {
41404 const stmtPrinted = print(stmtPath);
41405 const text = options.originalText;
41406 const parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
41407 // don't prepend the only JSX element in a program with semicolon
41409 if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
41410 if (stmt.comments && stmt.comments.some(comment => comment.leading)) {
41411 parts.push(print(stmtPath, {
41415 parts.push(";", stmtPrinted);
41418 parts.push(stmtPrinted);
41421 if (!options.semi && isClass) {
41422 if (classPropMayCauseASIProblems$1(stmtPath)) {
41424 } else if (stmt.type === "ClassProperty") {
41425 const nextChild = bodyNode.body[i + 1];
41427 if (classChildNeedsASIProtection$1(nextChild)) {
41433 if (isNextLineEmpty$2(text, stmt, options.locEnd) && !isLastStatement$1(stmtPath)) {
41434 parts.push(hardline$4);
41437 printed.push(concat$6(parts));
41439 return join$4(hardline$4, printed);
41442 function printPropertyKey(path, options, print) {
41443 const node = path.getNode();
41445 if (node.computed) {
41446 return concat$6(["[", path.call(print, "key"), "]"]);
41449 const parent = path.getParentNode();
41454 if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key
41455 key.type === "Identifier") {
41456 return concat$6(["#", path.call(print, "key")]);
41459 if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
41460 const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToCoerceToIdentifier$1(prop, options));
41461 needsQuoteProps.set(parent, objectHasStringProp);
41464 if (key.type === "Identifier" && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
41466 const prop = printString$1(JSON.stringify(key.name), options);
41467 return path.call(keyPath => comments.printComments(keyPath, () => prop, options), "key");
41470 if (isStringPropSafeToCoerceToIdentifier$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
41472 return path.call(keyPath => comments.printComments(keyPath, () => key.value, options), "key");
41475 return path.call(print, "key");
41478 function printMethod(path, options, print) {
41479 const node = path.getNode();
41483 const value = node.value || node;
41486 if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
41488 parts.push("async ");
41491 if (value.generator) {
41495 assert$1.ok(kind === "get" || kind === "set");
41496 parts.push(kind, " ");
41499 parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value"));
41500 return concat$6(parts);
41503 function printMethodInternal(path, options, print) {
41504 const parts = [printFunctionTypeParameters(path, options, print), group$2(concat$6([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
41506 if (path.getNode().body) {
41507 parts.push(" ", path.call(print, "body"));
41509 parts.push(options.semi ? ";" : "");
41512 return concat$6(parts);
41515 function couldGroupArg(arg) {
41516 return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords
41517 // https://github.com/prettier/prettier/issues/4070
41518 // export class Thing implements OtherThing {
41519 // do: (type: Type) => Provider<Prop> = memoize(
41520 // (type: ObjectType): Provider<Opts> => {}
41523 // https://github.com/prettier/prettier/issues/6099
41524 // app.get("/", (req, res): void => {
41525 // res.send("Hello World!");
41527 !arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode$1(arg.body));
41530 function shouldGroupLastArg(args) {
41531 const lastArg = getLast$2(args);
41532 const penultimateArg = getPenultimate$1(args);
41533 return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
41534 // disable last element expansion.
41535 !penultimateArg || penultimateArg.type !== lastArg.type);
41538 function shouldGroupFirstArg(args) {
41539 if (args.length !== 2) {
41543 const [firstArg, secondArg] = args;
41544 return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg);
41547 function printJestEachTemplateLiteral(node, expressions, options) {
41550 * ${1} | ${1} | ${2}
41551 * ${1} | ${2} | ${3}
41552 * ${2} | ${1} | ${3}
41554 const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
41556 if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) {
41558 const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, {
41559 printWidth: Infinity,
41561 })).formatted + "}");
41562 const tableBody = [{
41563 hasLineBreak: false,
41567 for (let i = 1; i < node.quasis.length; i++) {
41568 const row = tableBody[tableBody.length - 1];
41569 const correspondingExpression = stringifiedExpressions[i - 1];
41570 row.cells.push(correspondingExpression);
41572 if (correspondingExpression.includes("\n")) {
41573 row.hasLineBreak = true;
41576 if (node.quasis[i].value.raw.includes("\n")) {
41578 hasLineBreak: false,
41584 const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length));
41585 const maxColumnWidths = Array.from({
41586 length: maxColumnCount
41590 }, ...tableBody.filter(row => row.cells.length !== 0)];
41594 } of table.filter(row => !row.hasLineBreak)) {
41595 cells.forEach((cell, index) => {
41596 maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell));
41600 parts.push(lineSuffixBoundary$1, "`", indent$3(concat$6([hardline$4, join$4(hardline$4, table.map(row => join$4(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$4, "`");
41601 return concat$6(parts);
41605 function printArgumentsList(path, options, print) {
41606 const node = path.getValue();
41607 const args = node.arguments;
41609 if (args.length === 0) {
41610 return concat$6(["(", comments.printDanglingComments(path, options,
41613 } // useEffect(() => { ... }, [foo, bar, baz])
41616 if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(arg => arg.comments)) {
41617 return concat$6(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
41626 function shouldBreakForArrowFunctionInArguments(arg, argPath) {
41627 if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) {
41631 let shouldBreak = false;
41632 argPath.each(paramPath => {
41633 const printed = concat$6([print(paramPath)]);
41634 shouldBreak = shouldBreak || willBreak$1(printed);
41636 return shouldBreak;
41639 let anyArgEmptyLine = false;
41640 let shouldBreakForArrowFunction = false;
41641 let hasEmptyLineFollowingFirstArg = false;
41642 const lastArgIndex = args.length - 1;
41643 const printedArguments = path.map((argPath, index) => {
41644 const arg = argPath.getNode();
41645 const parts = [print(argPath)];
41647 if (index === lastArgIndex) ; else if (isNextLineEmpty$2(options.originalText, arg, options.locEnd)) {
41649 hasEmptyLineFollowingFirstArg = true;
41652 anyArgEmptyLine = true;
41653 parts.push(",", hardline$4, hardline$4);
41655 parts.push(",", line$4);
41658 shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
41659 return concat$6(parts);
41661 const maybeTrailingComma = // Dynamic imports cannot have trailing commas
41662 !(node.callee && node.callee.type === "Import") && shouldPrintComma(options, "all") ? "," : "";
41664 function allArgsBrokenOut() {
41665 return group$2(concat$6(["(", indent$3(concat$6([line$4, concat$6(printedArguments)])), maybeTrailingComma, line$4, ")"]), {
41670 if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) {
41671 return allArgsBrokenOut();
41674 const shouldGroupFirst = shouldGroupFirstArg(args);
41675 const shouldGroupLast = shouldGroupLastArg(args);
41677 if (shouldGroupFirst || shouldGroupLast) {
41678 const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag
41680 let printedExpanded;
41682 path.each(argPath => {
41683 if (shouldGroupFirst && i === 0) {
41684 printedExpanded = [concat$6([argPath.call(p => print(p, {
41685 expandFirstArg: true
41686 })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$4 : line$4, hasEmptyLineFollowingFirstArg ? hardline$4 : ""])].concat(printedArguments.slice(1));
41689 if (shouldGroupLast && i === args.length - 1) {
41690 printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, {
41691 expandLastArg: true
41697 const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
41698 const simpleConcat = concat$6(["(", concat$6(printedExpanded), ")"]);
41699 return concat$6([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$1(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$6(["(", group$2(printedExpanded[0], {
41701 }), concat$6(printedExpanded.slice(1)), ")"]) : concat$6(["(", concat$6(printedArguments.slice(0, -1)), group$2(getLast$2(printedExpanded), {
41703 }), ")"]), allArgsBrokenOut()], {
41708 const contents = concat$6(["(", indent$3(concat$6([softline$2, concat$6(printedArguments)])), ifBreak$1(maybeTrailingComma), softline$2, ")"]);
41710 if (isLongCurriedCallExpression$1(path)) {
41711 // By not wrapping the arguments in a group, the printer prioritizes
41712 // breaking up these arguments rather than the args of the parent call.
41716 return group$2(contents, {
41717 shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
41721 function printTypeAnnotation(path, options, print) {
41722 const node = path.getValue();
41724 if (!node.typeAnnotation) {
41728 const parentNode = path.getParentNode();
41729 const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
41730 const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
41732 if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
41733 return concat$6([" /*: ", path.call(print, "typeAnnotation"), " */"]);
41736 return concat$6([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
41739 function printFunctionTypeParameters(path, options, print) {
41740 const fun = path.getValue();
41742 if (fun.typeArguments) {
41743 return path.call(print, "typeArguments");
41746 if (fun.typeParameters) {
41747 return path.call(print, "typeParameters");
41753 function printFunctionParams(path, print, options, expandArg, printTypeParams) {
41754 const fun = path.getValue();
41755 const parent = path.getParentNode();
41756 const paramsField = fun.parameters ? "parameters" : "params";
41757 const isParametersInTestCall = isTestCall$1(parent);
41758 const shouldHugParameters = shouldHugArguments(fun);
41759 const shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments));
41760 const typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
41763 if (fun[paramsField]) {
41764 const lastArgIndex = fun[paramsField].length - 1;
41765 printed = path.map((childPath, index) => {
41767 const param = childPath.getValue();
41768 parts.push(print(childPath));
41770 if (index === lastArgIndex) {
41772 parts.push(",", line$4);
41774 } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
41776 } else if (isNextLineEmpty$2(options.originalText, param, options.locEnd)) {
41777 parts.push(",", hardline$4, hardline$4);
41779 parts.push(",", line$4);
41782 return concat$6(parts);
41787 printed.push(concat$6(["...", path.call(print, "rest")]));
41790 if (printed.length === 0) {
41791 return concat$6([typeParams, "(", comments.printDanglingComments(path, options,
41793 true, comment => getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")"), ")"]);
41796 const lastParam = getLast$2(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
41797 // params of the first/last argument, we don't want the arguments to break and instead
41798 // want the whole expression to be on a new line.
41801 // verylongcall( verylongcall((
41807 if (shouldExpandParameters) {
41808 return group$2(concat$6([removeLines$1(typeParams), "(", concat$6(printed.map(removeLines$1)), ")"]));
41809 } // Single object destructuring should hug
41818 const hasNotParameterDecorator = fun[paramsField].every(param => !param.decorators);
41820 if (shouldHugParameters && hasNotParameterDecorator) {
41821 return concat$6([typeParams, "(", concat$6(printed), ")"]);
41822 } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
41825 if (isParametersInTestCall) {
41826 return concat$6([typeParams, "(", concat$6(printed), ")"]);
41829 const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest;
41831 if (isFlowShorthandWithOneArg) {
41832 if (options.arrowParens === "always") {
41833 return concat$6(["(", concat$6(printed), ")"]);
41836 return concat$6(printed);
41839 const canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
41840 return concat$6([typeParams, "(", indent$3(concat$6([softline$2, concat$6(printed)])), ifBreak$1(canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : ""), softline$2, ")"]);
41843 function shouldPrintParamsWithoutParens(path, options) {
41844 if (options.arrowParens === "always") {
41848 if (options.arrowParens === "avoid") {
41849 const node = path.getValue();
41850 return canPrintParamsWithoutParens(node);
41851 } // Fallback default; should be unreachable
41857 function canPrintParamsWithoutParens(node) {
41858 return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments$1(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType;
41861 function printFunctionDeclaration(path, print, options) {
41862 const n = path.getValue();
41866 parts.push("async ");
41870 parts.push("function* ");
41872 parts.push("function ");
41876 parts.push(path.call(print, "id"));
41879 parts.push(printFunctionTypeParameters(path, options, print), group$2(concat$6([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
41880 return concat$6(parts);
41883 function printReturnType(path, print, options) {
41884 const n = path.getValue();
41885 const returnType = path.call(print, "returnType");
41887 if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
41888 return concat$6([" /*: ", returnType, " */"]);
41891 const parts = [returnType]; // prepend colon to TypeScript type annotation
41893 if (n.returnType && n.returnType.typeAnnotation) {
41894 parts.unshift(": ");
41898 // The return type will already add the colon, but otherwise we
41899 // need to do it ourselves
41900 parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
41903 return concat$6(parts);
41906 function printExportDeclaration(path, options, print) {
41907 const decl = path.getValue();
41908 const semi = options.semi ? ";" : "";
41909 const parts = ["export "];
41910 const isDefault = decl.default || decl.type === "ExportDefaultDeclaration";
41913 parts.push("default ");
41916 parts.push(comments.printDanglingComments(path, options,
41920 if (needsHardlineAfterDanglingComment$1(decl)) {
41921 parts.push(hardline$4);
41924 if (decl.declaration) {
41925 parts.push(path.call(print, "declaration"));
41927 if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction") {
41931 if (decl.specifiers && decl.specifiers.length > 0) {
41932 const specifiers = [];
41933 const defaultSpecifiers = [];
41934 const namespaceSpecifiers = [];
41935 path.each(specifierPath => {
41936 const specifierType = path.getValue().type;
41938 if (specifierType === "ExportSpecifier") {
41939 specifiers.push(print(specifierPath));
41940 } else if (specifierType === "ExportDefaultSpecifier") {
41941 defaultSpecifiers.push(print(specifierPath));
41942 } else if (specifierType === "ExportNamespaceSpecifier") {
41943 namespaceSpecifiers.push(concat$6(["* as ", print(specifierPath)]));
41946 const isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
41947 const isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
41948 const canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || decl.specifiers && decl.specifiers.some(node => node.comments);
41951 if (specifiers.length !== 0) {
41953 printed = group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$4 : softline$2, join$4(concat$6([",", line$4]), specifiers)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$4 : softline$2, "}"]));
41955 printed = concat$6(["{", options.bracketSpacing ? " " : "", concat$6(specifiers), options.bracketSpacing ? " " : "", "}"]);
41959 parts.push(decl.exportKind === "type" ? "type " : "", concat$6(defaultSpecifiers), concat$6([isDefaultFollowed ? ", " : ""]), concat$6(namespaceSpecifiers), concat$6([isNamespaceFollowed ? ", " : ""]), printed);
41965 parts.push(" from ", path.call(print, "source"));
41971 return concat$6(parts);
41974 function printFlowDeclaration(path, parts) {
41975 const parentExportDecl = getParentExportDeclaration$1(path);
41977 if (parentExportDecl) {
41978 assert$1.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
41980 // If the parent node has type DeclareExportDeclaration, then it
41981 // will be responsible for printing the "declare" token. Otherwise
41982 // it needs to be printed with this non-exported declaration node.
41983 parts.unshift("declare ");
41986 return concat$6(parts);
41989 function printTypeScriptModifiers(path, options, print) {
41990 const n = path.getValue();
41992 if (!n.modifiers || !n.modifiers.length) {
41996 return concat$6([join$4(" ", path.map(print, "modifiers")), " "]);
41999 function printTypeParameters(path, options, print, paramsKey) {
42000 const n = path.getValue();
42002 if (!n[paramsKey]) {
42004 } // for TypeParameterDeclaration typeParameters is a single node
42007 if (!Array.isArray(n[paramsKey])) {
42008 return path.call(print, paramsKey);
42011 const grandparent = path.getNode(2);
42012 const greatGrandParent = path.getNode(3);
42013 const greatGreatGrandParent = path.getNode(4);
42014 const isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
42015 const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation" || // See https://github.com/prettier/prettier/pull/6467 for the context.
42016 greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent.type === "TSTypeAnnotation" && greatGrandParent.type !== "ArrowFunctionExpression" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSIntersectionType" && n[paramsKey][0].type !== "IntersectionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType" && n[paramsKey][0].type !== "TSTypeOperator" && n[paramsKey][0].type !== "TSIndexedAccessType" && n[paramsKey][0].type !== "TSArrayType");
42018 function printDanglingCommentsForInline(n) {
42019 if (!hasDanglingComments$1(n)) {
42023 const hasOnlyBlockComments = n.comments.every(comments$1.isBlockComment);
42024 const printed = comments.printDanglingComments(path, options,
42026 hasOnlyBlockComments);
42028 if (hasOnlyBlockComments) {
42032 return concat$6([printed, hardline$4]);
42035 if (shouldInline) {
42036 return concat$6(["<", join$4(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), ">"]);
42039 return group$2(concat$6(["<", indent$3(concat$6([softline$2, join$4(concat$6([",", line$4]), path.map(print, paramsKey))])), ifBreak$1(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma(options, "all") ? "," : ""), softline$2, ">"]));
42042 function printClass(path, options, print) {
42043 const n = path.getValue();
42047 parts.push("abstract ");
42050 parts.push("class");
42053 parts.push(" ", path.call(print, "id"));
42056 parts.push(path.call(print, "typeParameters"));
42057 const partsGroup = [];
42059 if (n.superClass) {
42060 const printed = concat$6(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
42061 // If there is only on extends and there are not comments
42063 if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
42064 parts.push(concat$6([" ", path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")]));
42066 partsGroup.push(group$2(concat$6([line$4, path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")])));
42068 } else if (n.extends && n.extends.length > 0) {
42069 parts.push(" extends ", join$4(", ", path.map(print, "extends")));
42072 if (n.mixins && n.mixins.length > 0) {
42073 partsGroup.push(line$4, "mixins ", group$2(indent$3(join$4(concat$6([",", line$4]), path.map(print, "mixins")))));
42076 if (n.implements && n.implements.length > 0) {
42077 partsGroup.push(line$4, "implements", group$2(indent$3(concat$6([line$4, join$4(concat$6([",", line$4]), path.map(print, "implements"))]))));
42080 if (partsGroup.length > 0) {
42081 parts.push(group$2(indent$3(concat$6(partsGroup))));
42084 if (n.body && n.body.comments && hasLeadingOwnLineComment$1(options.originalText, n.body, options)) {
42085 parts.push(hardline$4);
42090 parts.push(path.call(print, "body"));
42094 function printOptionalToken(path) {
42095 const node = path.getValue();
42097 if (!node.optional || // It's an optional computed method parsed by typescript-estree.
42098 // "?" is printed in `printMethod`.
42099 node.type === "Identifier" && node === path.getParentNode().key) {
42103 if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
42110 function printMemberLookup(path, options, print) {
42111 const property = path.call(print, "property");
42112 const n = path.getValue();
42113 const optional = printOptionalToken(path);
42116 return concat$6([optional, ".", property]);
42119 if (!n.property || isNumericLiteral$1(n.property)) {
42120 return concat$6([optional, "[", property, "]"]);
42123 return group$2(concat$6([optional, "[", indent$3(concat$6([softline$2, property])), softline$2, "]"]));
42126 function printBindExpressionCallee(path, options, print) {
42127 return concat$6(["::", path.call(print, "callee")]);
42128 } // We detect calls on member expressions specially to format a
42129 // common pattern better. The pattern we are looking for is this:
42132 // .map(x => x + 1)
42133 // .filter(x => x > 10)
42134 // .some(x => x % 2)
42136 // The way it is structured in the AST is via a nested sequence of
42137 // MemberExpression and CallExpression. We need to traverse the AST
42138 // and make groups out of it to print it in the desired way.
42141 function printMemberChain(path, options, print) {
42142 // The first phase is to linearize the AST by traversing it down.
42145 // has the following AST structure:
42146 // CallExpression(MemberExpression(CallExpression(Identifier)))
42147 // and we transform it into
42148 // [Identifier, CallExpression, MemberExpression, CallExpression]
42149 const printedNodes = []; // Here we try to retain one typed empty line after each call expression or
42150 // the first group whether it is in parentheses or not
42152 function shouldInsertEmptyLineAfter(node) {
42156 const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$3(originalText, node, options.locEnd);
42157 const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
42158 // line after that parenthesis
42160 if (nextChar === ")") {
42161 return isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1, options.locEnd);
42164 return isNextLineEmpty$2(originalText, node, options.locEnd);
42167 function rec(path) {
42168 const node = path.getValue();
42170 if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish$1(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
42171 printedNodes.unshift({
42173 printed: concat$6([comments.printComments(path, () => concat$6([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$4 : ""])
42175 path.call(callee => rec(callee), "callee");
42176 } else if (isMemberish$1(node)) {
42177 printedNodes.unshift({
42179 needsParens: needsParens_1(path, options),
42180 printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print), options)
42182 path.call(object => rec(object), "object");
42183 } else if (node.type === "TSNonNullExpression") {
42184 printedNodes.unshift({
42186 printed: comments.printComments(path, () => "!", options)
42188 path.call(expression => rec(expression), "expression");
42190 printedNodes.unshift({
42192 printed: path.call(print)
42195 } // Note: the comments of the root node have already been printed, so we
42196 // need to extract this first call without printing them as they would
42197 // if handled inside of the recursive call.
42200 const node = path.getValue();
42201 printedNodes.unshift({
42203 printed: concat$6([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)])
42205 path.call(callee => rec(callee), "callee"); // Once we have a linear list of printed nodes, we want to create groups out
42209 // will be grouped as
42211 // [Identifier, CallExpression],
42212 // [MemberExpression, MemberExpression, CallExpression],
42213 // [MemberExpression, CallExpression],
42214 // [MemberExpression],
42216 // so that we can print it as
42221 // The first group is the first node followed by
42222 // - as many CallExpression as possible
42223 // < fn()()() >.something()
42224 // - as many array accessors as possible
42225 // < fn()[0][1][2] >.something()
42226 // - then, as many MemberExpression as possible but the last one
42227 // < this.items >.something()
42230 let currentGroup = [printedNodes[0]];
42233 for (; i < printedNodes.length; ++i) {
42234 if (printedNodes[i].node.type === "TSNonNullExpression" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
42235 currentGroup.push(printedNodes[i]);
42241 if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
42242 for (; i + 1 < printedNodes.length; ++i) {
42243 if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
42244 currentGroup.push(printedNodes[i]);
42251 groups.push(currentGroup);
42252 currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
42253 // a sequence of CallExpression. To compute it, we keep adding things to the
42254 // group until we has seen a CallExpression in the past and reach a
42255 // MemberExpression
42257 let hasSeenCallExpression = false;
42259 for (; i < printedNodes.length; ++i) {
42260 if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
42261 // [0] should be appended at the end of the group instead of the
42262 // beginning of the next one
42263 if (printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
42264 currentGroup.push(printedNodes[i]);
42268 groups.push(currentGroup);
42270 hasSeenCallExpression = false;
42273 if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
42274 hasSeenCallExpression = true;
42277 currentGroup.push(printedNodes[i]);
42279 if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) {
42280 groups.push(currentGroup);
42282 hasSeenCallExpression = false;
42286 if (currentGroup.length > 0) {
42287 groups.push(currentGroup);
42288 } // There are cases like Object.keys(), Observable.of(), _.values() where
42289 // they are the subject of all the chained calls and therefore should
42290 // be kept on the same line:
42292 // Object.keys(items)
42296 // In order to detect those cases, we use an heuristic: if the first
42297 // node is an identifier with the name starting with a capital
42298 // letter or just a sequence of _$. The rationale is that they are
42299 // likely to be factories.
42302 function isFactory(name) {
42303 return /^[A-Z]|^[_$]+$/.test(name);
42304 } // In case the Identifier is shorter than tab width, we can keep the
42305 // first call in a single line, if it's an ExpressionStatement.
42307 // d3.scaleLinear()
42308 // .domain([0, 100])
42309 // .range([0, width]);
42313 function isShort(name) {
42314 return name.length <= options.tabWidth;
42317 function shouldNotWrap(groups) {
42318 const parent = path.getParentNode();
42319 const isExpression = parent && parent.type === "ExpressionStatement";
42320 const hasComputed = groups[1].length && groups[1][0].node.computed;
42322 if (groups[0].length === 1) {
42323 const firstNode = groups[0][0].node;
42324 return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
42327 const lastNode = getLast$2(groups[0]).node;
42328 return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
42331 const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
42333 function printGroup(printedGroup) {
42334 const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print
42337 if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
42338 return concat$6(["(", ...printed, ")"]);
42341 return concat$6(printed);
42344 function printIndentedGroup(groups) {
42345 if (groups.length === 0) {
42349 return indent$3(group$2(concat$6([hardline$4, join$4(hardline$4, groups.map(printGroup))])));
42352 const printedGroups = groups.map(printGroup);
42353 const oneLine = concat$6(printedGroups);
42354 const cutoff = shouldMerge ? 3 : 2;
42355 const flatGroups = groups.reduce((res, group) => res.concat(group), []);
42356 const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$3(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$1(node.node)) || groups[cutoff] && hasLeadingComment$3(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
42357 // render everything concatenated together.
42359 if (groups.length <= cutoff && !hasComment) {
42360 if (isLongCurriedCallExpression$1(path)) {
42364 return group$2(oneLine);
42365 } // Find out the last node in the first group and check if it has an
42366 // empty line after
42369 const lastNodeBeforeIndent = getLast$2(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
42370 const shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
42371 const expanded = concat$6([printGroup(groups[0]), shouldMerge ? concat$6(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$4 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
42372 const callExpressions = printedNodes.map(({
42374 }) => node).filter(isCallOrOptionalCallExpression$1); // We don't want to print in one line if the chain has:
42376 // * Non-trivial arguments.
42377 // * Any group but the last one has a hard line.
42378 // If the last group is a function it's okay to inline if it fits.
42380 if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$1) ||
42382 * scopes.filter(scope => scope.value !== '').map((scope, i) => {
42383 * // multi line content
42386 ((lastGroupDoc, lastGroupNode) => isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$1(lastGroupDoc))(getLast$2(printedGroups), getLast$2(getLast$2(groups)).node) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1))) {
42387 return group$2(expanded);
42390 return concat$6([// We only need to check `oneLine` because if `expanded` is chosen
42391 // that means that the parent group has already been broken
42393 willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$2 : "", conditionalGroup$1([oneLine, expanded])]);
42396 function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
42397 if (isFacebookTranslationTag) {
42401 if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
42402 return child.length === 1 ? softline$2 : hardline$4;
42408 function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
42409 if (isFacebookTranslationTag) {
42413 if (child.length === 1) {
42414 return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$4 : softline$2;
42418 } // JSX Children are strange, mostly for two reasons:
42419 // 1. JSX reads newlines into string values, instead of skipping them like JS
42420 // 2. up to one whitespace between elements within a line is significant,
42421 // but not between lines.
42423 // Leading, trailing, and lone whitespace all need to
42424 // turn themselves into the rather ugly `{' '}` when breaking.
42426 // We print JSX using the `fill` doc primitive.
42427 // This requires that we give it an array of alternating
42428 // content and whitespace elements.
42429 // To ensure this we add dummy `""` content elements as needed.
42432 function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
42433 const n = path.getValue();
42434 const children = []; // using `map` instead of `each` because it provides `i`
42436 path.map((childPath, i) => {
42437 const child = childPath.getValue();
42439 if (isLiteral$1(child)) {
42440 const text = rawText$1(child); // Contains a non-whitespace character
42442 if (isMeaningfulJSXText$1(child)) {
42443 const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
42445 if (words[0] === "") {
42449 if (/\n/.test(words[0])) {
42450 const next = n.children[i + 1];
42451 children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
42453 children.push(jsxWhitespace);
42459 let endWhitespace; // Ends with whitespace
42461 if (getLast$2(words) === "") {
42463 endWhitespace = words.pop();
42464 } // This was whitespace only without a new line.
42467 if (words.length === 0) {
42471 words.forEach((word, i) => {
42473 children.push(line$4);
42475 children.push(word);
42479 if (endWhitespace !== undefined) {
42480 if (/\n/.test(endWhitespace)) {
42481 const next = n.children[i + 1];
42482 children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$2(children), child, next));
42484 children.push(jsxWhitespace);
42487 const next = n.children[i + 1];
42488 children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$2(children), child, next));
42490 } else if (/\n/.test(text)) {
42491 // Keep (up to one) blank line between tags/expressions/text.
42492 // Note: We don't keep blank lines between text elements.
42493 if (text.match(/\n/g).length > 1) {
42495 children.push(hardline$4);
42499 children.push(jsxWhitespace);
42502 const printedChild = print(childPath);
42503 children.push(printedChild);
42504 const next = n.children[i + 1];
42505 const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next);
42507 if (directlyFollowedByMeaningfulText) {
42508 const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0];
42509 children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next));
42511 children.push(hardline$4);
42516 } // JSX expands children from the inside-out, instead of the outside-in.
42517 // This is both to break children before attributes,
42518 // and to ensure that when children break, their parents do as well.
42520 // Any element that is written without any newlines and fits on a single line
42521 // is left that way.
42522 // Not only that, any user-written-line containing multiple JSX siblings
42523 // should also be kept on one line if possible,
42524 // so each user-written-line is wrapped in its own group.
42526 // Elements that contain newlines or don't fit on a single line (recursively)
42527 // are fully-split, using hardline and shouldBreak: true.
42529 // To support that case properly, all leading and trailing spaces
42530 // are stripped from the list of children, and replaced with a single hardline.
42533 function printJSXElement(path, options, print) {
42534 const n = path.getValue();
42536 if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
42537 return concat$6([path.call(print, "openingElement"), path.call(print, "closingElement")]);
42540 const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
42541 const closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
42543 if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
42544 return concat$6([openingLines, concat$6(path.map(print, "children")), closingLines]);
42545 } // Convert `{" "}` to text nodes containing a space.
42546 // This makes it easy to turn them into `jsxWhitespace` which
42547 // can then print as either a space or `{" "}` when breaking.
42550 n.children = n.children.map(child => {
42551 if (isJSXWhitespaceExpression$1(child)) {
42561 const containsTag = n.children.filter(isJSXNode$1).length > 0;
42562 const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1;
42563 const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
42565 let forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
42566 const isMdxBlock = path.getParentNode().rootMarker === "mdx";
42567 const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
42568 const jsxWhitespace = isMdxBlock ? concat$6([" "]) : ifBreak$1(concat$6([rawJsxWhitespace, softline$2]), " ");
42569 const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
42570 const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
42571 const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // We can end up we multiple whitespace elements with empty string
42572 // content between them.
42573 // We need to remove empty whitespace and softlines before JSX whitespace
42574 // to get the correct output.
42576 for (let i = children.length - 2; i >= 0; i--) {
42577 const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
42578 const isPairOfHardlines = children[i] === hardline$4 && children[i + 1] === "" && children[i + 2] === hardline$4;
42579 const isLineFollowedByJSXWhitespace = (children[i] === softline$2 || children[i] === hardline$4) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
42580 const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$2 || children[i + 2] === hardline$4);
42581 const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
42582 const isPairOfHardOrSoftLines = children[i] === softline$2 && children[i + 1] === "" && children[i + 2] === hardline$4 || children[i] === hardline$4 && children[i + 1] === "" && children[i + 2] === softline$2;
42584 if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
42585 children.splice(i, 2);
42586 } else if (isJSXWhitespaceFollowedByLine) {
42587 children.splice(i + 1, 2);
42589 } // Trim trailing lines (or empty strings)
42592 while (children.length && (isLineNext$1(getLast$2(children)) || isEmpty$1(getLast$2(children)))) {
42594 } // Trim leading lines (or empty strings)
42597 while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
42600 } // Tweak how we format children if outputting this element over multiple lines.
42601 // Also detect whether we will force this element to output over multiple lines.
42604 const multilineChildren = [];
42605 children.forEach((child, i) => {
42606 // There are a number of situations where we need to ensure we display
42607 // whitespace as `{" "}` when outputting this element over multiple lines.
42608 if (child === jsxWhitespace) {
42609 if (i === 1 && children[i - 1] === "") {
42610 if (children.length === 2) {
42611 // Solitary whitespace
42612 multilineChildren.push(rawJsxWhitespace);
42614 } // Leading whitespace
42617 multilineChildren.push(concat$6([rawJsxWhitespace, hardline$4]));
42619 } else if (i === children.length - 1) {
42620 // Trailing whitespace
42621 multilineChildren.push(rawJsxWhitespace);
42623 } else if (children[i - 1] === "" && children[i - 2] === hardline$4) {
42624 // Whitespace after line break
42625 multilineChildren.push(rawJsxWhitespace);
42630 multilineChildren.push(child);
42632 if (willBreak$1(child)) {
42633 forcedBreak = true;
42635 }); // If there is text we use `fill` to fit as much onto each line as possible.
42636 // When there is no text (just tags and expressions) we use `group`
42637 // to output each on a separate line.
42639 const content = containsText ? fill$3(multilineChildren) : group$2(concat$6(multilineChildren), {
42647 const multiLineElem = group$2(concat$6([openingLines, indent$3(concat$6([hardline$4, content])), hardline$4, closingLines]));
42650 return multiLineElem;
42653 return conditionalGroup$1([group$2(concat$6([openingLines, concat$6(children), closingLines])), multiLineElem]);
42656 function maybeWrapJSXElementInParens(path, elem, options) {
42657 const parent = path.getParentNode();
42663 const NO_WRAP_PARENTS = {
42664 ArrayExpression: true,
42665 JSXAttribute: true,
42667 JSXExpressionContainer: true,
42669 ExpressionStatement: true,
42670 CallExpression: true,
42671 OptionalCallExpression: true,
42672 ConditionalExpression: true,
42673 JsExpressionRoot: true
42676 if (NO_WRAP_PARENTS[parent.type]) {
42680 const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$1, node => node.type === "JSXExpressionContainer");
42681 const needsParens = needsParens_1(path, options);
42682 return group$2(concat$6([needsParens ? "" : ifBreak$1("("), indent$3(concat$6([softline$2, elem])), softline$2, needsParens ? "" : ifBreak$1(")")]), {
42687 function shouldInlineLogicalExpression(node) {
42688 if (node.type !== "LogicalExpression") {
42692 if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
42696 if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
42700 if (isJSXNode$1(node.right)) {
42705 } // For binary expressions to be consistent, we need to group
42706 // subsequent operators with the same precedence level under a single
42707 // group. Otherwise they will be nested such that some of them break
42708 // onto new lines but not all. Operators with the same precedence
42709 // level should either all break or not. Because we group them by
42710 // precedence level and the AST is structured based on precedence
42711 // level, things are naturally broken up correctly, i.e. `&&` is
42712 // broken before `+`.
42715 function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
42717 const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
42719 if (isBinaryish$1(node)) {
42720 // Put all operators with the same precedence level in the same
42721 // group. The reason we only need to do this with the `left`
42722 // expression is because given an expression like `1 + 2 - 3`, it
42723 // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
42724 // is where the rest of the expression will exist. Binary
42725 // expressions on the right side mean they have a difference
42726 // precedence level and should be treated as a separate group, so
42727 // print them normally. (This doesn't hold for the `**` operator,
42728 // which is unique in that it is right-associative.)
42729 if (shouldFlatten$1(node.operator, node.left.operator)) {
42730 // Flatten them out by recursively calling this function.
42731 parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options,
42733 true, isInsideParenthesis), "left"));
42735 parts.push(path.call(print, "left"));
42738 const shouldInline = shouldInlineLogicalExpression(node);
42739 const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
42740 const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
42741 const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$2(indent$3(concat$6([softline$2, ": ", join$4(concat$6([softline$2, ":", ifBreak$1(" ")]), path.map(print, "arguments").map(arg => align$1(2, group$2(arg))))]))) : "";
42742 const right = shouldInline ? concat$6([operator, " ", path.call(print, "right"), rightSuffix]) : concat$6([lineBeforeOperator ? softline$2 : "", operator, lineBeforeOperator ? " " : line$4, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
42743 // in order to avoid having a small right part like -1 be on its own line.
42745 const parent = path.getParentNode();
42746 const shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
42747 parts.push(" ", shouldGroup ? group$2(right) : right); // The root comments are already printed, but we need to manually print
42748 // the other ones since we don't call the normal print on BinaryExpression,
42749 // only for the left and right parts
42751 if (isNested && node.comments) {
42752 parts = comments.printComments(path, () => concat$6(parts), options);
42755 // Our stopping case. Simply print the node normally.
42756 parts.push(path.call(print));
42762 function printAssignmentRight(leftNode, rightNode, printedRight, options) {
42763 if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
42764 return indent$3(concat$6([line$4, printedRight]));
42767 const canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
42768 options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
42771 return group$2(indent$3(concat$6([line$4, printedRight])));
42774 return concat$6([" ", printedRight]);
42777 function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
42779 return printedLeft;
42782 const printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
42783 return group$2(concat$6([printedLeft, operator, printed]));
42786 function adjustClause(node, clause, forceSpace) {
42787 if (node.type === "EmptyStatement") {
42791 if (node.type === "BlockStatement" || forceSpace) {
42792 return concat$6([" ", clause]);
42795 return indent$3(concat$6([line$4, clause]));
42798 function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
42799 const raw = rawText$1(node);
42800 const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
42801 return printString$1(raw, options, isDirectiveLiteral);
42804 function printRegex(node) {
42805 const flags = node.flags.split("").sort().join("");
42806 return `/${node.pattern}/${flags}`;
42809 function exprNeedsASIProtection(path, options) {
42810 const node = path.getValue();
42811 const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$1(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
42813 if (maybeASIProblem) {
42817 if (!hasNakedLeftSide$2(node)) {
42821 return path.call(childPath => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node));
42824 function stmtNeedsASIProtection(path, options) {
42825 const node = path.getNode();
42827 if (node.type !== "ExpressionStatement") {
42831 return path.call(childPath => exprNeedsASIProtection(childPath, options), "expression");
42834 function shouldHugType(node) {
42835 if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
42839 if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
42840 const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length;
42841 const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
42842 n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference");
42844 if (node.types.length - 1 === voidCount && hasObject) {
42852 function shouldHugArguments(fun) {
42853 if (!fun || fun.rest) {
42857 const params = fun.params || fun.parameters;
42859 if (!params || params.length !== 1) {
42863 const param = params[0];
42864 return !param.comments && (param.type === "ObjectPattern" || param.type === "ArrayPattern" || param.type === "Identifier" && param.typeAnnotation && (param.typeAnnotation.type === "TypeAnnotation" || param.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(param.typeAnnotation.typeAnnotation) || param.type === "FunctionTypeParam" && isObjectType$1(param.typeAnnotation) || param.type === "AssignmentPattern" && (param.left.type === "ObjectPattern" || param.left.type === "ArrayPattern") && (param.right.type === "Identifier" || param.right.type === "ObjectExpression" && param.right.properties.length === 0 || param.right.type === "ArrayExpression" && param.right.elements.length === 0));
42867 function printArrayItems(path, options, printPath, print) {
42868 const printedElements = [];
42869 let separatorParts = [];
42870 path.each(childPath => {
42871 printedElements.push(concat$6(separatorParts));
42872 printedElements.push(group$2(print(childPath)));
42873 separatorParts = [",", line$4];
42875 if (childPath.getValue() && isNextLineEmpty$2(options.originalText, childPath.getValue(), options.locEnd)) {
42876 separatorParts.push(softline$2);
42879 return concat$6(printedElements);
42882 function printReturnAndThrowArgument(path, options, print) {
42883 const node = path.getValue();
42884 const semi = options.semi ? ";" : "";
42887 if (node.argument) {
42888 if (returnArgumentHasLeadingComment$1(options, node.argument)) {
42889 parts.push(concat$6([" (", indent$3(concat$6([hardline$4, path.call(print, "argument")])), hardline$4, ")"]));
42890 } else if (isBinaryish$1(node.argument) || node.argument.type === "SequenceExpression") {
42891 parts.push(group$2(concat$6([ifBreak$1(" (", " "), indent$3(concat$6([softline$2, path.call(print, "argument")])), softline$2, ifBreak$1(")")])));
42893 parts.push(" ", path.call(print, "argument"));
42897 const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1];
42898 const isLastCommentLine = lastComment && (lastComment.type === "CommentLine" || lastComment.type === "Line");
42900 if (isLastCommentLine) {
42904 if (hasDanglingComments$1(node)) {
42905 parts.push(" ", comments.printDanglingComments(path, options,
42910 if (!isLastCommentLine) {
42914 return concat$6(parts);
42917 function willPrintOwnComments(path
42920 const node = path.getValue();
42921 const parent = path.getParentNode();
42922 return (node && (isJSXNode$1(node) || hasFlowShorthandAnnotationComment$2(node) || parent && (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && (hasFlowAnnotationComment$1(node.leadingComments) || hasFlowAnnotationComment$1(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && (!hasIgnoreComment$2(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType");
42925 function canAttachComment(node) {
42926 return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
42929 function printComment$1(commentPath, options) {
42930 const comment = commentPath.getValue();
42932 switch (comment.type) {
42933 case "CommentBlock":
42936 if (isIndentableBlockComment(comment)) {
42937 const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
42938 // printed as a `lineSuffix` which causes the comments to be
42939 // interleaved. See https://github.com/prettier/prettier/issues/4412
42941 if (comment.trailing && !hasNewline$4(options.originalText, options.locStart(comment), {
42944 return concat$6([hardline$4, printed]);
42950 const commentEnd = options.locEnd(comment);
42951 const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
42952 return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
42955 case "CommentLine":
42957 // Print shebangs with the proper comment characters
42958 if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
42959 return "#!" + comment.value.trimEnd();
42962 return "//" + comment.value.trimEnd();
42965 throw new Error("Not a comment: " + JSON.stringify(comment));
42969 function isIndentableBlockComment(comment) {
42970 // If the comment has multiple lines and every line starts with a star
42971 // we can fix the indentation of each line. The stars in the `/*` and
42972 // `*/` delimiters are not included in the comment value, so add them
42974 const lines = `*${comment.value}*`.split("\n");
42975 return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
42978 function printIndentableBlockComment(comment) {
42979 const lines = comment.value.split("\n");
42980 return concat$6(["/*", join$4(hardline$4, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]);
42983 var printerEstree = {
42984 preprocess: preprocess_1,
42985 print: genericPrint,
42987 insertPragma: insertPragma$1,
42988 massageAstNode: clean_1,
42989 hasPrettierIgnore: hasPrettierIgnore$1,
42990 willPrintOwnComments,
42992 printComment: printComment$1,
42993 isBlockComment: comments$1.isBlockComment,
42995 ownLine: comments$1.handleOwnLineComment,
42996 endOfLine: comments$1.handleEndOfLineComment,
42997 remaining: comments$1.handleRemainingComment
42999 getGapRegex: comments$1.getGapRegex,
43000 getCommentChildNodes: comments$1.getCommentChildNodes
43005 hardline: hardline$5,
43008 } = document.builders;
43010 function genericPrint$1(path, options, print) {
43011 const node = path.getValue();
43013 switch (node.type) {
43015 return concat$7([path.call(print, "node"), hardline$5]);
43017 case "ArrayExpression":
43018 return node.elements.length === 0 ? "[]" : concat$7(["[", indent$4(concat$7([hardline$5, join$5(concat$7([",", hardline$5]), path.map(print, "elements"))])), hardline$5, "]"]);
43020 case "ObjectExpression":
43021 return node.properties.length === 0 ? "{}" : concat$7(["{", indent$4(concat$7([hardline$5, join$5(concat$7([",", hardline$5]), path.map(print, "properties"))])), hardline$5, "}"]);
43023 case "ObjectProperty":
43024 return concat$7([path.call(print, "key"), ": ", path.call(print, "value")]);
43026 case "UnaryExpression":
43027 return concat$7([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
43029 case "NullLiteral":
43032 case "BooleanLiteral":
43033 return node.value ? "true" : "false";
43035 case "StringLiteral":
43036 case "NumericLiteral":
43037 return JSON.stringify(node.value);
43040 return JSON.stringify(node.name);
43043 /* istanbul ignore next */
43044 throw new Error("unknown type: " + JSON.stringify(node.type));
43048 function clean$1(node, newNode
43051 delete newNode.start;
43052 delete newNode.end;
43053 delete newNode.extra;
43054 delete newNode.loc;
43055 delete newNode.comments;
43056 delete newNode.errors;
43058 if (node.type === "Identifier") {
43060 type: "StringLiteral",
43065 if (node.type === "UnaryExpression" && node.operator === "+") {
43066 return newNode.argument;
43070 var printerEstreeJson = {
43071 preprocess: preprocess_1,
43072 print: genericPrint$1,
43073 massageAstNode: clean$1
43076 const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
43078 var commonOptions = {
43081 category: CATEGORY_COMMON,
43084 description: "Print spaces between brackets.",
43085 oppositeDescription: "Do not print spaces between brackets."
43089 category: CATEGORY_COMMON,
43092 description: "Use single quotes instead of double quotes."
43096 category: CATEGORY_COMMON,
43105 description: "How to wrap prose.",
43109 description: "Wrap prose if it exceeds the print width."
43113 description: "Do not wrap prose."
43117 description: "Wrap prose as-is."
43122 const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
43127 category: CATEGORY_JAVASCRIPT,
43136 description: "Include parentheses around a sole arrow function parameter.",
43139 description: "Always include parens. Example: `(x) => x`"
43142 description: "Omit parens when possible. Example: `x => x`"
43145 bracketSpacing: commonOptions.bracketSpacing,
43146 jsxBracketSameLine: {
43148 category: CATEGORY_JAVASCRIPT,
43151 description: "Put > on the last line instead of at a new line."
43155 category: CATEGORY_JAVASCRIPT,
43158 description: "Print semicolons.",
43159 oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
43161 singleQuote: commonOptions.singleQuote,
43164 category: CATEGORY_JAVASCRIPT,
43167 description: "Use single quotes in JSX."
43171 category: CATEGORY_JAVASCRIPT,
43173 default: "as-needed",
43174 description: "Change when properties in objects are quoted.",
43176 value: "as-needed",
43177 description: "Only add quotes around object properties where required."
43179 value: "consistent",
43180 description: "If at least one property in an object requires quotes, quote all properties."
43183 description: "Respect the input use of quotes in object properties."
43188 category: CATEGORY_JAVASCRIPT,
43200 description: "Print trailing commas wherever possible when multi-line.",
43203 description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
43206 description: "No trailing commas."
43209 description: "Trailing commas wherever possible (including function arguments)."
43214 var createLanguage = function (linguistData, override) {
43218 rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]);
43220 return Object.assign({
43221 linguistLanguageId: languageId
43222 }, rest, {}, override(linguistData));
43225 var name$2 = "JavaScript";
43226 var type = "programming";
43227 var tmScope = "source.js";
43228 var aceMode = "javascript";
43229 var codemirrorMode = "javascript";
43230 var codemirrorMimeType = "text/javascript";
43231 var color = "#f1e05a";
43262 var interpreters = [
43273 var languageId = 183;
43279 codemirrorMode: codemirrorMode,
43280 codemirrorMimeType: codemirrorMimeType,
43283 extensions: extensions,
43284 filenames: filenames,
43285 interpreters: interpreters,
43286 languageId: languageId
43289 var JavaScript$1 = /*#__PURE__*/Object.freeze({
43295 codemirrorMode: codemirrorMode,
43296 codemirrorMimeType: codemirrorMimeType,
43299 extensions: extensions,
43300 filenames: filenames,
43301 interpreters: interpreters,
43302 languageId: languageId,
43303 'default': JavaScript
43306 var name$3 = "JSX";
43307 var type$1 = "programming";
43308 var group$3 = "JavaScript";
43309 var extensions$1 = [
43312 var tmScope$1 = "source.js.jsx";
43313 var aceMode$1 = "javascript";
43314 var codemirrorMode$1 = "jsx";
43315 var codemirrorMimeType$1 = "text/jsx";
43316 var languageId$1 = 178;
43321 extensions: extensions$1,
43322 tmScope: tmScope$1,
43323 aceMode: aceMode$1,
43324 codemirrorMode: codemirrorMode$1,
43325 codemirrorMimeType: codemirrorMimeType$1,
43326 languageId: languageId$1
43329 var JSX$1 = /*#__PURE__*/Object.freeze({
43334 extensions: extensions$1,
43335 tmScope: tmScope$1,
43336 aceMode: aceMode$1,
43337 codemirrorMode: codemirrorMode$1,
43338 codemirrorMimeType: codemirrorMimeType$1,
43339 languageId: languageId$1,
43343 var name$4 = "TypeScript";
43344 var type$2 = "programming";
43345 var color$1 = "#2b7489";
43349 var interpreters$1 = [
43353 var extensions$2 = [
43356 var tmScope$2 = "source.ts";
43357 var aceMode$2 = "typescript";
43358 var codemirrorMode$2 = "javascript";
43359 var codemirrorMimeType$2 = "application/typescript";
43360 var languageId$2 = 378;
43365 aliases: aliases$1,
43366 interpreters: interpreters$1,
43367 extensions: extensions$2,
43368 tmScope: tmScope$2,
43369 aceMode: aceMode$2,
43370 codemirrorMode: codemirrorMode$2,
43371 codemirrorMimeType: codemirrorMimeType$2,
43372 languageId: languageId$2
43375 var TypeScript$1 = /*#__PURE__*/Object.freeze({
43380 aliases: aliases$1,
43381 interpreters: interpreters$1,
43382 extensions: extensions$2,
43383 tmScope: tmScope$2,
43384 aceMode: aceMode$2,
43385 codemirrorMode: codemirrorMode$2,
43386 codemirrorMimeType: codemirrorMimeType$2,
43387 languageId: languageId$2,
43388 'default': TypeScript
43391 var name$5 = "TSX";
43392 var type$3 = "programming";
43393 var group$4 = "TypeScript";
43394 var extensions$3 = [
43397 var tmScope$3 = "source.tsx";
43398 var aceMode$3 = "javascript";
43399 var codemirrorMode$3 = "jsx";
43400 var codemirrorMimeType$3 = "text/jsx";
43401 var languageId$3 = 94901924;
43406 extensions: extensions$3,
43407 tmScope: tmScope$3,
43408 aceMode: aceMode$3,
43409 codemirrorMode: codemirrorMode$3,
43410 codemirrorMimeType: codemirrorMimeType$3,
43411 languageId: languageId$3
43414 var TSX$1 = /*#__PURE__*/Object.freeze({
43419 extensions: extensions$3,
43420 tmScope: tmScope$3,
43421 aceMode: aceMode$3,
43422 codemirrorMode: codemirrorMode$3,
43423 codemirrorMimeType: codemirrorMimeType$3,
43424 languageId: languageId$3,
43428 var name$6 = "JSON";
43429 var type$4 = "data";
43430 var tmScope$4 = "source.json";
43431 var aceMode$4 = "json";
43432 var codemirrorMode$4 = "javascript";
43433 var codemirrorMimeType$4 = "application/json";
43434 var searchable = false;
43435 var extensions$4 = [
43442 ".JSON-tmLanguage",
43453 var filenames$1 = [
43462 var languageId$4 = 174;
43466 tmScope: tmScope$4,
43467 aceMode: aceMode$4,
43468 codemirrorMode: codemirrorMode$4,
43469 codemirrorMimeType: codemirrorMimeType$4,
43470 searchable: searchable,
43471 extensions: extensions$4,
43472 filenames: filenames$1,
43473 languageId: languageId$4
43476 var _JSON$1 = /*#__PURE__*/Object.freeze({
43480 tmScope: tmScope$4,
43481 aceMode: aceMode$4,
43482 codemirrorMode: codemirrorMode$4,
43483 codemirrorMimeType: codemirrorMimeType$4,
43484 searchable: searchable,
43485 extensions: extensions$4,
43486 filenames: filenames$1,
43487 languageId: languageId$4,
43491 var name$7 = "JSON with Comments";
43492 var type$5 = "data";
43493 var group$5 = "JSON";
43494 var tmScope$5 = "source.js";
43495 var aceMode$5 = "javascript";
43496 var codemirrorMode$5 = "javascript";
43497 var codemirrorMimeType$5 = "text/javascript";
43501 var extensions$5 = [
43504 ".sublime-commands",
43505 ".sublime-completions",
43509 ".sublime-mousemap",
43510 ".sublime-project",
43511 ".sublime-settings",
43513 ".sublime-workspace",
43514 ".sublime_metrics",
43517 var filenames$2 = [
43524 "language-configuration.json",
43527 var languageId$5 = 423;
43528 var JSON_with_Comments = {
43532 tmScope: tmScope$5,
43533 aceMode: aceMode$5,
43534 codemirrorMode: codemirrorMode$5,
43535 codemirrorMimeType: codemirrorMimeType$5,
43536 aliases: aliases$2,
43537 extensions: extensions$5,
43538 filenames: filenames$2,
43539 languageId: languageId$5
43542 var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
43547 tmScope: tmScope$5,
43548 aceMode: aceMode$5,
43549 codemirrorMode: codemirrorMode$5,
43550 codemirrorMimeType: codemirrorMimeType$5,
43551 aliases: aliases$2,
43552 extensions: extensions$5,
43553 filenames: filenames$2,
43554 languageId: languageId$5,
43555 'default': JSON_with_Comments
43558 var name$8 = "JSON5";
43559 var type$6 = "data";
43560 var extensions$6 = [
43563 var tmScope$6 = "source.js";
43564 var aceMode$6 = "javascript";
43565 var codemirrorMode$6 = "javascript";
43566 var codemirrorMimeType$6 = "application/json";
43567 var languageId$6 = 175;
43571 extensions: extensions$6,
43572 tmScope: tmScope$6,
43573 aceMode: aceMode$6,
43574 codemirrorMode: codemirrorMode$6,
43575 codemirrorMimeType: codemirrorMimeType$6,
43576 languageId: languageId$6
43579 var JSON5$1 = /*#__PURE__*/Object.freeze({
43583 extensions: extensions$6,
43584 tmScope: tmScope$6,
43585 aceMode: aceMode$6,
43586 codemirrorMode: codemirrorMode$6,
43587 codemirrorMimeType: codemirrorMimeType$6,
43588 languageId: languageId$6,
43592 var require$$0$1 = getCjsExportFromNamespace(JavaScript$1);
43594 var require$$1 = getCjsExportFromNamespace(JSX$1);
43596 var require$$2 = getCjsExportFromNamespace(TypeScript$1);
43598 var require$$3 = getCjsExportFromNamespace(TSX$1);
43600 var require$$4$1 = getCjsExportFromNamespace(_JSON$1);
43602 var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
43604 var require$$6 = getCjsExportFromNamespace(JSON5$1);
43606 const languages = [createLanguage(require$$0$1, data => ({
43608 parsers: ["babel", "flow"],
43609 vscodeLanguageIds: ["javascript", "mongo"],
43610 interpreters: data.interpreters.concat(["nodejs"])
43611 })), createLanguage(require$$0$1, () => ({
43614 parsers: ["babel", "flow"],
43615 vscodeLanguageIds: ["javascript"],
43618 extensions: [".js.flow"]
43619 })), createLanguage(require$$1, () => ({
43621 parsers: ["babel", "flow"],
43622 vscodeLanguageIds: ["javascriptreact"]
43623 })), createLanguage(require$$2, () => ({
43625 parsers: ["typescript", "babel-ts"],
43626 vscodeLanguageIds: ["typescript"]
43627 })), createLanguage(require$$3, () => ({
43629 parsers: ["typescript", "babel-ts"],
43630 vscodeLanguageIds: ["typescriptreact"]
43631 })), createLanguage(require$$4$1, () => ({
43632 name: "JSON.stringify",
43634 parsers: ["json-stringify"],
43635 vscodeLanguageIds: ["json"],
43637 // .json file defaults to json instead of json-stringify
43638 filenames: ["package.json", "package-lock.json", "composer.json"]
43639 })), createLanguage(require$$4$1, data => ({
43642 vscodeLanguageIds: ["json"],
43643 filenames: data.filenames.concat([".prettierrc"])
43644 })), createLanguage(require$$5, data => ({
43647 vscodeLanguageIds: ["jsonc"],
43648 filenames: data.filenames.concat([".eslintrc"])
43649 })), createLanguage(require$$6, () => ({
43651 parsers: ["json5"],
43652 vscodeLanguageIds: ["json5"]
43655 estree: printerEstree,
43656 "estree-json": printerEstreeJson
43660 options: options$2,
43664 function clean$2(ast, newObj, parent) {
43665 ["raw", // front-matter
43666 "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => {
43667 delete newObj[name];
43670 if (ast.type === "yaml") {
43671 delete newObj.value;
43672 } // --insert-pragma
43675 if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment
43676 parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) {
43682 delete newObj.text; // standalone pragma
43684 if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
43689 if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
43690 delete newObj.value;
43693 if (ast.type === "css-rule") {
43694 delete newObj.params;
43697 if (ast.type === "selector-combinator") {
43698 newObj.value = newObj.value.replace(/\s+/g, " ");
43701 if (ast.type === "media-feature") {
43702 newObj.value = newObj.value.replace(/ /g, "");
43705 if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].includes(newObj.value.replace().toLowerCase())) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") {
43706 newObj.value = newObj.value.toLowerCase();
43709 if (ast.type === "css-decl") {
43710 newObj.prop = newObj.prop.toLowerCase();
43713 if (ast.type === "css-atrule" || ast.type === "css-import") {
43714 newObj.name = newObj.name.toLowerCase();
43717 if (ast.type === "value-number") {
43718 newObj.unit = newObj.unit.toLowerCase();
43721 if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) {
43722 newObj.value = cleanCSSStrings(newObj.value);
43725 if (ast.type === "selector-attribute") {
43726 newObj.attribute = newObj.attribute.trim();
43728 if (newObj.namespace) {
43729 if (typeof newObj.namespace === "string") {
43730 newObj.namespace = newObj.namespace.trim();
43732 if (newObj.namespace.length === 0) {
43733 newObj.namespace = true;
43738 if (newObj.value) {
43739 newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
43740 delete newObj.quoted;
43744 if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) {
43745 newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, (match, numStr, unit) => {
43746 const num = Number(numStr);
43747 return isNaN(num) ? match : num + unit.toLowerCase();
43751 if (ast.type === "selector-tag") {
43752 const lowercasedValue = ast.value.toLowerCase();
43754 if (["from", "to"].includes(lowercasedValue)) {
43755 newObj.value = lowercasedValue;
43757 } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
43760 if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
43761 delete newObj.value;
43762 } // Workaround for SCSS nested properties
43765 if (ast.type === "selector-unknown") {
43766 delete newObj.value;
43770 function cleanCSSStrings(value) {
43771 return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
43774 var clean_1$1 = clean$2;
43778 hardline: hardline$6,
43779 literalline: literalline$3,
43781 markAsRoot: markAsRoot$1
43788 function embed$1(path, print, textToDoc
43791 const node = path.getValue();
43793 if (node.type === "yaml") {
43794 return markAsRoot$1(concat$8(["---", hardline$6, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
43796 })) : "", "---", hardline$6]));
43801 function replaceNewlinesWithLiterallines(doc) {
43802 return mapDoc$2(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$8(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$3)) : currentDoc);
43806 var embed_1$1 = embed$1;
43808 const DELIMITER_MAP = {
43813 function parse$5(text) {
43814 const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp$2).join("|");
43815 const match = text.match( // trailing spaces after delimiters are allowed
43816 new RegExp(`^(${delimiterRegex})[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
43818 if (match === null) {
43825 const [raw, delimiter, value] = match;
43828 type: DELIMITER_MAP[delimiter],
43830 raw: raw.replace(/\n$/, "")
43832 content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
43836 var frontMatter = parse$5;
43838 function hasPragma$1(text) {
43839 return pragma.hasPragma(frontMatter(text).content);
43842 function insertPragma$2(text) {
43844 frontMatter: frontMatter$1,
43846 } = frontMatter(text);
43847 return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content);
43851 hasPragma: hasPragma$1,
43852 insertPragma: insertPragma$2
43855 var lineColumnToIndex = function (lineColumn, text) {
43858 for (let i = 0; i < lineColumn.line - 1; ++i) {
43859 index = text.indexOf("\n", index) + 1;
43861 if (index === -1) {
43866 return index + lineColumn.column;
43870 getLast: getLast$3,
43871 skipEverythingButNewLine: skipEverythingButNewLine$2
43874 function calculateLocStart(node, text) {
43876 return lineColumnToIndex(node.source.start, text) - 1;
43882 function calculateLocEnd(node, text) {
43883 if (node.type === "css-comment" && node.inline) {
43884 return skipEverythingButNewLine$2(text, node.source.startOffset);
43887 const endNode = node.nodes && getLast$3(node.nodes);
43889 if (endNode && node.source && !node.source.end) {
43893 if (node.source && node.source.end) {
43894 return lineColumnToIndex(node.source.end, text);
43900 function calculateLoc(node, text) {
43901 if (node && typeof node === "object") {
43903 node.source.startOffset = calculateLocStart(node, text);
43904 node.source.endOffset = calculateLocEnd(node, text);
43907 for (const key in node) {
43908 calculateLoc(node[key], text);
43913 * Workaround for a bug: quotes in inline comments corrupt loc data of subsequent nodes.
43914 * This function replaces the quotes with U+FFFE and U+FFFF. Later, when the comments are printed,
43915 * their content is extracted from the original text or restored by replacing the placeholder
43916 * characters back with quotes.
43917 * - https://github.com/prettier/prettier/issues/7780
43918 * - https://github.com/shellscape/postcss-less/issues/145
43919 * - About noncharacters (U+FFFE and U+FFFF): http://www.unicode.org/faq/private_use.html#nonchar1
43920 * @param text {string}
43924 function replaceQuotesInInlineComments(text) {
43925 /** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */
43927 /** @type {State} */
43928 let state = "initial";
43929 /** @type {State} */
43931 let stateToReturnFromQuotes = "initial";
43932 let inlineCommentStartIndex;
43933 let inlineCommentContainsQuotes = false;
43934 const inlineCommentsToReplace = [];
43936 for (let i = 0; i < text.length; i++) {
43942 state = "single-quotes";
43947 state = "double-quotes";
43951 if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") {
43957 if (c === "*" && text[i - 1] === "/") {
43958 state = "comment-block";
43962 if (c === "/" && text[i - 1] === "/") {
43963 state = "comment-inline";
43964 inlineCommentStartIndex = i - 1;
43970 case "single-quotes":
43971 if (c === "'" && text[i - 1] !== "\\") {
43972 state = stateToReturnFromQuotes;
43973 stateToReturnFromQuotes = "initial";
43976 if (c === "\n" || c === "\r") {
43977 return text; // invalid input
43982 case "double-quotes":
43983 if (c === '"' && text[i - 1] !== "\\") {
43984 state = stateToReturnFromQuotes;
43985 stateToReturnFromQuotes = "initial";
43988 if (c === "\n" || c === "\r") {
43989 return text; // invalid input
43999 if (c === "\n" || c === "\r") {
44000 return text; // invalid input
44004 state = "single-quotes";
44005 stateToReturnFromQuotes = "url";
44010 state = "double-quotes";
44011 stateToReturnFromQuotes = "url";
44017 case "comment-block":
44018 if (c === "/" && text[i - 1] === "*") {
44024 case "comment-inline":
44025 if (c === '"' || c === "'") {
44026 inlineCommentContainsQuotes = true;
44029 if (c === "\n" || c === "\r") {
44030 if (inlineCommentContainsQuotes) {
44031 inlineCommentsToReplace.push([inlineCommentStartIndex, i]);
44035 inlineCommentContainsQuotes = false;
44042 for (const [start, end] of inlineCommentsToReplace) {
44043 text = text.slice(0, start) + text.slice(start, end).replace(/'/g, "\ufffe").replace(/"/g, "\uffff") + text.slice(end);
44049 function restoreQuotesInInlineComments(text) {
44050 return text.replace(/\ufffe/g, "'").replace(/\uffff/g, '"');
44055 replaceQuotesInInlineComments,
44056 restoreQuotesInInlineComments
44059 const colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"];
44061 function getAncestorCounter(path, typeOrTypes) {
44062 const types = [].concat(typeOrTypes);
44066 while (ancestorNode = path.getParentNode(++counter)) {
44067 if (types.includes(ancestorNode.type)) {
44075 function getAncestorNode(path, typeOrTypes) {
44076 const counter = getAncestorCounter(path, typeOrTypes);
44077 return counter === -1 ? null : path.getParentNode(counter);
44080 function getPropOfDeclNode(path) {
44081 const declAncestorNode = getAncestorNode(path, "css-decl");
44082 return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
44085 function isSCSS(parser, text) {
44086 const hasExplicitParserChoice = parser === "less" || parser === "scss";
44087 const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^}:]+|#){|@import[^\n]+(?:url|,)/;
44088 return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
44091 function isWideKeywords(value) {
44092 return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase());
44095 function isKeyframeAtRuleKeywords(path, value) {
44096 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
44097 return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase());
44100 function maybeToLowerCase(value) {
44101 return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
44104 function insideValueFunctionNode(path, functionName) {
44105 const funcAncestorNode = getAncestorNode(path, "value-func");
44106 return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
44109 function insideICSSRuleNode(path) {
44110 const ruleAncestorNode = getAncestorNode(path, "css-rule");
44111 return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
44114 function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
44115 const atRuleNames = [].concat(atRuleNameOrAtRuleNames);
44116 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
44117 return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase());
44120 function insideURLFunctionInImportAtRuleNode(path) {
44121 const node = path.getValue();
44122 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
44123 return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
44126 function isURLFunctionNode(node) {
44127 return node.type === "value-func" && node.value.toLowerCase() === "url";
44130 function isLastNode(path, node) {
44131 const parentNode = path.getParentNode();
44140 return nodes && nodes.indexOf(node) === nodes.length - 1;
44143 function isDetachedRulesetDeclarationNode(node) {
44144 // If a Less file ends up being parsed with the SCSS parser, Less
44145 // variable declarations will be parsed as atrules with names ending
44146 // with a colon, so keep the original case then.
44147 if (!node.selector) {
44151 return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
44154 function isForKeywordNode(node) {
44155 return node.type === "value-word" && ["from", "through", "end"].includes(node.value);
44158 function isIfElseKeywordNode(node) {
44159 return node.type === "value-word" && ["and", "or", "not"].includes(node.value);
44162 function isEachKeywordNode(node) {
44163 return node.type === "value-word" && node.value === "in";
44166 function isMultiplicationNode(node) {
44167 return node.type === "value-operator" && node.value === "*";
44170 function isDivisionNode(node) {
44171 return node.type === "value-operator" && node.value === "/";
44174 function isAdditionNode(node) {
44175 return node.type === "value-operator" && node.value === "+";
44178 function isSubtractionNode(node) {
44179 return node.type === "value-operator" && node.value === "-";
44182 function isModuloNode(node) {
44183 return node.type === "value-operator" && node.value === "%";
44186 function isMathOperatorNode(node) {
44187 return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
44190 function isEqualityOperatorNode(node) {
44191 return node.type === "value-word" && ["==", "!="].includes(node.value);
44194 function isRelationalOperatorNode(node) {
44195 return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value);
44198 function isSCSSControlDirectiveNode(node) {
44199 return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name);
44202 function isSCSSNestedPropertyNode(node) {
44203 if (!node.selector) {
44207 return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
44210 function isDetachedRulesetCallNode(node) {
44211 return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
44214 function isTemplatePlaceholderNode(node) {
44215 return node.name.startsWith("prettier-placeholder");
44218 function isTemplatePropNode(node) {
44219 return node.prop.startsWith("@prettier-placeholder");
44222 function isPostcssSimpleVarNode(currentNode, nextNode) {
44223 return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
44226 function hasComposesNode(node) {
44227 return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
44230 function hasParensAroundNode(node) {
44231 return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null;
44234 function hasEmptyRawBefore(node) {
44235 return node.raws && node.raws.before === "";
44238 function isKeyValuePairNode(node) {
44239 return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
44242 function isKeyValuePairInParenGroupNode(node) {
44243 return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]);
44246 function isSCSSMapItemNode(path) {
44247 const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
44249 if (node.groups.length === 0) {
44253 const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
44255 if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
44259 const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
44261 if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
44263 } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
44266 if (isKeyValuePairInParenGroupNode(parentParentNode)) {
44268 } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
44271 if (parentParentNode.type === "value-func") {
44278 function isInlineValueCommentNode(node) {
44279 return node.type === "value-comment" && node.inline;
44282 function isHashNode(node) {
44283 return node.type === "value-word" && node.value === "#";
44286 function isLeftCurlyBraceNode(node) {
44287 return node.type === "value-word" && node.value === "{";
44290 function isRightCurlyBraceNode(node) {
44291 return node.type === "value-word" && node.value === "}";
44294 function isWordNode(node) {
44295 return ["value-word", "value-atword"].includes(node.type);
44298 function isColonNode(node) {
44299 return node.type === "value-colon";
44302 function isMediaAndSupportsKeywords(node) {
44303 return node.value && ["not", "and", "or"].includes(node.value.toLowerCase());
44306 function isColorAdjusterFuncNode(node) {
44307 if (node.type !== "value-func") {
44311 return colorAdjusterFunctions.includes(node.value.toLowerCase());
44312 } // TODO: only check `less` when we don't use `less` to parse `css`
44315 function isLessParser(options) {
44316 return options.parser === "css" || options.parser === "less";
44319 function lastLineHasInlineComment(text) {
44320 return /\/\//.test(text.split(/[\r\n]/).pop());
44324 getAncestorCounter,
44328 insideValueFunctionNode,
44329 insideICSSRuleNode,
44331 insideURLFunctionInImportAtRuleNode,
44332 isKeyframeAtRuleKeywords,
44337 isSCSSControlDirectiveNode,
44338 isDetachedRulesetDeclarationNode,
44339 isRelationalOperatorNode,
44340 isEqualityOperatorNode,
44341 isMultiplicationNode,
44346 isMathOperatorNode,
44350 isIfElseKeywordNode,
44352 hasParensAroundNode,
44354 isSCSSNestedPropertyNode,
44355 isDetachedRulesetCallNode,
44356 isTemplatePlaceholderNode,
44357 isTemplatePropNode,
44358 isPostcssSimpleVarNode,
44359 isKeyValuePairNode,
44360 isKeyValuePairInParenGroupNode,
44362 isInlineValueCommentNode,
44364 isLeftCurlyBraceNode,
44365 isRightCurlyBraceNode,
44368 isMediaAndSupportsKeywords,
44369 isColorAdjusterFuncNode,
44370 lastLineHasInlineComment
44374 insertPragma: insertPragma$3
44377 printNumber: printNumber$2,
44378 printString: printString$2,
44379 hasIgnoreComment: hasIgnoreComment$3,
44380 hasNewline: hasNewline$5
44383 isNextLineEmpty: isNextLineEmpty$3
44386 restoreQuotesInInlineComments: restoreQuotesInInlineComments$1
44393 hardline: hardline$7,
44394 softline: softline$3,
44402 removeLines: removeLines$2
44406 getAncestorNode: getAncestorNode$1,
44407 getPropOfDeclNode: getPropOfDeclNode$1,
44408 maybeToLowerCase: maybeToLowerCase$1,
44409 insideValueFunctionNode: insideValueFunctionNode$1,
44410 insideICSSRuleNode: insideICSSRuleNode$1,
44411 insideAtRuleNode: insideAtRuleNode$1,
44412 insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
44413 isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
44414 isWideKeywords: isWideKeywords$1,
44416 isLastNode: isLastNode$1,
44417 isLessParser: isLessParser$1,
44418 isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1,
44419 isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1,
44420 isRelationalOperatorNode: isRelationalOperatorNode$1,
44421 isEqualityOperatorNode: isEqualityOperatorNode$1,
44422 isMultiplicationNode: isMultiplicationNode$1,
44423 isDivisionNode: isDivisionNode$1,
44424 isAdditionNode: isAdditionNode$1,
44425 isSubtractionNode: isSubtractionNode$1,
44426 isMathOperatorNode: isMathOperatorNode$1,
44427 isEachKeywordNode: isEachKeywordNode$1,
44428 isForKeywordNode: isForKeywordNode$1,
44429 isURLFunctionNode: isURLFunctionNode$1,
44430 isIfElseKeywordNode: isIfElseKeywordNode$1,
44431 hasComposesNode: hasComposesNode$1,
44432 hasParensAroundNode: hasParensAroundNode$1,
44433 hasEmptyRawBefore: hasEmptyRawBefore$1,
44434 isKeyValuePairNode: isKeyValuePairNode$1,
44435 isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
44436 isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
44437 isTemplatePropNode: isTemplatePropNode$1,
44438 isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
44439 isSCSSMapItemNode: isSCSSMapItemNode$1,
44440 isInlineValueCommentNode: isInlineValueCommentNode$1,
44441 isHashNode: isHashNode$1,
44442 isLeftCurlyBraceNode: isLeftCurlyBraceNode$1,
44443 isRightCurlyBraceNode: isRightCurlyBraceNode$1,
44444 isWordNode: isWordNode$1,
44445 isColonNode: isColonNode$1,
44446 isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1,
44447 isColorAdjusterFuncNode: isColorAdjusterFuncNode$1,
44448 lastLineHasInlineComment: lastLineHasInlineComment$1
44451 function shouldPrintComma$1(options) {
44452 switch (options.trailingComma) {
44463 function genericPrint$2(path, options, print) {
44464 const node = path.getValue();
44465 /* istanbul ignore if */
44471 if (typeof node === "string") {
44475 switch (node.type) {
44478 return concat$9([node.raw, hardline$7]);
44482 const nodes = printNodeSequence(path, options, print);
44484 if (nodes.parts.length) {
44485 return concat$9([nodes, options.__isHTMLStyleAttribute ? "" : hardline$7]);
44491 case "css-comment":
44493 const isInlineComment = node.inline || node.raws.inline;
44494 const text = options.originalText.slice(options.locStart(node), options.locEnd(node));
44495 return isInlineComment ? text.trimEnd() : text;
44500 return concat$9([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$9([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$5 : " ", "{", node.nodes.length > 0 ? indent$5(concat$9([hardline$7, printNodeSequence(path, options, print)])) : "", hardline$7, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
44505 const parentNode = path.getParentNode();
44506 return concat$9([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode$1(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$9([" {", indent$5(concat$9([softline$3, printNodeSequence(path, options, print)])), softline$3, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
44511 const parentNode = path.getParentNode();
44512 const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";";
44514 if (isLessParser$1(options)) {
44516 return concat$9([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
44519 if (node.function) {
44520 return concat$9([node.name, concat$9([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
44523 if (node.variable) {
44524 return concat$9(["@", node.name, ": ", node.value ? concat$9([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$9(["{", indent$5(concat$9([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path, options, print)])), softline$3, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
44528 return concat$9(["@", // If a Less file ends up being parsed with the SCSS parser, Less
44529 // variable declarations will be parsed as at-rules with names ending
44530 // with a colon, so keep the original case then.
44531 isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$9([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$9([hardline$7, hardline$7]) : /^\s*\n/.test(node.raws.afterName) ? hardline$7 : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$5(concat$9([" ", path.call(print, "selector")])) : "", node.value ? group$6(concat$9([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$5 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$9([isSCSSControlDirectiveNode$1(node) ? "" : " ", "{", indent$5(concat$9([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path, options, print)])), softline$3, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
44533 // postcss-media-query-parser
44535 case "media-query-list":
44538 path.each(childPath => {
44539 const node = childPath.getValue();
44541 if (node.type === "media-query" && node.value === "") {
44545 parts.push(childPath.call(print));
44547 return group$6(indent$5(join$6(line$5, parts)));
44550 case "media-query":
44552 return concat$9([join$6(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
44557 return adjustNumbers(adjustStrings(node.value, options));
44560 case "media-feature-expression":
44566 return concat$9(["(", concat$9(path.map(print, "nodes")), ")"]);
44569 case "media-feature":
44571 return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
44574 case "media-colon":
44576 return concat$9([node.value, " "]);
44579 case "media-value":
44581 return adjustNumbers(adjustStrings(node.value, options));
44584 case "media-keyword":
44586 return adjustStrings(node.value, options);
44591 return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
44594 case "media-unknown":
44598 // postcss-selector-parser
44600 case "selector-root":
44602 return group$6(concat$9([insideAtRuleNode$1(path, "custom-selector") ? concat$9([getAncestorNode$1(path, "css-atrule").customSelector, line$5]) : "", join$6(concat$9([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$5 : hardline$7]), path.map(print, "nodes"))]));
44605 case "selector-selector":
44607 return group$6(indent$5(concat$9(path.map(print, "nodes"))));
44610 case "selector-comment":
44615 case "selector-string":
44617 return adjustStrings(node.value, options);
44620 case "selector-tag":
44622 const parentNode = path.getParentNode();
44623 const index = parentNode && parentNode.nodes.indexOf(node);
44624 const prevNode = index && parentNode.nodes[index - 1];
44625 return concat$9([node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
44628 case "selector-id":
44630 return concat$9(["#", node.value]);
44633 case "selector-class":
44635 return concat$9([".", adjustNumbers(adjustStrings(node.value, options))]);
44638 case "selector-attribute":
44640 return concat$9(["[", node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]);
44643 case "selector-combinator":
44645 if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
44646 const parentNode = path.getParentNode();
44647 const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$5;
44648 return concat$9([leading, node.value, isLastNode$1(path, node) ? "" : " "]);
44651 const leading = node.value.trim().startsWith("(") ? line$5 : "";
44652 const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$5;
44653 return concat$9([leading, value]);
44656 case "selector-universal":
44658 return concat$9([node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
44661 case "selector-pseudo":
44663 return concat$9([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$9(["(", join$6(", ", path.map(print, "nodes")), ")"]) : ""]);
44666 case "selector-nesting":
44671 case "selector-unknown":
44673 const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
44675 if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
44676 return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
44677 } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js
44680 const parentNode = path.getParentNode();
44682 if (parentNode.raws && parentNode.raws.selector) {
44683 const start = options.locStart(parentNode);
44684 const end = start + parentNode.raws.selector.length;
44685 return options.originalText.slice(start, end).trim();
44690 // postcss-values-parser
44692 case "value-value":
44695 return path.call(print, "group");
44698 case "value-comment":
44700 return concat$9([node.inline ? "//" : "/*", // see replaceQuotesInInlineComments in loc.js
44701 // value-* nodes don't have correct location data, so we have to rely on placeholder characters.
44702 restoreQuotesInInlineComments$1(node.value), node.inline ? "" : "*/"]);
44705 case "value-comma_group":
44707 const parentNode = path.getParentNode();
44708 const parentParentNode = path.getParentNode(1);
44709 const declAncestorProp = getPropOfDeclNode$1(path);
44710 const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
44711 const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
44712 const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
44713 const printed = path.map(print, "groups");
44715 const insideURLFunction = insideValueFunctionNode$1(path, "url");
44716 let insideSCSSInterpolationInString = false;
44717 let didBreak = false;
44719 for (let i = 0; i < node.groups.length; ++i) {
44720 parts.push(printed[i]);
44721 const iPrevNode = node.groups[i - 1];
44722 const iNode = node.groups[i];
44723 const iNextNode = node.groups[i + 1];
44724 const iNextNextNode = node.groups[i + 2];
44726 if (insideURLFunction) {
44727 if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) {
44732 } // Ignore after latest node (i.e. before semicolon)
44737 } // styled.div` background: var(--${one}); `
44740 if (!iPrevNode && iNode.value === "--" && iNextNode.type === "value-atword") {
44742 } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
44745 const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
44746 const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
44748 if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
44749 insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
44753 if (insideSCSSInterpolationInString) {
44755 } // Ignore colon (i.e. `:`)
44758 if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
44760 } // Ignore `@` in Less (i.e. `@@var;`)
44763 if (iNode.type === "value-atword" && iNode.value === "") {
44765 } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
44768 if (iNode.value === "~") {
44770 } // Ignore escape `\`
44773 if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") {
44775 } // Ignore escaped `/`
44778 if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
44780 } // Ignore `\` (i.e. `$variable: \@small;`)
44783 if (iNode.value === "\\") {
44785 } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
44788 if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
44790 } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
44793 if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
44795 } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
44798 if (iNode.value === "--" && isHashNode$1(iNextNode)) {
44800 } // Formatting math operations
44803 const isMathOperator = isMathOperatorNode$1(iNode);
44804 const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
44805 // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
44806 // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
44808 if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
44810 } // Print spaces before and after addition and subtraction math operators as is in `calc` function
44811 // due to the fact that it is not valid syntax
44812 // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
44815 if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
44817 } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
44818 // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
44821 const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
44822 const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
44823 const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
44825 if (!(isMultiplicationNode$1(iNextNode) || isMultiplicationNode$1(iNode)) && !insideValueFunctionNode$1(path, "calc") && !isColorAdjusterNode && (isDivisionNode$1(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode$1(iNode) && !requireSpaceAfterOperator || isAdditionNode$1(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode$1(iNode) && !requireSpaceAfterOperator || isSubtractionNode$1(iNextNode) || isSubtractionNode$1(iNode)) && (hasEmptyRawBefore$1(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode$1(iPrevNode)))) {
44827 } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
44830 if (isInlineValueCommentNode$1(iNode)) {
44831 parts.push(hardline$7);
44833 } // Handle keywords in SCSS control directive
44836 if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
44839 } // At-rule `namespace` should be in one line
44842 if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
44845 } // Formatting `grid` property
44849 if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
44850 parts.push(hardline$7);
44857 } // Add `space` before next math operation
44858 // Note: `grip` property have `/` delimiter and it is not math operation, so
44859 // `grid` property handles above
44862 if (isNextMathOperator) {
44865 } // Be default all values go through `line`
44868 parts.push(line$5);
44872 parts.unshift(hardline$7);
44875 if (isControlDirective) {
44876 return group$6(indent$5(concat$9(parts)));
44877 } // Indent is not needed for import url when url is very long
44878 // and node has two groups
44879 // when type is value-comma_group
44880 // example @import url("verylongurl") projection,tv
44883 if (insideURLFunctionInImportAtRuleNode$1(path)) {
44884 return group$6(fill$4(parts));
44887 return group$6(indent$5(fill$4(parts)));
44890 case "value-paren_group":
44892 const parentNode = path.getParentNode();
44894 if (parentNode && isURLFunctionNode$1(parentNode) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) {
44895 return concat$9([node.open ? path.call(print, "open") : "", join$6(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
44899 const printed = path.map(print, "groups");
44902 for (let i = 0; i < printed.length; i++) {
44904 res.push(concat$9([",", line$5]));
44907 res.push(printed[i]);
44910 return group$6(indent$5(fill$4(res)));
44913 const isSCSSMapItem = isSCSSMapItemNode$1(path);
44914 const lastItem = node.groups[node.groups.length - 1];
44915 const isLastItemComment = lastItem && lastItem.type === "value-comment";
44916 return group$6(concat$9([node.open ? path.call(print, "open") : "", indent$5(concat$9([softline$3, join$6(concat$9([",", line$5]), path.map(childPath => {
44917 const node = childPath.getValue();
44918 const printed = print(childPath); // Key/Value pair in open paren already indented
44920 if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
44921 printed.contents.contents.parts[1] = group$6(printed.contents.contents.parts[1]);
44922 return group$6(dedent$2(printed));
44926 }, "groups"))])), ifBreak$2(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$1(options) ? "," : ""), softline$3, node.close ? path.call(print, "close") : ""]), {
44927 shouldBreak: isSCSSMapItem
44933 return concat$9([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
44936 case "value-paren":
44941 case "value-number":
44943 return concat$9([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
44946 case "value-operator":
44953 if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
44954 return node.value.toLowerCase();
44960 case "value-colon":
44962 return concat$9([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
44963 insideValueFunctionNode$1(path, "url") ? "" : line$5]);
44966 case "value-comma":
44968 return concat$9([node.value, " "]);
44971 case "value-string":
44973 return printString$2(node.raws.quote + node.value + node.raws.quote, options);
44976 case "value-atword":
44978 return concat$9(["@", node.value]);
44981 case "value-unicode-range":
44986 case "value-unknown":
44992 /* istanbul ignore next */
44993 throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`);
44997 function printNodeSequence(path, options, print) {
44998 const node = path.getValue();
45001 path.map(pathChild => {
45002 const prevNode = node.nodes[i - 1];
45004 if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
45005 const childNode = pathChild.getValue();
45006 parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
45008 parts.push(pathChild.call(print));
45011 if (i !== node.nodes.length - 1) {
45012 if (node.nodes[i + 1].type === "css-comment" && !hasNewline$5(options.originalText, options.locStart(node.nodes[i + 1]), {
45014 }) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml" || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
45017 parts.push(options.__isHTMLStyleAttribute ? line$5 : hardline$7);
45019 if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options.locEnd) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") {
45020 parts.push(hardline$7);
45027 return concat$9(parts);
45030 const STRING_REGEX$3 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
45031 const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
45032 const STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
45033 const WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
45034 const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
45036 function adjustStrings(value, options) {
45037 return value.replace(STRING_REGEX$3, match => printString$2(match, options));
45040 function quoteAttributeValue(value, options) {
45041 const quote = options.singleQuote ? "'" : '"';
45042 return value.includes('"') || value.includes("'") ? value : quote + value + quote;
45045 function adjustNumbers(value) {
45046 return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match);
45049 function printCssNumber(rawNumber) {
45050 return printNumber$2(rawNumber) // Remove trailing `.0`.
45051 .replace(/\.0(?=$|e)/, "");
45054 var printerPostcss = {
45055 print: genericPrint$2,
45057 insertPragma: insertPragma$3,
45058 hasPrettierIgnore: hasIgnoreComment$3,
45059 massageAstNode: clean_1$1
45063 singleQuote: commonOptions.singleQuote
45066 var name$9 = "CSS";
45067 var type$7 = "markup";
45068 var tmScope$7 = "source.css";
45069 var aceMode$7 = "css";
45070 var codemirrorMode$7 = "css";
45071 var codemirrorMimeType$7 = "text/css";
45072 var color$2 = "#563d7c";
45073 var extensions$7 = [
45076 var languageId$7 = 50;
45080 tmScope: tmScope$7,
45081 aceMode: aceMode$7,
45082 codemirrorMode: codemirrorMode$7,
45083 codemirrorMimeType: codemirrorMimeType$7,
45085 extensions: extensions$7,
45086 languageId: languageId$7
45089 var CSS$1 = /*#__PURE__*/Object.freeze({
45093 tmScope: tmScope$7,
45094 aceMode: aceMode$7,
45095 codemirrorMode: codemirrorMode$7,
45096 codemirrorMimeType: codemirrorMimeType$7,
45098 extensions: extensions$7,
45099 languageId: languageId$7,
45103 var name$a = "PostCSS";
45104 var type$8 = "markup";
45105 var tmScope$8 = "source.postcss";
45106 var group$7 = "CSS";
45107 var extensions$8 = [
45111 var aceMode$8 = "text";
45112 var languageId$8 = 262764437;
45116 tmScope: tmScope$8,
45118 extensions: extensions$8,
45119 aceMode: aceMode$8,
45120 languageId: languageId$8
45123 var PostCSS$1 = /*#__PURE__*/Object.freeze({
45127 tmScope: tmScope$8,
45129 extensions: extensions$8,
45130 aceMode: aceMode$8,
45131 languageId: languageId$8,
45135 var name$b = "Less";
45136 var type$9 = "markup";
45137 var group$8 = "CSS";
45138 var extensions$9 = [
45141 var tmScope$9 = "source.css.less";
45142 var aceMode$9 = "less";
45143 var codemirrorMode$8 = "css";
45144 var codemirrorMimeType$8 = "text/css";
45145 var languageId$9 = 198;
45150 extensions: extensions$9,
45151 tmScope: tmScope$9,
45152 aceMode: aceMode$9,
45153 codemirrorMode: codemirrorMode$8,
45154 codemirrorMimeType: codemirrorMimeType$8,
45155 languageId: languageId$9
45158 var Less$1 = /*#__PURE__*/Object.freeze({
45163 extensions: extensions$9,
45164 tmScope: tmScope$9,
45165 aceMode: aceMode$9,
45166 codemirrorMode: codemirrorMode$8,
45167 codemirrorMimeType: codemirrorMimeType$8,
45168 languageId: languageId$9,
45172 var name$c = "SCSS";
45173 var type$a = "markup";
45174 var tmScope$a = "source.css.scss";
45175 var group$9 = "CSS";
45176 var aceMode$a = "scss";
45177 var codemirrorMode$9 = "css";
45178 var codemirrorMimeType$9 = "text/x-scss";
45179 var extensions$a = [
45182 var languageId$a = 329;
45186 tmScope: tmScope$a,
45188 aceMode: aceMode$a,
45189 codemirrorMode: codemirrorMode$9,
45190 codemirrorMimeType: codemirrorMimeType$9,
45191 extensions: extensions$a,
45192 languageId: languageId$a
45195 var SCSS$1 = /*#__PURE__*/Object.freeze({
45199 tmScope: tmScope$a,
45201 aceMode: aceMode$a,
45202 codemirrorMode: codemirrorMode$9,
45203 codemirrorMimeType: codemirrorMimeType$9,
45204 extensions: extensions$a,
45205 languageId: languageId$a,
45209 var require$$0$2 = getCjsExportFromNamespace(CSS$1);
45211 var require$$1$1 = getCjsExportFromNamespace(PostCSS$1);
45213 var require$$2$1 = getCjsExportFromNamespace(Less$1);
45215 var require$$3$1 = getCjsExportFromNamespace(SCSS$1);
45217 const languages$1 = [createLanguage(require$$0$2, () => ({
45220 vscodeLanguageIds: ["css"]
45221 })), createLanguage(require$$1$1, () => ({
45224 vscodeLanguageIds: ["postcss"]
45225 })), createLanguage(require$$2$1, () => ({
45228 vscodeLanguageIds: ["less"]
45229 })), createLanguage(require$$3$1, () => ({
45232 vscodeLanguageIds: ["scss"]
45234 const printers$1 = {
45235 postcss: printerPostcss
45237 var languageCss = {
45238 languages: languages$1,
45239 options: options$3,
45240 printers: printers$1
45243 var clean$3 = function (ast, newNode) {
45244 delete newNode.loc;
45245 delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace
45247 if (ast.type === "TextNode") {
45248 const trimmed = ast.chars.trim();
45254 newNode.chars = trimmed;
45258 function isUppercase(string) {
45259 return string.toUpperCase() === string;
45262 function isGlimmerComponent(node) {
45263 return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
45266 function isWhitespaceNode(node) {
45267 return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars);
45270 function isNodeOfSomeType(node, types) {
45271 return node && types.some(type => node.type === type);
45274 function isParentOfSomeType(path, types) {
45275 const parentNode = path.getParentNode(0);
45276 return isNodeOfSomeType(parentNode, types);
45279 function isPreviousNodeOfSomeType(path, types) {
45280 const previousNode = getPreviousNode(path);
45281 return isNodeOfSomeType(previousNode, types);
45284 function isNextNodeOfSomeType(path, types) {
45285 const nextNode = getNextNode(path);
45286 return isNodeOfSomeType(nextNode, types);
45289 function getSiblingNode(path, offset) {
45290 const node = path.getValue();
45291 const parentNode = path.getParentNode(0) || {};
45292 const children = parentNode.children || parentNode.body || [];
45293 const index = children.indexOf(node);
45294 return index !== -1 && children[index + offset];
45297 function getPreviousNode(path, lookBack = 1) {
45298 return getSiblingNode(path, -lookBack);
45301 function getNextNode(path) {
45302 return getSiblingNode(path, 1);
45305 function isPrettierIgnoreNode(node) {
45306 return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
45309 function hasPrettierIgnore$2(path) {
45310 const node = path.getValue();
45311 const previousPreviousNode = getPreviousNode(path, 2);
45312 return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode);
45318 hasPrettierIgnore: hasPrettierIgnore$2,
45319 isGlimmerComponent,
45320 isNextNodeOfSomeType,
45322 isParentOfSomeType,
45323 isPreviousNodeOfSomeType,
45330 softline: softline$4,
45331 hardline: hardline$8,
45336 } = document.builders;
45338 getNextNode: getNextNode$1,
45339 getPreviousNode: getPreviousNode$1,
45340 hasPrettierIgnore: hasPrettierIgnore$3,
45341 isGlimmerComponent: isGlimmerComponent$1,
45342 isNextNodeOfSomeType: isNextNodeOfSomeType$1,
45343 isParentOfSomeType: isParentOfSomeType$1,
45344 isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1,
45345 isWhitespaceNode: isWhitespaceNode$1
45346 } = utils$8; // http://w3c.github.io/html/single-page.html#void-elements
45348 const voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter:
45349 // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
45351 function print(path, options, print) {
45352 const n = path.getValue();
45353 /* istanbul ignore if*/
45359 if (hasPrettierIgnore$3(path)) {
45360 const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column);
45361 const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column);
45362 const ignoredText = options.originalText.slice(startOffset, endOffset);
45363 return ignoredText;
45371 return group$a(concat$a(path.map(print, "body")));
45374 case "ElementNode":
45376 const hasChildren = n.children.length > 0;
45377 const hasNonWhitespaceChildren = n.children.some(n => !isWhitespaceNode$1(n));
45378 const isVoid = isGlimmerComponent$1(n) && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.includes(n.tag);
45379 const closeTagForNoBreak = isVoid ? concat$a([" />", softline$4]) : ">";
45380 const closeTagForBreak = isVoid ? "/>" : ">";
45382 const printParams = (path, print) => indent$6(concat$a([n.attributes.length ? line$6 : "", join$7(line$6, path.map(print, "attributes")), n.modifiers.length ? line$6 : "", join$7(line$6, path.map(print, "modifiers")), n.comments.length ? line$6 : "", join$7(line$6, path.map(print, "comments"))]));
45384 const nextNode = getNextNode$1(path);
45385 return concat$a([group$a(concat$a(["<", n.tag, printParams(path, print), n.blockParams.length ? ` as |${n.blockParams.join(" ")}|` : "", ifBreak$3(softline$4, ""), ifBreak$3(closeTagForBreak, closeTagForNoBreak)])), !isVoid ? group$a(concat$a([hasNonWhitespaceChildren ? indent$6(printChildren(path, options, print)) : "", ifBreak$3(hasChildren ? hardline$8 : "", ""), concat$a(["</", n.tag, ">"])])) : "", nextNode && nextNode.type === "ElementNode" ? hardline$8 : ""]);
45388 case "BlockStatement":
45390 const pp = path.getParentNode(1);
45391 const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
45392 const hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if";
45393 const indentElse = hasElseIf ? a => a : indent$6;
45394 const inverseElseStatement = (n.inverseStrip.open ? "{{~" : "{{") + "else" + (n.inverseStrip.close ? "~}}" : "}}");
45397 return concat$a([isElseIf ? concat$a([n.openStrip.open ? "{{~else " : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]) : printOpenBlock(path, print, n.openStrip), indent$6(concat$a([hardline$8, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$a([hardline$8, inverseElseStatement]) : "", n.inverse ? indentElse(concat$a([hardline$8, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$a([hardline$8, printCloseBlock(path, print, n.closeStrip)])]);
45398 } else if (isElseIf) {
45399 return concat$a([concat$a([n.openStrip.open ? "{{~else" : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]), indent$6(concat$a([hardline$8, path.call(print, "program")]))]);
45402 const hasNonWhitespaceChildren = n.program.body.some(n => !isWhitespaceNode$1(n));
45403 return concat$a([printOpenBlock(path, print, n.openStrip), group$a(concat$a([indent$6(concat$a([softline$4, path.call(print, "program")])), hasNonWhitespaceChildren ? hardline$8 : softline$4, printCloseBlock(path, print, n.closeStrip)]))]);
45406 case "ElementModifierStatement":
45408 return group$a(concat$a(["{{", printPathParams(path, print), softline$4, "}}"]));
45411 case "MustacheStatement":
45413 const isEscaped = n.escaped === false;
45418 const opening = (isEscaped ? "{{{" : "{{") + (openStrip ? "~" : "");
45419 const closing = (closeStrip ? "~" : "") + (isEscaped ? "}}}" : "}}");
45420 const leading = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement", "ElementNode"]) ? [opening, indent$6(softline$4)] : [opening];
45421 return group$a(concat$a([...leading, printPathParams(path, print), softline$4, closing]));
45424 case "SubExpression":
45426 const params = printParams(path, print);
45427 const printedParams = params.length > 0 ? indent$6(concat$a([line$6, group$a(join$7(line$6, params))])) : "";
45428 return group$a(concat$a(["(", printPath(path, print), printedParams, softline$4, ")"]));
45433 const isText = n.value.type === "TextNode";
45434 const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the
45435 // same, there is no value for this AttrNode and it should be printed
45436 // without the `=""`. Example: `<img data-test>` -> `<img data-test>`
45438 const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column;
45440 if (isEmptyValue) {
45441 return concat$a([n.name]);
45444 const value = path.call(print, "value");
45445 const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
45446 return concat$a([n.name, "=", quotedValue]);
45449 case "ConcatStatement":
45451 return concat$a(['"', concat$a(path.map(partPath => print(partPath), "parts").filter(a => a !== "")), '"']);
45456 return concat$a([join$7(line$6, path.map(print, "pairs"))]);
45461 return concat$a([n.key, "=", path.call(print, "value")]);
45466 const maxLineBreaksToPreserve = 2;
45467 const isFirstElement = !getPreviousNode$1(path);
45468 const isLastElement = !getNextNode$1(path);
45469 const isWhitespaceOnly = !/\S/.test(n.chars);
45470 const lineBreaksCount = countNewLines(n.chars);
45471 const hasBlockParent = path.getParentNode(0).type === "Block";
45472 const hasElementParent = path.getParentNode(0).type === "ElementNode";
45473 const hasTemplateParent = path.getParentNode(0).type === "Template";
45474 let leadingLineBreaksCount = countLeadingNewLines(n.chars);
45475 let trailingLineBreaksCount = countTrailingNewLines(n.chars);
45477 if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) {
45481 if (isWhitespaceOnly && lineBreaksCount) {
45482 leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
45483 trailingLineBreaksCount = 0;
45485 if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
45486 trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
45489 if (isPreviousNodeOfSomeType$1(path, ["ElementNode"]) || isPreviousNodeOfSomeType$1(path, ["BlockStatement"])) {
45490 leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
45494 let leadingSpace = "";
45495 let trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present,
45496 // when next to mustache statement.
45498 const inAttrNode = path.stack.includes("attributes");
45501 const parentNode = path.getParentNode(0);
45502 const isConcat = parentNode.type === "ConcatStatement";
45508 const partIndex = parts.indexOf(n);
45510 if (partIndex > 0) {
45511 const partType = parts[partIndex - 1].type;
45512 const isMustache = partType === "MustacheStatement";
45515 leadingSpace = " ";
45519 if (partIndex < parts.length - 1) {
45520 const partType = parts[partIndex + 1].type;
45521 const isMustache = partType === "MustacheStatement";
45524 trailingSpace = " ";
45529 if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
45530 trailingSpace = " ";
45533 if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
45534 leadingSpace = " ";
45537 if (isFirstElement) {
45538 leadingLineBreaksCount = 0;
45542 if (isLastElement) {
45543 trailingLineBreaksCount = 0;
45544 trailingSpace = "";
45548 return concat$a([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^[\s ]+/g, leadingSpace).replace(/[\s ]+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)].filter(Boolean));
45551 case "MustacheCommentStatement":
45553 const dashes = n.value.includes("}}") ? "--" : "";
45554 return concat$a(["{{!", dashes, n.value, dashes, "}}"]);
45557 case "PathExpression":
45562 case "BooleanLiteral":
45564 return String(n.value);
45567 case "CommentStatement":
45569 return concat$a(["<!--", n.value, "-->"]);
45572 case "StringLiteral":
45574 return printStringLiteral(n.value, options);
45577 case "NumberLiteral":
45579 return String(n.value);
45582 case "UndefinedLiteral":
45584 return "undefined";
45587 case "NullLiteral":
45592 /* istanbul ignore next */
45595 throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
45599 function printChildren(path, options, print) {
45600 return concat$a(path.map((childPath, childIndex) => {
45601 const childNode = path.getValue();
45602 const isFirstNode = childIndex === 0;
45603 const isLastNode = childIndex === path.getParentNode(0).children.length - 1;
45604 const isLastNodeInMultiNodeList = isLastNode && !isFirstNode;
45605 const isWhitespace = isWhitespaceNode$1(childNode);
45607 if (isWhitespace && isLastNodeInMultiNodeList) {
45608 return print(childPath, options, print);
45609 } else if (isFirstNode) {
45610 return concat$a([softline$4, print(childPath, options, print)]);
45613 return print(childPath, options, print);
45617 * Prints a string literal with the correct surrounding quotes based on
45618 * `options.singleQuote` and the number of escaped quotes contained in
45619 * the string literal. This function is the glimmer equivalent of `printString`
45620 * in `common/util`, but has differences because of the way escaped characters
45621 * are treated in hbs string literals.
45622 * @param {string} stringLiteral - the string literal value
45623 * @param {object} options - the prettier options object
45627 function printStringLiteral(stringLiteral, options) {
45636 const preferred = options.singleQuote ? single : double;
45637 const alternate = preferred === single ? double : single;
45638 let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
45639 // enclosing the string, we might want to enclose with the alternate quote
45640 // instead, to minimize the number of escaped quotes.
45642 if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
45643 const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
45644 const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
45645 shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
45648 const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
45649 const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
45650 return concat$a([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]);
45653 function printPath(path, print) {
45654 return path.call(print, "path");
45657 function printParams(path, print) {
45658 const node = path.getValue();
45661 if (node.params.length > 0) {
45662 parts = parts.concat(path.map(print, "params"));
45665 if (node.hash && node.hash.pairs.length > 0) {
45666 parts.push(path.call(print, "hash"));
45672 function printPathParams(path, print) {
45673 const printedPath = printPath(path, print);
45674 const printedParams = printParams(path, print);
45675 const parts = [printedPath, ...printedParams];
45676 return indent$6(group$a(join$7(line$6, parts)));
45679 function printBlockParams(path) {
45680 const block = path.getValue();
45682 if (!block.program || !block.program.blockParams.length) {
45686 return concat$a([" as |", block.program.blockParams.join(" "), "|"]);
45689 function printOpenBlock(path, print, {
45690 open: isOpenStrip = false,
45691 close: isCloseStrip = false
45693 return group$a(concat$a([isOpenStrip ? "{{~#" : "{{#", printPathParams(path, print), printBlockParams(path), softline$4, isCloseStrip ? "~}}" : "}}"]));
45696 function printCloseBlock(path, print, {
45697 open: isOpenStrip = false,
45698 close: isCloseStrip = false
45700 return concat$a([isOpenStrip ? "{{~/" : "{{/", path.call(print, "path"), isCloseStrip ? "~}}" : "}}"]);
45703 function countNewLines(string) {
45704 /* istanbul ignore next */
45705 string = typeof string === "string" ? string : "";
45706 return string.split("\n").length - 1;
45709 function countLeadingNewLines(string) {
45710 /* istanbul ignore next */
45711 string = typeof string === "string" ? string : "";
45712 const newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || "";
45713 return countNewLines(newLines);
45716 function countTrailingNewLines(string) {
45717 /* istanbul ignore next */
45718 string = typeof string === "string" ? string : "";
45719 const newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || "";
45720 return countNewLines(newLines);
45723 function generateHardlines(number = 0, max = 0) {
45724 return new Array(Math.min(number, max)).fill(hardline$8);
45726 /* istanbul ignore next
45727 https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29
45731 function locationToOffset(source, line, column) {
45733 let seenChars = 0; // eslint-disable-next-line no-constant-condition
45736 if (seenChars === source.length) {
45740 let nextLine = source.indexOf("\n", seenChars);
45742 if (nextLine === -1) {
45743 nextLine = source.length;
45746 if (seenLines === line) {
45747 if (seenChars + column > nextLine) {
45751 return seenChars + column;
45752 } else if (nextLine === -1) {
45757 seenChars = nextLine + 1;
45761 var printerGlimmer = {
45763 massageAstNode: clean$3
45766 var name$d = "Handlebars";
45767 var type$b = "markup";
45768 var group$b = "HTML";
45773 var extensions$b = [
45777 var tmScope$b = "text.html.handlebars";
45778 var aceMode$b = "handlebars";
45779 var languageId$b = 155;
45784 aliases: aliases$3,
45785 extensions: extensions$b,
45786 tmScope: tmScope$b,
45787 aceMode: aceMode$b,
45788 languageId: languageId$b
45791 var Handlebars$1 = /*#__PURE__*/Object.freeze({
45796 aliases: aliases$3,
45797 extensions: extensions$b,
45798 tmScope: tmScope$b,
45799 aceMode: aceMode$b,
45800 languageId: languageId$b,
45801 'default': Handlebars
45804 var require$$0$3 = getCjsExportFromNamespace(Handlebars$1);
45806 const languages$2 = [createLanguage(require$$0$3, () => ({
45809 parsers: ["glimmer"],
45810 vscodeLanguageIds: ["handlebars"]
45812 const printers$2 = {
45813 glimmer: printerGlimmer
45815 var languageHandlebars = {
45816 languages: languages$2,
45817 printers: printers$2
45820 function hasPragma$2(text) {
45821 return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text);
45824 function insertPragma$4(text) {
45825 return "# @format\n\n" + text;
45829 hasPragma: hasPragma$2,
45830 insertPragma: insertPragma$4
45836 hardline: hardline$9,
45838 softline: softline$5,
45842 } = document.builders;
45844 hasIgnoreComment: hasIgnoreComment$4
45847 isNextLineEmpty: isNextLineEmpty$4
45850 insertPragma: insertPragma$5
45853 function genericPrint$3(path, options, print) {
45854 const n = path.getValue();
45860 if (typeof n === "string") {
45868 path.map((pathChild, index) => {
45869 parts.push(concat$b([pathChild.call(print)]));
45871 if (index !== n.definitions.length - 1) {
45872 parts.push(hardline$9);
45874 if (isNextLineEmpty$4(options.originalText, pathChild.getValue(), options.locEnd)) {
45875 parts.push(hardline$9);
45879 return concat$b([concat$b(parts), hardline$9]);
45882 case "OperationDefinition":
45884 const hasOperation = options.originalText[options.locStart(n)] !== "{";
45885 const hasName = !!n.name;
45886 return concat$b([hasOperation ? n.operation : "", hasOperation && hasName ? concat$b([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "variableDefinitions"))])), softline$5, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
45889 case "FragmentDefinition":
45891 return concat$b(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "variableDefinitions"))])), softline$5, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
45894 case "SelectionSet":
45896 return concat$b(["{", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$9, "}"]);
45901 return group$c(concat$b([n.alias ? concat$b([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$5, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
45909 case "StringValue":
45912 return concat$b(['"""', hardline$9, join$8(hardline$9, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$9, '"""']);
45915 return concat$b(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
45925 case "BooleanValue":
45927 return n.value ? "true" : "false";
45937 return concat$b(["$", path.call(print, "name")]);
45942 return group$c(concat$b(["[", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "values"))])), softline$5, "]"]));
45945 case "ObjectValue":
45947 return group$c(concat$b(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "fields"))])), softline$5, ifBreak$4("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
45950 case "ObjectField":
45953 return concat$b([path.call(print, "name"), ": ", path.call(print, "value")]);
45958 return concat$b(["@", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$5, ")"])) : ""]);
45963 return path.call(print, "name");
45966 case "VariableDefinition":
45968 return concat$b([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$b([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
45971 case "TypeExtensionDefinition":
45973 return concat$b(["extend ", path.call(print, "definition")]);
45976 case "ObjectTypeExtension":
45977 case "ObjectTypeDefinition":
45979 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$b([" implements ", concat$b(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$9, "}"]) : ""]);
45982 case "FieldDefinition":
45984 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$5, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
45987 case "DirectiveDefinition":
45989 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$5, ")"])) : "", n.repeatable ? " repeatable" : "", concat$b([" on ", join$8(" | ", path.map(print, "locations"))])]);
45992 case "EnumTypeExtension":
45993 case "EnumTypeDefinition":
45995 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$9, "}"]) : ""]);
45998 case "EnumValueDefinition":
46000 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", path.call(print, "name"), printDirectives(path, print, n)]);
46003 case "InputValueDefinition":
46005 return concat$b([path.call(print, "description"), n.description ? n.description.block ? hardline$9 : line$7 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$b([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
46008 case "InputObjectTypeExtension":
46009 case "InputObjectTypeDefinition":
46011 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$9, "}"]) : ""]);
46014 case "SchemaDefinition":
46016 return concat$b(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$9, "}"]);
46019 case "OperationTypeDefinition":
46021 return concat$b([path.call(print, "operation"), ": ", path.call(print, "type")]);
46024 case "InterfaceTypeExtension":
46025 case "InterfaceTypeDefinition":
46027 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$9, "}"]) : ""]);
46030 case "FragmentSpread":
46032 return concat$b(["...", path.call(print, "name"), printDirectives(path, print, n)]);
46035 case "InlineFragment":
46037 return concat$b(["...", n.typeCondition ? concat$b([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
46040 case "UnionTypeExtension":
46041 case "UnionTypeDefinition":
46043 return group$c(concat$b([path.call(print, "description"), n.description ? hardline$9 : "", group$c(concat$b([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$b([" =", ifBreak$4("", " "), indent$7(concat$b([ifBreak$4(concat$b([line$7, " "])), join$8(concat$b([line$7, "| "]), path.map(print, "types"))]))]) : ""]))]));
46046 case "ScalarTypeExtension":
46047 case "ScalarTypeDefinition":
46049 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
46052 case "NonNullType":
46054 return concat$b([path.call(print, "type"), "!"]);
46059 return concat$b(["[", path.call(print, "type"), "]"]);
46063 /* istanbul ignore next */
46064 throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
46068 function printDirectives(path, print, n) {
46069 if (n.directives.length === 0) {
46073 return concat$b([" ", group$c(indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", " "), softline$5]), path.map(print, "directives"))])))]);
46076 function printSequence(sequencePath, options, print) {
46077 const count = sequencePath.getValue().length;
46078 return sequencePath.map((path, i) => {
46079 const printed = print(path);
46081 if (isNextLineEmpty$4(options.originalText, path.getValue(), options.locEnd) && i < count - 1) {
46082 return concat$b([printed, hardline$9]);
46089 function canAttachComment$1(node) {
46090 return node.kind && node.kind !== "Comment";
46093 function printComment$2(commentPath) {
46094 const comment = commentPath.getValue();
46096 if (comment.kind === "Comment") {
46097 return "#" + comment.value.trimEnd();
46100 throw new Error("Not a comment: " + JSON.stringify(comment));
46103 function determineInterfaceSeparatorBetween(first, second, options) {
46104 const textBetween = options.originalText.slice(first.loc.end, second.loc.start).replace(/#.*/g, "").trim();
46105 return textBetween === "," ? ", " : " & ";
46108 function printInterfaces(path, options, print) {
46109 const node = path.getNode();
46114 const printed = path.map(node => print(node), "interfaces");
46116 for (let index = 0; index < interfaces.length; index++) {
46117 const interfaceNode = interfaces[index];
46120 parts.push(determineInterfaceSeparatorBetween(interfaces[index - 1], interfaceNode, options));
46123 parts.push(printed[index]);
46129 function clean$4(node, newNode
46132 delete newNode.loc;
46133 delete newNode.comments;
46136 var printerGraphql = {
46137 print: genericPrint$3,
46138 massageAstNode: clean$4,
46139 hasPrettierIgnore: hasIgnoreComment$4,
46140 insertPragma: insertPragma$5,
46141 printComment: printComment$2,
46142 canAttachComment: canAttachComment$1
46146 bracketSpacing: commonOptions.bracketSpacing
46149 var name$e = "GraphQL";
46150 var type$c = "data";
46151 var extensions$c = [
46156 var tmScope$c = "source.graphql";
46157 var aceMode$c = "text";
46158 var languageId$c = 139;
46162 extensions: extensions$c,
46163 tmScope: tmScope$c,
46164 aceMode: aceMode$c,
46165 languageId: languageId$c
46168 var GraphQL$1 = /*#__PURE__*/Object.freeze({
46172 extensions: extensions$c,
46173 tmScope: tmScope$c,
46174 aceMode: aceMode$c,
46175 languageId: languageId$c,
46179 var require$$0$4 = getCjsExportFromNamespace(GraphQL$1);
46181 const languages$3 = [createLanguage(require$$0$4, () => ({
46183 parsers: ["graphql"],
46184 vscodeLanguageIds: ["graphql"]
46186 const printers$3 = {
46187 graphql: printerGraphql
46189 var languageGraphql = {
46190 languages: languages$3,
46191 options: options$4,
46192 printers: printers$3
46196 "cjkPattern": "[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d]",
46197 "kPattern": "[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]",
46198 "punctuationPattern": "[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c77\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e4f\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud803[\\udf55-\\udf59]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc8\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\udc3b\\udde2\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71\\udef7-\\udef8\\udfff]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud81b[\\ude97-\\ude9a\\udfe2]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]"
46209 const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
46210 const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
46211 const kRegex = new RegExp(kPattern);
46212 const punctuationRegex = new RegExp(punctuationPattern);
46214 * split text into whitespaces and words
46215 * @param {string} text
46216 * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
46219 function splitText(text, options) {
46220 const KIND_NON_CJK = "non-cjk";
46221 const KIND_CJ_LETTER = "cj-letter";
46222 const KIND_K_LETTER = "k-letter";
46223 const KIND_CJK_PUNCTUATION = "cjk-punctuation";
46225 (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([ \t\n]+)/).forEach((token, index, tokens) => {
46227 if (index % 2 === 1) {
46229 type: "whitespace",
46230 value: /\n/.test(token) ? "\n" : " "
46233 } // word separated by whitespace
46236 if ((index === 0 || index === tokens.length - 1) && token === "") {
46240 token.split(new RegExp(`(${cjkPattern})`)).forEach((innerToken, innerIndex, innerTokens) => {
46241 if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
46246 if (innerIndex % 2 === 0) {
46247 if (innerToken !== "") {
46251 kind: KIND_NON_CJK,
46252 hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
46253 hasTrailingPunctuation: punctuationRegex.test(getLast$4(innerToken))
46261 appendNode(punctuationRegex.test(innerToken) ? {
46264 kind: KIND_CJK_PUNCTUATION,
46265 hasLeadingPunctuation: true,
46266 hasTrailingPunctuation: true
46270 kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
46271 hasLeadingPunctuation: false,
46272 hasTrailingPunctuation: false
46278 function appendNode(node) {
46279 const lastNode = getLast$4(nodes);
46281 if (lastNode && lastNode.type === "word") {
46282 if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
46284 type: "whitespace",
46287 } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
46288 ![lastNode.value, node.value].some(value => /\u3000/.test(value))) {
46290 type: "whitespace",
46298 function isBetween(kind1, kind2) {
46299 return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
46304 function getOrderedListItemInfo(orderListItem, originalText) {
46305 const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/);
46313 function hasGitDiffFriendlyOrderedList(node, options) {
46314 if (!node.ordered) {
46318 if (node.children.length < 2) {
46322 const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText);
46323 const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText);
46325 if (firstNumber === 0 && node.children.length > 2) {
46326 const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText);
46327 return secondNumber === 1 && thirdNumber === 1;
46330 return secondNumber === 1;
46331 } // workaround for https://github.com/remarkjs/remark/issues/351
46332 // leading and trailing newlines are stripped by remark
46335 function getFencedCodeBlockValue(node, originalText) {
46336 const text = originalText.slice(node.position.start.offset, node.position.end.offset);
46337 const leadingSpaceCount = text.match(/^\s*/)[0].length;
46338 const replaceRegex = new RegExp(`^\\s{0,${leadingSpaceCount}}`);
46339 const lineContents = text.split("\n");
46340 const markerStyle = text[leadingSpaceCount]; // ` or ~
46342 const marker = text.slice(leadingSpaceCount).match(new RegExp(`^[${markerStyle}]+`))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
46343 // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
46345 const hasEndMarker = new RegExp(`^\\s{0,3}${marker}`).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
46346 return lineContents.slice(1, hasEndMarker ? -1 : undefined).map((x, i) => x.slice(getIndent(i + 1)).replace(replaceRegex, "")).join("\n");
46348 function getIndent(lineIndex) {
46349 return node.position.indent[lineIndex - 1] - 1;
46353 function mapAst(ast, handler) {
46354 return function preorder(node, index, parentStack) {
46355 parentStack = parentStack || [];
46356 const newNode = Object.assign({}, handler(node, index, parentStack));
46358 if (newNode.children) {
46359 newNode.children = newNode.children.map((child, index) => {
46360 return preorder(child, index, [newNode].concat(parentStack));
46365 }(ast, null, null);
46371 punctuationPattern,
46372 getFencedCodeBlockValue,
46373 getOrderedListItemInfo,
46374 hasGitDiffFriendlyOrderedList,
46376 INLINE_NODE_WRAPPER_TYPES
46381 hardline: hardline$a,
46382 literalline: literalline$4,
46384 markAsRoot: markAsRoot$2
46391 getFencedCodeBlockValue: getFencedCodeBlockValue$1
46394 function embed$2(path, print, textToDoc, options) {
46395 const node = path.getValue();
46397 if (node.type === "code" && node.lang !== null) {
46398 // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
46399 const langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
46400 const lang = langMatch ? langMatch[0] : "";
46401 const parser = getParserName(lang);
46404 const styleUnit = options.__inJsTemplate ? "~" : "`";
46405 const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
46406 const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
46409 return markAsRoot$2(concat$c([style, node.lang, hardline$a, replaceNewlinesWithLiterallines(doc), style]));
46413 if (node.type === "yaml") {
46414 return markAsRoot$2(concat$c(["---", hardline$a, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
46416 })) : "", "---"]));
46420 switch (node.type) {
46421 case "importExport":
46422 return textToDoc(node.value, {
46427 return textToDoc(`<$>${node.value}</$>`, {
46428 parser: "__js_expression",
46435 function getParserName(lang) {
46436 const supportInfo = support.getSupportInfo({
46437 plugins: options.plugins
46439 const language = supportInfo.languages.find(language => language.name.toLowerCase() === lang || language.aliases && language.aliases.includes(lang) || language.extensions && language.extensions.find(ext => ext === `.${lang}`));
46442 return language.parsers[0];
46448 function replaceNewlinesWithLiterallines(doc) {
46449 return mapDoc$3(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$c(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$4)) : currentDoc);
46453 var embed_1$2 = embed$2;
46455 const pragmas = ["format", "prettier"];
46457 function startWithPragma(text) {
46458 const pragma = `@(${pragmas.join("|")})`;
46459 const regex = new RegExp([`<!--\\s*${pragma}\\s*-->`, `<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*${pragma}[^\\S\n]*($|\n)[\\s\\S]*\n.*-->`].join("|"), "m");
46460 const matched = text.match(regex);
46461 return matched && matched.index === 0;
46466 hasPragma: text => startWithPragma(frontMatter(text).content.trimStart()),
46467 insertPragma: text => {
46468 const extracted = frontMatter(text);
46469 const pragma = `<!-- @${pragmas[0]} -->`;
46470 return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
46475 getOrderedListItemInfo: getOrderedListItemInfo$1,
46477 splitText: splitText$1
46478 } = utils$9; // 0x0 ~ 0x10ffff
46479 // eslint-disable-next-line no-control-regex
46481 const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
46483 function preprocess$1(ast, options) {
46484 ast = restoreUnescapedCharacter(ast, options);
46485 ast = mergeContinuousTexts(ast);
46486 ast = transformInlineCode(ast);
46487 ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
46488 ast = markAlignedList(ast, options);
46489 ast = splitTextIntoSentences(ast, options);
46490 ast = transformImportExport(ast);
46491 ast = mergeContinuousImportExport(ast);
46495 function transformImportExport(ast) {
46496 return mapAst$1(ast, node => {
46497 if (node.type !== "import" && node.type !== "export") {
46501 return Object.assign({}, node, {
46502 type: "importExport"
46507 function transformInlineCode(ast) {
46508 return mapAst$1(ast, node => {
46509 if (node.type !== "inlineCode") {
46513 return Object.assign({}, node, {
46514 value: node.value.replace(/\s+/g, " ")
46519 function restoreUnescapedCharacter(ast, options) {
46520 return mapAst$1(ast, node => {
46521 return node.type !== "text" ? node : Object.assign({}, node, {
46522 value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
46523 isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value
46528 function mergeContinuousImportExport(ast) {
46529 return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({
46530 type: "importExport",
46531 value: prevNode.value + "\n\n" + node.value,
46533 start: prevNode.position.start,
46534 end: node.position.end
46539 function mergeChildren(ast, shouldMerge, mergeNode) {
46540 return mapAst$1(ast, node => {
46541 if (!node.children) {
46545 const children = node.children.reduce((current, child) => {
46546 const lastChild = current[current.length - 1];
46548 if (lastChild && shouldMerge(lastChild, child)) {
46549 current.splice(-1, 1, mergeNode(lastChild, child));
46551 current.push(child);
46556 return Object.assign({}, node, {
46562 function mergeContinuousTexts(ast) {
46563 return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({
46565 value: prevNode.value + node.value,
46567 start: prevNode.position.start,
46568 end: node.position.end
46573 function splitTextIntoSentences(ast, options) {
46574 return mapAst$1(ast, (node, index, [parentNode]) => {
46575 if (node.type !== "text") {
46583 if (parentNode.type === "paragraph") {
46585 value = value.trimStart();
46588 if (index === parentNode.children.length - 1) {
46589 value = value.trimEnd();
46595 position: node.position,
46596 children: splitText$1(value, options)
46601 function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
46602 return mapAst$1(ast, (node, index, parentStack) => {
46603 if (node.type === "code") {
46604 // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
46605 const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
46606 node.isIndented = isIndented;
46609 for (let i = 0; i < parentStack.length; i++) {
46610 const parent = parentStack[i]; // no need to check checked items
46612 if (parent.hasIndentedCodeblock) {
46616 if (parent.type === "list") {
46617 parent.hasIndentedCodeblock = true;
46627 function markAlignedList(ast, options) {
46628 return mapAst$1(ast, (node, index, parentStack) => {
46629 if (node.type === "list" && node.children.length !== 0) {
46630 // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
46631 for (let i = 0; i < parentStack.length; i++) {
46632 const parent = parentStack[i];
46634 if (parent.type === "list" && !parent.isAligned) {
46635 node.isAligned = false;
46640 node.isAligned = isAligned(node);
46646 function getListItemStart(listItem) {
46647 return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
46650 function isAligned(list) {
46651 if (!list.ordered) {
46659 const [firstItem, secondItem] = list.children;
46660 const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
46662 if (firstInfo.leadingSpaces.length > 1) {
46672 const firstStart = getListItemStart(firstItem);
46674 if (firstStart === -1) {
46684 if (list.children.length === 1) {
46694 return firstStart % options.tabWidth === 0;
46697 const secondStart = getListItemStart(secondItem);
46699 if (firstStart !== secondStart) {
46710 if (firstStart % options.tabWidth === 0) {
46730 const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
46731 return secondInfo.leadingSpaces.length > 1;
46735 var preprocess_1$1 = preprocess$1;
46739 breakParent: breakParent$3,
46743 literalline: literalline$5,
46744 markAsRoot: markAsRoot$3,
46745 hardline: hardline$b,
46746 softline: softline$6,
46747 ifBreak: ifBreak$5,
46757 printDocToString: printDocToString$3
46761 getFencedCodeBlockValue: getFencedCodeBlockValue$2,
46762 hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
46763 splitText: splitText$2,
46764 punctuationPattern: punctuationPattern$1,
46765 INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
46766 INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1
46769 replaceEndOfLineWith: replaceEndOfLineWith$1
46771 const TRAILING_HARDLINE_NODES = ["importExport"];
46772 const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
46773 const SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
46775 function genericPrint$4(path, options, print) {
46776 const node = path.getValue();
46778 if (shouldRemainTheSameContent(path)) {
46779 return concat$d(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options)));
46782 switch (node.type) {
46784 if (node.children.length === 0) {
46788 return concat$d([normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.includes(getLastDescendantNode(node).type) ? hardline$b : ""]);
46791 return printChildren$1(path, options, print, {
46792 postprocessor: fill$5
46796 return printChildren$1(path, options, print);
46799 return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
46800 .replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_"));
46801 // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
46805 const parentNode = path.getParentNode();
46806 const index = parentNode.children.indexOf(node);
46807 const nextNode = parentNode.children[index + 1];
46808 const proseWrap = // leading char that may cause different syntax
46809 nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
46810 return printLine(path, node.value, {
46817 const parentNode = path.getParentNode();
46818 const index = parentNode.children.indexOf(node);
46819 const prevNode = parentNode.children[index - 1];
46820 const nextNode = parentNode.children[index + 1];
46821 const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
46822 prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util$1.getLast(prevNode.children).type === "word" && !util$1.getLast(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
46823 const style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
46824 return concat$d([style, printChildren$1(path, options, print), style]);
46828 return concat$d(["**", printChildren$1(path, options, print), "**"]);
46831 return concat$d(["~~", printChildren$1(path, options, print), "~~"]);
46835 const backtickCount = util$1.getMinNotPresentContinuousCount(node.value, "`");
46836 const style = "`".repeat(backtickCount || 1);
46837 const gap = backtickCount ? " " : "";
46838 return concat$d([style, gap, node.value, gap, style]);
46842 switch (options.originalText[node.position.start.offset]) {
46845 const mailto = "mailto:";
46846 const url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
46847 node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url;
46848 return concat$d(["<", url, ">"]);
46852 return concat$d(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
46855 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
46859 return concat$d(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
46862 return concat$d(["> ", align$2("> ", printChildren$1(path, options, print))]);
46865 return concat$d(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
46869 if (node.isIndented) {
46870 // indented code block
46871 const alignment = " ".repeat(4);
46872 return align$2(alignment, concat$d([alignment, concat$d(replaceEndOfLineWith$1(node.value, hardline$b))]));
46873 } // fenced code block
46876 const styleUnit = options.__inJsTemplate ? "~" : "`";
46877 const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
46878 return concat$d([style, node.lang || "", hardline$b, concat$d(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$b)), hardline$b, style]);
46883 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
46887 const parentNode = path.getParentNode();
46888 const value = parentNode.type === "root" && util$1.getLast(parentNode.children) === node ? node.value.trimEnd() : node.value;
46889 const isHtmlComment = /^<!--[\s\S]*-->$/.test(value);
46890 return concat$d(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$b : markAsRoot$3(literalline$5)));
46895 const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
46896 const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options);
46897 return printChildren$1(path, options, print, {
46898 processor: (childPath, index) => {
46899 const prefix = getPrefix();
46900 const childNode = childPath.getValue();
46902 if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) {
46903 return concat$d([prefix, printListItem(childPath, options, print, prefix)]);
46906 return concat$d([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
46908 function getPrefix() {
46909 const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
46910 return node.isAligned ||
46911 /* workaround for https://github.com/remarkjs/remark/issues/315 */
46912 node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
46918 case "thematicBreak":
46920 const counter = getAncestorCounter$1(path, "list");
46922 if (counter === -1) {
46926 const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
46927 return nthSiblingIndex % 2 === 0 ? "***" : "---";
46930 case "linkReference":
46931 return concat$d(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$d(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
46933 case "imageReference":
46934 switch (node.referenceType) {
46936 return concat$d(["![", node.alt || "", "][", node.identifier, "]"]);
46939 return concat$d(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
46944 const lineOrSpace = options.proseWrap === "always" ? line$8 : " ";
46945 return group$d(concat$d([concat$d(["[", node.identifier, "]:"]), indent$8(concat$d([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$d([lineOrSpace, printTitle(node.title, options, false)])]))]));
46949 return concat$d(["[^", printChildren$1(path, options, print), "]"]);
46951 case "footnoteReference":
46952 return concat$d(["[^", node.identifier, "]"]);
46954 case "footnoteDefinition":
46956 const nextNode = path.getParentNode().children[path.getName() + 1];
46957 const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
46958 return concat$d(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$d(concat$d([align$2(" ".repeat(options.tabWidth), printChildren$1(path, options, print, {
46959 processor: (childPath, index) => {
46960 return index === 0 ? group$d(concat$d([softline$6, childPath.call(print)])) : childPath.call(print);
46962 })), nextNode && nextNode.type === "footnoteDefinition" ? softline$6 : ""]))]);
46966 return printTable(path, options, print);
46969 return printChildren$1(path, options, print);
46972 return /\s/.test(options.originalText[node.position.start.offset]) ? concat$d([" ", markAsRoot$3(literalline$5)]) : concat$d(["\\", hardline$b]);
46975 return concat$d(replaceEndOfLineWith$1(node.value, hardline$b));
46978 case "importExport":
46981 // fallback to the original text if multiparser failed
46984 return concat$d(["$$", hardline$b, node.value ? concat$d([concat$d(replaceEndOfLineWith$1(node.value, hardline$b)), hardline$b]) : "", "$$"]);
46988 // remark-math trims content but we don't want to remove whitespaces
46989 // since it's very possible that it's recognized as math accidentally
46990 return options.originalText.slice(options.locStart(node), options.locEnd(node));
46993 case "tableRow": // handled in "table"
46995 case "listItem": // handled in "list"
46998 throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
47002 function printListItem(path, options, print, listPrefix) {
47003 const node = path.getValue();
47004 const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
47005 return concat$d([prefix, printChildren$1(path, options, print, {
47006 processor: (childPath, index) => {
47007 if (index === 0 && childPath.getValue().type !== "list") {
47008 return align$2(" ".repeat(prefix.length), childPath.call(print));
47011 const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
47013 return concat$d([alignment, align$2(alignment, childPath.call(print))]);
47018 function alignListPrefix(prefix, options) {
47019 const additionalSpaces = getAdditionalSpaces();
47020 return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
47023 function getAdditionalSpaces() {
47024 const restSpaces = prefix.length % options.tabWidth;
47025 return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
47029 function getNthListSiblingIndex(node, parentNode) {
47030 return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered);
47033 function getNthSiblingIndex(node, parentNode, condition) {
47034 condition = condition || (() => true);
47038 for (const childNode of parentNode.children) {
47039 if (childNode.type === node.type && condition(childNode)) {
47045 if (childNode === node) {
47051 function getAncestorCounter$1(path, typeOrTypes) {
47052 const types = [].concat(typeOrTypes);
47056 while (ancestorNode = path.getParentNode(++counter)) {
47057 if (types.includes(ancestorNode.type)) {
47065 function getAncestorNode$2(path, typeOrTypes) {
47066 const counter = getAncestorCounter$1(path, typeOrTypes);
47067 return counter === -1 ? null : path.getParentNode(counter);
47070 function printLine(path, value, options) {
47071 if (options.proseWrap === "preserve" && value === "\n") {
47075 const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
47076 return value !== "" ? isBreakable ? line$8 : " " : isBreakable ? softline$6 : "";
47079 function printTable(path, options, print) {
47080 const hardlineWithoutBreakParent = hardline$b.parts[0];
47081 const node = path.getValue();
47082 const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
47084 path.map(rowPath => {
47085 const rowContents = [];
47086 rowPath.map(cellPath => {
47087 rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
47089 contents.push(rowContents);
47090 }, "children"); // Get the width of each column
47092 const columnMaxWidths = contents.reduce((currentWidths, rowContents) => currentWidths.map((width, columnIndex) => Math.max(width, util$1.getStringWidth(rowContents[columnIndex]))), contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:)
47094 const alignedTable = join$9(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$9(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents)))]);
47096 if (options.proseWrap !== "never") {
47097 return concat$d([breakParent$3, alignedTable]);
47098 } // Only if the --prose-wrap never is set and it exceeds the print width.
47101 const compactTable = join$9(hardlineWithoutBreakParent, [printRow(contents[0],
47103 true), printSeparator(
47105 true), join$9(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents,
47108 return concat$d([breakParent$3, group$d(ifBreak$5(compactTable, alignedTable))]);
47110 function printSeparator(isCompact) {
47111 return concat$d(["| ", join$9(" | ", columnMaxWidths.map((width, index) => {
47112 const spaces = isCompact ? 3 : width;
47114 switch (node.align[index]) {
47116 return ":" + "-".repeat(spaces - 1);
47119 return "-".repeat(spaces - 1) + ":";
47122 return ":" + "-".repeat(spaces - 2) + ":";
47125 return "-".repeat(spaces);
47130 function printRow(rowContents, isCompact) {
47131 return concat$d(["| ", join$9(" | ", isCompact ? rowContents : rowContents.map((rowContent, columnIndex) => {
47132 switch (node.align[columnIndex]) {
47134 return alignRight(rowContent, columnMaxWidths[columnIndex]);
47137 return alignCenter(rowContent, columnMaxWidths[columnIndex]);
47140 return alignLeft(rowContent, columnMaxWidths[columnIndex]);
47145 function alignLeft(text, width) {
47146 const spaces = width - util$1.getStringWidth(text);
47147 return concat$d([text, " ".repeat(spaces)]);
47150 function alignRight(text, width) {
47151 const spaces = width - util$1.getStringWidth(text);
47152 return concat$d([" ".repeat(spaces), text]);
47155 function alignCenter(text, width) {
47156 const spaces = width - util$1.getStringWidth(text);
47157 const left = Math.floor(spaces / 2);
47158 const right = spaces - left;
47159 return concat$d([" ".repeat(left), text, " ".repeat(right)]);
47163 function printRoot(path, options, print) {
47164 /** @typedef {{ index: number, offset: number }} IgnorePosition */
47166 /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
47167 const ignoreRanges = [];
47168 /** @type {IgnorePosition | null} */
47170 let ignoreStart = null;
47173 } = path.getValue();
47174 children.forEach((childNode, index) => {
47175 switch (isPrettierIgnore(childNode)) {
47177 if (ignoreStart === null) {
47180 offset: childNode.position.end.offset
47187 if (ignoreStart !== null) {
47188 ignoreRanges.push({
47189 start: ignoreStart,
47192 offset: childNode.position.start.offset
47195 ignoreStart = null;
47201 return printChildren$1(path, options, print, {
47202 processor: (childPath, index) => {
47203 if (ignoreRanges.length !== 0) {
47204 const ignoreRange = ignoreRanges[0];
47206 if (index === ignoreRange.start.index) {
47207 return concat$d([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
47210 if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
47214 if (index === ignoreRange.end.index) {
47215 ignoreRanges.shift();
47220 return childPath.call(print);
47225 function printChildren$1(path, options, print, events) {
47226 events = events || {};
47227 const postprocessor = events.postprocessor || concat$d;
47229 const processor = events.processor || (childPath => childPath.call(print));
47231 const node = path.getValue();
47234 path.map((childPath, index) => {
47235 const childNode = childPath.getValue();
47236 const result = processor(childPath, index);
47238 if (result !== false) {
47241 prevNode: lastChildNode,
47246 if (!shouldNotPrePrintHardline(childNode, data)) {
47247 parts.push(hardline$b);
47249 if (lastChildNode && TRAILING_HARDLINE_NODES.includes(lastChildNode.type)) {
47250 if (shouldPrePrintTripleHardline(childNode, data)) {
47251 parts.push(hardline$b);
47254 if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
47255 parts.push(hardline$b);
47258 if (shouldPrePrintTripleHardline(childNode, data)) {
47259 parts.push(hardline$b);
47264 parts.push(result);
47265 lastChildNode = childNode;
47268 return postprocessor(parts);
47271 function getLastDescendantNode(node) {
47272 let current = node;
47274 while (current.children && current.children.length !== 0) {
47275 current = current.children[current.children.length - 1];
47280 /** @return {false | 'next' | 'start' | 'end'} */
47283 function isPrettierIgnore(node) {
47284 if (node.type !== "html") {
47288 const match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
47289 return match === null ? false : match[1] ? match[1] : "next";
47292 function shouldNotPrePrintHardline(node, data) {
47293 const isFirstNode = data.parts.length === 0;
47294 const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type);
47295 const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type);
47296 return isFirstNode || isInlineNode || isInlineHTML;
47299 function shouldPrePrintDoubleHardline(node, data) {
47300 const isSequence = (data.prevNode && data.prevNode.type) === node.type;
47301 const isSiblingNode = isSequence && SIBLING_NODE_TYPES.includes(node.type);
47302 const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
47303 const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
47304 const isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next";
47305 const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
47306 const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line;
47307 return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem);
47310 function shouldPrePrintTripleHardline(node, data) {
47311 const isPrevNodeList = data.prevNode && data.prevNode.type === "list";
47312 const isIndentedCode = node.type === "code" && node.isIndented;
47313 return isPrevNodeList && isIndentedCode;
47316 function shouldRemainTheSameContent(path) {
47317 const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
47318 return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
47321 function normalizeDoc(doc) {
47322 return mapDoc$4(doc, currentDoc => {
47323 if (!currentDoc.parts) {
47327 if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
47328 return currentDoc.parts[0];
47331 const parts = currentDoc.parts.reduce((parts, part) => {
47332 if (part.type === "concat") {
47333 parts.push(...part.parts);
47334 } else if (part !== "") {
47340 return Object.assign({}, currentDoc, {
47341 parts: normalizeParts(parts)
47346 function printUrl(url, dangerousCharOrChars) {
47347 const dangerousChars = [" "].concat(dangerousCharOrChars || []);
47348 return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url;
47351 function printTitle(title, options, printSpace) {
47352 if (printSpace == null) {
47361 return " " + printTitle(title, options, false);
47364 if (title.includes('"') && title.includes("'") && !title.includes(")")) {
47365 return `(${title})`; // avoid escaped quotes
47366 } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
47369 const singleCount = title.split("'").length - 1;
47370 const doubleCount = title.split('"').length - 1;
47371 const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
47372 title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
47373 return `${quote}${title}${quote}`;
47376 function normalizeParts(parts) {
47377 return parts.reduce((current, part) => {
47378 const lastPart = util$1.getLast(current);
47380 if (typeof lastPart === "string" && typeof part === "string") {
47381 current.splice(-1, 1, lastPart + part);
47383 current.push(part);
47390 function clamp(value, min, max) {
47391 return value < min ? min : value > max ? max : value;
47394 function clean$5(ast, newObj, parent) {
47395 delete newObj.position;
47396 delete newObj.raw; // front-matter
47399 if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
47400 delete newObj.value;
47403 if (ast.type === "list") {
47404 delete newObj.isAligned;
47405 } // texts can be splitted or merged
47408 if (ast.type === "text") {
47412 if (ast.type === "inlineCode") {
47413 newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
47414 } // for insert pragma
47417 if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || (parent.children[0].type === "yaml" || parent.children[0].type === "toml") && parent.children[1] === ast) && ast.type === "html" && pragma$3.startWithPragma(ast.value)) {
47422 function hasPrettierIgnore$4(path) {
47423 const index = +path.getName();
47429 const prevNode = path.getParentNode().children[index - 1];
47430 return isPrettierIgnore(prevNode) === "next";
47433 var printerMarkdown = {
47434 preprocess: preprocess_1$1,
47435 print: genericPrint$4,
47437 massageAstNode: clean$5,
47438 hasPrettierIgnore: hasPrettierIgnore$4,
47439 insertPragma: pragma$3.insertPragma
47443 proseWrap: commonOptions.proseWrap,
47444 singleQuote: commonOptions.singleQuote
47447 var name$f = "Markdown";
47448 var type$d = "prose";
47452 var aceMode$d = "markdown";
47453 var codemirrorMode$a = "gfm";
47454 var codemirrorMimeType$a = "text/x-gfm";
47456 var extensions$d = [
47468 var filenames$3 = [
47471 var tmScope$d = "source.gfm";
47472 var languageId$d = 222;
47476 aliases: aliases$4,
47477 aceMode: aceMode$d,
47478 codemirrorMode: codemirrorMode$a,
47479 codemirrorMimeType: codemirrorMimeType$a,
47481 extensions: extensions$d,
47482 filenames: filenames$3,
47483 tmScope: tmScope$d,
47484 languageId: languageId$d
47487 var Markdown$1 = /*#__PURE__*/Object.freeze({
47491 aliases: aliases$4,
47492 aceMode: aceMode$d,
47493 codemirrorMode: codemirrorMode$a,
47494 codemirrorMimeType: codemirrorMimeType$a,
47496 extensions: extensions$d,
47497 filenames: filenames$3,
47498 tmScope: tmScope$d,
47499 languageId: languageId$d,
47500 'default': Markdown
47503 var require$$0$5 = getCjsExportFromNamespace(Markdown$1);
47505 const languages$4 = [createLanguage(require$$0$5, data => ({
47507 parsers: ["markdown"],
47508 vscodeLanguageIds: ["markdown"],
47509 filenames: data.filenames.concat(["README"]),
47510 extensions: data.extensions.filter(extension => extension !== ".mdx")
47511 })), createLanguage(require$$0$5, () => ({
47515 vscodeLanguageIds: ["mdx"],
47517 extensions: [".mdx"]
47519 const printers$4 = {
47520 mdast: printerMarkdown
47522 var languageMarkdown = {
47523 languages: languages$4,
47524 options: options$5,
47525 printers: printers$4
47528 var clean$6 = function (ast, newNode) {
47529 delete newNode.sourceSpan;
47530 delete newNode.startSourceSpan;
47531 delete newNode.endSourceSpan;
47532 delete newNode.nameSpan;
47533 delete newNode.valueSpan;
47535 if (ast.type === "text" || ast.type === "comment") {
47537 } // may be formatted by multiparser
47540 if (ast.type === "yaml" || ast.type === "toml") {
47544 if (ast.type === "attribute") {
47545 delete newNode.value;
47548 if (ast.type === "docType") {
47549 delete newNode.value;
47554 "CSS_DISPLAY_TAGS": {
47557 "basefont": "none",
47558 "datalist": "none",
47563 "noframes": "none",
47569 "template": "inline",
47574 "address": "block",
47575 "blockquote": "block",
47579 "figcaption": "block",
47585 "listing": "block",
47588 "plaintext": "block",
47591 "slot": "contents",
47594 "article": "block",
47604 "section": "block",
47613 "caption": "table-caption",
47614 "colgroup": "table-column-group",
47615 "col": "table-column",
47616 "thead": "table-header-group",
47617 "tbody": "table-row-group",
47618 "tfoot": "table-footer-group",
47620 "td": "table-cell",
47621 "th": "table-cell",
47622 "fieldset": "block",
47623 "button": "inline-block",
47624 "video": "inline-block",
47625 "audio": "inline-block"
47627 "CSS_DISPLAY_DEFAULT": "inline",
47628 "CSS_WHITE_SPACE_TAGS": {
47630 "plaintext": "pre",
47634 "table": "initial",
47635 "textarea": "pre-wrap"
47637 "CSS_WHITE_SPACE_DEFAULT": "normal"
47791 var htmlTagNames = /*#__PURE__*/Object.freeze({
48019 "allowpaymentrequest",
48401 basefont: basefont,
48403 blockquote: blockquote,
48410 colgroup: colgroup,
48420 fieldset: fieldset,
48424 frameset: frameset,
48449 optgroup: optgroup,
48455 progress: progress,
48465 textarea: textarea,
48476 var htmlElementAttributes = /*#__PURE__*/Object.freeze({
48484 basefont: basefont,
48486 blockquote: blockquote,
48493 colgroup: colgroup,
48503 fieldset: fieldset,
48507 frameset: frameset,
48532 optgroup: optgroup,
48538 progress: progress,
48548 textarea: textarea,
48560 var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames);
48562 var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes);
48566 CSS_DISPLAY_DEFAULT,
48567 CSS_WHITE_SPACE_TAGS,
48568 CSS_WHITE_SPACE_DEFAULT
48570 const HTML_TAGS = arrayToMap(htmlTagNames$1);
48571 const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap);
48573 function arrayToMap(array) {
48574 const map = Object.create(null);
48576 for (const value of array) {
48583 function mapObject(object, fn) {
48584 const newObject = Object.create(null);
48586 for (const key of Object.keys(object)) {
48587 newObject[key] = fn(object[key], key);
48593 function shouldPreserveContent(node, options) {
48594 if (!node.endSourceSpan) {
48598 if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") {
48600 } // unterminated node in ie conditional comment
48601 // e.g. <!--[if lt IE 9]><html><![endif]-->
48604 if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
48606 } // incomplete html in ie conditional comment
48607 // e.g. <!--[if lt IE 9]></div><![endif]-->
48610 if (node.type === "ieConditionalComment" && !node.complete) {
48612 } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
48613 // custom blocks can be written in other languages so we should preserve them to not break the code
48616 if (options.parser === "vue" && node.type === "element" && node.parent.type === "root" && !["template", "style", "script", // vue parser can be used for vue dom template as well, so we should still format top-level <html>
48617 "html"].includes(node.fullName)) {
48619 } // TODO: handle non-text children in <pre>
48622 if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
48629 function hasPrettierIgnore$5(node) {
48630 if (node.type === "attribute") {
48634 if (!node.parent) {
48638 if (typeof node.index !== "number" || node.index === 0) {
48642 const prevNode = node.parent.children[node.index - 1];
48643 return isPrettierIgnore$1(prevNode);
48646 function isPrettierIgnore$1(node) {
48647 return node.type === "comment" && node.value.trim() === "prettier-ignore";
48650 function getPrettierIgnoreAttributeCommentData(value) {
48651 const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
48661 return match[1].split(/\s+/);
48663 /** there's no opening/closing tag or it's considered not breakable */
48666 function isTextLikeNode(node) {
48667 return node.type === "text" || node.type === "comment";
48670 function isScriptLikeTag(node) {
48671 return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
48674 function isFrontMatterNode(node) {
48675 return node.type === "yaml" || node.type === "toml";
48678 function canHaveInterpolation(node) {
48679 return node.children && !isScriptLikeTag(node);
48682 function isWhitespaceSensitiveNode(node) {
48683 return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
48686 function isIndentationSensitiveNode(node) {
48687 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
48690 function isLeadingSpaceSensitiveNode(node) {
48691 const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
48693 if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
48694 return node.type === "interpolation";
48697 return isLeadingSpaceSensitive;
48699 function _isLeadingSpaceSensitiveNode() {
48700 if (isFrontMatterNode(node)) {
48704 if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
48708 if (!node.parent || node.parent.cssDisplay === "none") {
48712 if (isPreLikeNode(node.parent)) {
48716 if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
48720 if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
48728 function isTrailingSpaceSensitiveNode(node) {
48729 if (isFrontMatterNode(node)) {
48733 if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
48737 if (!node.parent || node.parent.cssDisplay === "none") {
48741 if (isPreLikeNode(node.parent)) {
48745 if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
48749 if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
48756 function isDanglingSpaceSensitiveNode(node) {
48757 return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
48760 function forceNextEmptyLine(node) {
48761 return isFrontMatterNode(node) || node.next && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
48763 /** firstChild leadingSpaces and lastChild trailingSpaces */
48766 function forceBreakContent(node) {
48767 return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
48769 /** spaces between children */
48772 function forceBreakChildren(node) {
48773 return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
48776 function preferHardlineAsLeadingSpaces(node) {
48777 return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
48780 function preferHardlineAsTrailingSpaces(node) {
48781 return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
48784 function hasSurroundingLineBreak(node) {
48785 return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
48788 function hasLeadingLineBreak(node) {
48789 return node.hasLeadingSpaces && (node.prev ? node.prev.sourceSpan.end.line < node.sourceSpan.start.line : node.parent.type === "root" || node.parent.startSourceSpan.end.line < node.sourceSpan.start.line);
48792 function hasTrailingLineBreak(node) {
48793 return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan && node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
48796 function preferHardlineAsSurroundingSpaces(node) {
48797 switch (node.type) {
48798 case "ieConditionalComment":
48804 return ["script", "select"].includes(node.name);
48810 function getLastDescendant(node) {
48811 return node.lastChild ? getLastDescendant(node.lastChild) : node;
48814 function hasNonTextChild(node) {
48815 return node.children && node.children.some(child => child.type !== "text");
48818 function inferScriptParser(node) {
48819 if (node.name === "script" && !node.attrMap.src) {
48820 if (!node.attrMap.lang && !node.attrMap.type || node.attrMap.type === "module" || node.attrMap.type === "text/javascript" || node.attrMap.type === "text/babel" || node.attrMap.type === "application/javascript" || node.attrMap.lang === "jsx") {
48824 if (node.attrMap.type === "application/x-typescript" || node.attrMap.lang === "ts" || node.attrMap.lang === "tsx") {
48825 return "typescript";
48828 if (node.attrMap.type === "text/markdown") {
48832 if (node.attrMap.type.endsWith("json") || node.attrMap.type.endsWith("importmap")) {
48836 if (node.attrMap.type === "text/x-handlebars-template") {
48841 if (node.name === "style") {
48842 if (!node.attrMap.lang || node.attrMap.lang === "postcss" || node.attrMap.lang === "css") {
48846 if (node.attrMap.lang === "scss") {
48850 if (node.attrMap.lang === "less") {
48858 function isBlockLikeCssDisplay(cssDisplay) {
48859 return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
48862 function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
48863 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
48866 function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
48867 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
48870 function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
48871 return !isBlockLikeCssDisplay(cssDisplay);
48874 function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
48875 return !isBlockLikeCssDisplay(cssDisplay);
48878 function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
48879 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
48882 function isPreLikeNode(node) {
48883 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
48886 function countParents(path, predicate = () => true) {
48889 for (let i = path.stack.length - 1; i >= 0; i--) {
48890 const value = path.stack[i];
48892 if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
48900 function hasParent(node, fn) {
48901 let current = node;
48908 current = current.parent;
48914 function getNodeCssStyleDisplay(node, options) {
48915 if (node.prev && node.prev.type === "comment") {
48916 // <!-- display: block -->
48917 const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
48924 let isInSvgForeignObject = false;
48926 if (node.type === "element" && node.namespace === "svg") {
48927 if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) {
48928 isInSvgForeignObject = true;
48930 return node.name === "svg" ? "inline-block" : "block";
48934 switch (options.htmlWhitespaceSensitivity) {
48942 return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
48946 function isUnknownNamespace(node) {
48947 return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace);
48950 function getNodeCssStyleWhiteSpace(node) {
48951 return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
48954 function getMinIndentation(text) {
48955 let minIndentation = Infinity;
48957 for (const lineText of text.split("\n")) {
48958 if (lineText.length === 0) {
48962 if (/\S/.test(lineText[0])) {
48966 const indentation = lineText.match(/^\s*/)[0].length;
48968 if (lineText.length === indentation) {
48972 if (indentation < minIndentation) {
48973 minIndentation = indentation;
48977 return minIndentation === Infinity ? 0 : minIndentation;
48980 function dedentString(text, minIndent = getMinIndentation(text)) {
48981 return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
48984 function normalizeParts$1(parts) {
48985 const newParts = [];
48986 const restParts = parts.slice();
48988 while (restParts.length !== 0) {
48989 const part = restParts.shift();
48995 if (part.type === "concat") {
48996 restParts.unshift(...part.parts);
49000 if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
49001 newParts.push(newParts.pop() + part);
49005 newParts.push(part);
49011 function identity$3(x) {
49015 function shouldNotPrintClosingTag(node, options) {
49016 return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$5(node) || shouldPreserveContent(node.parent, options));
49019 function countChars(text, char) {
49022 for (let i = 0; i < text.length; i++) {
49023 if (text[i] === char) {
49031 function unescapeQuoteEntities(text) {
49032 return text.replace(/'/g, "'").replace(/"/g, '"');
49036 HTML_ELEMENT_ATTRIBUTES,
49038 canHaveInterpolation,
49042 forceBreakChildren,
49044 forceNextEmptyLine,
49046 getNodeCssStyleDisplay,
49047 getNodeCssStyleWhiteSpace,
49048 getPrettierIgnoreAttributeCommentData,
49049 hasPrettierIgnore: hasPrettierIgnore$5,
49050 identity: identity$3,
49052 isDanglingSpaceSensitiveNode,
49054 isIndentationSensitiveNode,
49055 isLeadingSpaceSensitiveNode,
49059 isTrailingSpaceSensitiveNode,
49060 isWhitespaceSensitiveNode,
49061 isUnknownNamespace,
49062 normalizeParts: normalizeParts$1,
49063 preferHardlineAsLeadingSpaces,
49064 preferHardlineAsTrailingSpaces,
49065 shouldNotPrintClosingTag,
49066 shouldPreserveContent,
49067 unescapeQuoteEntities
49071 canHaveInterpolation: canHaveInterpolation$1,
49072 getNodeCssStyleDisplay: getNodeCssStyleDisplay$1,
49073 isDanglingSpaceSensitiveNode: isDanglingSpaceSensitiveNode$1,
49074 isIndentationSensitiveNode: isIndentationSensitiveNode$1,
49075 isLeadingSpaceSensitiveNode: isLeadingSpaceSensitiveNode$1,
49076 isTrailingSpaceSensitiveNode: isTrailingSpaceSensitiveNode$1,
49077 isWhitespaceSensitiveNode: isWhitespaceSensitiveNode$1
49079 const PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
49081 function preprocess$2(ast, options) {
49082 for (const fn of PREPROCESS_PIPELINE) {
49083 ast = fn(ast, options);
49089 function removeIgnorableFirstLf(ast
49092 return ast.map(node => {
49093 if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
49094 const [text, ...rest] = node.children;
49095 return node.clone({
49096 children: text.value.length === 1 ? rest : [text.clone({
49097 value: text.value.slice(1)
49106 function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
49110 * <!--[if ...]><!--><target><!--<![endif]-->
49112 const isTarget = node => node.type === "element" && node.prev && node.prev.type === "ieConditionalStartComment" && node.prev.sourceSpan.end.offset === node.startSourceSpan.start.offset && node.firstChild && node.firstChild.type === "ieConditionalEndComment" && node.firstChild.sourceSpan.start.offset === node.startSourceSpan.end.offset;
49114 return ast.map(node => {
49115 if (node.children) {
49116 const isTargetResults = node.children.map(isTarget);
49118 if (isTargetResults.some(Boolean)) {
49119 const newChildren = [];
49121 for (let i = 0; i < node.children.length; i++) {
49122 const child = node.children[i];
49124 if (isTargetResults[i + 1]) {
49125 // ieConditionalStartComment
49129 if (isTargetResults[i]) {
49130 const ieConditionalStartComment = child.prev;
49131 const ieConditionalEndComment = child.firstChild;
49132 const ParseSourceSpan = child.sourceSpan.constructor;
49133 const startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
49134 const sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
49135 newChildren.push(child.clone({
49136 condition: ieConditionalStartComment.condition,
49139 children: child.children.slice(1)
49144 newChildren.push(child);
49147 return node.clone({
49148 children: newChildren
49157 function mergeNodeIntoText(ast, shouldMerge, getValue) {
49158 return ast.map(node => {
49159 if (node.children) {
49160 const shouldMergeResults = node.children.map(shouldMerge);
49162 if (shouldMergeResults.some(Boolean)) {
49163 const newChildren = [];
49165 for (let i = 0; i < node.children.length; i++) {
49166 const child = node.children[i];
49168 if (child.type !== "text" && !shouldMergeResults[i]) {
49169 newChildren.push(child);
49173 const newChild = child.type === "text" ? child : child.clone({
49175 value: getValue(child)
49178 if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
49179 newChildren.push(newChild);
49183 const lastChild = newChildren.pop();
49184 const ParseSourceSpan = lastChild.sourceSpan.constructor;
49185 newChildren.push(lastChild.clone({
49186 value: lastChild.value + newChild.value,
49187 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
49191 return node.clone({
49192 children: newChildren
49201 function mergeCdataIntoText(ast
49204 return mergeNodeIntoText(ast, node => node.type === "cdata", node => `<![CDATA[${node.value}]]>`);
49207 function mergeSimpleElementIntoText(ast
49210 const isSimpleElement = node => node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && // \xA0: non-breaking whitespace
49211 !/[^\S\xA0]/.test(node.children[0].value) && !node.firstChild.hasLeadingSpaces && !node.firstChild.hasTrailingSpaces && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces && node.prev && node.prev.type === "text" && node.next && node.next.type === "text";
49213 return ast.map(node => {
49214 if (node.children) {
49215 const isSimpleElementResults = node.children.map(isSimpleElement);
49217 if (isSimpleElementResults.some(Boolean)) {
49218 const newChildren = [];
49220 for (let i = 0; i < node.children.length; i++) {
49221 const child = node.children[i];
49223 if (isSimpleElementResults[i]) {
49224 const lastChild = newChildren.pop();
49225 const nextChild = node.children[++i];
49226 const ParseSourceSpan = node.sourceSpan.constructor;
49228 isTrailingSpaceSensitive,
49231 newChildren.push(lastChild.clone({
49232 value: lastChild.value + `<${child.rawName}>` + child.firstChild.value + `</${child.rawName}>` + nextChild.value,
49233 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
49234 isTrailingSpaceSensitive,
49238 newChildren.push(child);
49242 return node.clone({
49243 children: newChildren
49252 function extractInterpolation(ast, options) {
49253 if (options.parser === "html") {
49257 const interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
49258 return ast.map(node => {
49259 if (!canHaveInterpolation$1(node)) {
49263 const newChildren = [];
49265 for (const child of node.children) {
49266 if (child.type !== "text") {
49267 newChildren.push(child);
49271 const ParseSourceSpan = child.sourceSpan.constructor;
49272 let startSourceSpan = child.sourceSpan.start;
49273 let endSourceSpan = null;
49274 const components = child.value.split(interpolationRegex);
49276 for (let i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
49277 const value = components[i];
49280 endSourceSpan = startSourceSpan.moveBy(value.length);
49282 if (value.length !== 0) {
49286 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
49293 endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
49296 type: "interpolation",
49297 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
49298 children: value.length === 0 ? [] : [{
49301 sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
49307 return node.clone({
49308 children: newChildren
49313 * - add `hasLeadingSpaces` field
49314 * - add `hasTrailingSpaces` field
49315 * - add `hasDanglingSpaces` field for parent nodes
49316 * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
49317 * - remove insensitive whitespaces
49321 function extractWhitespaces(ast
49324 const TYPE_WHITESPACE = "whitespace";
49325 return ast.map(node => {
49326 if (!node.children) {
49330 if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && node.children[0].value.trim().length === 0) {
49331 return node.clone({
49333 hasDanglingSpaces: node.children.length !== 0
49337 const isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
49338 const isIndentationSensitive = isIndentationSensitiveNode$1(node);
49339 return node.clone({
49340 isWhitespaceSensitive,
49341 isIndentationSensitive,
49342 children: node.children // extract whitespace nodes
49343 .reduce((newChildren, child) => {
49344 if (child.type !== "text" || isWhitespaceSensitive) {
49345 return newChildren.concat(child);
49348 const localChildren = [];
49349 const [, leadingSpaces, text, trailingSpaces] = child.value.match(/^(\s*)([\s\S]*?)(\s*)$/);
49351 if (leadingSpaces) {
49352 localChildren.push({
49353 type: TYPE_WHITESPACE
49357 const ParseSourceSpan = child.sourceSpan.constructor;
49360 localChildren.push({
49363 sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length))
49367 if (trailingSpaces) {
49368 localChildren.push({
49369 type: TYPE_WHITESPACE
49373 return newChildren.concat(localChildren);
49374 }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
49375 .reduce((newChildren, child, i, children) => {
49376 if (child.type === TYPE_WHITESPACE) {
49377 return newChildren;
49380 const hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
49381 const hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
49382 return newChildren.concat(Object.assign({}, child, {
49391 function addIsSelfClosing(ast
49394 return ast.map(node => Object.assign(node, {
49395 isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
49396 node.startSourceSpan === node.endSourceSpan)
49400 function addHasHtmComponentClosingTag(ast, options) {
49401 return ast.map(node => node.type !== "element" ? node : Object.assign(node, {
49402 hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
49406 function addCssDisplay(ast, options) {
49407 return ast.map(node => Object.assign(node, {
49408 cssDisplay: getNodeCssStyleDisplay$1(node, options)
49412 * - add `isLeadingSpaceSensitive` field
49413 * - add `isTrailingSpaceSensitive` field
49414 * - add `isDanglingSpaceSensitive` field for parent nodes
49418 function addIsSpaceSensitive(ast
49421 return ast.map(node => {
49422 if (!node.children) {
49426 if (node.children.length === 0) {
49427 return node.clone({
49428 isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
49432 return node.clone({
49433 children: node.children.map(child => {
49434 return Object.assign({}, child, {
49435 isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child),
49436 isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child)
49438 }).map((child, index, children) => Object.assign({}, child, {
49439 isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
49440 isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
49446 var preprocess_1$2 = preprocess$2;
49448 function hasPragma$3(text) {
49449 return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
49452 function insertPragma$6(text) {
49453 return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
49457 hasPragma: hasPragma$3,
49458 insertPragma: insertPragma$6
49468 * v-for="... in ..."
49469 * v-for="... of ..."
49470 * v-for="(..., ...) in ..."
49471 * v-for="(..., ...) of ..."
49474 function printVueFor(value, textToDoc) {
49479 } = parseVueFor(value);
49480 return concat$e([group$e(textToDoc(`function _(${left}) {}`, {
49482 __isVueForBindingLeft: true
49483 })), " ", operator, " ", textToDoc(right, {
49484 parser: "__js_expression"
49486 } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
49489 function parseVueFor(value) {
49490 const forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
49491 const forIteratorRE = /,([^,}\]]*)(?:,([^,}\]]*))?$/;
49492 const stripParensRE = /^\(|\)$/g;
49493 const inMatch = value.match(forAliasRE);
49500 res.for = inMatch[3].trim();
49501 const alias = inMatch[1].trim().replace(stripParensRE, "");
49502 const iteratorMatch = alias.match(forIteratorRE);
49504 if (iteratorMatch) {
49505 res.alias = alias.replace(forIteratorRE, "");
49506 res.iterator1 = iteratorMatch[1].trim();
49508 if (iteratorMatch[2]) {
49509 res.iterator2 = iteratorMatch[2].trim();
49516 left: `${[res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")}`,
49517 operator: inMatch[2],
49522 function printVueSlotScope(value, textToDoc) {
49523 return textToDoc(`function _(${value}) {}`, {
49525 __isVueSlotScope: true
49529 function isVueEventBindingExpression$2(eventBindingValue) {
49530 // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
49531 // arrow function or anonymous function
49532 const fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
49534 const simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104
49536 const value = eventBindingValue.trim();
49537 return fnExpRE.test(value) || simplePathRE.test(value);
49541 isVueEventBindingExpression: isVueEventBindingExpression$2,
49546 const integerRegex = /^\d+$/;
49548 function deepUnique(array) {
49549 return array.sort().filter((element, index) => {
49550 return JSON.stringify(element) !== JSON.stringify(array[index - 1]);
49554 var parse$6 = string => {
49555 return deepUnique(string.split(',').map(part => {
49557 part.trim().split(/\s+/).forEach((element, index) => {
49559 result.url = element;
49563 const value = element.slice(0, element.length - 1);
49564 const postfix = element[element.length - 1];
49565 const integerValue = parseInt(value, 10);
49566 const floatValue = parseFloat(value);
49568 if (postfix === 'w' && integerRegex.test(value)) {
49569 result.width = integerValue;
49570 } else if (postfix === 'h' && integerRegex.test(value)) {
49571 result.height = integerValue;
49572 } else if (postfix === 'x' && !Number.isNaN(floatValue)) {
49573 result.density = floatValue;
49575 throw new Error(`Invalid srcset descriptor: ${element}`);
49582 var stringify$2 = array => {
49583 return [...new Set(array.map(element => {
49584 if (!element.url) {
49585 throw new Error('URL is required');
49588 const result = [element.url];
49590 if (element.width) {
49591 result.push(`${element.width}w`);
49594 if (element.height) {
49595 result.push(`${element.height}h`);
49598 if (element.density) {
49599 result.push(`${element.density}x`);
49602 return result.join(' ');
49608 stringify: stringify$2
49614 ifBreak: ifBreak$6,
49619 const parseSrcset = srcset.parse;
49621 function printImgSrcset(value) {
49622 const srcset = parseSrcset(value);
49623 const hasW = srcset.some(src => src.width);
49624 const hasH = srcset.some(src => src.height);
49625 const hasX = srcset.some(src => src.density);
49627 if (hasW + hasH + hasX > 1) {
49628 throw new Error("Mixed descriptor in srcset is not supported");
49631 const key = hasW ? "width" : hasH ? "height" : "density";
49632 const unit = hasW ? "w" : hasH ? "h" : "x";
49634 const getMax = values => Math.max(...values);
49636 const urls = srcset.map(src => src.url);
49637 const maxUrlLength = getMax(urls.map(url => url.length));
49638 const descriptors = srcset.map(src => src[key]).map(descriptor => descriptor ? descriptor.toString() : "");
49639 const descriptorLeftLengths = descriptors.map(descriptor => {
49640 const index = descriptor.indexOf(".");
49641 return index === -1 ? descriptor.length : index;
49643 const maxDescriptorLeftLength = getMax(descriptorLeftLengths);
49644 return join$a(concat$f([",", line$9]), urls.map((url, index) => {
49645 const parts = [url];
49646 const descriptor = descriptors[index];
49649 const urlPadding = maxUrlLength - url.length + 1;
49650 const descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
49651 const alignment = " ".repeat(urlPadding + descriptorPadding);
49652 parts.push(ifBreak$6(alignment, " "), descriptor + unit);
49655 return concat$f(parts);
49659 function printClassNames(value) {
49660 return value.trim().split(/\s+/).join(" ");
49663 var syntaxAttribute = {
49671 stripTrailingHardline: stripTrailingHardline$2,
49676 breakParent: breakParent$4,
49677 dedentToRoot: dedentToRoot$2,
49680 hardline: hardline$c,
49681 ifBreak: ifBreak$7,
49685 literalline: literalline$6,
49686 markAsRoot: markAsRoot$4,
49687 softline: softline$7
49690 countChars: countChars$1,
49691 countParents: countParents$1,
49692 dedentString: dedentString$1,
49693 forceBreakChildren: forceBreakChildren$1,
49694 forceBreakContent: forceBreakContent$1,
49695 forceNextEmptyLine: forceNextEmptyLine$1,
49696 getLastDescendant: getLastDescendant$1,
49697 getPrettierIgnoreAttributeCommentData: getPrettierIgnoreAttributeCommentData$1,
49698 hasPrettierIgnore: hasPrettierIgnore$6,
49699 inferScriptParser: inferScriptParser$1,
49700 isScriptLikeTag: isScriptLikeTag$1,
49701 isTextLikeNode: isTextLikeNode$1,
49702 normalizeParts: normalizeParts$2,
49703 preferHardlineAsLeadingSpaces: preferHardlineAsLeadingSpaces$1,
49704 shouldNotPrintClosingTag: shouldNotPrintClosingTag$1,
49705 shouldPreserveContent: shouldPreserveContent$1,
49706 unescapeQuoteEntities: unescapeQuoteEntities$1
49709 replaceEndOfLineWith: replaceEndOfLineWith$2
49712 insertPragma: insertPragma$7
49715 printVueFor: printVueFor$1,
49716 printVueSlotScope: printVueSlotScope$1,
49717 isVueEventBindingExpression: isVueEventBindingExpression$3
49720 printImgSrcset: printImgSrcset$1,
49721 printClassNames: printClassNames$1
49722 } = syntaxAttribute;
49724 function concat$g(parts) {
49725 const newParts = normalizeParts$2(parts);
49726 return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
49729 function embed$4(path, print, textToDoc, options) {
49730 const node = path.getValue();
49732 switch (node.type) {
49735 if (isScriptLikeTag$1(node.parent)) {
49736 const parser = inferScriptParser$1(node.parent);
49739 const value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
49740 return builders.concat([concat$g([breakParent$4, printOpeningTagPrefix(node, options), stripTrailingHardline$2(textToDoc(value, {
49742 })), printClosingTagSuffix(node, options)])]);
49744 } else if (node.parent.type === "interpolation") {
49745 return concat$g([indent$9(concat$g([line$a, textToDoc(node.value, Object.assign({
49746 __isInHtmlInterpolation: true
49747 }, options.parser === "angular" ? {
49748 parser: "__ng_interpolation",
49749 trailingComma: "none"
49750 } : options.parser === "vue" ? {
49751 parser: "__vue_expression"
49753 parser: "__js_expression"
49754 }))])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$a]);
49764 } // lit-html: html`<my-element obj=${obj}></my-element>`
49767 if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
49768 return concat$g([node.rawName, "=", node.value]);
49769 } // lwc: html`<my-element data-for={value}></my-element>`
49772 if (options.parser === "lwc") {
49773 const interpolationRegex = /^\{[\s\S]*\}$/;
49775 if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
49776 return concat$g([node.rawName, "=", node.value]);
49780 const embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, (code, opts) => // strictly prefer single quote to avoid unnecessary html entity escape
49781 textToDoc(code, Object.assign({
49782 __isInHtmlAttribute: true
49783 }, opts)), options);
49785 if (embeddedAttributeValueDoc) {
49786 return concat$g([node.rawName, '="', group$f(mapDoc$5(embeddedAttributeValueDoc, doc => typeof doc === "string" ? doc.replace(/"/g, """) : doc)), '"']);
49793 return markAsRoot$4(concat$g(["---", hardline$c, node.value.trim().length === 0 ? "" : textToDoc(node.value, {
49799 function genericPrint$5(path, options, print) {
49800 const node = path.getValue();
49802 switch (node.type) {
49804 if (options.__onHtmlRoot) {
49805 options.__onHtmlRoot(node);
49806 } // use original concat to not break stripTrailingHardline
49809 return builders.concat([group$f(printChildren$2(path, options, print)), hardline$c]);
49812 case "ieConditionalComment":
49823 * exception: break if the opening tag breaks
49834 const shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
49835 const attrGroupId = Symbol("element-attr-group-id");
49836 return concat$g([group$f(concat$g([group$f(printOpeningTag(path, options, print), {
49838 }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$a : "" : concat$g([forceBreakContent$1(node) ? breakParent$4 : "", (childrenDoc => shouldHugContent ? ifBreak$7(indent$9(childrenDoc), childrenDoc, {
49839 groupId: attrGroupId
49840 }) : isScriptLikeTag$1(node) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$9(childrenDoc))(concat$g([shouldHugContent ? ifBreak$7(softline$7, "", {
49841 groupId: attrGroupId
49842 }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$a : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$2(softline$7) : softline$7, printChildren$2(path, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$7(softline$7, "", {
49843 groupId: attrGroupId
49844 }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$a : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp(`\\n\\s{${options.tabWidth * countParents$1(path, n => n.parent && n.parent.type !== "root")}}$`).test(node.lastChild.value) ?
49853 "" : softline$7])])), printClosingTag(node, options)]);
49856 case "ieConditionalStartComment":
49857 case "ieConditionalEndComment":
49858 return concat$g([printOpeningTagStart(node), printClosingTagEnd(node)]);
49860 case "interpolation":
49861 return concat$g([printOpeningTagStart(node, options), concat$g(path.map(print, "children")), printClosingTagEnd(node, options)]);
49865 if (node.parent.type === "interpolation") {
49866 // replace the trailing literalline with hardline for better readability
49867 const trailingNewlineRegex = /\n[^\S\n]*?$/;
49868 const hasTrailingNewline = trailingNewlineRegex.test(node.value);
49869 const value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
49870 return concat$g([concat$g(replaceEndOfLineWith$2(value, literalline$6)), hasTrailingNewline ? hardline$c : ""]);
49873 return fill$6(normalizeParts$2([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
49877 return concat$g([group$f(concat$g([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
49881 return concat$g([printOpeningTagPrefix(node, options), concat$g(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$6)), printClosingTagSuffix(node, options)]);
49886 if (node.value === null) {
49887 return node.rawName;
49890 const value = unescapeQuoteEntities$1(node.value);
49891 const singleQuoteCount = countChars$1(value, "'");
49892 const doubleQuoteCount = countChars$1(value, '"');
49893 const quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
49894 return concat$g([node.rawName, concat$g(["=", quote, concat$g(replaceEndOfLineWith$2(quote === '"' ? value.replace(/"/g, """) : value.replace(/'/g, "'"), literalline$6)), quote])]);
49899 return concat$g(replaceEndOfLineWith$2(node.raw, literalline$6));
49902 throw new Error(`Unexpected node type ${node.type}`);
49906 function printChildren$2(path, options, print) {
49907 const node = path.getValue();
49909 if (forceBreakChildren$1(node)) {
49910 return concat$g([breakParent$4, concat$g(path.map(childPath => {
49911 const childNode = childPath.getValue();
49912 const prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
49913 return concat$g([!prevBetweenLine ? "" : concat$g([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$c : ""]), printChild(childPath)]);
49917 const groupIds = node.children.map(() => Symbol(""));
49918 return concat$g(path.map((childPath, childIndex) => {
49919 const childNode = childPath.getValue();
49921 if (isTextLikeNode$1(childNode)) {
49922 if (childNode.prev && isTextLikeNode$1(childNode.prev)) {
49923 const prevBetweenLine = printBetweenLine(childNode.prev, childNode);
49925 if (prevBetweenLine) {
49926 if (forceNextEmptyLine$1(childNode.prev)) {
49927 return concat$g([hardline$c, hardline$c, printChild(childPath)]);
49930 return concat$g([prevBetweenLine, printChild(childPath)]);
49934 return printChild(childPath);
49937 const prevParts = [];
49938 const leadingParts = [];
49939 const trailingParts = [];
49940 const nextParts = [];
49941 const prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
49942 const nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
49944 if (prevBetweenLine) {
49945 if (forceNextEmptyLine$1(childNode.prev)) {
49946 prevParts.push(hardline$c, hardline$c);
49947 } else if (prevBetweenLine === hardline$c) {
49948 prevParts.push(hardline$c);
49950 if (isTextLikeNode$1(childNode.prev)) {
49951 leadingParts.push(prevBetweenLine);
49953 leadingParts.push(ifBreak$7("", softline$7, {
49954 groupId: groupIds[childIndex - 1]
49960 if (nextBetweenLine) {
49961 if (forceNextEmptyLine$1(childNode)) {
49962 if (isTextLikeNode$1(childNode.next)) {
49963 nextParts.push(hardline$c, hardline$c);
49965 } else if (nextBetweenLine === hardline$c) {
49966 if (isTextLikeNode$1(childNode.next)) {
49967 nextParts.push(hardline$c);
49970 trailingParts.push(nextBetweenLine);
49974 return concat$g([].concat(prevParts, group$f(concat$g([concat$g(leadingParts), group$f(concat$g([printChild(childPath), concat$g(trailingParts)]), {
49975 id: groupIds[childIndex]
49976 })])), nextParts));
49979 function printChild(childPath) {
49980 const child = childPath.getValue();
49982 if (hasPrettierIgnore$6(child)) {
49983 return concat$g([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$2(options.originalText.slice(options.locStart(child) + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) ? printOpeningTagStartMarker(child).length : 0), options.locEnd(child) - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) ? printClosingTagEndMarker(child, options).length : 0)), literalline$6), printClosingTagSuffix(child, options)));
49986 if (shouldPreserveContent$1(child, options)) {
49987 return concat$g([].concat(printOpeningTagPrefix(child, options), group$f(printOpeningTag(childPath, options, print)), replaceEndOfLineWith$2(options.originalText.slice(child.startSourceSpan.end.offset + (child.firstChild && needsToBorrowParentOpeningTagEndMarker(child.firstChild) ? -printOpeningTagEndMarker(child).length : 0), child.endSourceSpan.start.offset + (child.lastChild && needsToBorrowParentClosingTagStartMarker(child.lastChild) ? printClosingTagStartMarker(child, options).length : needsToBorrowLastChildClosingTagEndMarker(child) ? -printClosingTagEndMarker(child.lastChild, options).length : 0)), literalline$6), printClosingTag(child, options), printClosingTagSuffix(child, options)));
49990 return print(childPath);
49993 function printBetweenLine(prevNode, nextNode) {
49994 return isTextLikeNode$1(prevNode) && isTextLikeNode$1(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$c : line$a : "" : preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$c : softline$7 : needsToBorrowNextOpeningTagStartMarker(prevNode) && (hasPrettierIgnore$6(nextNode) ||
50000 nextNode.firstChild ||
50006 nextNode.isSelfClosing ||
50012 nextNode.type === "element" && nextNode.attrs.length !== 0) ||
50019 prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) ||
50021 * Want to write us a letter? Use our<a
50022 * ><b><a>mailing address</a></b></a
50026 needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$c : nextNode.hasLeadingSpaces ? line$a : softline$7;
50030 function printOpeningTag(path, options, print) {
50031 const node = path.getValue();
50032 const forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
50033 return concat$g([printOpeningTagStart(node, options), !node.attrs || node.attrs.length === 0 ? node.isSelfClosing ?
50038 " " : "" : concat$g([indent$9(concat$g([forceNotToBreakAttrContent ? " " : line$a, join$b(line$a, (ignoreAttributeData => {
50039 const hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? () => ignoreAttributeData : Array.isArray(ignoreAttributeData) ? attr => ignoreAttributeData.includes(attr.rawName) : () => false;
50040 return path.map(attrPath => {
50041 const attr = attrPath.getValue();
50042 return hasPrettierIgnoreAttribute(attr) ? concat$g(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(attr), options.locEnd(attr)), literalline$6)) : print(attrPath);
50044 })(node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value)))])),
50051 node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
50058 node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) ? node.isSelfClosing ? " " : "" : node.isSelfClosing ? forceNotToBreakAttrContent ? " " : line$a : forceNotToBreakAttrContent ? "" : softline$7]), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
50061 function printOpeningTagStart(node, options) {
50062 return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$g([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
50065 function printOpeningTagEnd(node) {
50066 return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
50069 function printClosingTag(node, options) {
50070 return concat$g([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
50073 function printClosingTagStart(node, options) {
50074 return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$g([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
50077 function printClosingTagEnd(node, options) {
50078 return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$g([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
50081 function needsToBorrowNextOpeningTagStartMarker(node) {
50087 return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
50090 function needsToBorrowParentOpeningTagEndMarker(node) {
50100 return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
50103 function needsToBorrowPrevClosingTagEndMarker(node) {
50113 return node.prev && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
50116 function needsToBorrowLastChildClosingTagEndMarker(node) {
50124 return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild));
50127 function needsToBorrowParentClosingTagStartMarker(node) {
50139 return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node));
50142 function printOpeningTagPrefix(node, options) {
50143 return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
50146 function printClosingTagPrefix(node, options) {
50147 return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
50150 function printClosingTagSuffix(node, options) {
50151 return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
50154 function printOpeningTagStartMarker(node) {
50155 switch (node.type) {
50156 case "ieConditionalComment":
50157 case "ieConditionalStartComment":
50158 return `<!--[if ${node.condition}`;
50160 case "ieConditionalEndComment":
50163 case "interpolation":
50167 return "<!DOCTYPE";
50170 if (node.condition) {
50171 return `<!--[if ${node.condition}]><!--><${node.rawName}`;
50177 return `<${node.rawName}`;
50181 function printOpeningTagEndMarker(node) {
50182 assert$1(!node.isSelfClosing);
50184 switch (node.type) {
50185 case "ieConditionalComment":
50189 if (node.condition) {
50190 return "><!--<![endif]-->";
50200 function printClosingTagStartMarker(node, options) {
50201 assert$1(!node.isSelfClosing);
50203 if (shouldNotPrintClosingTag$1(node, options)) {
50207 switch (node.type) {
50208 case "ieConditionalComment":
50212 if (node.hasHtmComponentClosingTag) {
50219 return `</${node.rawName}`;
50223 function printClosingTagEndMarker(node, options) {
50224 if (shouldNotPrintClosingTag$1(node, options)) {
50228 switch (node.type) {
50229 case "ieConditionalComment":
50230 case "ieConditionalEndComment":
50231 return "[endif]-->";
50233 case "ieConditionalStartComment":
50236 case "interpolation":
50240 if (node.isSelfClosing) {
50251 function getTextValueParts(node, value = node.value) {
50252 return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$2(value, literalline$6) : replaceEndOfLineWith$2(dedentString$1(value.replace(/^\s*?\n|\n\s*?$/g, "")), hardline$c) : // https://infra.spec.whatwg.org/#ascii-whitespace
50253 join$b(line$a, value.split(/[\t\n\f\r ]+/)).parts;
50256 function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
50257 const isKeyMatched = patterns => new RegExp(patterns.join("|")).test(node.fullName);
50259 const getValue = () => unescapeQuoteEntities$1(node.value);
50261 let shouldHug = false;
50263 const __onHtmlBindingRoot = (root, options) => {
50264 const rootNode = root.type === "NGRoot" ? root.node.type === "NGMicrosyntax" && root.node.body.length === 1 && root.node.body[0].type === "NGMicrosyntaxExpression" ? root.node.body[0].expression : root.node : root.type === "JsExpressionRoot" ? root.node : root;
50266 if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression" || options.parser === "__vue_expression" && (rootNode.type === "TemplateLiteral" || rootNode.type === "StringLiteral"))) {
50271 const printHug = doc => group$f(doc);
50273 const printExpand = (doc, canHaveTrailingWhitespace = true) => group$f(concat$g([indent$9(concat$g([softline$7, doc])), canHaveTrailingWhitespace ? softline$7 : ""]));
50275 const printMaybeHug = doc => shouldHug ? printHug(doc) : printExpand(doc);
50277 const textToDoc = (code, opts) => originalTextToDoc(code, Object.assign({
50278 __onHtmlBindingRoot
50281 if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
50282 return printExpand(printImgSrcset$1(getValue()));
50285 if (node.fullName === "class" && !options.parentParser) {
50286 const value = getValue();
50288 if (!value.includes("{{")) {
50289 return printClassNames$1(value);
50293 if (node.fullName === "style" && !options.parentParser) {
50294 const value = getValue();
50296 if (!value.includes("{{")) {
50297 return printExpand(textToDoc(value, {
50299 __isHTMLStyleAttribute: true
50304 if (options.parser === "vue") {
50305 if (node.fullName === "v-for") {
50306 return printVueFor$1(getValue(), textToDoc);
50309 if (node.fullName === "slot-scope") {
50310 return printVueSlotScope$1(getValue(), textToDoc);
50313 * @click="jsStatement"
50314 * @click="jsExpression"
50315 * v-on:click="jsStatement"
50316 * v-on:click="jsExpression"
50320 const vueEventBindingPatterns = ["^@", "^v-on:"];
50322 * :class="vueExpression"
50323 * v-bind:id="vueExpression"
50326 const vueExpressionBindingPatterns = ["^:", "^v-bind:"];
50328 * v-if="jsExpression"
50331 const jsExpressionBindingPatterns = ["^v-"];
50333 if (isKeyMatched(vueEventBindingPatterns)) {
50334 const value = getValue();
50335 return printMaybeHug(isVueEventBindingExpression$3(value) ? textToDoc(value, {
50336 parser: "__js_expression"
50337 }) : stripTrailingHardline$2(textToDoc(value, {
50338 parser: "__vue_event_binding"
50342 if (isKeyMatched(vueExpressionBindingPatterns)) {
50343 return printMaybeHug(textToDoc(getValue(), {
50344 parser: "__vue_expression"
50348 if (isKeyMatched(jsExpressionBindingPatterns)) {
50349 return printMaybeHug(textToDoc(getValue(), {
50350 parser: "__js_expression"
50355 if (options.parser === "angular") {
50356 const ngTextToDoc = (code, opts) => // angular does not allow trailing comma
50357 textToDoc(code, Object.assign({}, opts, {
50358 trailingComma: "none"
50361 * *directive="angularDirective"
50365 const ngDirectiveBindingPatterns = ["^\\*"];
50367 * (click)="angularStatement"
50368 * on-click="angularStatement"
50371 const ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
50373 * [target]="angularExpression"
50374 * bind-target="angularExpression"
50375 * [(target)]="angularExpression"
50376 * bindon-target="angularExpression"
50379 const ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-", // Unofficial rudimentary support for some of the most used directives of AngularJS 1.x
50380 "^ng-(if|show|hide|class|style)$"];
50382 * i18n="longDescription"
50383 * i18n-attr="longDescription"
50386 const ngI18nPatterns = ["^i18n(-.+)?$"];
50388 if (isKeyMatched(ngStatementBindingPatterns)) {
50389 return printMaybeHug(ngTextToDoc(getValue(), {
50390 parser: "__ng_action"
50394 if (isKeyMatched(ngExpressionBindingPatterns)) {
50395 return printMaybeHug(ngTextToDoc(getValue(), {
50396 parser: "__ng_binding"
50400 if (isKeyMatched(ngI18nPatterns)) {
50401 const value = getValue().trim();
50402 return printExpand(fill$6(getTextValueParts(node, value)), !value.includes("@@"));
50405 if (isKeyMatched(ngDirectiveBindingPatterns)) {
50406 return printMaybeHug(ngTextToDoc(getValue(), {
50407 parser: "__ng_directive"
50411 const interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
50412 const value = getValue();
50414 if (interpolationRegex.test(value)) {
50416 value.split(interpolationRegex).forEach((part, index) => {
50417 if (index % 2 === 0) {
50418 parts.push(concat$g(replaceEndOfLineWith$2(part, literalline$6)));
50421 parts.push(group$f(concat$g(["{{", indent$9(concat$g([line$a, ngTextToDoc(part, {
50422 parser: "__ng_interpolation",
50423 __isInHtmlInterpolation: true // to avoid unexpected `}}`
50425 })])), line$a, "}}"])));
50427 parts.push("{{", concat$g(replaceEndOfLineWith$2(part, literalline$6)), "}}");
50431 return group$f(concat$g(parts));
50438 var printerHtml = {
50439 preprocess: preprocess_1$2,
50440 print: genericPrint$5,
50441 insertPragma: insertPragma$7,
50442 massageAstNode: clean$6,
50446 const CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
50449 htmlWhitespaceSensitivity: {
50451 category: CATEGORY_HTML,
50454 description: "How to handle whitespaces in HTML.",
50457 description: "Respect the default value of CSS display property."
50460 description: "Whitespaces are considered sensitive."
50463 description: "Whitespaces are considered insensitive."
50466 vueIndentScriptAndStyle: {
50468 category: CATEGORY_HTML,
50471 description: "Indent script and style tags in Vue files."
50475 var name$g = "HTML";
50476 var type$e = "markup";
50477 var tmScope$e = "text.html.basic";
50478 var aceMode$e = "html";
50479 var codemirrorMode$b = "htmlmixed";
50480 var codemirrorMimeType$b = "text/html";
50481 var color$3 = "#e34c26";
50485 var extensions$e = [
50494 var languageId$e = 146;
50498 tmScope: tmScope$e,
50499 aceMode: aceMode$e,
50500 codemirrorMode: codemirrorMode$b,
50501 codemirrorMimeType: codemirrorMimeType$b,
50503 aliases: aliases$5,
50504 extensions: extensions$e,
50505 languageId: languageId$e
50508 var HTML$1 = /*#__PURE__*/Object.freeze({
50512 tmScope: tmScope$e,
50513 aceMode: aceMode$e,
50514 codemirrorMode: codemirrorMode$b,
50515 codemirrorMimeType: codemirrorMimeType$b,
50517 aliases: aliases$5,
50518 extensions: extensions$e,
50519 languageId: languageId$e,
50523 var name$h = "Vue";
50524 var type$f = "markup";
50525 var color$4 = "#2c3e50";
50526 var extensions$f = [
50529 var tmScope$f = "text.html.vue";
50530 var aceMode$f = "html";
50531 var languageId$f = 391;
50536 extensions: extensions$f,
50537 tmScope: tmScope$f,
50538 aceMode: aceMode$f,
50539 languageId: languageId$f
50542 var Vue$1 = /*#__PURE__*/Object.freeze({
50547 extensions: extensions$f,
50548 tmScope: tmScope$f,
50549 aceMode: aceMode$f,
50550 languageId: languageId$f,
50554 var require$$0$6 = getCjsExportFromNamespace(HTML$1);
50556 var require$$1$2 = getCjsExportFromNamespace(Vue$1);
50558 const languages$5 = [createLanguage(require$$0$6, () => ({
50561 parsers: ["angular"],
50562 vscodeLanguageIds: ["html"],
50563 extensions: [".component.html"],
50565 })), createLanguage(require$$0$6, data => ({
50568 vscodeLanguageIds: ["html"],
50569 extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
50571 })), createLanguage(require$$0$6, () => ({
50572 name: "Lightning Web Components",
50575 vscodeLanguageIds: ["html"],
50578 })), createLanguage(require$$1$2, () => ({
50581 vscodeLanguageIds: ["vue"]
50583 const printers$5 = {
50586 var languageHtml = {
50587 languages: languages$5,
50588 printers: printers$5,
50592 function isPragma(text) {
50593 return /^\s*@(prettier|format)\s*$/.test(text);
50596 function hasPragma$4(text) {
50597 return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
50600 function insertPragma$8(text) {
50601 return `# @format\n\n${text}`;
50606 hasPragma: hasPragma$4,
50607 insertPragma: insertPragma$8
50614 function getAncestorCount(path, filter) {
50616 const pathStackLength = path.stack.length - 1;
50618 for (let i = 0; i < pathStackLength; i++) {
50619 const value = path.stack[i];
50621 if (isNode(value) && filter(value)) {
50629 * @param {any} value
50630 * @param {string[]=} types
50634 function isNode(value, types) {
50635 return value && typeof value.type === "string" && (!types || types.includes(value.type));
50638 function mapNode(node, callback, parent) {
50639 return callback("children" in node ? Object.assign({}, node, {
50640 children: node.children.map(childNode => mapNode(childNode, callback, node))
50641 }) : node, parent);
50644 function defineShortcut(x, key, getter) {
50645 Object.defineProperty(x, key, {
50651 function isNextLineEmpty$5(node, text) {
50652 let newlineCount = 0;
50653 const textLength = text.length;
50655 for (let i = node.position.end.offset - 1; i < textLength; i++) {
50656 const char = text[i];
50658 if (char === "\n") {
50662 if (newlineCount === 1 && /\S/.test(char)) {
50666 if (newlineCount === 2) {
50674 function isLastDescendantNode(path) {
50675 const node = path.getValue();
50677 switch (node.type) {
50684 const pathStackLength = path.stack.length;
50686 for (let i = 1; i < pathStackLength; i++) {
50687 const item = path.stack[i];
50688 const parentItem = path.stack[i - 1];
50690 if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
50698 function getLastDescendantNode$1(node) {
50699 return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$5(node.children)) : node;
50702 function isPrettierIgnore$2(comment) {
50703 return comment.value.trim() === "prettier-ignore";
50706 function hasPrettierIgnore$7(path) {
50707 const node = path.getValue();
50709 if (node.type === "documentBody") {
50710 const document = path.getParentNode();
50711 return hasEndComments(document.head) && isPrettierIgnore$2(getLast$5(document.head.endComments));
50714 return hasLeadingComments(node) && isPrettierIgnore$2(getLast$5(node.leadingComments));
50717 function isEmptyNode(node) {
50718 return (!node.children || node.children.length === 0) && !hasComments(node);
50721 function hasComments(node) {
50722 return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$2(node) || hasEndComments(node);
50725 function hasLeadingComments(node) {
50726 return node && node.leadingComments && node.leadingComments.length !== 0;
50729 function hasMiddleComments(node) {
50730 return node && node.middleComments && node.middleComments.length !== 0;
50733 function hasIndicatorComment(node) {
50734 return node && node.indicatorComment;
50737 function hasTrailingComment$2(node) {
50738 return node && node.trailingComment;
50741 function hasEndComments(node) {
50742 return node && node.endComments && node.endComments.length !== 0;
50745 * " a b c d e f " -> [" a b", "c d", "e f "]
50749 function splitWithSingleSpace(text) {
50751 let lastPart = undefined;
50753 for (const part of text.split(/( +)/g)) {
50754 if (part !== " ") {
50755 if (lastPart === " ") {
50758 parts.push((parts.pop() || "") + part);
50760 } else if (lastPart === undefined) {
50767 if (lastPart === " ") {
50768 parts.push((parts.pop() || "") + " ");
50771 if (parts[0] === "") {
50773 parts.unshift(" " + (parts.shift() || ""));
50779 function getFlowScalarLineContents(nodeType, content, options) {
50780 const rawLineContents = content.split("\n").map((lineContent, index, lineContents) => index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimEnd() : lineContent.trimStart());
50782 if (options.proseWrap === "preserve") {
50783 return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]);
50786 return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
50787 nodeType === "quoteDouble" && getLast$5(getLast$5(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords);
50790 function getBlockValueLineContents(node, {
50795 const content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
50796 .match(/^[^\n]*?\n([\s\S]*)$/)[1];
50797 const leadingSpaceCount = node.indent === null ? (match => match ? match[1].length : Infinity)(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
50798 const rawLineContents = content.split("\n").map(lineContent => lineContent.slice(leadingSpaceCount));
50800 if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
50801 return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]));
50804 return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$5(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => lineContentWords.reduce((reduced, word) => // disallow trailing spaces
50805 reduced.length !== 0 && /\s$/.test(getLast$5(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word), [])).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords));
50807 function removeUnnecessaryTrailingNewlines(lineContents) {
50808 if (node.chomping === "keep") {
50809 return getLast$5(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
50812 let trailingNewlineCount = 0;
50814 for (let i = lineContents.length - 1; i >= 0; i--) {
50815 if (lineContents[i].length === 0) {
50816 trailingNewlineCount++;
50822 return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
50823 lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
50828 getLast: getLast$5,
50834 isNextLineEmpty: isNextLineEmpty$5,
50835 isLastDescendantNode,
50836 getBlockValueLineContents,
50837 getFlowScalarLineContents,
50838 getLastDescendantNode: getLastDescendantNode$1,
50839 hasPrettierIgnore: hasPrettierIgnore$7,
50840 hasLeadingComments,
50842 hasIndicatorComment,
50843 hasTrailingComment: hasTrailingComment$2,
50848 insertPragma: insertPragma$9,
50849 isPragma: isPragma$1
50852 getAncestorCount: getAncestorCount$1,
50853 getBlockValueLineContents: getBlockValueLineContents$1,
50854 getFlowScalarLineContents: getFlowScalarLineContents$1,
50855 getLast: getLast$6,
50856 getLastDescendantNode: getLastDescendantNode$2,
50857 hasLeadingComments: hasLeadingComments$1,
50858 hasMiddleComments: hasMiddleComments$1,
50859 hasIndicatorComment: hasIndicatorComment$1,
50860 hasTrailingComment: hasTrailingComment$3,
50861 hasEndComments: hasEndComments$1,
50862 hasPrettierIgnore: hasPrettierIgnore$8,
50863 isLastDescendantNode: isLastDescendantNode$1,
50864 isNextLineEmpty: isNextLineEmpty$6,
50866 isEmptyNode: isEmptyNode$1,
50867 defineShortcut: defineShortcut$1,
50870 const docBuilders$2 = document.builders;
50872 conditionalGroup: conditionalGroup$2,
50873 breakParent: breakParent$5,
50876 dedentToRoot: dedentToRoot$3,
50879 hardline: hardline$d,
50880 ifBreak: ifBreak$8,
50883 lineSuffix: lineSuffix$2,
50884 literalline: literalline$7,
50885 markAsRoot: markAsRoot$5,
50886 softline: softline$8
50889 replaceEndOfLineWith: replaceEndOfLineWith$3
50892 function preprocess$3(ast) {
50893 return mapNode$1(ast, defineShortcuts);
50896 function defineShortcuts(node) {
50897 switch (node.type) {
50899 defineShortcut$1(node, "head", () => node.children[0]);
50900 defineShortcut$1(node, "body", () => node.children[1]);
50903 case "documentBody":
50904 case "sequenceItem":
50905 case "flowSequenceItem":
50907 case "mappingValue":
50908 defineShortcut$1(node, "content", () => node.children[0]);
50911 case "mappingItem":
50912 case "flowMappingItem":
50913 defineShortcut$1(node, "key", () => node.children[0]);
50914 defineShortcut$1(node, "value", () => node.children[1]);
50921 function genericPrint$6(path, options, print) {
50922 const node = path.getValue();
50923 const parentNode = path.getParentNode();
50924 const tag = !node.tag ? "" : path.call(print, "tag");
50925 const anchor = !node.anchor ? "" : path.call(print, "anchor");
50926 const nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
50927 return concat$h([node.type !== "mappingValue" && hasLeadingComments$1(node) ? concat$h([join$c(hardline$d, path.map(print, "leadingComments")), hardline$d]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$1(node, ["sequence", "mapping"]) && !hasMiddleComments$1(node) ? hardline$d : " " : "", hasMiddleComments$1(node) ? concat$h([node.middleComments.length === 1 ? "" : hardline$d, join$c(hardline$d, path.map(print, "middleComments")), hardline$d]) : "", hasPrettierIgnore$8(path) ? concat$h(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset), literalline$7)) : group$g(_print(node, parentNode, path, options, print)), hasTrailingComment$3(node) && !isNode$1(node, ["document", "documentHead"]) ? lineSuffix$2(concat$h([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$5, path.call(print, "trailingComment")])) : "", nextEmptyLine, hasEndComments$1(node) && !isNode$1(node, ["documentHead", "documentBody"]) ? align$3(node.type === "sequenceItem" ? 2 : 0, concat$h([hardline$d, join$c(hardline$d, path.map(print, "endComments"))])) : ""]);
50930 function _print(node, parentNode, path, options, print) {
50931 switch (node.type) {
50933 return concat$h([join$c(hardline$d, path.map((childPath, index) => {
50934 const document = node.children[index];
50935 const nextDocument = node.children[index + 1];
50936 return concat$h([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$h([hardline$d, "...", hasTrailingComment$3(document) ? concat$h([" ", path.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$3(nextDocument.head) ? "" : concat$h([hardline$d, "---"])]);
50937 }, "children")), node.children.length === 0 || (lastDescendantNode => isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep")(getLastDescendantNode$2(node)) ? "" : hardline$d]);
50941 const nextDocument = parentNode.children[path.getName() + 1];
50942 return join$c(hardline$d, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$c(hardline$d, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path.call(print, "head"), concat$h(["---", hasTrailingComment$3(node.head) ? concat$h([" ", path.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path.call(print, "body") : ""].filter(Boolean));
50945 case "documentHead":
50946 return join$c(hardline$d, [].concat(path.map(print, "children"), path.map(print, "endComments")));
50948 case "documentBody":
50950 const children = join$c(hardline$d, path.map(print, "children")).parts;
50951 const endComments = join$c(hardline$d, path.map(print, "endComments")).parts;
50952 const separator = children.length === 0 || endComments.length === 0 ? "" : (lastDescendantNode => isNode$1(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
50953 "" : // an extra newline for better readability
50954 concat$h([hardline$d, hardline$d]) : hardline$d)(getLastDescendantNode$2(node));
50955 return concat$h([].concat(children, separator, endComments));
50959 return concat$h(["%", join$c(" ", [node.name].concat(node.parameters))]);
50962 return concat$h(["#", node.value]);
50965 return concat$h(["*", node.value]);
50968 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
50971 return concat$h(["&", node.value]);
50974 return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
50976 case "quoteDouble":
50977 case "quoteSingle":
50979 const singleQuote = "'";
50980 const doubleQuote = '"';
50981 const raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
50983 if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
50984 // only quoteDouble can use escape chars
50985 // and quoteSingle do not need to escape backslashes
50986 const originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
50987 return concat$h([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
50988 } else if (raw.includes(doubleQuote)) {
50989 return concat$h([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
50990 .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
50993 if (raw.includes(singleQuote)) {
50994 return concat$h([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
50995 raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
50998 const quote = options.singleQuote ? singleQuote : doubleQuote;
50999 return concat$h([quote, printFlowScalarContent(node.type, raw, options), quote]);
51002 case "blockFolded":
51003 case "blockLiteral":
51005 const parentIndent = getAncestorCount$1(path, ancestorNode => isNode$1(ancestorNode, ["sequence", "mapping"]));
51006 const isLastDescendant = isLastDescendantNode$1(path);
51007 return concat$h([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment$1(node) ? concat$h([" ", path.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$3 : dedentToRoot$3)(align$3(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$h(getBlockValueLineContents$1(node, {
51011 }).reduce((reduced, lineWords, index, lineContents) => reduced.concat(index === 0 ? hardline$d : "", fill$7(join$c(line$b, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$d : markAsRoot$5(literalline$7) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$d) : dedentToRoot$3(literalline$7) : ""), []))))]);
51015 return join$c(hardline$d, path.map(print, "children"));
51017 case "sequenceItem":
51018 return concat$h(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]);
51021 return !node.content ? "" : path.call(print, "content");
51023 case "mappingValue":
51024 return !node.content ? "" : path.call(print, "content");
51027 return join$c(hardline$d, path.map(print, "children"));
51029 case "mappingItem":
51030 case "flowMappingItem":
51032 const isEmptyMappingKey = isEmptyNode$1(node.key);
51033 const isEmptyMappingValue = isEmptyNode$1(node.value);
51035 if (isEmptyMappingKey && isEmptyMappingValue) {
51036 return concat$h([": "]);
51039 const key = path.call(print, "key");
51040 const value = path.call(print, "value");
51042 if (isEmptyMappingValue) {
51043 return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$3(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$h(["? ", align$3(2, key)]);
51046 if (isEmptyMappingKey) {
51047 return concat$h([": ", align$3(2, value)]);
51050 const groupId = Symbol("mappingKey");
51051 const forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode(node.key.content);
51052 return forceExplicitKey ? concat$h(["? ", align$3(2, key), hardline$d, join$c("", path.map(print, "value", "leadingComments").map(comment => concat$h([comment, hardline$d]))), ": ", align$3(2, value)]) : // force singleline
51053 isSingleLineNode(node.key.content) && !hasLeadingComments$1(node.key.content) && !hasMiddleComments$1(node.key.content) && !hasTrailingComment$3(node.key.content) && !hasEndComments$1(node.key) && !hasLeadingComments$1(node.value.content) && !hasMiddleComments$1(node.value.content) && !hasEndComments$1(node.value) && isAbsolutelyPrintedAsSingleLineNode(node.value.content, options) ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$2([concat$h([group$g(concat$h([ifBreak$8("? "), group$g(align$3(2, key), {
51055 })])), ifBreak$8(concat$h([hardline$d, ": ", align$3(2, value)]), indent(concat$h([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments$1(node.value.content) || hasEndComments$1(node.value) && node.value.content && !isNode$1(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$3(node.key.content) && isInlineNode(node.value.content) || isNode$1(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$d : !node.value.content ? "" : line$b, value])), {
51060 case "flowMapping":
51061 case "flowSequence":
51063 const openMarker = node.type === "flowMapping" ? "{" : "[";
51064 const closeMarker = node.type === "flowMapping" ? "}" : "]";
51065 const bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$b : softline$8;
51067 const isLastItemEmptyMappingItem = node.children.length !== 0 && (lastItem => lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value))(getLast$6(node.children));
51069 return concat$h([openMarker, indent(concat$h([bracketSpacing, concat$h(path.map((childPath, index) => concat$h([print(childPath), index === node.children.length - 1 ? "" : concat$h([",", line$b, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]), "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
51072 case "flowSequenceItem":
51073 return path.call(print, "content");
51074 // istanbul ignore next
51077 throw new Error(`Unexpected node type ${node.type}`);
51080 function indent(doc) {
51081 return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
51085 function align$3(n, doc) {
51086 return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
51089 function isInlineNode(node) {
51094 switch (node.type) {
51096 case "quoteDouble":
51097 case "quoteSingle":
51099 case "flowMapping":
51100 case "flowSequence":
51108 function isSingleLineNode(node) {
51113 switch (node.type) {
51115 case "quoteDouble":
51116 case "quoteSingle":
51117 return node.position.start.line === node.position.end.line;
51127 function shouldPrintDocumentBody(document) {
51128 return document.body.children.length !== 0 || hasEndComments$1(document.body);
51131 function shouldPrintDocumentEndMarker(document, nextDocument) {
51134 *... # trailingComment
51136 hasTrailingComment$3(document) || nextDocument && (
51142 nextDocument.head.children.length !== 0 ||
51148 hasEndComments$1(nextDocument.head))
51152 function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
51156 * preserve the first document head end marker
51158 root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
51163 document.head.children.length !== 0 ||
51168 hasEndComments$1(document.head) ||
51170 * --- # trailing comment
51172 hasTrailingComment$3(document.head)) {
51176 if (shouldPrintDocumentEndMarker(document, nextDocument)) {
51180 return nextDocument ? "root" : false;
51183 function isAbsolutelyPrintedAsSingleLineNode(node, options) {
51188 switch (node.type) {
51190 case "quoteSingle":
51191 case "quoteDouble":
51201 if (options.proseWrap === "preserve") {
51202 return node.position.start.line === node.position.end.line;
51205 if ( // backslash-newline
51206 /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
51210 switch (options.proseWrap) {
51212 return !node.value.includes("\n");
51215 return !/[\n ]/.test(node.value);
51216 // istanbul ignore next
51223 function needsSpaceInFrontOfMappingValue(node) {
51224 return node.key.content && node.key.content.type === "alias";
51227 function printNextEmptyLine(path, originalText) {
51228 const node = path.getValue();
51229 const root = path.stack[0];
51230 root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
51232 if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
51233 if (isNextLineEmpty$6(node, originalText)) {
51234 root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
51242 function printFlowScalarContent(nodeType, content, options) {
51243 const lineContents = getFlowScalarLineContents$1(nodeType, content, options);
51244 return join$c(hardline$d, lineContents.map(lineContentWords => fill$7(join$c(line$b, lineContentWords).parts)));
51247 function clean$7(node, newNode
51250 if (isNode$1(newNode)) {
51251 delete newNode.position;
51253 switch (newNode.type) {
51256 if (isPragma$1(newNode.value)) {
51262 case "quoteDouble":
51263 case "quoteSingle":
51264 newNode.type = "quote";
51270 var printerYaml = {
51271 preprocess: preprocess$3,
51272 print: genericPrint$6,
51273 massageAstNode: clean$7,
51274 insertPragma: insertPragma$9
51278 bracketSpacing: commonOptions.bracketSpacing,
51279 singleQuote: commonOptions.singleQuote,
51280 proseWrap: commonOptions.proseWrap
51283 var name$i = "YAML";
51284 var type$g = "data";
51285 var tmScope$g = "source.yaml";
51289 var extensions$g = [
51297 ".yaml-tmlanguage",
51301 var filenames$4 = [
51308 var aceMode$g = "yaml";
51309 var codemirrorMode$c = "yaml";
51310 var codemirrorMimeType$c = "text/x-yaml";
51311 var languageId$g = 407;
51315 tmScope: tmScope$g,
51316 aliases: aliases$6,
51317 extensions: extensions$g,
51318 filenames: filenames$4,
51319 aceMode: aceMode$g,
51320 codemirrorMode: codemirrorMode$c,
51321 codemirrorMimeType: codemirrorMimeType$c,
51322 languageId: languageId$g
51325 var YAML$1 = /*#__PURE__*/Object.freeze({
51329 tmScope: tmScope$g,
51330 aliases: aliases$6,
51331 extensions: extensions$g,
51332 filenames: filenames$4,
51333 aceMode: aceMode$g,
51334 codemirrorMode: codemirrorMode$c,
51335 codemirrorMimeType: codemirrorMimeType$c,
51336 languageId: languageId$g,
51340 var require$$0$7 = getCjsExportFromNamespace(YAML$1);
51342 const languages$6 = [createLanguage(require$$0$7, data => ({
51345 vscodeLanguageIds: ["yaml"],
51346 // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629
51347 filenames: data.filenames.filter(filename => filename !== "yarn.lock")
51349 var languageYaml = {
51350 languages: languages$6,
51357 // plugin will look for `eval("require")()` and transform to `require()` in the bundle,
51358 // and rewrite the paths to require from the top-level.
51359 // We need to list the parsers and getters so we can load them only when necessary.
51362 var internalPlugins = [// JS
51367 return require("./parser-babel").parsers.babel;
51370 get "babel-flow"() {
51371 return require("./parser-babel").parsers["babel-flow"];
51375 return require("./parser-babel").parsers["babel-ts"];
51379 return require("./parser-babel").parsers.json;
51383 return require("./parser-babel").parsers.json5;
51386 get "json-stringify"() {
51387 return require("./parser-babel").parsers["json-stringify"];
51390 get __js_expression() {
51391 return require("./parser-babel").parsers.__js_expression;
51394 get __vue_expression() {
51395 return require("./parser-babel").parsers.__vue_expression;
51398 get __vue_event_binding() {
51399 return require("./parser-babel").parsers.__vue_event_binding;
51404 return require("./parser-flow").parsers.flow;
51409 return require("./parser-typescript").parsers.typescript;
51412 // JS - Angular Action
51413 get __ng_action() {
51414 return require("./parser-angular").parsers.__ng_action;
51417 // JS - Angular Binding
51418 get __ng_binding() {
51419 return require("./parser-angular").parsers.__ng_binding;
51422 // JS - Angular Interpolation
51423 get __ng_interpolation() {
51424 return require("./parser-angular").parsers.__ng_interpolation;
51427 // JS - Angular Directive
51428 get __ng_directive() {
51429 return require("./parser-angular").parsers.__ng_directive;
51436 // TODO: switch these to just `postcss` and use `language` instead.
51438 return require("./parser-postcss").parsers.css;
51442 return require("./parser-postcss").parsers.less;
51446 return require("./parser-postcss").parsers.scss;
51451 languageHandlebars, {
51454 return require("./parser-glimmer").parsers.glimmer;
51462 return require("./parser-graphql").parsers.graphql;
51467 languageMarkdown, {
51470 return require("./parser-markdown").parsers.remark;
51474 return require("./parser-markdown").parsers.remark;
51478 return require("./parser-markdown").parsers.mdx;
51486 return require("./parser-html").parsers.html;
51491 return require("./parser-html").parsers.vue;
51496 return require("./parser-html").parsers.angular;
51499 // Lightning Web Components
51501 return require("./parser-html").parsers.lwc;
51509 return require("./parser-yaml").parsers.yaml;
51515 const memoizedLoad = mem_1(load, {
51516 cacheKey: JSON.stringify
51518 const memoizedSearch = mem_1(findPluginsInNodeModules);
51520 const clearCache$2 = () => {
51521 mem_1.clear(memoizedLoad);
51522 mem_1.clear(memoizedSearch);
51525 function load(plugins, pluginSearchDirs) {
51530 if (!pluginSearchDirs) {
51531 pluginSearchDirs = [];
51532 } // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
51535 if (!pluginSearchDirs.length) {
51536 const autoLoadDir = thirdParty.findParentDir(__dirname, "node_modules");
51539 pluginSearchDirs = [autoLoadDir];
51543 const [externalPluginNames, externalPluginInstances] = partition_1(plugins, plugin => typeof plugin === "string");
51544 const externalManualLoadPluginInfos = externalPluginNames.map(pluginName => {
51549 requirePath = resolve_1(path$2.resolve(process.cwd(), pluginName));
51551 // try node modules
51552 requirePath = resolve_1(pluginName, {
51553 paths: [process.cwd()]
51562 const externalAutoLoadPluginInfos = pluginSearchDirs.map(pluginSearchDir => {
51563 const resolvedPluginSearchDir = path$2.resolve(process.cwd(), pluginSearchDir);
51564 const nodeModulesDir = path$2.resolve(resolvedPluginSearchDir, "node_modules"); // In some fringe cases (ex: files "mounted" as virtual directories), the
51565 // isDirectory(resolvedPluginSearchDir) check might be false even though
51566 // the node_modules actually exists.
51568 if (!isDirectory$1(nodeModulesDir) && !isDirectory$1(resolvedPluginSearchDir)) {
51569 throw new Error(`${pluginSearchDir} does not exist or is not a directory`);
51572 return memoizedSearch(nodeModulesDir).map(pluginName => ({
51574 requirePath: resolve_1(pluginName, {
51575 paths: [resolvedPluginSearchDir]
51578 }).reduce((a, b) => a.concat(b), []);
51579 const externalPlugins = uniqBy_1(externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath").map(externalPluginInfo => Object.assign({
51580 name: externalPluginInfo.name
51581 }, require(externalPluginInfo.requirePath))).concat(externalPluginInstances);
51582 return internalPlugins.concat(externalPlugins);
51585 function findPluginsInNodeModules(nodeModulesDir) {
51586 const pluginPackageJsonPaths = globby$1.sync(["prettier-plugin-*/package.json", "@*/prettier-plugin-*/package.json", "@prettier/plugin-*/package.json"], {
51587 cwd: nodeModulesDir,
51588 expandDirectories: false
51590 return pluginPackageJsonPaths.map(path$2.dirname);
51593 function isDirectory$1(dir) {
51595 return fs$3.statSync(dir).isDirectory();
51601 var loadPlugins = {
51602 loadPlugins: memoizedLoad,
51603 clearCache: clearCache$2
51610 getSupportInfo: getSupportInfo$2
51613 function _withPlugins(fn, optsArgIdx = 1 // Usually `opts` is the 2nd argument
51615 return (...args) => {
51616 const opts = args[optsArgIdx] || {};
51617 args[optsArgIdx] = Object.assign({}, opts, {
51618 plugins: loadPlugins.loadPlugins(opts.plugins, opts.pluginSearchDirs)
51620 return fn(...args);
51624 function withPlugins(fn, optsArgIdx) {
51625 const resultingFn = _withPlugins(fn, optsArgIdx);
51629 resultingFn.sync = _withPlugins(fn.sync, optsArgIdx);
51632 return resultingFn;
51635 const formatWithCursor = withPlugins(core.formatWithCursor);
51639 format(text, opts) {
51640 return formatWithCursor(text, opts).formatted;
51643 check(text, opts) {
51646 } = formatWithCursor(text, opts);
51647 return formatted === text;
51651 resolveConfig: resolveConfig_1.resolveConfig,
51652 resolveConfigFile: resolveConfig_1.resolveConfigFile,
51654 clearConfigCache() {
51655 resolveConfig_1.clearCache();
51656 loadPlugins.clearCache();
51660 /** @type {typeof getFileInfo} */
51661 withPlugins(getFileInfo_1),
51663 /** @type {typeof getSupportInfo} */
51664 withPlugins(getSupportInfo$2, 0),
51665 version: version$2,
51668 /* istanbul ignore next */
51670 parse: withPlugins(core.parse),
51671 formatAST: withPlugins(core.formatAST),
51672 formatDoc: withPlugins(core.formatDoc),
51673 printToDoc: withPlugins(core.printToDoc),
51674 printDocToString: withPlugins(core.printDocToString)
51678 var prettier = src$1;
51680 module.exports = prettier;