1 (function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (global = global || self, global.prettier = factory());
5 }(this, (function () { 'use strict';
8 var version = "1.19.1";
9 var description = "Prettier is an opinionated code formatter";
11 prettier: "./bin/prettier.js"
13 var repository = "prettier/prettier";
14 var homepage = "https://prettier.io";
15 var author = "James Long";
17 var main = "./index.js";
22 "@angular/compiler": "8.2.13",
23 "@babel/code-frame": "7.5.5",
24 "@babel/parser": "7.7.3",
25 "@glimmer/syntax": "0.41.0",
26 "@iarna/toml": "2.2.3",
27 "@typescript-eslint/typescript-estree": "2.6.1",
28 "angular-estree-parser": "1.1.5",
29 "angular-html-parser": "1.3.0",
37 editorconfig: "0.15.3",
38 "editorconfig-to-prettier": "0.1.1",
39 "escape-string-regexp": "1.0.5",
41 "find-parent-dir": "0.3.0",
42 "find-project-root": "1.1.1",
43 "flow-parser": "0.111.3",
44 "get-stream": "4.1.0",
47 "html-element-attributes": "2.2.0",
48 "html-styles": "1.0.0",
49 "html-tag-names": "1.1.4",
52 "jest-docblock": "24.9.0",
53 "json-stable-stringify": "1.0.1",
55 "lines-and-columns": "1.1.6",
56 "linguist-languages": "7.6.0",
57 "lodash.uniqby": "4.7.0",
61 "n-readlines": "1.0.0",
62 "normalize-path": "3.0.0",
63 "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
64 "postcss-less": "2.0.0",
65 "postcss-media-query-parser": "0.2.3",
66 "postcss-scss": "2.0.0",
67 "postcss-selector-parser": "2.2.3",
68 "postcss-values-parser": "1.5.0",
69 "regexp-util": "1.2.2",
70 "remark-math": "1.0.6",
71 "remark-parse": "5.0.0",
74 "string-width": "4.1.0",
76 "unicode-regex": "3.0.0",
79 "yaml-unist-parser": "1.1.1"
81 var devDependencies = {
82 "@babel/core": "7.7.2",
83 "@babel/preset-env": "7.7.1",
84 "@rollup/plugin-alias": "2.2.0",
85 "@rollup/plugin-replace": "2.2.1",
86 "babel-loader": "8.0.6",
88 "builtin-modules": "3.1.0",
92 "eslint-config-prettier": "6.5.0",
93 "eslint-formatter-friendly": "7.0.0",
94 "eslint-plugin-import": "2.18.2",
95 "eslint-plugin-prettier": "3.1.1",
96 "eslint-plugin-react": "7.16.0",
99 "jest-junit": "9.0.0",
100 "jest-snapshot-serializer-ansi": "1.0.0",
101 "jest-snapshot-serializer-raw": "1.1.0",
102 "jest-watch-typeahead": "0.4.0",
108 "rollup-plugin-babel": "4.3.3",
109 "rollup-plugin-commonjs": "10.1.0",
110 "rollup-plugin-json": "4.0.0",
111 "rollup-plugin-node-globals": "1.4.0",
112 "rollup-plugin-node-resolve": "5.2.0",
113 "rollup-plugin-terser": "5.1.2",
115 "snapshot-diff": "0.4.0",
116 "strip-ansi": "5.2.0",
117 "synchronous-promise": "2.0.10",
119 "terser-webpack-plugin": "2.2.1",
123 prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
124 "prepare-release": "yarn && yarn build && yarn test:dist",
126 "test:dist": "node ./scripts/test-dist.js",
127 "test-integration": "jest tests_integration",
128 "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",
129 "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",
130 "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",
131 "check-types": "tsc",
132 lint: "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
133 "lint-docs": "prettylint {.,docs,website,website/blog}/*.md",
134 "lint-dist": "eslint --no-eslintrc --no-ignore --env=browser \"dist/!(bin-prettier|index|third-party).js\"",
135 build: "node --max-old-space-size=3072 ./scripts/build/build.js",
136 "build-docs": "node ./scripts/build-docs.js",
137 "check-deps": "node ./scripts/check-deps.js",
138 spellcheck: "npx -p cspell@4.0.31 cspell {bin,scripts,src}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md"
143 description: description,
145 repository: repository,
151 dependencies: dependencies,
152 devDependencies: devDependencies,
156 var _package$1 = /*#__PURE__*/Object.freeze({
160 description: description,
162 repository: repository,
168 dependencies: dependencies,
169 devDependencies: devDependencies,
174 function _typeof(obj) {
175 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
176 _typeof = function (obj) {
180 _typeof = function (obj) {
181 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
188 function _classCallCheck(instance, Constructor) {
189 if (!(instance instanceof Constructor)) {
190 throw new TypeError("Cannot call a class as a function");
194 function _defineProperties(target, props) {
195 for (var i = 0; i < props.length; i++) {
196 var descriptor = props[i];
197 descriptor.enumerable = descriptor.enumerable || false;
198 descriptor.configurable = true;
199 if ("value" in descriptor) descriptor.writable = true;
200 Object.defineProperty(target, descriptor.key, descriptor);
204 function _createClass(Constructor, protoProps, staticProps) {
205 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
206 if (staticProps) _defineProperties(Constructor, staticProps);
210 function _defineProperty(obj, key, value) {
212 Object.defineProperty(obj, key, {
225 function _inherits(subClass, superClass) {
226 if (typeof superClass !== "function" && superClass !== null) {
227 throw new TypeError("Super expression must either be null or a function");
230 subClass.prototype = Object.create(superClass && superClass.prototype, {
237 if (superClass) _setPrototypeOf(subClass, superClass);
240 function _getPrototypeOf(o) {
241 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
242 return o.__proto__ || Object.getPrototypeOf(o);
244 return _getPrototypeOf(o);
247 function _setPrototypeOf(o, p) {
248 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
253 return _setPrototypeOf(o, p);
256 function isNativeReflectConstruct() {
257 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
258 if (Reflect.construct.sham) return false;
259 if (typeof Proxy === "function") return true;
262 Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
269 function _construct(Parent, args, Class) {
270 if (isNativeReflectConstruct()) {
271 _construct = Reflect.construct;
273 _construct = function _construct(Parent, args, Class) {
275 a.push.apply(a, args);
276 var Constructor = Function.bind.apply(Parent, a);
277 var instance = new Constructor();
278 if (Class) _setPrototypeOf(instance, Class.prototype);
283 return _construct.apply(null, arguments);
286 function _isNativeFunction(fn) {
287 return Function.toString.call(fn).indexOf("[native code]") !== -1;
290 function _wrapNativeSuper(Class) {
291 var _cache = typeof Map === "function" ? new Map() : undefined;
293 _wrapNativeSuper = function _wrapNativeSuper(Class) {
294 if (Class === null || !_isNativeFunction(Class)) return Class;
296 if (typeof Class !== "function") {
297 throw new TypeError("Super expression must either be null or a function");
300 if (typeof _cache !== "undefined") {
301 if (_cache.has(Class)) return _cache.get(Class);
303 _cache.set(Class, Wrapper);
307 return _construct(Class, arguments, _getPrototypeOf(this).constructor);
310 Wrapper.prototype = Object.create(Class.prototype, {
318 return _setPrototypeOf(Wrapper, Class);
321 return _wrapNativeSuper(Class);
324 function _assertThisInitialized(self) {
325 if (self === void 0) {
326 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
332 function _possibleConstructorReturn(self, call) {
333 if (call && (typeof call === "object" || typeof call === "function")) {
337 return _assertThisInitialized(self);
340 function _superPropBase(object, property) {
341 while (!Object.prototype.hasOwnProperty.call(object, property)) {
342 object = _getPrototypeOf(object);
343 if (object === null) break;
349 function _get(target, property, receiver) {
350 if (typeof Reflect !== "undefined" && Reflect.get) {
353 _get = function _get(target, property, receiver) {
354 var base = _superPropBase(target, property);
357 var desc = Object.getOwnPropertyDescriptor(base, property);
360 return desc.get.call(receiver);
367 return _get(target, property, receiver || target);
370 function _taggedTemplateLiteral(strings, raw) {
372 raw = strings.slice(0);
375 return Object.freeze(Object.defineProperties(strings, {
377 value: Object.freeze(raw)
382 function _slicedToArray(arr, i) {
383 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
386 function _toConsumableArray(arr) {
387 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
390 function _arrayWithoutHoles(arr) {
391 if (Array.isArray(arr)) {
392 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
398 function _arrayWithHoles(arr) {
399 if (Array.isArray(arr)) return arr;
402 function _iterableToArray(iter) {
403 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
406 function _iterableToArrayLimit(arr, i) {
407 if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
417 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
420 if (i && _arr.length === i) break;
427 if (!_n && _i["return"] != null) _i["return"]();
436 function _nonIterableSpread() {
437 throw new TypeError("Invalid attempt to spread non-iterable instance");
440 function _nonIterableRest() {
441 throw new TypeError("Invalid attempt to destructure non-iterable instance");
447 diff: function diff(oldString, newString) {
448 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
449 var callback = options.callback;
451 if (typeof options === 'function') {
456 this.options = options;
459 function done(value) {
461 setTimeout(function () {
462 callback(undefined, value);
468 } // Allow subclasses to massage the input prior to running
471 oldString = this.castInput(oldString);
472 newString = this.castInput(newString);
473 oldString = this.removeEmpty(this.tokenize(oldString));
474 newString = this.removeEmpty(this.tokenize(newString));
475 var newLen = newString.length,
476 oldLen = oldString.length;
478 var maxEditLength = newLen + oldLen;
482 }]; // Seed editLength = 0, i.e. the content starts with the same values
484 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
486 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
487 // Identity per the equality and tokenizer
489 value: this.join(newString),
490 count: newString.length
492 } // Main worker method. checks all permutations of a given edit length for acceptance.
495 function execEditLength() {
496 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
497 var basePath = void 0;
499 var addPath = bestPath[diagonalPath - 1],
500 removePath = bestPath[diagonalPath + 1],
501 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
504 // No one else is going to attempt to use this value, clear it
505 bestPath[diagonalPath - 1] = undefined;
508 var canAdd = addPath && addPath.newPos + 1 < newLen,
509 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
511 if (!canAdd && !canRemove) {
512 // If this path is a terminal then prune
513 bestPath[diagonalPath] = undefined;
515 } // Select the diagonal that we want to branch from. We select the prior
516 // path whose position in the new string is the farthest from the origin
517 // and does not pass the bounds of the diff graph
520 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
521 basePath = clonePath(removePath);
522 self.pushComponent(basePath.components, undefined, true);
524 basePath = addPath; // No need to clone, we've pulled it from the list
527 self.pushComponent(basePath.components, true, undefined);
530 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
532 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
533 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
535 // Otherwise track this path as a potential candidate and continue.
536 bestPath[diagonalPath] = basePath;
541 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
542 // sync and async mode which is never fun. Loops over execEditLength until a value
548 setTimeout(function () {
549 // This should not happen, but we want to be safe.
551 /* istanbul ignore next */
552 if (editLength > maxEditLength) {
556 if (!execEditLength()) {
562 while (editLength <= maxEditLength) {
563 var ret = execEditLength();
571 pushComponent: function pushComponent(components, added, removed) {
572 var last = components[components.length - 1];
574 if (last && last.added === added && last.removed === removed) {
575 // We need to clone here as the component clone operation is just
576 // as shallow array clone
577 components[components.length - 1] = {
578 count: last.count + 1,
590 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
591 var newLen = newString.length,
592 oldLen = oldString.length,
593 newPos = basePath.newPos,
594 oldPos = newPos - diagonalPath,
597 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
604 basePath.components.push({
609 basePath.newPos = newPos;
612 equals: function equals(left, right) {
613 if (this.options.comparator) {
614 return this.options.comparator(left, right);
616 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
619 removeEmpty: function removeEmpty(array) {
622 for (var i = 0; i < array.length; i++) {
630 castInput: function castInput(value) {
633 tokenize: function tokenize(value) {
634 return value.split('');
636 join: function join(chars) {
637 return chars.join('');
641 function buildValues(diff, components, newString, oldString, useLongestToken) {
642 var componentPos = 0,
643 componentLen = components.length,
647 for (; componentPos < componentLen; componentPos++) {
648 var component = components[componentPos];
650 if (!component.removed) {
651 if (!component.added && useLongestToken) {
652 var value = newString.slice(newPos, newPos + component.count);
653 value = value.map(function (value, i) {
654 var oldValue = oldString[oldPos + i];
655 return oldValue.length > value.length ? oldValue : value;
657 component.value = diff.join(value);
659 component.value = diff.join(newString.slice(newPos, newPos + component.count));
662 newPos += component.count; // Common case
664 if (!component.added) {
665 oldPos += component.count;
668 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
669 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
670 // The diffing algorithm is tied to add then remove output and this is the simplest
671 // route to get the desired output with minimal overhead.
673 if (componentPos && components[componentPos - 1].added) {
674 var tmp = components[componentPos - 1];
675 components[componentPos - 1] = components[componentPos];
676 components[componentPos] = tmp;
679 } // Special case handle for when one terminal is ignored (i.e. whitespace).
680 // For this case we merge the terminal into the prior string and drop the change.
681 // This is only available for string mode.
684 var lastComponent = components[componentLen - 1];
686 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
687 components[componentLen - 2].value += lastComponent.value;
694 function clonePath(path) {
697 components: path.components.slice(0)
701 var characterDiff = new Diff();
703 function diffChars(oldStr, newStr, options) {
704 return characterDiff.diff(oldStr, newStr, options);
707 function generateOptions(options, defaults) {
708 if (typeof options === 'function') {
709 defaults.callback = options;
710 } else if (options) {
711 for (var name in options) {
712 /* istanbul ignore else */
713 if (options.hasOwnProperty(name)) {
714 defaults[name] = options[name];
721 // Ranges and exceptions:
722 // Latin-1 Supplement, 0080–00FF
723 // - U+00D7 × Multiplication sign
724 // - U+00F7 ÷ Division sign
725 // Latin Extended-A, 0100–017F
726 // Latin Extended-B, 0180–024F
727 // IPA Extensions, 0250–02AF
728 // Spacing Modifier Letters, 02B0–02FF
729 // - U+02C7 ˇ ˇ Caron
730 // - U+02D8 ˘ ˘ Breve
731 // - U+02D9 ˙ ˙ Dot Above
732 // - U+02DA ˚ ˚ Ring Above
733 // - U+02DB ˛ ˛ Ogonek
734 // - U+02DC ˜ ˜ Small Tilde
735 // - U+02DD ˝ ˝ Double Acute Accent
736 // Latin Extended Additional, 1E00–1EFF
739 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
740 var reWhitespace = /\S/;
741 var wordDiff = new Diff();
743 wordDiff.equals = function (left, right) {
744 if (this.options.ignoreCase) {
745 left = left.toLowerCase();
746 right = right.toLowerCase();
749 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
752 wordDiff.tokenize = function (value) {
753 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.
755 for (var i = 0; i < tokens.length - 1; i++) {
756 // If we have an empty string in the next field and we have only word chars before and after, merge
757 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
758 tokens[i] += tokens[i + 2];
759 tokens.splice(i + 1, 2);
767 function diffWords(oldStr, newStr, options) {
768 options = generateOptions(options, {
769 ignoreWhitespace: true
771 return wordDiff.diff(oldStr, newStr, options);
774 function diffWordsWithSpace(oldStr, newStr, options) {
775 return wordDiff.diff(oldStr, newStr, options);
778 var lineDiff = new Diff();
780 lineDiff.tokenize = function (value) {
782 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
784 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
785 linesAndNewlines.pop();
786 } // Merge the content and line separators into single tokens
789 for (var i = 0; i < linesAndNewlines.length; i++) {
790 var line = linesAndNewlines[i];
792 if (i % 2 && !this.options.newlineIsToken) {
793 retLines[retLines.length - 1] += line;
795 if (this.options.ignoreWhitespace) {
806 function diffLines(oldStr, newStr, callback) {
807 return lineDiff.diff(oldStr, newStr, callback);
810 function diffTrimmedLines(oldStr, newStr, callback) {
811 var options = generateOptions(callback, {
812 ignoreWhitespace: true
814 return lineDiff.diff(oldStr, newStr, options);
817 var sentenceDiff = new Diff();
819 sentenceDiff.tokenize = function (value) {
820 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
823 function diffSentences(oldStr, newStr, callback) {
824 return sentenceDiff.diff(oldStr, newStr, callback);
827 var cssDiff = new Diff();
829 cssDiff.tokenize = function (value) {
830 return value.split(/([{}:;,]|\s+)/);
833 function diffCss(oldStr, newStr, callback) {
834 return cssDiff.diff(oldStr, newStr, callback);
837 function _typeof$1(obj) {
838 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
839 _typeof$1 = function _typeof$1(obj) {
843 _typeof$1 = function _typeof$1(obj) {
844 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
848 return _typeof$1(obj);
851 function _toConsumableArray$1(arr) {
852 return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _nonIterableSpread$1();
855 function _arrayWithoutHoles$1(arr) {
856 if (Array.isArray(arr)) {
857 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
865 function _iterableToArray$1(iter) {
866 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
869 function _nonIterableSpread$1() {
870 throw new TypeError("Invalid attempt to spread non-iterable instance");
873 var objectPrototypeToString = Object.prototype.toString;
874 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
875 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
877 jsonDiff.useLongestToken = true;
878 jsonDiff.tokenize = lineDiff.tokenize;
880 jsonDiff.castInput = function (value) {
881 var _this$options = this.options,
882 undefinedReplacement = _this$options.undefinedReplacement,
883 _this$options$stringi = _this$options.stringifyReplacer,
884 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
885 return typeof v === 'undefined' ? undefinedReplacement : v;
886 } : _this$options$stringi;
887 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
890 jsonDiff.equals = function (left, right) {
891 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
894 function diffJson(oldObj, newObj, options) {
895 return jsonDiff.diff(oldObj, newObj, options);
896 } // This function handles the presence of circular references by bailing out when encountering an
897 // object that is already on the "stack" of items being processed. Accepts an optional replacer
900 function canonicalize(obj, stack, replacementStack, replacer, key) {
902 replacementStack = replacementStack || [];
905 obj = replacer(key, obj);
910 for (i = 0; i < stack.length; i += 1) {
911 if (stack[i] === obj) {
912 return replacementStack[i];
916 var canonicalizedObj;
918 if ('[object Array]' === objectPrototypeToString.call(obj)) {
920 canonicalizedObj = new Array(obj.length);
921 replacementStack.push(canonicalizedObj);
923 for (i = 0; i < obj.length; i += 1) {
924 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
928 replacementStack.pop();
929 return canonicalizedObj;
932 if (obj && obj.toJSON) {
936 if (_typeof$1(obj) === 'object' && obj !== null) {
938 canonicalizedObj = {};
939 replacementStack.push(canonicalizedObj);
945 /* istanbul ignore else */
946 if (obj.hasOwnProperty(_key)) {
947 sortedKeys.push(_key);
953 for (i = 0; i < sortedKeys.length; i += 1) {
954 _key = sortedKeys[i];
955 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
959 replacementStack.pop();
961 canonicalizedObj = obj;
964 return canonicalizedObj;
967 var arrayDiff = new Diff();
969 arrayDiff.tokenize = function (value) {
970 return value.slice();
973 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
977 function diffArrays(oldArr, newArr, callback) {
978 return arrayDiff.diff(oldArr, newArr, callback);
981 function parsePatch(uniDiff) {
982 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
983 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
984 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
988 function parseIndex() {
990 list.push(index); // Parse diff metadata
992 while (i < diffstr.length) {
993 var line = diffstr[i]; // File header found, end parsing diff metadata
995 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
1000 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
1003 index.index = header[1];
1007 } // Parse file headers if they are defined. Unified diff requires them, but
1008 // there's no technical issues to have an isolated hunk without file header
1011 parseFileHeader(index);
1012 parseFileHeader(index); // Parse hunks
1016 while (i < diffstr.length) {
1017 var _line = diffstr[i];
1019 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
1021 } else if (/^@@/.test(_line)) {
1022 index.hunks.push(parseHunk());
1023 } else if (_line && options.strict) {
1024 // Ignore unexpected content unless in strict mode
1025 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
1030 } // Parses the --- and +++ headers, if none are found, no lines
1034 function parseFileHeader(index) {
1035 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
1038 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
1039 var data = fileHeader[2].split('\t', 2);
1040 var fileName = data[0].replace(/\\\\/g, '\\');
1042 if (/^".*"$/.test(fileName)) {
1043 fileName = fileName.substr(1, fileName.length - 2);
1046 index[keyPrefix + 'FileName'] = fileName;
1047 index[keyPrefix + 'Header'] = (data[1] || '').trim();
1051 // This assumes that we are at the start of a hunk.
1054 function parseHunk() {
1055 var chunkHeaderIndex = i,
1056 chunkHeaderLine = diffstr[i++],
1057 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
1059 oldStart: +chunkHeader[1],
1060 oldLines: +chunkHeader[2] || 1,
1061 newStart: +chunkHeader[3],
1062 newLines: +chunkHeader[4] || 1,
1069 for (; i < diffstr.length; i++) {
1070 // Lines starting with '---' could be mistaken for the "remove line" operation
1071 // But they could be the header for the next file. Therefore prune such cases out.
1072 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
1076 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
1078 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
1079 hunk.lines.push(diffstr[i]);
1080 hunk.linedelimiters.push(delimiters[i] || '\n');
1082 if (operation === '+') {
1084 } else if (operation === '-') {
1086 } else if (operation === ' ') {
1093 } // Handle the empty block count case
1096 if (!addCount && hunk.newLines === 1) {
1100 if (!removeCount && hunk.oldLines === 1) {
1102 } // Perform optional sanity checking
1105 if (options.strict) {
1106 if (addCount !== hunk.newLines) {
1107 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
1110 if (removeCount !== hunk.oldLines) {
1111 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
1118 while (i < diffstr.length) {
1123 } // Iterator that traverses in the range of [min, max], stepping
1124 // by distance from a given start position. I.e. for [0, 4], with
1125 // start of 2, this will iterate 2, 3, 1, 4, 0.
1128 function distanceIterator(start, minLine, maxLine) {
1129 var wantForward = true,
1130 backwardExhausted = false,
1131 forwardExhausted = false,
1133 return function iterator() {
1134 if (wantForward && !forwardExhausted) {
1135 if (backwardExhausted) {
1138 wantForward = false;
1139 } // Check if trying to fit beyond text length, and if not, check it fits
1140 // after offset location (or desired location on first iteration)
1143 if (start + localOffset <= maxLine) {
1147 forwardExhausted = true;
1150 if (!backwardExhausted) {
1151 if (!forwardExhausted) {
1153 } // Check if trying to fit before text beginning, and if not, check it fits
1154 // before offset location
1157 if (minLine <= start - localOffset) {
1158 return -localOffset++;
1161 backwardExhausted = true;
1163 } // We tried to fit hunk before text beginning and beyond text length, then
1164 // hunk can't fit on the text. Return undefined
1169 function applyPatch(source, uniDiff) {
1170 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1172 if (typeof uniDiff === 'string') {
1173 uniDiff = parsePatch(uniDiff);
1176 if (Array.isArray(uniDiff)) {
1177 if (uniDiff.length > 1) {
1178 throw new Error('applyPatch only works with a single input.');
1181 uniDiff = uniDiff[0];
1182 } // Apply the diff to the input
1185 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
1186 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
1187 hunks = uniDiff.hunks,
1188 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
1189 return line === patchContent;
1192 fuzzFactor = options.fuzzFactor || 0,
1198 * Checks if the hunk exactly fits on the provided location
1202 function hunkFits(hunk, toPos) {
1203 for (var j = 0; j < hunk.lines.length; j++) {
1204 var line = hunk.lines[j],
1205 operation = line.length > 0 ? line[0] : ' ',
1206 content = line.length > 0 ? line.substr(1) : line;
1208 if (operation === ' ' || operation === '-') {
1209 // Context sanity check
1210 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
1213 if (errorCount > fuzzFactor) {
1223 } // Search best fit offsets for each hunk based on the previous ones
1226 for (var i = 0; i < hunks.length; i++) {
1227 var hunk = hunks[i],
1228 maxLine = lines.length - hunk.oldLines,
1230 toPos = offset + hunk.oldStart - 1;
1231 var iterator = distanceIterator(toPos, minLine, maxLine);
1233 for (; localOffset !== undefined; localOffset = iterator()) {
1234 if (hunkFits(hunk, toPos + localOffset)) {
1235 hunk.offset = offset += localOffset;
1240 if (localOffset === undefined) {
1242 } // Set lower text limit to end of the current hunk, so next ones don't try
1243 // to fit over already patched text
1246 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
1247 } // Apply patch hunks
1252 for (var _i = 0; _i < hunks.length; _i++) {
1253 var _hunk = hunks[_i],
1254 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
1256 diffOffset += _hunk.newLines - _hunk.oldLines;
1259 // Creating a new file
1263 for (var j = 0; j < _hunk.lines.length; j++) {
1264 var line = _hunk.lines[j],
1265 operation = line.length > 0 ? line[0] : ' ',
1266 content = line.length > 0 ? line.substr(1) : line,
1267 delimiter = _hunk.linedelimiters[j];
1269 if (operation === ' ') {
1271 } else if (operation === '-') {
1272 lines.splice(_toPos, 1);
1273 delimiters.splice(_toPos, 1);
1274 /* istanbul ignore else */
1275 } else if (operation === '+') {
1276 lines.splice(_toPos, 0, content);
1277 delimiters.splice(_toPos, 0, delimiter);
1279 } else if (operation === '\\') {
1280 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
1282 if (previousOperation === '+') {
1284 } else if (previousOperation === '-') {
1289 } // Handle EOFNL insertion/removal
1293 while (!lines[lines.length - 1]) {
1297 } else if (addEOFNL) {
1299 delimiters.push('\n');
1302 for (var _k = 0; _k < lines.length - 1; _k++) {
1303 lines[_k] = lines[_k] + delimiters[_k];
1306 return lines.join('');
1307 } // Wrapper that supports multiple file patches via callbacks.
1310 function applyPatches(uniDiff, options) {
1311 if (typeof uniDiff === 'string') {
1312 uniDiff = parsePatch(uniDiff);
1315 var currentIndex = 0;
1317 function processIndex() {
1318 var index = uniDiff[currentIndex++];
1321 return options.complete();
1324 options.loadFile(index, function (err, data) {
1326 return options.complete(err);
1329 var updatedContent = applyPatch(data, index, options);
1330 options.patched(index, updatedContent, function (err) {
1332 return options.complete(err);
1343 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1348 if (typeof options.context === 'undefined') {
1349 options.context = 4;
1352 var diff = diffLines(oldStr, newStr, options);
1356 }); // Append an empty value to make cleanup easier
1358 function contextLines(lines) {
1359 return lines.map(function (entry) {
1365 var oldRangeStart = 0,
1371 var _loop = function _loop(i) {
1372 var current = diff[i],
1373 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
1374 current.lines = lines;
1376 if (current.added || current.removed) {
1377 var _curRange; // If we have previous context, start with that
1380 if (!oldRangeStart) {
1381 var prev = diff[i - 1];
1382 oldRangeStart = oldLine;
1383 newRangeStart = newLine;
1386 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
1387 oldRangeStart -= curRange.length;
1388 newRangeStart -= curRange.length;
1390 } // Output our changes
1393 (_curRange = curRange).push.apply(_curRange, _toConsumableArray$1(lines.map(function (entry) {
1394 return (current.added ? '+' : '-') + entry;
1395 }))); // Track the updated file position
1398 if (current.added) {
1399 newLine += lines.length;
1401 oldLine += lines.length;
1404 // Identical context lines. Track line changes
1405 if (oldRangeStart) {
1406 // Close out any changes that have been output (or join overlapping)
1407 if (lines.length <= options.context * 2 && i < diff.length - 2) {
1408 var _curRange2; // Overlapping
1411 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray$1(contextLines(lines)));
1413 var _curRange3; // end the range and output
1416 var contextSize = Math.min(lines.length, options.context);
1418 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray$1(contextLines(lines.slice(0, contextSize))));
1421 oldStart: oldRangeStart,
1422 oldLines: oldLine - oldRangeStart + contextSize,
1423 newStart: newRangeStart,
1424 newLines: newLine - newRangeStart + contextSize,
1428 if (i >= diff.length - 2 && lines.length <= options.context) {
1429 // EOF is inside this hunk
1430 var oldEOFNewline = /\n$/.test(oldStr);
1431 var newEOFNewline = /\n$/.test(newStr);
1432 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
1434 if (!oldEOFNewline && noNlBeforeAdds) {
1435 // special case: old has no eol and no trailing context; no-nl can end up before adds
1436 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
1439 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
1440 curRange.push('\\ No newline at end of file');
1451 oldLine += lines.length;
1452 newLine += lines.length;
1456 for (var i = 0; i < diff.length; i++) {
1461 oldFileName: oldFileName,
1462 newFileName: newFileName,
1463 oldHeader: oldHeader,
1464 newHeader: newHeader,
1469 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1470 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
1473 if (oldFileName == newFileName) {
1474 ret.push('Index: ' + oldFileName);
1477 ret.push('===================================================================');
1478 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
1479 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
1481 for (var i = 0; i < diff.hunks.length; i++) {
1482 var hunk = diff.hunks[i];
1483 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
1484 ret.push.apply(ret, hunk.lines);
1487 return ret.join('\n') + '\n';
1490 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1491 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1494 function arrayEqual(a, b) {
1495 if (a.length !== b.length) {
1499 return arrayStartsWith(a, b);
1502 function arrayStartsWith(array, start) {
1503 if (start.length > array.length) {
1507 for (var i = 0; i < start.length; i++) {
1508 if (start[i] !== array[i]) {
1516 function calcLineCount(hunk) {
1517 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
1518 oldLines = _calcOldNewLineCount.oldLines,
1519 newLines = _calcOldNewLineCount.newLines;
1521 if (oldLines !== undefined) {
1522 hunk.oldLines = oldLines;
1524 delete hunk.oldLines;
1527 if (newLines !== undefined) {
1528 hunk.newLines = newLines;
1530 delete hunk.newLines;
1534 function merge(mine, theirs, base) {
1535 mine = loadPatch(mine, base);
1536 theirs = loadPatch(theirs, base);
1537 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
1538 // Leaving sanity checks on this to the API consumer that may know more about the
1539 // meaning in their own context.
1541 if (mine.index || theirs.index) {
1542 ret.index = mine.index || theirs.index;
1545 if (mine.newFileName || theirs.newFileName) {
1546 if (!fileNameChanged(mine)) {
1547 // No header or no change in ours, use theirs (and ours if theirs does not exist)
1548 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
1549 ret.newFileName = theirs.newFileName || mine.newFileName;
1550 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
1551 ret.newHeader = theirs.newHeader || mine.newHeader;
1552 } else if (!fileNameChanged(theirs)) {
1553 // No header or no change in theirs, use ours
1554 ret.oldFileName = mine.oldFileName;
1555 ret.newFileName = mine.newFileName;
1556 ret.oldHeader = mine.oldHeader;
1557 ret.newHeader = mine.newHeader;
1559 // Both changed... figure it out
1560 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
1561 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
1562 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
1563 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
1573 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
1574 var mineCurrent = mine.hunks[mineIndex] || {
1577 theirsCurrent = theirs.hunks[theirsIndex] || {
1581 if (hunkBefore(mineCurrent, theirsCurrent)) {
1582 // This patch does not overlap with any of the others, yay.
1583 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
1585 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
1586 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
1587 // This patch does not overlap with any of the others, yay.
1588 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
1590 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
1592 // Overlap, merge as best we can
1594 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
1596 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
1600 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
1603 ret.hunks.push(mergedHunk);
1610 function loadPatch(param, base) {
1611 if (typeof param === 'string') {
1612 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
1613 return parsePatch(param)[0];
1617 throw new Error('Must provide a base reference or pass in a patch');
1620 return structuredPatch(undefined, undefined, base, param);
1626 function fileNameChanged(patch) {
1627 return patch.newFileName && patch.newFileName !== patch.oldFileName;
1630 function selectField(index, mine, theirs) {
1631 if (mine === theirs) {
1634 index.conflict = true;
1642 function hunkBefore(test, check) {
1643 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
1646 function cloneHunk(hunk, offset) {
1648 oldStart: hunk.oldStart,
1649 oldLines: hunk.oldLines,
1650 newStart: hunk.newStart + offset,
1651 newLines: hunk.newLines,
1656 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
1657 // This will generally result in a conflicted hunk, but there are cases where the context
1658 // is the only overlap where we can successfully merge the content here.
1665 offset: theirOffset,
1668 }; // Handle any leading content
1670 insertLeading(hunk, mine, their);
1671 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
1673 while (mine.index < mine.lines.length && their.index < their.lines.length) {
1674 var mineCurrent = mine.lines[mine.index],
1675 theirCurrent = their.lines[their.index];
1677 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
1678 // Both modified ...
1679 mutualChange(hunk, mine, their);
1680 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
1681 var _hunk$lines; // Mine inserted
1684 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray$1(collectChange(mine)));
1685 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
1686 var _hunk$lines2; // Theirs inserted
1689 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray$1(collectChange(their)));
1690 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
1691 // Mine removed or edited
1692 removal(hunk, mine, their);
1693 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
1694 // Their removed or edited
1695 removal(hunk, their, mine, true);
1696 } else if (mineCurrent === theirCurrent) {
1698 hunk.lines.push(mineCurrent);
1703 conflict(hunk, collectChange(mine), collectChange(their));
1705 } // Now push anything that may be remaining
1708 insertTrailing(hunk, mine);
1709 insertTrailing(hunk, their);
1710 calcLineCount(hunk);
1713 function mutualChange(hunk, mine, their) {
1714 var myChanges = collectChange(mine),
1715 theirChanges = collectChange(their);
1717 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
1718 // Special case for remove changes that are supersets of one another
1719 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
1722 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray$1(myChanges));
1725 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
1728 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray$1(theirChanges));
1732 } else if (arrayEqual(myChanges, theirChanges)) {
1735 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray$1(myChanges));
1740 conflict(hunk, myChanges, theirChanges);
1743 function removal(hunk, mine, their, swap) {
1744 var myChanges = collectChange(mine),
1745 theirChanges = collectContext(their, myChanges);
1747 if (theirChanges.merged) {
1750 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray$1(theirChanges.merged));
1752 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
1756 function conflict(hunk, mine, their) {
1757 hunk.conflict = true;
1765 function insertLeading(hunk, insert, their) {
1766 while (insert.offset < their.offset && insert.index < insert.lines.length) {
1767 var line = insert.lines[insert.index++];
1768 hunk.lines.push(line);
1773 function insertTrailing(hunk, insert) {
1774 while (insert.index < insert.lines.length) {
1775 var line = insert.lines[insert.index++];
1776 hunk.lines.push(line);
1780 function collectChange(state) {
1782 operation = state.lines[state.index][0];
1784 while (state.index < state.lines.length) {
1785 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
1787 if (operation === '-' && line[0] === '+') {
1791 if (operation === line[0]) {
1802 function collectContext(state, matchChanges) {
1806 contextChanges = false,
1809 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
1810 var change = state.lines[state.index],
1811 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
1813 if (match[0] === '+') {
1817 contextChanges = contextChanges || change[0] !== ' ';
1819 matchIndex++; // Consume any additions in the other block as a conflict to attempt
1820 // to pull in the remaining context after this
1822 if (change[0] === '+') {
1825 while (change[0] === '+') {
1826 changes.push(change);
1827 change = state.lines[++state.index];
1831 if (match.substr(1) === change.substr(1)) {
1832 changes.push(change);
1839 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
1847 while (matchIndex < matchChanges.length) {
1848 merged.push(matchChanges[matchIndex++]);
1857 function allRemoves(changes) {
1858 return changes.reduce(function (prev, change) {
1859 return prev && change[0] === '-';
1863 function skipRemoveSuperset(state, removeChanges, delta) {
1864 for (var i = 0; i < delta; i++) {
1865 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
1867 if (state.lines[state.index + i] !== ' ' + changeContent) {
1872 state.index += delta;
1876 function calcOldNewLineCount(lines) {
1879 lines.forEach(function (line) {
1880 if (typeof line !== 'string') {
1881 var myCount = calcOldNewLineCount(line.mine);
1882 var theirCount = calcOldNewLineCount(line.theirs);
1884 if (oldLines !== undefined) {
1885 if (myCount.oldLines === theirCount.oldLines) {
1886 oldLines += myCount.oldLines;
1888 oldLines = undefined;
1892 if (newLines !== undefined) {
1893 if (myCount.newLines === theirCount.newLines) {
1894 newLines += myCount.newLines;
1896 newLines = undefined;
1900 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
1904 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
1913 } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
1916 function convertChangesToDMP(changes) {
1921 for (var i = 0; i < changes.length; i++) {
1922 change = changes[i];
1926 } else if (change.removed) {
1932 ret.push([operation, change.value]);
1938 function convertChangesToXML(changes) {
1941 for (var i = 0; i < changes.length; i++) {
1942 var change = changes[i];
1946 } else if (change.removed) {
1950 ret.push(escapeHTML(change.value));
1954 } else if (change.removed) {
1959 return ret.join('');
1962 function escapeHTML(s) {
1964 n = n.replace(/&/g, '&');
1965 n = n.replace(/</g, '<');
1966 n = n.replace(/>/g, '>');
1967 n = n.replace(/"/g, '"');
1971 var index_es6 = /*#__PURE__*/Object.freeze({
1974 diffChars: diffChars,
1975 diffWords: diffWords,
1976 diffWordsWithSpace: diffWordsWithSpace,
1977 diffLines: diffLines,
1978 diffTrimmedLines: diffTrimmedLines,
1979 diffSentences: diffSentences,
1982 diffArrays: diffArrays,
1983 structuredPatch: structuredPatch,
1984 createTwoFilesPatch: createTwoFilesPatch,
1985 createPatch: createPatch,
1986 applyPatch: applyPatch,
1987 applyPatches: applyPatches,
1988 parsePatch: parsePatch,
1990 convertChangesToDMP: convertChangesToDMP,
1991 convertChangesToXML: convertChangesToXML,
1992 canonicalize: canonicalize
1997 var _shim_fs$1 = /*#__PURE__*/Object.freeze({
2003 * normalize-path <https://github.com/jonschlinkert/normalize-path>
2005 * Copyright (c) 2014-2018, Jon Schlinkert.
2006 * Released under the MIT License.
2008 var normalizePath = function normalizePath(path, stripTrailing) {
2009 if (typeof path !== 'string') {
2010 throw new TypeError('expected path to be a string');
2013 if (path === '\\' || path === '/') return '/';
2014 var len = path.length;
2015 if (len <= 1) return path; // ensure that win32 namespaces has two leading slashes, so that the path is
2016 // handled properly by the win32 version of path.parse() after being normalized
2017 // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
2021 if (len > 4 && path[3] === '\\') {
2024 if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
2025 path = path.slice(2);
2030 var segs = path.split(/[/\\]+/);
2032 if (stripTrailing !== false && segs[segs.length - 1] === '') {
2036 return prefix + segs.join('/');
2039 var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
2043 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
2048 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2050 for (var i = 0, len = code.length; i < len; ++i) {
2051 lookup[i] = code[i];
2052 revLookup[code.charCodeAt(i)] = i;
2055 revLookup['-'.charCodeAt(0)] = 62;
2056 revLookup['_'.charCodeAt(0)] = 63;
2059 function toByteArray(b64) {
2064 var i, j, l, tmp, placeHolders, arr;
2065 var len = b64.length;
2068 throw new Error('Invalid string. Length must be a multiple of 4');
2069 } // the number of equal signs (place holders)
2070 // if there are two placeholders, than the two characters before it
2071 // represent one byte
2072 // if there is only one, then the three characters before it represent 2 bytes
2073 // this is just a cheap hack to not do indexOf twice
2076 placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data
2078 arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars
2080 l = placeHolders > 0 ? len - 4 : len;
2083 for (i = 0, j = 0; i < l; i += 4, j += 3) {
2084 tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
2085 arr[L++] = tmp >> 16 & 0xFF;
2086 arr[L++] = tmp >> 8 & 0xFF;
2087 arr[L++] = tmp & 0xFF;
2090 if (placeHolders === 2) {
2091 tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
2092 arr[L++] = tmp & 0xFF;
2093 } else if (placeHolders === 1) {
2094 tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
2095 arr[L++] = tmp >> 8 & 0xFF;
2096 arr[L++] = tmp & 0xFF;
2102 function tripletToBase64(num) {
2103 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
2106 function encodeChunk(uint8, start, end) {
2110 for (var i = start; i < end; i += 3) {
2111 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
2112 output.push(tripletToBase64(tmp));
2115 return output.join('');
2118 function fromByteArray(uint8) {
2124 var len = uint8.length;
2125 var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
2129 var maxChunkLength = 16383; // must be multiple of 3
2130 // go through the array every three bytes, we'll deal with trailing stuff later
2132 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
2133 parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
2134 } // pad the end with zeros, but make sure to not forget the extra bytes
2137 if (extraBytes === 1) {
2138 tmp = uint8[len - 1];
2139 output += lookup[tmp >> 2];
2140 output += lookup[tmp << 4 & 0x3F];
2142 } else if (extraBytes === 2) {
2143 tmp = (uint8[len - 2] << 8) + uint8[len - 1];
2144 output += lookup[tmp >> 10];
2145 output += lookup[tmp >> 4 & 0x3F];
2146 output += lookup[tmp << 2 & 0x3F];
2151 return parts.join('');
2154 function read(buffer, offset, isLE, mLen, nBytes) {
2156 var eLen = nBytes * 8 - mLen - 1;
2157 var eMax = (1 << eLen) - 1;
2158 var eBias = eMax >> 1;
2160 var i = isLE ? nBytes - 1 : 0;
2161 var d = isLE ? -1 : 1;
2162 var s = buffer[offset + i];
2164 e = s & (1 << -nBits) - 1;
2168 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2170 m = e & (1 << -nBits) - 1;
2174 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2178 } else if (e === eMax) {
2179 return m ? NaN : (s ? -1 : 1) * Infinity;
2181 m = m + Math.pow(2, mLen);
2185 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
2187 function write(buffer, value, offset, isLE, mLen, nBytes) {
2189 var eLen = nBytes * 8 - mLen - 1;
2190 var eMax = (1 << eLen) - 1;
2191 var eBias = eMax >> 1;
2192 var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
2193 var i = isLE ? 0 : nBytes - 1;
2194 var d = isLE ? 1 : -1;
2195 var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
2196 value = Math.abs(value);
2198 if (isNaN(value) || value === Infinity) {
2199 m = isNaN(value) ? 1 : 0;
2202 e = Math.floor(Math.log(value) / Math.LN2);
2204 if (value * (c = Math.pow(2, -e)) < 1) {
2209 if (e + eBias >= 1) {
2212 value += rt * Math.pow(2, 1 - eBias);
2215 if (value * c >= 2) {
2220 if (e + eBias >= eMax) {
2223 } else if (e + eBias >= 1) {
2224 m = (value * c - 1) * Math.pow(2, mLen);
2227 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
2232 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2237 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2239 buffer[offset + i - d] |= s * 128;
2242 var toString = {}.toString;
2243 var isArray = Array.isArray || function (arr) {
2244 return toString.call(arr) == '[object Array]';
2247 var INSPECT_MAX_BYTES = 50;
2249 * If `Buffer.TYPED_ARRAY_SUPPORT`:
2250 * === true Use Uint8Array implementation (fastest)
2251 * === false Use Object implementation (most compatible, even IE6)
2253 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
2254 * Opera 11.6+, iOS 4.2+.
2256 * Due to various browser bugs, sometimes the Object implementation will be used even
2257 * when the browser supports typed arrays.
2261 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
2262 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
2264 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
2266 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
2267 * incorrect length in some situations.
2269 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
2270 * get the Object implementation, which is slower but behaves correctly.
2273 Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true;
2275 function kMaxLength() {
2276 return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff;
2279 function createBuffer(that, length) {
2280 if (kMaxLength() < length) {
2281 throw new RangeError('Invalid typed array length');
2284 if (Buffer.TYPED_ARRAY_SUPPORT) {
2285 // Return an augmented `Uint8Array` instance, for best performance
2286 that = new Uint8Array(length);
2287 that.__proto__ = Buffer.prototype;
2289 // Fallback: Return an object instance of the Buffer class
2290 if (that === null) {
2291 that = new Buffer(length);
2294 that.length = length;
2300 * The Buffer constructor returns instances of `Uint8Array` that have their
2301 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
2302 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
2303 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
2304 * returns a single octet.
2306 * The `Uint8Array` prototype remains unmodified.
2310 function Buffer(arg, encodingOrOffset, length) {
2311 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
2312 return new Buffer(arg, encodingOrOffset, length);
2316 if (typeof arg === 'number') {
2317 if (typeof encodingOrOffset === 'string') {
2318 throw new Error('If encoding is specified then the first argument must be a string');
2321 return allocUnsafe(this, arg);
2324 return from(this, arg, encodingOrOffset, length);
2326 Buffer.poolSize = 8192; // not used by this implementation
2327 // TODO: Legacy, not needed anymore. Remove in next major version.
2329 Buffer._augment = function (arr) {
2330 arr.__proto__ = Buffer.prototype;
2334 function from(that, value, encodingOrOffset, length) {
2335 if (typeof value === 'number') {
2336 throw new TypeError('"value" argument must not be a number');
2339 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
2340 return fromArrayBuffer(that, value, encodingOrOffset, length);
2343 if (typeof value === 'string') {
2344 return fromString(that, value, encodingOrOffset);
2347 return fromObject(that, value);
2350 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
2351 * if value is a number.
2352 * Buffer.from(str[, encoding])
2353 * Buffer.from(array)
2354 * Buffer.from(buffer)
2355 * Buffer.from(arrayBuffer[, byteOffset[, length]])
2359 Buffer.from = function (value, encodingOrOffset, length) {
2360 return from(null, value, encodingOrOffset, length);
2363 if (Buffer.TYPED_ARRAY_SUPPORT) {
2364 Buffer.prototype.__proto__ = Uint8Array.prototype;
2365 Buffer.__proto__ = Uint8Array;
2368 function assertSize(size) {
2369 if (typeof size !== 'number') {
2370 throw new TypeError('"size" argument must be a number');
2371 } else if (size < 0) {
2372 throw new RangeError('"size" argument must not be negative');
2376 function alloc(that, size, fill, encoding) {
2380 return createBuffer(that, size);
2383 if (fill !== undefined) {
2384 // Only pay attention to encoding if it's a string. This
2385 // prevents accidentally sending in a number that would
2386 // be interpretted as a start offset.
2387 return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill);
2390 return createBuffer(that, size);
2393 * Creates a new filled Buffer instance.
2394 * alloc(size[, fill[, encoding]])
2398 Buffer.alloc = function (size, fill, encoding) {
2399 return alloc(null, size, fill, encoding);
2402 function allocUnsafe(that, size) {
2404 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
2406 if (!Buffer.TYPED_ARRAY_SUPPORT) {
2407 for (var i = 0; i < size; ++i) {
2415 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
2419 Buffer.allocUnsafe = function (size) {
2420 return allocUnsafe(null, size);
2423 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
2427 Buffer.allocUnsafeSlow = function (size) {
2428 return allocUnsafe(null, size);
2431 function fromString(that, string, encoding) {
2432 if (typeof encoding !== 'string' || encoding === '') {
2436 if (!Buffer.isEncoding(encoding)) {
2437 throw new TypeError('"encoding" must be a valid string encoding');
2440 var length = byteLength(string, encoding) | 0;
2441 that = createBuffer(that, length);
2442 var actual = that.write(string, encoding);
2444 if (actual !== length) {
2445 // Writing a hex string, for example, that contains invalid characters will
2446 // cause everything after the first invalid character to be ignored. (e.g.
2447 // 'abxxcd' will be treated as 'ab')
2448 that = that.slice(0, actual);
2454 function fromArrayLike(that, array) {
2455 var length = array.length < 0 ? 0 : checked(array.length) | 0;
2456 that = createBuffer(that, length);
2458 for (var i = 0; i < length; i += 1) {
2459 that[i] = array[i] & 255;
2465 function fromArrayBuffer(that, array, byteOffset, length) {
2466 array.byteLength; // this throws if `array` is not a valid ArrayBuffer
2468 if (byteOffset < 0 || array.byteLength < byteOffset) {
2469 throw new RangeError('\'offset\' is out of bounds');
2472 if (array.byteLength < byteOffset + (length || 0)) {
2473 throw new RangeError('\'length\' is out of bounds');
2476 if (byteOffset === undefined && length === undefined) {
2477 array = new Uint8Array(array);
2478 } else if (length === undefined) {
2479 array = new Uint8Array(array, byteOffset);
2481 array = new Uint8Array(array, byteOffset, length);
2484 if (Buffer.TYPED_ARRAY_SUPPORT) {
2485 // Return an augmented `Uint8Array` instance, for best performance
2487 that.__proto__ = Buffer.prototype;
2489 // Fallback: Return an object instance of the Buffer class
2490 that = fromArrayLike(that, array);
2496 function fromObject(that, obj) {
2497 if (internalIsBuffer(obj)) {
2498 var len = checked(obj.length) | 0;
2499 that = createBuffer(that, len);
2501 if (that.length === 0) {
2505 obj.copy(that, 0, 0, len);
2510 if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) {
2511 if (typeof obj.length !== 'number' || isnan(obj.length)) {
2512 return createBuffer(that, 0);
2515 return fromArrayLike(that, obj);
2518 if (obj.type === 'Buffer' && isArray(obj.data)) {
2519 return fromArrayLike(that, obj.data);
2523 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.');
2526 function checked(length) {
2527 // Note: cannot use `length < kMaxLength()` here because that fails when
2528 // length is NaN (which is otherwise coerced to zero.)
2529 if (length >= kMaxLength()) {
2530 throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes');
2535 Buffer.isBuffer = isBuffer;
2537 function internalIsBuffer(b) {
2538 return !!(b != null && b._isBuffer);
2541 Buffer.compare = function compare(a, b) {
2542 if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
2543 throw new TypeError('Arguments must be Buffers');
2546 if (a === b) return 0;
2550 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2551 if (a[i] !== b[i]) {
2558 if (x < y) return -1;
2559 if (y < x) return 1;
2563 Buffer.isEncoding = function isEncoding(encoding) {
2564 switch (String(encoding).toLowerCase()) {
2583 Buffer.concat = function concat(list, length) {
2584 if (!isArray(list)) {
2585 throw new TypeError('"list" argument must be an Array of Buffers');
2588 if (list.length === 0) {
2589 return Buffer.alloc(0);
2594 if (length === undefined) {
2597 for (i = 0; i < list.length; ++i) {
2598 length += list[i].length;
2602 var buffer = Buffer.allocUnsafe(length);
2605 for (i = 0; i < list.length; ++i) {
2608 if (!internalIsBuffer(buf)) {
2609 throw new TypeError('"list" argument must be an Array of Buffers');
2612 buf.copy(buffer, pos);
2619 function byteLength(string, encoding) {
2620 if (internalIsBuffer(string)) {
2621 return string.length;
2624 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
2625 return string.byteLength;
2628 if (typeof string !== 'string') {
2629 string = '' + string;
2632 var len = string.length;
2633 if (len === 0) return 0; // Use a for loop to avoid recursion
2635 var loweredCase = false;
2647 return utf8ToBytes(string).length;
2659 return base64ToBytes(string).length;
2662 if (loweredCase) return utf8ToBytes(string).length; // assume utf8
2664 encoding = ('' + encoding).toLowerCase();
2670 Buffer.byteLength = byteLength;
2672 function slowToString(encoding, start, end) {
2673 var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2674 // property of a typed array.
2675 // This behaves neither like String nor Uint8Array in that we set start/end
2676 // to their upper/lower bounds if the value passed is out of range.
2677 // undefined is handled specially as per ECMA-262 6th Edition,
2678 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2680 if (start === undefined || start < 0) {
2682 } // Return early if start > this.length. Done here to prevent potential uint32
2683 // coercion fail below.
2686 if (start > this.length) {
2690 if (end === undefined || end > this.length) {
2696 } // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
2706 if (!encoding) encoding = 'utf8';
2711 return hexSlice(this, start, end);
2715 return utf8Slice(this, start, end);
2718 return asciiSlice(this, start, end);
2722 return latin1Slice(this, start, end);
2725 return base64Slice(this, start, end);
2731 return utf16leSlice(this, start, end);
2734 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
2735 encoding = (encoding + '').toLowerCase();
2739 } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
2740 // Buffer instances.
2743 Buffer.prototype._isBuffer = true;
2745 function swap(b, n, m) {
2751 Buffer.prototype.swap16 = function swap16() {
2752 var len = this.length;
2754 if (len % 2 !== 0) {
2755 throw new RangeError('Buffer size must be a multiple of 16-bits');
2758 for (var i = 0; i < len; i += 2) {
2759 swap(this, i, i + 1);
2765 Buffer.prototype.swap32 = function swap32() {
2766 var len = this.length;
2768 if (len % 4 !== 0) {
2769 throw new RangeError('Buffer size must be a multiple of 32-bits');
2772 for (var i = 0; i < len; i += 4) {
2773 swap(this, i, i + 3);
2774 swap(this, i + 1, i + 2);
2780 Buffer.prototype.swap64 = function swap64() {
2781 var len = this.length;
2783 if (len % 8 !== 0) {
2784 throw new RangeError('Buffer size must be a multiple of 64-bits');
2787 for (var i = 0; i < len; i += 8) {
2788 swap(this, i, i + 7);
2789 swap(this, i + 1, i + 6);
2790 swap(this, i + 2, i + 5);
2791 swap(this, i + 3, i + 4);
2797 Buffer.prototype.toString = function toString() {
2798 var length = this.length | 0;
2799 if (length === 0) return '';
2800 if (arguments.length === 0) return utf8Slice(this, 0, length);
2801 return slowToString.apply(this, arguments);
2804 Buffer.prototype.equals = function equals(b) {
2805 if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer');
2806 if (this === b) return true;
2807 return Buffer.compare(this, b) === 0;
2810 Buffer.prototype.inspect = function inspect() {
2812 var max = INSPECT_MAX_BYTES;
2814 if (this.length > 0) {
2815 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
2816 if (this.length > max) str += ' ... ';
2819 return '<Buffer ' + str + '>';
2822 Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
2823 if (!internalIsBuffer(target)) {
2824 throw new TypeError('Argument must be a Buffer');
2827 if (start === undefined) {
2831 if (end === undefined) {
2832 end = target ? target.length : 0;
2835 if (thisStart === undefined) {
2839 if (thisEnd === undefined) {
2840 thisEnd = this.length;
2843 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2844 throw new RangeError('out of range index');
2847 if (thisStart >= thisEnd && start >= end) {
2851 if (thisStart >= thisEnd) {
2863 if (this === target) return 0;
2864 var x = thisEnd - thisStart;
2865 var y = end - start;
2866 var len = Math.min(x, y);
2867 var thisCopy = this.slice(thisStart, thisEnd);
2868 var targetCopy = target.slice(start, end);
2870 for (var i = 0; i < len; ++i) {
2871 if (thisCopy[i] !== targetCopy[i]) {
2878 if (x < y) return -1;
2879 if (y < x) return 1;
2881 }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2882 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2885 // - buffer - a Buffer to search
2886 // - val - a string, Buffer, or number
2887 // - byteOffset - an index into `buffer`; will be clamped to an int32
2888 // - encoding - an optional encoding, relevant is val is a string
2889 // - dir - true for indexOf, false for lastIndexOf
2892 function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
2893 // Empty buffer means no match
2894 if (buffer.length === 0) return -1; // Normalize byteOffset
2896 if (typeof byteOffset === 'string') {
2897 encoding = byteOffset;
2899 } else if (byteOffset > 0x7fffffff) {
2900 byteOffset = 0x7fffffff;
2901 } else if (byteOffset < -0x80000000) {
2902 byteOffset = -0x80000000;
2905 byteOffset = +byteOffset; // Coerce to Number.
2907 if (isNaN(byteOffset)) {
2908 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2909 byteOffset = dir ? 0 : buffer.length - 1;
2910 } // Normalize byteOffset: negative offsets start from the end of the buffer
2913 if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
2915 if (byteOffset >= buffer.length) {
2916 if (dir) return -1;else byteOffset = buffer.length - 1;
2917 } else if (byteOffset < 0) {
2918 if (dir) byteOffset = 0;else return -1;
2922 if (typeof val === 'string') {
2923 val = Buffer.from(val, encoding);
2924 } // Finally, search either indexOf (if dir is true) or lastIndexOf
2927 if (internalIsBuffer(val)) {
2928 // Special case: looking for empty string/buffer always fails
2929 if (val.length === 0) {
2933 return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
2934 } else if (typeof val === 'number') {
2935 val = val & 0xFF; // Search for a byte value [0-255]
2937 if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') {
2939 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
2941 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
2945 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
2948 throw new TypeError('val must be string, number or Buffer');
2951 function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
2953 var arrLength = arr.length;
2954 var valLength = val.length;
2956 if (encoding !== undefined) {
2957 encoding = String(encoding).toLowerCase();
2959 if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
2960 if (arr.length < 2 || val.length < 2) {
2971 function read(buf, i) {
2972 if (indexSize === 1) {
2975 return buf.readUInt16BE(i * indexSize);
2982 var foundIndex = -1;
2984 for (i = byteOffset; i < arrLength; i++) {
2985 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2986 if (foundIndex === -1) foundIndex = i;
2987 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
2989 if (foundIndex !== -1) i -= i - foundIndex;
2994 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
2996 for (i = byteOffset; i >= 0; i--) {
2999 for (var j = 0; j < valLength; j++) {
3000 if (read(arr, i + j) !== read(val, j)) {
3006 if (found) return i;
3013 Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
3014 return this.indexOf(val, byteOffset, encoding) !== -1;
3017 Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
3018 return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
3021 Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
3022 return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
3025 function hexWrite(buf, string, offset, length) {
3026 offset = Number(offset) || 0;
3027 var remaining = buf.length - offset;
3032 length = Number(length);
3034 if (length > remaining) {
3037 } // must be an even number of digits
3040 var strLen = string.length;
3041 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string');
3043 if (length > strLen / 2) {
3044 length = strLen / 2;
3047 for (var i = 0; i < length; ++i) {
3048 var parsed = parseInt(string.substr(i * 2, 2), 16);
3049 if (isNaN(parsed)) return i;
3050 buf[offset + i] = parsed;
3056 function utf8Write(buf, string, offset, length) {
3057 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
3060 function asciiWrite(buf, string, offset, length) {
3061 return blitBuffer(asciiToBytes(string), buf, offset, length);
3064 function latin1Write(buf, string, offset, length) {
3065 return asciiWrite(buf, string, offset, length);
3068 function base64Write(buf, string, offset, length) {
3069 return blitBuffer(base64ToBytes(string), buf, offset, length);
3072 function ucs2Write(buf, string, offset, length) {
3073 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
3076 Buffer.prototype.write = function write(string, offset, length, encoding) {
3077 // Buffer#write(string)
3078 if (offset === undefined) {
3080 length = this.length;
3081 offset = 0; // Buffer#write(string, encoding)
3082 } else if (length === undefined && typeof offset === 'string') {
3084 length = this.length;
3085 offset = 0; // Buffer#write(string, offset[, length][, encoding])
3086 } else if (isFinite(offset)) {
3087 offset = offset | 0;
3089 if (isFinite(length)) {
3090 length = length | 0;
3091 if (encoding === undefined) encoding = 'utf8';
3095 } // legacy write(string, encoding, offset, length) - remove in v0.13
3098 throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
3101 var remaining = this.length - offset;
3102 if (length === undefined || length > remaining) length = remaining;
3104 if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
3105 throw new RangeError('Attempt to write outside buffer bounds');
3108 if (!encoding) encoding = 'utf8';
3109 var loweredCase = false;
3114 return hexWrite(this, string, offset, length);
3118 return utf8Write(this, string, offset, length);
3121 return asciiWrite(this, string, offset, length);
3125 return latin1Write(this, string, offset, length);
3128 // Warning: maxLength not taken into account in base64Write
3129 return base64Write(this, string, offset, length);
3135 return ucs2Write(this, string, offset, length);
3138 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
3139 encoding = ('' + encoding).toLowerCase();
3145 Buffer.prototype.toJSON = function toJSON() {
3148 data: Array.prototype.slice.call(this._arr || this, 0)
3152 function base64Slice(buf, start, end) {
3153 if (start === 0 && end === buf.length) {
3154 return fromByteArray(buf);
3156 return fromByteArray(buf.slice(start, end));
3160 function utf8Slice(buf, start, end) {
3161 end = Math.min(buf.length, end);
3166 var firstByte = buf[i];
3167 var codePoint = null;
3168 var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
3170 if (i + bytesPerSequence <= end) {
3171 var secondByte, thirdByte, fourthByte, tempCodePoint;
3173 switch (bytesPerSequence) {
3175 if (firstByte < 0x80) {
3176 codePoint = firstByte;
3182 secondByte = buf[i + 1];
3184 if ((secondByte & 0xC0) === 0x80) {
3185 tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
3187 if (tempCodePoint > 0x7F) {
3188 codePoint = tempCodePoint;
3195 secondByte = buf[i + 1];
3196 thirdByte = buf[i + 2];
3198 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
3199 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
3201 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
3202 codePoint = tempCodePoint;
3209 secondByte = buf[i + 1];
3210 thirdByte = buf[i + 2];
3211 fourthByte = buf[i + 3];
3213 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
3214 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
3216 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
3217 codePoint = tempCodePoint;
3224 if (codePoint === null) {
3225 // we did not generate a valid codePoint so insert a
3226 // replacement char (U+FFFD) and advance only 1 byte
3228 bytesPerSequence = 1;
3229 } else if (codePoint > 0xFFFF) {
3230 // encode to utf16 (surrogate pair dance)
3231 codePoint -= 0x10000;
3232 res.push(codePoint >>> 10 & 0x3FF | 0xD800);
3233 codePoint = 0xDC00 | codePoint & 0x3FF;
3236 res.push(codePoint);
3237 i += bytesPerSequence;
3240 return decodeCodePointsArray(res);
3241 } // Based on http://stackoverflow.com/a/22747272/680742, the browser with
3242 // the lowest limit is Chrome, with 0x10000 args.
3243 // We go 1 magnitude less, for safety
3246 var MAX_ARGUMENTS_LENGTH = 0x1000;
3248 function decodeCodePointsArray(codePoints) {
3249 var len = codePoints.length;
3251 if (len <= MAX_ARGUMENTS_LENGTH) {
3252 return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
3253 } // Decode in chunks to avoid "call stack size exceeded".
3260 res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
3266 function asciiSlice(buf, start, end) {
3268 end = Math.min(buf.length, end);
3270 for (var i = start; i < end; ++i) {
3271 ret += String.fromCharCode(buf[i] & 0x7F);
3277 function latin1Slice(buf, start, end) {
3279 end = Math.min(buf.length, end);
3281 for (var i = start; i < end; ++i) {
3282 ret += String.fromCharCode(buf[i]);
3288 function hexSlice(buf, start, end) {
3289 var len = buf.length;
3290 if (!start || start < 0) start = 0;
3291 if (!end || end < 0 || end > len) end = len;
3294 for (var i = start; i < end; ++i) {
3295 out += toHex(buf[i]);
3301 function utf16leSlice(buf, start, end) {
3302 var bytes = buf.slice(start, end);
3305 for (var i = 0; i < bytes.length; i += 2) {
3306 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
3312 Buffer.prototype.slice = function slice(start, end) {
3313 var len = this.length;
3315 end = end === undefined ? len : ~~end;
3319 if (start < 0) start = 0;
3320 } else if (start > len) {
3326 if (end < 0) end = 0;
3327 } else if (end > len) {
3331 if (end < start) end = start;
3334 if (Buffer.TYPED_ARRAY_SUPPORT) {
3335 newBuf = this.subarray(start, end);
3336 newBuf.__proto__ = Buffer.prototype;
3338 var sliceLen = end - start;
3339 newBuf = new Buffer(sliceLen, undefined);
3341 for (var i = 0; i < sliceLen; ++i) {
3342 newBuf[i] = this[i + start];
3349 * Need to make sure that buffer isn't trying to write out of bounds.
3353 function checkOffset(offset, ext, length) {
3354 if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
3355 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
3358 Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
3359 offset = offset | 0;
3360 byteLength = byteLength | 0;
3361 if (!noAssert) checkOffset(offset, byteLength, this.length);
3362 var val = this[offset];
3366 while (++i < byteLength && (mul *= 0x100)) {
3367 val += this[offset + i] * mul;
3373 Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
3374 offset = offset | 0;
3375 byteLength = byteLength | 0;
3378 checkOffset(offset, byteLength, this.length);
3381 var val = this[offset + --byteLength];
3384 while (byteLength > 0 && (mul *= 0x100)) {
3385 val += this[offset + --byteLength] * mul;
3391 Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
3392 if (!noAssert) checkOffset(offset, 1, this.length);
3393 return this[offset];
3396 Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
3397 if (!noAssert) checkOffset(offset, 2, this.length);
3398 return this[offset] | this[offset + 1] << 8;
3401 Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
3402 if (!noAssert) checkOffset(offset, 2, this.length);
3403 return this[offset] << 8 | this[offset + 1];
3406 Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
3407 if (!noAssert) checkOffset(offset, 4, this.length);
3408 return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
3411 Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
3412 if (!noAssert) checkOffset(offset, 4, this.length);
3413 return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
3416 Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
3417 offset = offset | 0;
3418 byteLength = byteLength | 0;
3419 if (!noAssert) checkOffset(offset, byteLength, this.length);
3420 var val = this[offset];
3424 while (++i < byteLength && (mul *= 0x100)) {
3425 val += this[offset + i] * mul;
3429 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
3433 Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
3434 offset = offset | 0;
3435 byteLength = byteLength | 0;
3436 if (!noAssert) checkOffset(offset, byteLength, this.length);
3439 var val = this[offset + --i];
3441 while (i > 0 && (mul *= 0x100)) {
3442 val += this[offset + --i] * mul;
3446 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
3450 Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
3451 if (!noAssert) checkOffset(offset, 1, this.length);
3452 if (!(this[offset] & 0x80)) return this[offset];
3453 return (0xff - this[offset] + 1) * -1;
3456 Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
3457 if (!noAssert) checkOffset(offset, 2, this.length);
3458 var val = this[offset] | this[offset + 1] << 8;
3459 return val & 0x8000 ? val | 0xFFFF0000 : val;
3462 Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
3463 if (!noAssert) checkOffset(offset, 2, this.length);
3464 var val = this[offset + 1] | this[offset] << 8;
3465 return val & 0x8000 ? val | 0xFFFF0000 : val;
3468 Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
3469 if (!noAssert) checkOffset(offset, 4, this.length);
3470 return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
3473 Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
3474 if (!noAssert) checkOffset(offset, 4, this.length);
3475 return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
3478 Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
3479 if (!noAssert) checkOffset(offset, 4, this.length);
3480 return read(this, offset, true, 23, 4);
3483 Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
3484 if (!noAssert) checkOffset(offset, 4, this.length);
3485 return read(this, offset, false, 23, 4);
3488 Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
3489 if (!noAssert) checkOffset(offset, 8, this.length);
3490 return read(this, offset, true, 52, 8);
3493 Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
3494 if (!noAssert) checkOffset(offset, 8, this.length);
3495 return read(this, offset, false, 52, 8);
3498 function checkInt(buf, value, offset, ext, max, min) {
3499 if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
3500 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
3501 if (offset + ext > buf.length) throw new RangeError('Index out of range');
3504 Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
3506 offset = offset | 0;
3507 byteLength = byteLength | 0;
3510 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
3511 checkInt(this, value, offset, byteLength, maxBytes, 0);
3516 this[offset] = value & 0xFF;
3518 while (++i < byteLength && (mul *= 0x100)) {
3519 this[offset + i] = value / mul & 0xFF;
3522 return offset + byteLength;
3525 Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
3527 offset = offset | 0;
3528 byteLength = byteLength | 0;
3531 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
3532 checkInt(this, value, offset, byteLength, maxBytes, 0);
3535 var i = byteLength - 1;
3537 this[offset + i] = value & 0xFF;
3539 while (--i >= 0 && (mul *= 0x100)) {
3540 this[offset + i] = value / mul & 0xFF;
3543 return offset + byteLength;
3546 Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
3548 offset = offset | 0;
3549 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
3550 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
3551 this[offset] = value & 0xff;
3555 function objectWriteUInt16(buf, value, offset, littleEndian) {
3556 if (value < 0) value = 0xffff + value + 1;
3558 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
3559 buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
3563 Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
3565 offset = offset | 0;
3566 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
3568 if (Buffer.TYPED_ARRAY_SUPPORT) {
3569 this[offset] = value & 0xff;
3570 this[offset + 1] = value >>> 8;
3572 objectWriteUInt16(this, value, offset, true);
3578 Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
3580 offset = offset | 0;
3581 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
3583 if (Buffer.TYPED_ARRAY_SUPPORT) {
3584 this[offset] = value >>> 8;
3585 this[offset + 1] = value & 0xff;
3587 objectWriteUInt16(this, value, offset, false);
3593 function objectWriteUInt32(buf, value, offset, littleEndian) {
3594 if (value < 0) value = 0xffffffff + value + 1;
3596 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
3597 buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff;
3601 Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
3603 offset = offset | 0;
3604 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
3606 if (Buffer.TYPED_ARRAY_SUPPORT) {
3607 this[offset + 3] = value >>> 24;
3608 this[offset + 2] = value >>> 16;
3609 this[offset + 1] = value >>> 8;
3610 this[offset] = value & 0xff;
3612 objectWriteUInt32(this, value, offset, true);
3618 Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
3620 offset = offset | 0;
3621 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
3623 if (Buffer.TYPED_ARRAY_SUPPORT) {
3624 this[offset] = value >>> 24;
3625 this[offset + 1] = value >>> 16;
3626 this[offset + 2] = value >>> 8;
3627 this[offset + 3] = value & 0xff;
3629 objectWriteUInt32(this, value, offset, false);
3635 Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
3637 offset = offset | 0;
3640 var limit = Math.pow(2, 8 * byteLength - 1);
3641 checkInt(this, value, offset, byteLength, limit - 1, -limit);
3647 this[offset] = value & 0xFF;
3649 while (++i < byteLength && (mul *= 0x100)) {
3650 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
3654 this[offset + i] = (value / mul >> 0) - sub & 0xFF;
3657 return offset + byteLength;
3660 Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
3662 offset = offset | 0;
3665 var limit = Math.pow(2, 8 * byteLength - 1);
3666 checkInt(this, value, offset, byteLength, limit - 1, -limit);
3669 var i = byteLength - 1;
3672 this[offset + i] = value & 0xFF;
3674 while (--i >= 0 && (mul *= 0x100)) {
3675 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3679 this[offset + i] = (value / mul >> 0) - sub & 0xFF;
3682 return offset + byteLength;
3685 Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
3687 offset = offset | 0;
3688 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
3689 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
3690 if (value < 0) value = 0xff + value + 1;
3691 this[offset] = value & 0xff;
3695 Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
3697 offset = offset | 0;
3698 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
3700 if (Buffer.TYPED_ARRAY_SUPPORT) {
3701 this[offset] = value & 0xff;
3702 this[offset + 1] = value >>> 8;
3704 objectWriteUInt16(this, value, offset, true);
3710 Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
3712 offset = offset | 0;
3713 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
3715 if (Buffer.TYPED_ARRAY_SUPPORT) {
3716 this[offset] = value >>> 8;
3717 this[offset + 1] = value & 0xff;
3719 objectWriteUInt16(this, value, offset, false);
3725 Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
3727 offset = offset | 0;
3728 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
3730 if (Buffer.TYPED_ARRAY_SUPPORT) {
3731 this[offset] = value & 0xff;
3732 this[offset + 1] = value >>> 8;
3733 this[offset + 2] = value >>> 16;
3734 this[offset + 3] = value >>> 24;
3736 objectWriteUInt32(this, value, offset, true);
3742 Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
3744 offset = offset | 0;
3745 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
3746 if (value < 0) value = 0xffffffff + value + 1;
3748 if (Buffer.TYPED_ARRAY_SUPPORT) {
3749 this[offset] = value >>> 24;
3750 this[offset + 1] = value >>> 16;
3751 this[offset + 2] = value >>> 8;
3752 this[offset + 3] = value & 0xff;
3754 objectWriteUInt32(this, value, offset, false);
3760 function checkIEEE754(buf, value, offset, ext, max, min) {
3761 if (offset + ext > buf.length) throw new RangeError('Index out of range');
3762 if (offset < 0) throw new RangeError('Index out of range');
3765 function writeFloat(buf, value, offset, littleEndian, noAssert) {
3767 checkIEEE754(buf, value, offset, 4);
3770 write(buf, value, offset, littleEndian, 23, 4);
3774 Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
3775 return writeFloat(this, value, offset, true, noAssert);
3778 Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
3779 return writeFloat(this, value, offset, false, noAssert);
3782 function writeDouble(buf, value, offset, littleEndian, noAssert) {
3784 checkIEEE754(buf, value, offset, 8);
3787 write(buf, value, offset, littleEndian, 52, 8);
3791 Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
3792 return writeDouble(this, value, offset, true, noAssert);
3795 Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
3796 return writeDouble(this, value, offset, false, noAssert);
3797 }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3800 Buffer.prototype.copy = function copy(target, targetStart, start, end) {
3801 if (!start) start = 0;
3802 if (!end && end !== 0) end = this.length;
3803 if (targetStart >= target.length) targetStart = target.length;
3804 if (!targetStart) targetStart = 0;
3805 if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done
3807 if (end === start) return 0;
3808 if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions
3810 if (targetStart < 0) {
3811 throw new RangeError('targetStart out of bounds');
3814 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds');
3815 if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob?
3817 if (end > this.length) end = this.length;
3819 if (target.length - targetStart < end - start) {
3820 end = target.length - targetStart + start;
3823 var len = end - start;
3826 if (this === target && start < targetStart && targetStart < end) {
3827 // descending copy from end
3828 for (i = len - 1; i >= 0; --i) {
3829 target[i + targetStart] = this[i + start];
3831 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
3832 // ascending copy from start
3833 for (i = 0; i < len; ++i) {
3834 target[i + targetStart] = this[i + start];
3837 Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
3842 // buffer.fill(number[, offset[, end]])
3843 // buffer.fill(buffer[, offset[, end]])
3844 // buffer.fill(string[, offset[, end]][, encoding])
3847 Buffer.prototype.fill = function fill(val, start, end, encoding) {
3848 // Handle string cases:
3849 if (typeof val === 'string') {
3850 if (typeof start === 'string') {
3854 } else if (typeof end === 'string') {
3859 if (val.length === 1) {
3860 var code = val.charCodeAt(0);
3867 if (encoding !== undefined && typeof encoding !== 'string') {
3868 throw new TypeError('encoding must be a string');
3871 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3872 throw new TypeError('Unknown encoding: ' + encoding);
3874 } else if (typeof val === 'number') {
3876 } // Invalid ranges are not set to a default, so can range check early.
3879 if (start < 0 || this.length < start || this.length < end) {
3880 throw new RangeError('Out of range index');
3887 start = start >>> 0;
3888 end = end === undefined ? this.length : end >>> 0;
3892 if (typeof val === 'number') {
3893 for (i = start; i < end; ++i) {
3897 var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString());
3898 var len = bytes.length;
3900 for (i = 0; i < end - start; ++i) {
3901 this[i + start] = bytes[i % len];
3906 }; // HELPER FUNCTIONS
3910 var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
3912 function base64clean(str) {
3913 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3914 str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to ''
3916 if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3918 while (str.length % 4 !== 0) {
3925 function stringtrim(str) {
3926 if (str.trim) return str.trim();
3927 return str.replace(/^\s+|\s+$/g, '');
3931 if (n < 16) return '0' + n.toString(16);
3932 return n.toString(16);
3935 function utf8ToBytes(string, units) {
3936 units = units || Infinity;
3938 var length = string.length;
3939 var leadSurrogate = null;
3942 for (var i = 0; i < length; ++i) {
3943 codePoint = string.charCodeAt(i); // is surrogate component
3945 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3946 // last char was a lead
3947 if (!leadSurrogate) {
3949 if (codePoint > 0xDBFF) {
3951 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3953 } else if (i + 1 === length) {
3955 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3960 leadSurrogate = codePoint;
3962 } // 2 leads in a row
3965 if (codePoint < 0xDC00) {
3966 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3967 leadSurrogate = codePoint;
3969 } // valid surrogate pair
3972 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
3973 } else if (leadSurrogate) {
3974 // valid bmp char, but last char was a lead
3975 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3978 leadSurrogate = null; // encode utf8
3980 if (codePoint < 0x80) {
3981 if ((units -= 1) < 0) break;
3982 bytes.push(codePoint);
3983 } else if (codePoint < 0x800) {
3984 if ((units -= 2) < 0) break;
3985 bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
3986 } else if (codePoint < 0x10000) {
3987 if ((units -= 3) < 0) break;
3988 bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
3989 } else if (codePoint < 0x110000) {
3990 if ((units -= 4) < 0) break;
3991 bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
3993 throw new Error('Invalid code point');
4000 function asciiToBytes(str) {
4003 for (var i = 0; i < str.length; ++i) {
4004 // Node's code seems to be doing this and not & 0x7F..
4005 byteArray.push(str.charCodeAt(i) & 0xFF);
4011 function utf16leToBytes(str, units) {
4015 for (var i = 0; i < str.length; ++i) {
4016 if ((units -= 2) < 0) break;
4017 c = str.charCodeAt(i);
4027 function base64ToBytes(str) {
4028 return toByteArray(base64clean(str));
4031 function blitBuffer(src, dst, offset, length) {
4032 for (var i = 0; i < length; ++i) {
4033 if (i + offset >= dst.length || i >= src.length) break;
4034 dst[i + offset] = src[i];
4040 function isnan(val) {
4041 return val !== val; // eslint-disable-line no-self-compare
4042 } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
4043 // The _isBuffer check is for Safari 5-7 support, because it's missing
4044 // Object.prototype.constructor. Remove this eventually
4047 function isBuffer(obj) {
4048 return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj));
4051 function isFastBuffer(obj) {
4052 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
4053 } // For Node v0.10 support. Remove this eventually.
4056 function isSlowBuffer(obj) {
4057 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0));
4060 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
4062 function unwrapExports (x) {
4063 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
4066 function createCommonjsModule(fn, module) {
4067 return module = { exports: {} }, fn(module, module.exports), module.exports;
4070 function getCjsExportFromNamespace (n) {
4071 return n && n['default'] || n;
4074 var fs = getCjsExportFromNamespace(_shim_fs$1);
4084 function LineByLine(file, options) {
4085 _classCallCheck(this, LineByLine);
4087 options = options || {};
4088 if (!options.readChunk) options.readChunk = 1024;
4090 if (!options.newLineCharacter) {
4091 options.newLineCharacter = 0x0a; //linux line ending
4093 options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
4096 if (typeof file === 'number') {
4099 this.fd = fs.openSync(file, 'r');
4102 this.options = options;
4103 this.newLineCharacter = options.newLineCharacter;
4107 _createClass(LineByLine, [{
4108 key: "_searchInBuffer",
4109 value: function _searchInBuffer(buffer, hexNeedle) {
4112 for (var i = 0; i <= buffer.length; i++) {
4113 var b_byte = buffer[i];
4115 if (b_byte === hexNeedle) {
4125 value: function reset() {
4126 this.eofReached = false;
4127 this.linesCache = [];
4128 this.fdPosition = 0;
4132 value: function close() {
4133 fs.closeSync(this.fd);
4137 key: "_extractLines",
4138 value: function _extractLines(buffer) {
4141 var bufferPosition = 0;
4142 var lastNewLineBufferPosition = 0;
4145 var bufferPositionValue = buffer[bufferPosition++];
4147 if (bufferPositionValue === this.newLineCharacter) {
4148 line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
4150 lastNewLineBufferPosition = bufferPosition;
4151 } else if (!bufferPositionValue) {
4156 var leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
4158 if (leftovers.length) {
4159 lines.push(leftovers);
4166 value: function _readChunk(lineLeftovers) {
4167 var totalBytesRead = 0;
4172 var readBuffer = new Buffer(this.options.readChunk);
4173 bytesRead = fs.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
4174 totalBytesRead = totalBytesRead + bytesRead;
4175 this.fdPosition = this.fdPosition + bytesRead;
4176 buffers.push(readBuffer);
4177 } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
4179 var bufferData = Buffer.concat(buffers);
4181 if (bytesRead < this.options.readChunk) {
4182 this.eofReached = true;
4183 bufferData = bufferData.slice(0, totalBytesRead);
4186 if (totalBytesRead) {
4187 this.linesCache = this._extractLines(bufferData);
4189 if (lineLeftovers) {
4190 this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
4194 return totalBytesRead;
4198 value: function next() {
4199 if (!this.fd) return false;
4202 if (this.eofReached && this.linesCache.length === 0) {
4208 if (!this.linesCache.length) {
4209 bytesRead = this._readChunk();
4212 if (this.linesCache.length) {
4213 line = this.linesCache.shift();
4214 var lastLineCharacter = line[line.length - 1];
4216 if (lastLineCharacter !== 0x0a) {
4217 bytesRead = this._readChunk(line);
4220 line = this.linesCache.shift();
4225 if (this.eofReached && this.linesCache.length === 0) {
4229 if (line && line[line.length - 1] === this.newLineCharacter) {
4230 line = line.slice(0, line.length - 1);
4240 var readlines = LineByLine;
4245 _inherits(ConfigError, _Error);
4247 function ConfigError() {
4248 _classCallCheck(this, ConfigError);
4250 return _possibleConstructorReturn(this, _getPrototypeOf(ConfigError).apply(this, arguments));
4254 }(_wrapNativeSuper(Error));
4258 function (_Error2) {
4259 _inherits(DebugError, _Error2);
4261 function DebugError() {
4262 _classCallCheck(this, DebugError);
4264 return _possibleConstructorReturn(this, _getPrototypeOf(DebugError).apply(this, arguments));
4268 }(_wrapNativeSuper(Error));
4270 var UndefinedParserError =
4272 function (_Error3) {
4273 _inherits(UndefinedParserError, _Error3);
4275 function UndefinedParserError() {
4276 _classCallCheck(this, UndefinedParserError);
4278 return _possibleConstructorReturn(this, _getPrototypeOf(UndefinedParserError).apply(this, arguments));
4281 return UndefinedParserError;
4282 }(_wrapNativeSuper(Error));
4285 ConfigError: ConfigError,
4286 DebugError: DebugError,
4287 UndefinedParserError: UndefinedParserError
4290 // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
4292 function defaultSetTimout() {
4293 throw new Error('setTimeout has not been defined');
4296 function defaultClearTimeout() {
4297 throw new Error('clearTimeout has not been defined');
4300 var cachedSetTimeout = defaultSetTimout;
4301 var cachedClearTimeout = defaultClearTimeout;
4303 if (typeof global$1.setTimeout === 'function') {
4304 cachedSetTimeout = setTimeout;
4307 if (typeof global$1.clearTimeout === 'function') {
4308 cachedClearTimeout = clearTimeout;
4311 function runTimeout(fun) {
4312 if (cachedSetTimeout === setTimeout) {
4313 //normal enviroments in sane situations
4314 return setTimeout(fun, 0);
4315 } // if setTimeout wasn't available but was latter defined
4318 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
4319 cachedSetTimeout = setTimeout;
4320 return setTimeout(fun, 0);
4324 // when when somebody has screwed with setTimeout but no I.E. maddness
4325 return cachedSetTimeout(fun, 0);
4328 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4329 return cachedSetTimeout.call(null, fun, 0);
4331 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
4332 return cachedSetTimeout.call(this, fun, 0);
4337 function runClearTimeout(marker) {
4338 if (cachedClearTimeout === clearTimeout) {
4339 //normal enviroments in sane situations
4340 return clearTimeout(marker);
4341 } // if clearTimeout wasn't available but was latter defined
4344 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
4345 cachedClearTimeout = clearTimeout;
4346 return clearTimeout(marker);
4350 // when when somebody has screwed with setTimeout but no I.E. maddness
4351 return cachedClearTimeout(marker);
4354 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4355 return cachedClearTimeout.call(null, marker);
4357 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
4358 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
4359 return cachedClearTimeout.call(this, marker);
4365 var draining = false;
4367 var queueIndex = -1;
4369 function cleanUpNextTick() {
4370 if (!draining || !currentQueue) {
4376 if (currentQueue.length) {
4377 queue = currentQueue.concat(queue);
4387 function drainQueue() {
4392 var timeout = runTimeout(cleanUpNextTick);
4394 var len = queue.length;
4397 currentQueue = queue;
4400 while (++queueIndex < len) {
4402 currentQueue[queueIndex].run();
4410 currentQueue = null;
4412 runClearTimeout(timeout);
4415 function nextTick(fun) {
4416 var args = new Array(arguments.length - 1);
4418 if (arguments.length > 1) {
4419 for (var i = 1; i < arguments.length; i++) {
4420 args[i - 1] = arguments[i];
4424 queue.push(new Item(fun, args));
4426 if (queue.length === 1 && !draining) {
4427 runTimeout(drainQueue);
4429 } // v8 likes predictible objects
4431 function Item(fun, array) {
4436 Item.prototype.run = function () {
4437 this.fun.apply(null, this.array);
4440 var title = 'browser';
4441 var platform = 'browser';
4445 var version$1 = ''; // empty string to avoid regexp issues
4454 var addListener = noop;
4457 var removeListener = noop;
4458 var removeAllListeners = noop;
4460 function binding(name) {
4461 throw new Error('process.binding is not supported');
4466 function chdir(dir) {
4467 throw new Error('process.chdir is not supported');
4471 } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
4473 var performance = global$1.performance || {};
4475 var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
4476 return new Date().getTime();
4477 }; // generate timestamp or delta
4478 // see http://nodejs.org/api/process.html#process_process_hrtime
4481 function hrtime(previousTimestamp) {
4482 var clocktime = performanceNow.call(performance) * 1e-3;
4483 var seconds = Math.floor(clocktime);
4484 var nanoseconds = Math.floor(clocktime % 1 * 1e9);
4486 if (previousTimestamp) {
4487 seconds = seconds - previousTimestamp[0];
4488 nanoseconds = nanoseconds - previousTimestamp[1];
4490 if (nanoseconds < 0) {
4496 return [seconds, nanoseconds];
4498 var startTime = new Date();
4500 var currentTime = new Date();
4501 var dif = currentTime - startTime;
4513 addListener: addListener,
4516 removeListener: removeListener,
4517 removeAllListeners: removeAllListeners,
4530 var semver = createCommonjsModule(function (module, exports) {
4531 exports = module.exports = SemVer;
4533 /* istanbul ignore next */
4535 if (_typeof(process) === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
4536 debug = function debug() {
4537 var args = Array.prototype.slice.call(arguments, 0);
4538 args.unshift('SEMVER');
4539 console.log.apply(console, args);
4542 debug = function debug() {};
4543 } // Note: this is the semver.org version of the spec that it implements
4544 // Not necessarily the package version of this code.
4547 exports.SEMVER_SPEC_VERSION = '2.0.0';
4548 var MAX_LENGTH = 256;
4549 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
4550 /* istanbul ignore next */
4551 9007199254740991; // Max safe segment length for coercion.
4553 var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
4555 var re = exports.re = [];
4556 var src = exports.src = [];
4557 var t = exports.tokens = {};
4562 } // The following Regular Expressions can be used for tokenizing,
4563 // validating, and parsing SemVer version strings.
4564 // ## Numeric Identifier
4565 // A single `0`, or a non-zero digit followed by zero or more digits.
4568 tok('NUMERICIDENTIFIER');
4569 src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*';
4570 tok('NUMERICIDENTIFIERLOOSE');
4571 src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
4572 // Zero or more digits, followed by a letter or hyphen, and then zero or
4573 // more letters, digits, or hyphens.
4575 tok('NONNUMERICIDENTIFIER');
4576 src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
4577 // Three dot-separated numeric identifiers.
4580 src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')';
4581 tok('MAINVERSIONLOOSE');
4582 src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
4583 // A numeric identifier, or a non-numeric identifier.
4585 tok('PRERELEASEIDENTIFIER');
4586 src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')';
4587 tok('PRERELEASEIDENTIFIERLOOSE');
4588 src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
4589 // Hyphen, followed by one or more dot-separated pre-release version
4593 src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))';
4594 tok('PRERELEASELOOSE');
4595 src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
4596 // Any combination of digits, letters, or hyphens.
4598 tok('BUILDIDENTIFIER');
4599 src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
4600 // Plus sign, followed by one or more period-separated build metadata
4604 src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))'; // ## Full Version String
4605 // A main version, followed optionally by a pre-release version and
4607 // Note that the only major, minor, patch, and pre-release sections of
4608 // the version string are capturing groups. The build metadata is not a
4609 // capturing group, because it should not ever be used in version
4614 src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?';
4615 src[t.FULL] = '^' + src[t.FULLPLAIN] + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
4616 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
4617 // common in the npm registry.
4620 src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?';
4622 src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$';
4624 src[t.GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
4625 // Note that "x.x" is a valid xRange identifer, meaning "any version"
4626 // Only the first item is strictly required.
4628 tok('XRANGEIDENTIFIERLOOSE');
4629 src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
4630 tok('XRANGEIDENTIFIER');
4631 src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*';
4633 src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?';
4634 tok('XRANGEPLAINLOOSE');
4635 src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?';
4637 src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$';
4639 src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$'; // Coercion.
4640 // Extract anything that could conceivably be a part of a valid semver
4643 src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])';
4645 re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g'); // Tilde ranges.
4646 // Meaning is "reasonably at or greater than"
4649 src[t.LONETILDE] = '(?:~>?)';
4651 src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+';
4652 re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g');
4653 var tildeTrimReplace = '$1~';
4655 src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$';
4657 src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'; // Caret ranges.
4658 // Meaning is "at least and backwards compatible with"
4661 src[t.LONECARET] = '(?:\\^)';
4663 src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+';
4664 re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g');
4665 var caretTrimReplace = '$1^';
4667 src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$';
4669 src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
4671 tok('COMPARATORLOOSE');
4672 src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$';
4674 src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
4675 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
4677 tok('COMPARATORTRIM');
4678 src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')'; // this one has to use the /g flag
4680 re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g');
4681 var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
4682 // Note that these all use the loose form, because they'll be
4683 // checked against either the strict or loose comparator form
4687 src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$';
4688 tok('HYPHENRANGELOOSE');
4689 src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
4692 src[t.STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
4693 // All are flag-free, unless they were created above with a flag.
4695 for (var i = 0; i < R; i++) {
4699 re[i] = new RegExp(src[i]);
4703 exports.parse = parse;
4705 function parse(version, options) {
4706 if (!options || _typeof(options) !== 'object') {
4709 includePrerelease: false
4713 if (version instanceof SemVer) {
4717 if (typeof version !== 'string') {
4721 if (version.length > MAX_LENGTH) {
4725 var r = options.loose ? re[t.LOOSE] : re[t.FULL];
4727 if (!r.test(version)) {
4732 return new SemVer(version, options);
4738 exports.valid = valid;
4740 function valid(version, options) {
4741 var v = parse(version, options);
4742 return v ? v.version : null;
4745 exports.clean = clean;
4747 function clean(version, options) {
4748 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
4749 return s ? s.version : null;
4752 exports.SemVer = SemVer;
4754 function SemVer(version, options) {
4755 if (!options || _typeof(options) !== 'object') {
4758 includePrerelease: false
4762 if (version instanceof SemVer) {
4763 if (version.loose === options.loose) {
4766 version = version.version;
4768 } else if (typeof version !== 'string') {
4769 throw new TypeError('Invalid Version: ' + version);
4772 if (version.length > MAX_LENGTH) {
4773 throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
4776 if (!(this instanceof SemVer)) {
4777 return new SemVer(version, options);
4780 debug('SemVer', version, options);
4781 this.options = options;
4782 this.loose = !!options.loose;
4783 var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
4786 throw new TypeError('Invalid Version: ' + version);
4789 this.raw = version; // these are actually numbers
4795 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
4796 throw new TypeError('Invalid major version');
4799 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
4800 throw new TypeError('Invalid minor version');
4803 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
4804 throw new TypeError('Invalid patch version');
4805 } // numberify any prerelease numeric ids
4809 this.prerelease = [];
4811 this.prerelease = m[4].split('.').map(function (id) {
4812 if (/^[0-9]+$/.test(id)) {
4815 if (num >= 0 && num < MAX_SAFE_INTEGER) {
4824 this.build = m[5] ? m[5].split('.') : [];
4828 SemVer.prototype.format = function () {
4829 this.version = this.major + '.' + this.minor + '.' + this.patch;
4831 if (this.prerelease.length) {
4832 this.version += '-' + this.prerelease.join('.');
4835 return this.version;
4838 SemVer.prototype.toString = function () {
4839 return this.version;
4842 SemVer.prototype.compare = function (other) {
4843 debug('SemVer.compare', this.version, this.options, other);
4845 if (!(other instanceof SemVer)) {
4846 other = new SemVer(other, this.options);
4849 return this.compareMain(other) || this.comparePre(other);
4852 SemVer.prototype.compareMain = function (other) {
4853 if (!(other instanceof SemVer)) {
4854 other = new SemVer(other, this.options);
4857 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
4860 SemVer.prototype.comparePre = function (other) {
4861 if (!(other instanceof SemVer)) {
4862 other = new SemVer(other, this.options);
4863 } // NOT having a prerelease is > having one
4866 if (this.prerelease.length && !other.prerelease.length) {
4868 } else if (!this.prerelease.length && other.prerelease.length) {
4870 } else if (!this.prerelease.length && !other.prerelease.length) {
4877 var a = this.prerelease[i];
4878 var b = other.prerelease[i];
4879 debug('prerelease compare', i, a, b);
4881 if (a === undefined && b === undefined) {
4883 } else if (b === undefined) {
4885 } else if (a === undefined) {
4887 } else if (a === b) {
4890 return compareIdentifiers(a, b);
4895 SemVer.prototype.compareBuild = function (other) {
4896 if (!(other instanceof SemVer)) {
4897 other = new SemVer(other, this.options);
4903 var a = this.build[i];
4904 var b = other.build[i];
4905 debug('prerelease compare', i, a, b);
4907 if (a === undefined && b === undefined) {
4909 } else if (b === undefined) {
4911 } else if (a === undefined) {
4913 } else if (a === b) {
4916 return compareIdentifiers(a, b);
4919 }; // preminor will bump the version up to the next minor release, and immediately
4920 // down to pre-release. premajor and prepatch work the same way.
4923 SemVer.prototype.inc = function (release, identifier) {
4926 this.prerelease.length = 0;
4930 this.inc('pre', identifier);
4934 this.prerelease.length = 0;
4937 this.inc('pre', identifier);
4941 // If this is already a prerelease, it will bump to the next version
4942 // drop any prereleases that might already exist, since they are not
4943 // relevant at this point.
4944 this.prerelease.length = 0;
4945 this.inc('patch', identifier);
4946 this.inc('pre', identifier);
4948 // If the input is a non-prerelease version, this acts the same as
4952 if (this.prerelease.length === 0) {
4953 this.inc('patch', identifier);
4956 this.inc('pre', identifier);
4960 // If this is a pre-major version, bump up to the same major version.
4961 // Otherwise increment major.
4962 // 1.0.0-5 bumps to 1.0.0
4963 // 1.1.0 bumps to 2.0.0
4964 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
4970 this.prerelease = [];
4974 // If this is a pre-minor version, bump up to the same minor version.
4975 // Otherwise increment minor.
4976 // 1.2.0-5 bumps to 1.2.0
4977 // 1.2.1 bumps to 1.3.0
4978 if (this.patch !== 0 || this.prerelease.length === 0) {
4983 this.prerelease = [];
4987 // If this is not a pre-release version, it will increment the patch.
4988 // If it is a pre-release it will bump up to the same patch version.
4989 // 1.2.0-5 patches to 1.2.0
4990 // 1.2.0 patches to 1.2.1
4991 if (this.prerelease.length === 0) {
4995 this.prerelease = [];
4997 // This probably shouldn't be used publicly.
4998 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
5001 if (this.prerelease.length === 0) {
5002 this.prerelease = [0];
5004 var i = this.prerelease.length;
5007 if (typeof this.prerelease[i] === 'number') {
5008 this.prerelease[i]++;
5014 // didn't increment anything
5015 this.prerelease.push(0);
5020 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
5021 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
5022 if (this.prerelease[0] === identifier) {
5023 if (isNaN(this.prerelease[1])) {
5024 this.prerelease = [identifier, 0];
5027 this.prerelease = [identifier, 0];
5034 throw new Error('invalid increment argument: ' + release);
5038 this.raw = this.version;
5044 function inc(version, release, loose, identifier) {
5045 if (typeof loose === 'string') {
5051 return new SemVer(version, loose).inc(release, identifier).version;
5057 exports.diff = diff;
5059 function diff(version1, version2) {
5060 if (eq(version1, version2)) {
5063 var v1 = parse(version1);
5064 var v2 = parse(version2);
5067 if (v1.prerelease.length || v2.prerelease.length) {
5069 var defaultResult = 'prerelease';
5072 for (var key in v1) {
5073 if (key === 'major' || key === 'minor' || key === 'patch') {
5074 if (v1[key] !== v2[key]) {
5075 return prefix + key;
5080 return defaultResult; // may be undefined
5084 exports.compareIdentifiers = compareIdentifiers;
5085 var numeric = /^[0-9]+$/;
5087 function compareIdentifiers(a, b) {
5088 var anum = numeric.test(a);
5089 var bnum = numeric.test(b);
5096 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
5099 exports.rcompareIdentifiers = rcompareIdentifiers;
5101 function rcompareIdentifiers(a, b) {
5102 return compareIdentifiers(b, a);
5105 exports.major = major;
5107 function major(a, loose) {
5108 return new SemVer(a, loose).major;
5111 exports.minor = minor;
5113 function minor(a, loose) {
5114 return new SemVer(a, loose).minor;
5117 exports.patch = patch;
5119 function patch(a, loose) {
5120 return new SemVer(a, loose).patch;
5123 exports.compare = compare;
5125 function compare(a, b, loose) {
5126 return new SemVer(a, loose).compare(new SemVer(b, loose));
5129 exports.compareLoose = compareLoose;
5131 function compareLoose(a, b) {
5132 return compare(a, b, true);
5135 exports.compareBuild = compareBuild;
5137 function compareBuild(a, b, loose) {
5138 var versionA = new SemVer(a, loose);
5139 var versionB = new SemVer(b, loose);
5140 return versionA.compare(versionB) || versionA.compareBuild(versionB);
5143 exports.rcompare = rcompare;
5145 function rcompare(a, b, loose) {
5146 return compare(b, a, loose);
5149 exports.sort = sort;
5151 function sort(list, loose) {
5152 return list.sort(function (a, b) {
5153 return exports.compareBuild(a, b, loose);
5157 exports.rsort = rsort;
5159 function rsort(list, loose) {
5160 return list.sort(function (a, b) {
5161 return exports.compareBuild(b, a, loose);
5167 function gt(a, b, loose) {
5168 return compare(a, b, loose) > 0;
5173 function lt(a, b, loose) {
5174 return compare(a, b, loose) < 0;
5179 function eq(a, b, loose) {
5180 return compare(a, b, loose) === 0;
5185 function neq(a, b, loose) {
5186 return compare(a, b, loose) !== 0;
5191 function gte(a, b, loose) {
5192 return compare(a, b, loose) >= 0;
5197 function lte(a, b, loose) {
5198 return compare(a, b, loose) <= 0;
5203 function cmp(a, op, b, loose) {
5206 if (_typeof(a) === 'object') a = a.version;
5207 if (_typeof(b) === 'object') b = b.version;
5211 if (_typeof(a) === 'object') a = a.version;
5212 if (_typeof(b) === 'object') b = b.version;
5218 return eq(a, b, loose);
5221 return neq(a, b, loose);
5224 return gt(a, b, loose);
5227 return gte(a, b, loose);
5230 return lt(a, b, loose);
5233 return lte(a, b, loose);
5236 throw new TypeError('Invalid operator: ' + op);
5240 exports.Comparator = Comparator;
5242 function Comparator(comp, options) {
5243 if (!options || _typeof(options) !== 'object') {
5246 includePrerelease: false
5250 if (comp instanceof Comparator) {
5251 if (comp.loose === !!options.loose) {
5258 if (!(this instanceof Comparator)) {
5259 return new Comparator(comp, options);
5262 debug('comparator', comp, options);
5263 this.options = options;
5264 this.loose = !!options.loose;
5267 if (this.semver === ANY) {
5270 this.value = this.operator + this.semver.version;
5273 debug('comp', this);
5278 Comparator.prototype.parse = function (comp) {
5279 var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
5280 var m = comp.match(r);
5283 throw new TypeError('Invalid comparator: ' + comp);
5286 this.operator = m[1] !== undefined ? m[1] : '';
5288 if (this.operator === '=') {
5290 } // if it literally is just '>' or '' then allow anything.
5296 this.semver = new SemVer(m[2], this.options.loose);
5300 Comparator.prototype.toString = function () {
5304 Comparator.prototype.test = function (version) {
5305 debug('Comparator.test', version, this.options.loose);
5307 if (this.semver === ANY || version === ANY) {
5311 if (typeof version === 'string') {
5313 version = new SemVer(version, this.options);
5319 return cmp(version, this.operator, this.semver, this.options);
5322 Comparator.prototype.intersects = function (comp, options) {
5323 if (!(comp instanceof Comparator)) {
5324 throw new TypeError('a Comparator is required');
5327 if (!options || _typeof(options) !== 'object') {
5330 includePrerelease: false
5336 if (this.operator === '') {
5337 if (this.value === '') {
5341 rangeTmp = new Range(comp.value, options);
5342 return satisfies(this.value, rangeTmp, options);
5343 } else if (comp.operator === '') {
5344 if (comp.value === '') {
5348 rangeTmp = new Range(this.value, options);
5349 return satisfies(comp.semver, rangeTmp, options);
5352 var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
5353 var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
5354 var sameSemVer = this.semver.version === comp.semver.version;
5355 var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
5356 var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
5357 var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
5358 return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
5361 exports.Range = Range;
5363 function Range(range, options) {
5364 if (!options || _typeof(options) !== 'object') {
5367 includePrerelease: false
5371 if (range instanceof Range) {
5372 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
5375 return new Range(range.raw, options);
5379 if (range instanceof Comparator) {
5380 return new Range(range.value, options);
5383 if (!(this instanceof Range)) {
5384 return new Range(range, options);
5387 this.options = options;
5388 this.loose = !!options.loose;
5389 this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
5392 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
5393 return this.parseRange(range.trim());
5394 }, this).filter(function (c) {
5395 // throw out any that are not relevant for whatever reason
5399 if (!this.set.length) {
5400 throw new TypeError('Invalid SemVer Range: ' + range);
5406 Range.prototype.format = function () {
5407 this.range = this.set.map(function (comps) {
5408 return comps.join(' ').trim();
5409 }).join('||').trim();
5413 Range.prototype.toString = function () {
5417 Range.prototype.parseRange = function (range) {
5418 var loose = this.options.loose;
5419 range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
5421 var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
5422 range = range.replace(hr, hyphenReplace);
5423 debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
5425 range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
5426 debug('comparator trim', range, re[t.COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
5428 range = range.replace(re[t.TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
5430 range = range.replace(re[t.CARETTRIM], caretTrimReplace); // normalize spaces
5432 range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
5433 // ready to be split into comparators.
5435 var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
5436 var set = range.split(' ').map(function (comp) {
5437 return parseComparator(comp, this.options);
5438 }, this).join(' ').split(/\s+/);
5440 if (this.options.loose) {
5441 // in loose mode, throw out any that are not valid comparators
5442 set = set.filter(function (comp) {
5443 return !!comp.match(compRe);
5447 set = set.map(function (comp) {
5448 return new Comparator(comp, this.options);
5453 Range.prototype.intersects = function (range, options) {
5454 if (!(range instanceof Range)) {
5455 throw new TypeError('a Range is required');
5458 return this.set.some(function (thisComparators) {
5459 return isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) {
5460 return isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) {
5461 return rangeComparators.every(function (rangeComparator) {
5462 return thisComparator.intersects(rangeComparator, options);
5467 }; // take a set of comparators and determine whether there
5468 // exists a version which can satisfy it
5471 function isSatisfiable(comparators, options) {
5473 var remainingComparators = comparators.slice();
5474 var testComparator = remainingComparators.pop();
5476 while (result && remainingComparators.length) {
5477 result = remainingComparators.every(function (otherComparator) {
5478 return testComparator.intersects(otherComparator, options);
5480 testComparator = remainingComparators.pop();
5484 } // Mostly just for testing and legacy API reasons
5487 exports.toComparators = toComparators;
5489 function toComparators(range, options) {
5490 return new Range(range, options).set.map(function (comp) {
5491 return comp.map(function (c) {
5493 }).join(' ').trim().split(' ');
5495 } // comprised of xranges, tildes, stars, and gtlt's at this point.
5496 // already replaced the hyphen ranges
5497 // turn into a set of JUST comparators.
5500 function parseComparator(comp, options) {
5501 debug('comp', comp, options);
5502 comp = replaceCarets(comp, options);
5503 debug('caret', comp);
5504 comp = replaceTildes(comp, options);
5505 debug('tildes', comp);
5506 comp = replaceXRanges(comp, options);
5507 debug('xrange', comp);
5508 comp = replaceStars(comp, options);
5509 debug('stars', comp);
5514 return !id || id.toLowerCase() === 'x' || id === '*';
5515 } // ~, ~> --> * (any, kinda silly)
5516 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
5517 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
5518 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
5519 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
5520 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
5523 function replaceTildes(comp, options) {
5524 return comp.trim().split(/\s+/).map(function (comp) {
5525 return replaceTilde(comp, options);
5529 function replaceTilde(comp, options) {
5530 var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
5531 return comp.replace(r, function (_, M, m, p, pr) {
5532 debug('tilde', comp, _, M, m, p, pr);
5537 } else if (isX(m)) {
5538 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
5539 } else if (isX(p)) {
5540 // ~1.2 == >=1.2.0 <1.3.0
5541 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
5543 debug('replaceTilde pr', pr);
5544 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
5546 // ~1.2.3 == >=1.2.3 <1.3.0
5547 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
5550 debug('tilde return', ret);
5553 } // ^ --> * (any, kinda silly)
5554 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
5555 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
5556 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
5557 // ^1.2.3 --> >=1.2.3 <2.0.0
5558 // ^1.2.0 --> >=1.2.0 <2.0.0
5561 function replaceCarets(comp, options) {
5562 return comp.trim().split(/\s+/).map(function (comp) {
5563 return replaceCaret(comp, options);
5567 function replaceCaret(comp, options) {
5568 debug('caret', comp, options);
5569 var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
5570 return comp.replace(r, function (_, M, m, p, pr) {
5571 debug('caret', comp, _, M, m, p, pr);
5576 } else if (isX(m)) {
5577 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
5578 } else if (isX(p)) {
5580 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
5582 ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
5585 debug('replaceCaret pr', pr);
5589 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1);
5591 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
5594 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0';
5601 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);
5603 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
5606 ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
5610 debug('caret return', ret);
5615 function replaceXRanges(comp, options) {
5616 debug('replaceXRanges', comp, options);
5617 return comp.split(/\s+/).map(function (comp) {
5618 return replaceXRange(comp, options);
5622 function replaceXRange(comp, options) {
5624 var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
5625 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
5626 debug('xRange', comp, ret, gtlt, M, m, p, pr);
5628 var xm = xM || isX(m);
5629 var xp = xm || isX(p);
5632 if (gtlt === '=' && anyX) {
5634 } // if we're including prereleases in the match, then we need
5635 // to fix this to -0, the lowest possible prerelease value
5638 pr = options.includePrerelease ? '-0' : '';
5641 if (gtlt === '>' || gtlt === '<') {
5642 // nothing is allowed
5645 // nothing is forbidden
5648 } else if (gtlt && anyX) {
5649 // we know patch is an x, because we have any x at all.
5660 // >1.2.3 => >= 1.2.4
5671 } else if (gtlt === '<=') {
5672 // <=0.7.x is actually <0.8.0, since any 0.7.x should
5673 // pass. Similarly, <=7.x is actually <8.0.0, etc.
5683 ret = gtlt + M + '.' + m + '.' + p + pr;
5685 ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr;
5687 ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr;
5690 debug('xRange return', ret);
5693 } // Because * is AND-ed with everything else in the comparator,
5694 // and '' means "any version", just remove the *s entirely.
5697 function replaceStars(comp, options) {
5698 debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
5700 return comp.trim().replace(re[t.STAR], '');
5701 } // This function is passed to string.replace(re[t.HYPHENRANGE])
5702 // M, m, patch, prerelease, build
5703 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
5704 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
5705 // 1.2 - 3.4 => >=1.2.0 <3.5.0
5708 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
5711 } else if (isX(fm)) {
5712 from = '>=' + fM + '.0.0';
5713 } else if (isX(fp)) {
5714 from = '>=' + fM + '.' + fm + '.0';
5721 } else if (isX(tm)) {
5722 to = '<' + (+tM + 1) + '.0.0';
5723 } else if (isX(tp)) {
5724 to = '<' + tM + '.' + (+tm + 1) + '.0';
5726 to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
5731 return (from + ' ' + to).trim();
5732 } // if ANY of the sets match ALL of its comparators, then pass
5735 Range.prototype.test = function (version) {
5740 if (typeof version === 'string') {
5742 version = new SemVer(version, this.options);
5748 for (var i = 0; i < this.set.length; i++) {
5749 if (testSet(this.set[i], version, this.options)) {
5757 function testSet(set, version, options) {
5758 for (var i = 0; i < set.length; i++) {
5759 if (!set[i].test(version)) {
5764 if (version.prerelease.length && !options.includePrerelease) {
5765 // Find the set of versions that are allowed to have prereleases
5766 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
5767 // That should allow `1.2.3-pr.2` to pass.
5768 // However, `1.2.4-alpha.notready` should NOT be allowed,
5769 // even though it's within the range set by the comparators.
5770 for (i = 0; i < set.length; i++) {
5771 debug(set[i].semver);
5773 if (set[i].semver === ANY) {
5777 if (set[i].semver.prerelease.length > 0) {
5778 var allowed = set[i].semver;
5780 if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
5784 } // Version has a -pre, but it's not one of the ones we like.
5793 exports.satisfies = satisfies;
5795 function satisfies(version, range, options) {
5797 range = new Range(range, options);
5802 return range.test(version);
5805 exports.maxSatisfying = maxSatisfying;
5807 function maxSatisfying(versions, range, options) {
5812 var rangeObj = new Range(range, options);
5817 versions.forEach(function (v) {
5818 if (rangeObj.test(v)) {
5819 // satisfies(v, range, options)
5820 if (!max || maxSV.compare(v) === -1) {
5821 // compare(max, v, true)
5823 maxSV = new SemVer(max, options);
5830 exports.minSatisfying = minSatisfying;
5832 function minSatisfying(versions, range, options) {
5837 var rangeObj = new Range(range, options);
5842 versions.forEach(function (v) {
5843 if (rangeObj.test(v)) {
5844 // satisfies(v, range, options)
5845 if (!min || minSV.compare(v) === 1) {
5846 // compare(min, v, true)
5848 minSV = new SemVer(min, options);
5855 exports.minVersion = minVersion;
5857 function minVersion(range, loose) {
5858 range = new Range(range, loose);
5859 var minver = new SemVer('0.0.0');
5861 if (range.test(minver)) {
5865 minver = new SemVer('0.0.0-0');
5867 if (range.test(minver)) {
5873 for (var i = 0; i < range.set.length; ++i) {
5874 var comparators = range.set[i];
5875 comparators.forEach(function (comparator) {
5876 // Clone to avoid manipulating the comparator's semver object.
5877 var compver = new SemVer(comparator.semver.version);
5879 switch (comparator.operator) {
5881 if (compver.prerelease.length === 0) {
5884 compver.prerelease.push(0);
5887 compver.raw = compver.format();
5893 if (!minver || gt(minver, compver)) {
5901 /* Ignore maximum versions */
5904 /* istanbul ignore next */
5907 throw new Error('Unexpected operation: ' + comparator.operator);
5912 if (minver && range.test(minver)) {
5919 exports.validRange = validRange;
5921 function validRange(range, options) {
5923 // Return '*' instead of '' so that truthiness works.
5924 // This will throw if it's invalid anyway
5925 return new Range(range, options).range || '*';
5929 } // Determine if version is less than all the versions possible in the range
5934 function ltr(version, range, options) {
5935 return outside(version, range, '<', options);
5936 } // Determine if version is greater than all the versions possible in the range.
5941 function gtr(version, range, options) {
5942 return outside(version, range, '>', options);
5945 exports.outside = outside;
5947 function outside(version, range, hilo, options) {
5948 version = new SemVer(version, options);
5949 range = new Range(range, options);
5950 var gtfn, ltefn, ltfn, comp, ecomp;
5970 throw new TypeError('Must provide a hilo val of "<" or ">"');
5971 } // If it satisifes the range it is not outside
5974 if (satisfies(version, range, options)) {
5976 } // From now on, variable terms are as if we're in "gtr" mode.
5977 // but note that everything is flipped for the "ltr" function.
5980 for (var i = 0; i < range.set.length; ++i) {
5981 var comparators = range.set[i];
5984 comparators.forEach(function (comparator) {
5985 if (comparator.semver === ANY) {
5986 comparator = new Comparator('>=0.0.0');
5989 high = high || comparator;
5990 low = low || comparator;
5992 if (gtfn(comparator.semver, high.semver, options)) {
5994 } else if (ltfn(comparator.semver, low.semver, options)) {
5997 }); // If the edge version comparator has a operator then our version
6000 if (high.operator === comp || high.operator === ecomp) {
6002 } // If the lowest version comparator has an operator and our version
6003 // is less than it then it isn't higher than the range
6006 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
6008 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
6016 exports.prerelease = prerelease;
6018 function prerelease(version, options) {
6019 var parsed = parse(version, options);
6020 return parsed && parsed.prerelease.length ? parsed.prerelease : null;
6023 exports.intersects = intersects;
6025 function intersects(r1, r2, options) {
6026 r1 = new Range(r1, options);
6027 r2 = new Range(r2, options);
6028 return r1.intersects(r2);
6031 exports.coerce = coerce;
6033 function coerce(version, options) {
6034 if (version instanceof SemVer) {
6038 if (typeof version === 'number') {
6039 version = String(version);
6042 if (typeof version !== 'string') {
6046 options = options || {};
6050 match = version.match(re[t.COERCE]);
6052 // Find the right-most coercible string that does not share
6053 // a terminus with a more left-ward coercible string.
6054 // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
6056 // Walk through the string checking with a /g regexp
6057 // Manually set the index so as to pick up overlapping matches.
6058 // Stop when we get a match that ends at the string end, since no
6059 // coercible string can be more right-ward without the same terminus.
6062 while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
6063 if (!match || next.index + next[0].length !== match.index + match[0].length) {
6067 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
6068 } // leave it in a clean state
6071 re[t.COERCERTL].lastIndex = -1;
6074 if (match === null) {
6078 return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options);
6081 var semver_1 = semver.SEMVER_SPEC_VERSION;
6082 var semver_2 = semver.re;
6083 var semver_3 = semver.src;
6084 var semver_4 = semver.tokens;
6085 var semver_5 = semver.parse;
6086 var semver_6 = semver.valid;
6087 var semver_7 = semver.clean;
6088 var semver_8 = semver.SemVer;
6089 var semver_9 = semver.inc;
6090 var semver_10 = semver.diff;
6091 var semver_11 = semver.compareIdentifiers;
6092 var semver_12 = semver.rcompareIdentifiers;
6093 var semver_13 = semver.major;
6094 var semver_14 = semver.minor;
6095 var semver_15 = semver.patch;
6096 var semver_16 = semver.compare;
6097 var semver_17 = semver.compareLoose;
6098 var semver_18 = semver.compareBuild;
6099 var semver_19 = semver.rcompare;
6100 var semver_20 = semver.sort;
6101 var semver_21 = semver.rsort;
6102 var semver_22 = semver.gt;
6103 var semver_23 = semver.lt;
6104 var semver_24 = semver.eq;
6105 var semver_25 = semver.neq;
6106 var semver_26 = semver.gte;
6107 var semver_27 = semver.lte;
6108 var semver_28 = semver.cmp;
6109 var semver_29 = semver.Comparator;
6110 var semver_30 = semver.Range;
6111 var semver_31 = semver.toComparators;
6112 var semver_32 = semver.satisfies;
6113 var semver_33 = semver.maxSatisfying;
6114 var semver_34 = semver.minSatisfying;
6115 var semver_35 = semver.minVersion;
6116 var semver_36 = semver.validRange;
6117 var semver_37 = semver.ltr;
6118 var semver_38 = semver.gtr;
6119 var semver_39 = semver.outside;
6120 var semver_40 = semver.prerelease;
6121 var semver_41 = semver.intersects;
6122 var semver_42 = semver.coerce;
6124 var arrayify = function arrayify(object, keyName) {
6125 return Object.keys(object).reduce(function (array, key) {
6126 return array.concat(Object.assign(_defineProperty({}, keyName, key), object[key]));
6130 var dedent_1 = createCommonjsModule(function (module) {
6132 function dedent(strings) {
6135 if (typeof strings === "string") {
6136 // dedent can be used as a plain function
6140 } // first, perform interpolation
6145 for (var i = 0; i < raw.length; i++) {
6146 result += raw[i]. // join lines when there is a suppressed newline
6147 replace(/\\\n[ \t]*/g, ""). // handle escaped backticks
6148 replace(/\\`/g, "`");
6150 if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
6151 result += arguments.length <= i + 1 ? undefined : arguments[i + 1];
6153 } // now strip indentation
6156 var lines = result.split("\n");
6158 lines.forEach(function (l) {
6159 var m = l.match(/^(\s+)\S+/);
6162 var indent = m[1].length;
6165 // this is the first indented line
6168 mindent = Math.min(mindent, indent);
6173 if (mindent !== null) {
6174 result = lines.map(function (l) {
6175 return l[0] === " " ? l.slice(mindent) : l;
6177 } // dedent eats leading and trailing whitespace too
6180 result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too
6182 return result.replace(/\\n/g, "\n");
6186 module.exports = dedent;
6190 function _templateObject6() {
6191 var data = _taggedTemplateLiteral(["\n Require either '@prettier' or '@format' to be present in the file's first docblock comment\n in order for it to be formatted.\n "]);
6193 _templateObject6 = function _templateObject6() {
6200 function _templateObject5() {
6201 var data = _taggedTemplateLiteral(["\n Format code starting at a given character offset.\n The range will extend backwards to the start of the first line containing the selected statement.\n This option cannot be used with --cursor-offset.\n "]);
6203 _templateObject5 = function _templateObject5() {
6210 function _templateObject4() {
6211 var data = _taggedTemplateLiteral(["\n Format code ending at a given character offset (exclusive).\n The range will extend forwards to the end of the selected statement.\n This option cannot be used with --cursor-offset.\n "]);
6213 _templateObject4 = function _templateObject4() {
6220 function _templateObject3() {
6221 var data = _taggedTemplateLiteral(["\n Custom directory that contains prettier plugins in node_modules subdirectory.\n Overrides default behavior when plugins are searched relatively to the location of Prettier.\n Multiple values are accepted.\n "]);
6223 _templateObject3 = function _templateObject3() {
6230 function _templateObject2() {
6231 var data = _taggedTemplateLiteral(["\n Maintain existing\n (mixed values within one file are normalised by looking at what's used after the first line)\n "]);
6233 _templateObject2 = function _templateObject2() {
6240 function _templateObject() {
6241 var data = _taggedTemplateLiteral(["\n Print (to stderr) where a cursor at the given position would move to after formatting.\n This option cannot be used with --range-start and --range-end.\n "]);
6243 _templateObject = function _templateObject() {
6250 var CATEGORY_CONFIG = "Config";
6251 var CATEGORY_EDITOR = "Editor";
6252 var CATEGORY_FORMAT = "Format";
6253 var CATEGORY_OTHER = "Other";
6254 var CATEGORY_OUTPUT = "Output";
6255 var CATEGORY_GLOBAL = "Global";
6256 var CATEGORY_SPECIAL = "Special";
6258 * @typedef {Object} OptionInfo
6259 * @property {string} [since] - available since version
6260 * @property {string} category
6261 * @property {'int' | 'boolean' | 'choice' | 'path'} type
6262 * @property {boolean} [array] - indicate it's an array of the specified type
6263 * @property {OptionValueInfo} [default]
6264 * @property {OptionRangeInfo} [range] - for type int
6265 * @property {string} description
6266 * @property {string} [deprecated] - deprecated since version
6267 * @property {OptionRedirectInfo} [redirect] - redirect deprecated option
6268 * @property {(value: any) => boolean} [exception]
6269 * @property {OptionChoiceInfo[]} [choices] - for type choice
6270 * @property {string} [cliName]
6271 * @property {string} [cliCategory]
6272 * @property {string} [cliDescription]
6274 * @typedef {number | boolean | string} OptionValue
6275 * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
6277 * @typedef {Object} OptionRedirectInfo
6278 * @property {string} option
6279 * @property {OptionValue} value
6281 * @typedef {Object} OptionRangeInfo
6282 * @property {number} start - recommended range start
6283 * @property {number} end - recommended range end
6284 * @property {number} step - recommended range step
6286 * @typedef {Object} OptionChoiceInfo
6287 * @property {boolean | string} value - boolean for the option that is originally boolean type
6288 * @property {string} description
6289 * @property {string} [since] - undefined if available since the first version of the option
6290 * @property {string} [deprecated] - deprecated since version
6291 * @property {OptionValueInfo} [redirect] - redirect deprecated value
6294 /** @type {{ [name: string]: OptionInfo }} */
6299 category: CATEGORY_SPECIAL,
6307 description: dedent_1(_templateObject()),
6308 cliCategory: CATEGORY_EDITOR
6312 category: CATEGORY_GLOBAL,
6315 description: "Which end of line characters to apply.",
6318 description: dedent_1(_templateObject2())
6321 description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
6324 description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
6327 description: "Carriage Return character only (\\r), used very rarely"
6332 category: CATEGORY_SPECIAL,
6334 description: "Specify the input filepath. This will be used to do parser inference.",
6335 cliName: "stdin-filepath",
6336 cliCategory: CATEGORY_OTHER,
6337 cliDescription: "Path to the file to pretend that stdin comes from."
6341 category: CATEGORY_SPECIAL,
6344 description: "Insert @format pragma into file's first docblock comment.",
6345 cliCategory: CATEGORY_OTHER
6349 category: CATEGORY_GLOBAL,
6358 description: "Which parser to use.",
6359 exception: function exception(value) {
6360 return typeof value === "string" || typeof value === "function";
6367 description: "JavaScript",
6368 deprecated: "1.16.0",
6373 description: "JavaScript"
6375 value: "babel-flow",
6379 value: "typescript",
6381 description: "TypeScript"
6389 description: "CSS/Less/SCSS",
6390 deprecated: "1.7.1",
6407 description: "JSON5"
6409 value: "json-stringify",
6411 description: "JSON.stringify"
6415 description: "GraphQL"
6419 description: "Markdown"
6435 description: "Handlebars"
6443 description: "Angular"
6447 description: "Lightning Web Components"
6457 category: CATEGORY_GLOBAL,
6458 description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
6459 exception: function exception(value) {
6460 return typeof value === "string" || _typeof(value) === "object";
6463 cliCategory: CATEGORY_CONFIG
6472 category: CATEGORY_GLOBAL,
6473 description: dedent_1(_templateObject3()),
6474 exception: function exception(value) {
6475 return typeof value === "string" || _typeof(value) === "object";
6477 cliName: "plugin-search-dir",
6478 cliCategory: CATEGORY_CONFIG
6482 category: CATEGORY_GLOBAL,
6485 description: "The line length where Prettier will try wrap.",
6494 category: CATEGORY_SPECIAL,
6502 description: dedent_1(_templateObject4()),
6503 cliCategory: CATEGORY_EDITOR
6507 category: CATEGORY_SPECIAL,
6515 description: dedent_1(_templateObject5()),
6516 cliCategory: CATEGORY_EDITOR
6520 category: CATEGORY_SPECIAL,
6523 description: dedent_1(_templateObject6()),
6524 cliCategory: CATEGORY_OTHER
6528 category: CATEGORY_GLOBAL,
6530 description: "Number of spaces per indentation level.",
6539 category: CATEGORY_GLOBAL,
6548 deprecated: "0.0.10",
6549 description: "Use flow parser.",
6554 cliName: "flow-parser"
6558 category: CATEGORY_GLOBAL,
6561 description: "Indent with tabs instead of spaces."
6565 CATEGORY_CONFIG: CATEGORY_CONFIG,
6566 CATEGORY_EDITOR: CATEGORY_EDITOR,
6567 CATEGORY_FORMAT: CATEGORY_FORMAT,
6568 CATEGORY_OTHER: CATEGORY_OTHER,
6569 CATEGORY_OUTPUT: CATEGORY_OUTPUT,
6570 CATEGORY_GLOBAL: CATEGORY_GLOBAL,
6571 CATEGORY_SPECIAL: CATEGORY_SPECIAL,
6575 var require$$0 = getCjsExportFromNamespace(_package$1);
6577 var currentVersion = require$$0.version;
6578 var coreOptions$1 = coreOptions.options;
6580 function getSupportInfo(version, opts) {
6581 opts = Object.assign({
6583 showUnreleased: false,
6584 showDeprecated: false,
6589 // pre-release version is smaller than the normal version in semver,
6590 // we need to treat it as the normal one so as to test new features.
6591 version = currentVersion.split("-", 1)[0];
6594 var plugins = opts.plugins;
6595 var options = arrayify(Object.assign(plugins.reduce(function (currentOptions, plugin) {
6596 return Object.assign(currentOptions, plugin.options);
6597 }, {}), coreOptions$1), "name").sort(function (a, b) {
6598 return a.name === b.name ? 0 : a.name < b.name ? -1 : 1;
6599 }).filter(filterSince).filter(filterDeprecated).map(mapDeprecated).map(mapInternal).map(function (option) {
6600 var newOption = Object.assign({}, option);
6602 if (Array.isArray(newOption.default)) {
6603 newOption.default = newOption.default.length === 1 ? newOption.default[0].value : newOption.default.filter(filterSince).sort(function (info1, info2) {
6604 return semver.compare(info2.since, info1.since);
6608 if (Array.isArray(newOption.choices)) {
6609 newOption.choices = newOption.choices.filter(filterSince).filter(filterDeprecated).map(mapDeprecated);
6613 }).map(function (option) {
6614 var filteredPlugins = plugins.filter(function (plugin) {
6615 return plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined;
6617 var pluginDefaults = filteredPlugins.reduce(function (reduced, plugin) {
6618 reduced[plugin.name] = plugin.defaultOptions[option.name];
6621 return Object.assign(option, {
6622 pluginDefaults: pluginDefaults
6625 var usePostCssParser = semver.lt(version, "1.7.1");
6626 var useBabylonParser = semver.lt(version, "1.16.0");
6627 var languages = plugins.reduce(function (all, plugin) {
6628 return all.concat(plugin.languages || []);
6629 }, []).filter(filterSince).map(function (language) {
6630 // Prevent breaking changes
6631 if (language.name === "Markdown") {
6632 return Object.assign({}, language, {
6633 parsers: ["markdown"]
6637 if (language.name === "TypeScript") {
6638 return Object.assign({}, language, {
6639 parsers: ["typescript"]
6641 } // "babylon" was renamed to "babel" in 1.16.0
6644 if (useBabylonParser && language.parsers.indexOf("babel") !== -1) {
6645 return Object.assign({}, language, {
6646 parsers: language.parsers.map(function (parser) {
6647 return parser === "babel" ? "babylon" : parser;
6652 if (usePostCssParser && (language.name === "CSS" || language.group === "CSS")) {
6653 return Object.assign({}, language, {
6654 parsers: ["postcss"]
6661 languages: languages,
6665 function filterSince(object) {
6666 return opts.showUnreleased || !("since" in object) || object.since && semver.gte(version, object.since);
6669 function filterDeprecated(object) {
6670 return opts.showDeprecated || !("deprecated" in object) || object.deprecated && semver.lt(version, object.deprecated);
6673 function mapDeprecated(object) {
6674 if (!object.deprecated || opts.showDeprecated) {
6678 var newObject = Object.assign({}, object);
6679 delete newObject.deprecated;
6680 delete newObject.redirect;
6684 function mapInternal(object) {
6685 if (opts.showInternal) {
6689 var newObject = Object.assign({}, object);
6690 delete newObject.cliName;
6691 delete newObject.cliCategory;
6692 delete newObject.cliDescription;
6698 getSupportInfo: getSupportInfo
6701 /*! *****************************************************************************
6702 Copyright (c) Microsoft Corporation. All rights reserved.
6703 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
6704 this file except in compliance with the License. You may obtain a copy of the
6705 License at http://www.apache.org/licenses/LICENSE-2.0
6707 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6708 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
6709 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
6710 MERCHANTABLITY OR NON-INFRINGEMENT.
6712 See the Apache Version 2.0 License for specific language governing permissions
6713 and limitations under the License.
6714 ***************************************************************************** */
6716 /* global Reflect, Promise */
6717 var _extendStatics = function extendStatics(d, b) {
6718 _extendStatics = Object.setPrototypeOf || {
6720 } instanceof Array && function (d, b) {
6722 } || function (d, b) {
6724 if (b.hasOwnProperty(p)) d[p] = b[p];
6728 return _extendStatics(d, b);
6731 function __extends(d, b) {
6732 _extendStatics(d, b);
6735 this.constructor = d;
6738 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6741 var _assign = function __assign() {
6742 _assign = Object.assign || function __assign(t) {
6743 for (var s, i = 1, n = arguments.length; i < n; i++) {
6747 if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
6754 return _assign.apply(this, arguments);
6756 function __rest(s, e) {
6760 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
6763 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
6764 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
6768 function __decorate(decorators, target, key, desc) {
6769 var c = arguments.length,
6770 r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
6772 if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
6773 if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6775 return c > 3 && r && Object.defineProperty(target, key, r), r;
6777 function __param(paramIndex, decorator) {
6778 return function (target, key) {
6779 decorator(target, key, paramIndex);
6782 function __metadata(metadataKey, metadataValue) {
6783 if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
6785 function __awaiter(thisArg, _arguments, P, generator) {
6786 return new (P || (P = Promise))(function (resolve, reject) {
6787 function fulfilled(value) {
6789 step(generator.next(value));
6795 function rejected(value) {
6797 step(generator["throw"](value));
6803 function step(result) {
6804 result.done ? resolve(result.value) : new P(function (resolve) {
6805 resolve(result.value);
6806 }).then(fulfilled, rejected);
6809 step((generator = generator.apply(thisArg, _arguments || [])).next());
6812 function __generator(thisArg, body) {
6815 sent: function sent() {
6816 if (t[0] & 1) throw t[1];
6830 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
6835 return function (v) {
6836 return step([n, v]);
6841 if (f) throw new TypeError("Generator is already executing.");
6845 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;
6846 if (y = 0, t) op = [op[0] & 2, t.value];
6875 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
6880 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
6885 if (op[0] === 6 && _.label < t[1]) {
6891 if (t && _.label < t[2]) {
6899 if (t[2]) _.ops.pop();
6906 op = body.call(thisArg, _);
6915 if (op[0] & 5) throw op[1];
6917 value: op[0] ? op[1] : void 0,
6922 function __exportStar(m, exports) {
6924 if (!exports.hasOwnProperty(p)) exports[p] = m[p];
6927 function __values(o) {
6928 var m = typeof Symbol === "function" && o[Symbol.iterator],
6930 if (m) return m.call(o);
6932 next: function next() {
6933 if (o && i >= o.length) o = void 0;
6941 function __read(o, n) {
6942 var m = typeof Symbol === "function" && o[Symbol.iterator];
6950 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
6959 if (r && !r.done && (m = i["return"])) m.call(i);
6961 if (e) throw e.error;
6967 function __spread() {
6968 for (var ar = [], i = 0; i < arguments.length; i++) {
6969 ar = ar.concat(__read(arguments[i]));
6974 function __spreadArrays() {
6975 for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
6976 s += arguments[i].length;
6979 for (var r = Array(s), k = 0, i = 0; i < il; i++) {
6980 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
6987 function __await(v) {
6988 return this instanceof __await ? (this.v = v, this) : new __await(v);
6990 function __asyncGenerator(thisArg, _arguments, generator) {
6991 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
6992 var g = generator.apply(thisArg, _arguments || []),
6995 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
7000 if (g[n]) i[n] = function (v) {
7001 return new Promise(function (a, b) {
7002 q.push([n, v, a, b]) > 1 || resume(n, v);
7007 function resume(n, v) {
7016 r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
7019 function fulfill(value) {
7020 resume("next", value);
7023 function reject(value) {
7024 resume("throw", value);
7027 function settle(f, v) {
7028 if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
7031 function __asyncDelegator(o) {
7033 return i = {}, verb("next"), verb("throw", function (e) {
7035 }), verb("return"), i[Symbol.iterator] = function () {
7039 function verb(n, f) {
7040 i[n] = o[n] ? function (v) {
7042 value: __await(o[n](v)),
7043 done: n === "return"
7048 function __asyncValues(o) {
7049 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
7050 var m = o[Symbol.asyncIterator],
7052 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 () {
7057 i[n] = o[n] && function (v) {
7058 return new Promise(function (resolve, reject) {
7059 v = o[n](v), settle(resolve, reject, v.done, v.value);
7064 function settle(resolve, reject, d, v) {
7065 Promise.resolve(v).then(function (v) {
7073 function __makeTemplateObject(cooked, raw) {
7074 if (Object.defineProperty) {
7075 Object.defineProperty(cooked, "raw", {
7084 function __importStar(mod) {
7085 if (mod && mod.__esModule) return mod;
7087 if (mod != null) for (var k in mod) {
7088 if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
7090 result.default = mod;
7093 function __importDefault(mod) {
7094 return mod && mod.__esModule ? mod : {
7099 var tslib_es6 = /*#__PURE__*/Object.freeze({
7101 __extends: __extends,
7102 get __assign () { return _assign; },
7104 __decorate: __decorate,
7106 __metadata: __metadata,
7107 __awaiter: __awaiter,
7108 __generator: __generator,
7109 __exportStar: __exportStar,
7113 __spreadArrays: __spreadArrays,
7115 __asyncGenerator: __asyncGenerator,
7116 __asyncDelegator: __asyncDelegator,
7117 __asyncValues: __asyncValues,
7118 __makeTemplateObject: __makeTemplateObject,
7119 __importStar: __importStar,
7120 __importDefault: __importDefault
7123 var api = createCommonjsModule(function (module, exports) {
7125 Object.defineProperty(exports, "__esModule", {
7128 exports.apiDescriptor = {
7129 key: function key(_key) {
7130 return /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key);
7132 value: function value(_value) {
7133 if (_value === null || _typeof(_value) !== 'object') {
7134 return JSON.stringify(_value);
7137 if (Array.isArray(_value)) {
7138 return "[".concat(_value.map(function (subValue) {
7139 return exports.apiDescriptor.value(subValue);
7140 }).join(', '), "]");
7143 var keys = Object.keys(_value);
7144 return keys.length === 0 ? '{}' : "{ ".concat(keys.map(function (key) {
7145 return "".concat(exports.apiDescriptor.key(key), ": ").concat(exports.apiDescriptor.value(_value[key]));
7146 }).join(', '), " }");
7148 pair: function pair(_ref) {
7151 return exports.apiDescriptor.value(_defineProperty({}, key, value));
7156 var api_1 = api.apiDescriptor;
7158 var tslib_1 = getCjsExportFromNamespace(tslib_es6);
7160 var descriptors = createCommonjsModule(function (module, exports) {
7162 Object.defineProperty(exports, "__esModule", {
7166 tslib_1.__exportStar(api, exports);
7168 unwrapExports(descriptors);
7170 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
7172 var escapeStringRegexp = function escapeStringRegexp(str) {
7173 if (typeof str !== 'string') {
7174 throw new TypeError('Expected a string');
7177 return str.replace(matchOperatorsRe, '\\$&');
7181 "aliceblue": [240, 248, 255],
7182 "antiquewhite": [250, 235, 215],
7183 "aqua": [0, 255, 255],
7184 "aquamarine": [127, 255, 212],
7185 "azure": [240, 255, 255],
7186 "beige": [245, 245, 220],
7187 "bisque": [255, 228, 196],
7189 "blanchedalmond": [255, 235, 205],
7190 "blue": [0, 0, 255],
7191 "blueviolet": [138, 43, 226],
7192 "brown": [165, 42, 42],
7193 "burlywood": [222, 184, 135],
7194 "cadetblue": [95, 158, 160],
7195 "chartreuse": [127, 255, 0],
7196 "chocolate": [210, 105, 30],
7197 "coral": [255, 127, 80],
7198 "cornflowerblue": [100, 149, 237],
7199 "cornsilk": [255, 248, 220],
7200 "crimson": [220, 20, 60],
7201 "cyan": [0, 255, 255],
7202 "darkblue": [0, 0, 139],
7203 "darkcyan": [0, 139, 139],
7204 "darkgoldenrod": [184, 134, 11],
7205 "darkgray": [169, 169, 169],
7206 "darkgreen": [0, 100, 0],
7207 "darkgrey": [169, 169, 169],
7208 "darkkhaki": [189, 183, 107],
7209 "darkmagenta": [139, 0, 139],
7210 "darkolivegreen": [85, 107, 47],
7211 "darkorange": [255, 140, 0],
7212 "darkorchid": [153, 50, 204],
7213 "darkred": [139, 0, 0],
7214 "darksalmon": [233, 150, 122],
7215 "darkseagreen": [143, 188, 143],
7216 "darkslateblue": [72, 61, 139],
7217 "darkslategray": [47, 79, 79],
7218 "darkslategrey": [47, 79, 79],
7219 "darkturquoise": [0, 206, 209],
7220 "darkviolet": [148, 0, 211],
7221 "deeppink": [255, 20, 147],
7222 "deepskyblue": [0, 191, 255],
7223 "dimgray": [105, 105, 105],
7224 "dimgrey": [105, 105, 105],
7225 "dodgerblue": [30, 144, 255],
7226 "firebrick": [178, 34, 34],
7227 "floralwhite": [255, 250, 240],
7228 "forestgreen": [34, 139, 34],
7229 "fuchsia": [255, 0, 255],
7230 "gainsboro": [220, 220, 220],
7231 "ghostwhite": [248, 248, 255],
7232 "gold": [255, 215, 0],
7233 "goldenrod": [218, 165, 32],
7234 "gray": [128, 128, 128],
7235 "green": [0, 128, 0],
7236 "greenyellow": [173, 255, 47],
7237 "grey": [128, 128, 128],
7238 "honeydew": [240, 255, 240],
7239 "hotpink": [255, 105, 180],
7240 "indianred": [205, 92, 92],
7241 "indigo": [75, 0, 130],
7242 "ivory": [255, 255, 240],
7243 "khaki": [240, 230, 140],
7244 "lavender": [230, 230, 250],
7245 "lavenderblush": [255, 240, 245],
7246 "lawngreen": [124, 252, 0],
7247 "lemonchiffon": [255, 250, 205],
7248 "lightblue": [173, 216, 230],
7249 "lightcoral": [240, 128, 128],
7250 "lightcyan": [224, 255, 255],
7251 "lightgoldenrodyellow": [250, 250, 210],
7252 "lightgray": [211, 211, 211],
7253 "lightgreen": [144, 238, 144],
7254 "lightgrey": [211, 211, 211],
7255 "lightpink": [255, 182, 193],
7256 "lightsalmon": [255, 160, 122],
7257 "lightseagreen": [32, 178, 170],
7258 "lightskyblue": [135, 206, 250],
7259 "lightslategray": [119, 136, 153],
7260 "lightslategrey": [119, 136, 153],
7261 "lightsteelblue": [176, 196, 222],
7262 "lightyellow": [255, 255, 224],
7263 "lime": [0, 255, 0],
7264 "limegreen": [50, 205, 50],
7265 "linen": [250, 240, 230],
7266 "magenta": [255, 0, 255],
7267 "maroon": [128, 0, 0],
7268 "mediumaquamarine": [102, 205, 170],
7269 "mediumblue": [0, 0, 205],
7270 "mediumorchid": [186, 85, 211],
7271 "mediumpurple": [147, 112, 219],
7272 "mediumseagreen": [60, 179, 113],
7273 "mediumslateblue": [123, 104, 238],
7274 "mediumspringgreen": [0, 250, 154],
7275 "mediumturquoise": [72, 209, 204],
7276 "mediumvioletred": [199, 21, 133],
7277 "midnightblue": [25, 25, 112],
7278 "mintcream": [245, 255, 250],
7279 "mistyrose": [255, 228, 225],
7280 "moccasin": [255, 228, 181],
7281 "navajowhite": [255, 222, 173],
7282 "navy": [0, 0, 128],
7283 "oldlace": [253, 245, 230],
7284 "olive": [128, 128, 0],
7285 "olivedrab": [107, 142, 35],
7286 "orange": [255, 165, 0],
7287 "orangered": [255, 69, 0],
7288 "orchid": [218, 112, 214],
7289 "palegoldenrod": [238, 232, 170],
7290 "palegreen": [152, 251, 152],
7291 "paleturquoise": [175, 238, 238],
7292 "palevioletred": [219, 112, 147],
7293 "papayawhip": [255, 239, 213],
7294 "peachpuff": [255, 218, 185],
7295 "peru": [205, 133, 63],
7296 "pink": [255, 192, 203],
7297 "plum": [221, 160, 221],
7298 "powderblue": [176, 224, 230],
7299 "purple": [128, 0, 128],
7300 "rebeccapurple": [102, 51, 153],
7302 "rosybrown": [188, 143, 143],
7303 "royalblue": [65, 105, 225],
7304 "saddlebrown": [139, 69, 19],
7305 "salmon": [250, 128, 114],
7306 "sandybrown": [244, 164, 96],
7307 "seagreen": [46, 139, 87],
7308 "seashell": [255, 245, 238],
7309 "sienna": [160, 82, 45],
7310 "silver": [192, 192, 192],
7311 "skyblue": [135, 206, 235],
7312 "slateblue": [106, 90, 205],
7313 "slategray": [112, 128, 144],
7314 "slategrey": [112, 128, 144],
7315 "snow": [255, 250, 250],
7316 "springgreen": [0, 255, 127],
7317 "steelblue": [70, 130, 180],
7318 "tan": [210, 180, 140],
7319 "teal": [0, 128, 128],
7320 "thistle": [216, 191, 216],
7321 "tomato": [255, 99, 71],
7322 "turquoise": [64, 224, 208],
7323 "violet": [238, 130, 238],
7324 "wheat": [245, 222, 179],
7325 "white": [255, 255, 255],
7326 "whitesmoke": [245, 245, 245],
7327 "yellow": [255, 255, 0],
7328 "yellowgreen": [154, 205, 50]
7331 var conversions = createCommonjsModule(function (module) {
7333 // NOTE: conversions should only return primitive values (i.e. arrays, or
7334 // values that give correct `typeof` results).
7335 // do not use box values types (i.e. Number(), String(), etc.)
7336 var reverseKeywords = {};
7338 for (var key in colorName) {
7339 if (colorName.hasOwnProperty(key)) {
7340 reverseKeywords[colorName[key]] = key;
7344 var convert = module.exports = {
7395 labels: ['h', 'c', 'g']
7399 labels: ['r16', 'g16', 'b16']
7405 }; // hide .channels and .labels properties
7407 for (var model in convert) {
7408 if (convert.hasOwnProperty(model)) {
7409 if (!('channels' in convert[model])) {
7410 throw new Error('missing channels property: ' + model);
7413 if (!('labels' in convert[model])) {
7414 throw new Error('missing channel labels property: ' + model);
7417 if (convert[model].labels.length !== convert[model].channels) {
7418 throw new Error('channel and label counts mismatch: ' + model);
7421 var channels = convert[model].channels;
7422 var labels = convert[model].labels;
7423 delete convert[model].channels;
7424 delete convert[model].labels;
7425 Object.defineProperty(convert[model], 'channels', {
7428 Object.defineProperty(convert[model], 'labels', {
7434 convert.rgb.hsl = function (rgb) {
7435 var r = rgb[0] / 255;
7436 var g = rgb[1] / 255;
7437 var b = rgb[2] / 255;
7438 var min = Math.min(r, g, b);
7439 var max = Math.max(r, g, b);
7440 var delta = max - min;
7447 } else if (r === max) {
7448 h = (g - b) / delta;
7449 } else if (g === max) {
7450 h = 2 + (b - r) / delta;
7451 } else if (b === max) {
7452 h = 4 + (r - g) / delta;
7455 h = Math.min(h * 60, 360);
7461 l = (min + max) / 2;
7465 } else if (l <= 0.5) {
7466 s = delta / (max + min);
7468 s = delta / (2 - max - min);
7471 return [h, s * 100, l * 100];
7474 convert.rgb.hsv = function (rgb) {
7478 var min = Math.min(r, g, b);
7479 var max = Math.max(r, g, b);
7480 var delta = max - min;
7488 s = delta / max * 1000 / 10;
7493 } else if (r === max) {
7494 h = (g - b) / delta;
7495 } else if (g === max) {
7496 h = 2 + (b - r) / delta;
7497 } else if (b === max) {
7498 h = 4 + (r - g) / delta;
7501 h = Math.min(h * 60, 360);
7507 v = max / 255 * 1000 / 10;
7511 convert.rgb.hwb = function (rgb) {
7515 var h = convert.rgb.hsl(rgb)[0];
7516 var w = 1 / 255 * Math.min(r, Math.min(g, b));
7517 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
7518 return [h, w * 100, b * 100];
7521 convert.rgb.cmyk = function (rgb) {
7522 var r = rgb[0] / 255;
7523 var g = rgb[1] / 255;
7524 var b = rgb[2] / 255;
7529 k = Math.min(1 - r, 1 - g, 1 - b);
7530 c = (1 - r - k) / (1 - k) || 0;
7531 m = (1 - g - k) / (1 - k) || 0;
7532 y = (1 - b - k) / (1 - k) || 0;
7533 return [c * 100, m * 100, y * 100, k * 100];
7536 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
7540 function comparativeDistance(x, y) {
7541 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
7544 convert.rgb.keyword = function (rgb) {
7545 var reversed = reverseKeywords[rgb];
7551 var currentClosestDistance = Infinity;
7552 var currentClosestKeyword;
7554 for (var keyword in colorName) {
7555 if (colorName.hasOwnProperty(keyword)) {
7556 var value = colorName[keyword]; // Compute comparative distance
7558 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
7560 if (distance < currentClosestDistance) {
7561 currentClosestDistance = distance;
7562 currentClosestKeyword = keyword;
7567 return currentClosestKeyword;
7570 convert.keyword.rgb = function (keyword) {
7571 return colorName[keyword];
7574 convert.rgb.xyz = function (rgb) {
7575 var r = rgb[0] / 255;
7576 var g = rgb[1] / 255;
7577 var b = rgb[2] / 255; // assume sRGB
7579 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
7580 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
7581 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
7582 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
7583 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
7584 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
7585 return [x * 100, y * 100, z * 100];
7588 convert.rgb.lab = function (rgb) {
7589 var xyz = convert.rgb.xyz(rgb);
7599 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
7600 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
7601 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
7608 convert.hsl.rgb = function (hsl) {
7609 var h = hsl[0] / 360;
7610 var s = hsl[1] / 100;
7611 var l = hsl[2] / 100;
7620 return [val, val, val];
7632 for (var i = 0; i < 3; i++) {
7633 t3 = h + 1 / 3 * -(i - 1);
7644 val = t1 + (t2 - t1) * 6 * t3;
7645 } else if (2 * t3 < 1) {
7647 } else if (3 * t3 < 2) {
7648 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
7659 convert.hsl.hsv = function (hsl) {
7661 var s = hsl[1] / 100;
7662 var l = hsl[2] / 100;
7664 var lmin = Math.max(l, 0.01);
7668 s *= l <= 1 ? l : 2 - l;
7669 smin *= lmin <= 1 ? lmin : 2 - lmin;
7671 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
7672 return [h, sv * 100, v * 100];
7675 convert.hsv.rgb = function (hsv) {
7676 var h = hsv[0] / 60;
7677 var s = hsv[1] / 100;
7678 var v = hsv[2] / 100;
7679 var hi = Math.floor(h) % 6;
7680 var f = h - Math.floor(h);
7681 var p = 255 * v * (1 - s);
7682 var q = 255 * v * (1 - s * f);
7683 var t = 255 * v * (1 - s * (1 - f));
7707 convert.hsv.hsl = function (hsv) {
7709 var s = hsv[1] / 100;
7710 var v = hsv[2] / 100;
7711 var vmin = Math.max(v, 0.01);
7716 lmin = (2 - s) * vmin;
7718 sl /= lmin <= 1 ? lmin : 2 - lmin;
7721 return [h, sl * 100, l * 100];
7722 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
7725 convert.hwb.rgb = function (hwb) {
7726 var h = hwb[0] / 360;
7727 var wh = hwb[1] / 100;
7728 var bl = hwb[2] / 100;
7729 var ratio = wh + bl;
7733 var n; // wh + bl cant be > 1
7740 i = Math.floor(6 * h);
7744 if ((i & 0x01) !== 0) {
7748 n = wh + f * (v - wh); // linear interpolation
7794 return [r * 255, g * 255, b * 255];
7797 convert.cmyk.rgb = function (cmyk) {
7798 var c = cmyk[0] / 100;
7799 var m = cmyk[1] / 100;
7800 var y = cmyk[2] / 100;
7801 var k = cmyk[3] / 100;
7805 r = 1 - Math.min(1, c * (1 - k) + k);
7806 g = 1 - Math.min(1, m * (1 - k) + k);
7807 b = 1 - Math.min(1, y * (1 - k) + k);
7808 return [r * 255, g * 255, b * 255];
7811 convert.xyz.rgb = function (xyz) {
7812 var x = xyz[0] / 100;
7813 var y = xyz[1] / 100;
7814 var z = xyz[2] / 100;
7818 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
7819 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
7820 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
7822 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
7823 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
7824 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
7825 r = Math.min(Math.max(0, r), 1);
7826 g = Math.min(Math.max(0, g), 1);
7827 b = Math.min(Math.max(0, b), 1);
7828 return [r * 255, g * 255, b * 255];
7831 convert.xyz.lab = function (xyz) {
7841 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
7842 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
7843 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
7850 convert.lab.xyz = function (lab) {
7860 var y2 = Math.pow(y, 3);
7861 var x2 = Math.pow(x, 3);
7862 var z2 = Math.pow(z, 3);
7863 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
7864 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
7865 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
7872 convert.lab.lch = function (lab) {
7879 hr = Math.atan2(b, a);
7880 h = hr * 360 / 2 / Math.PI;
7886 c = Math.sqrt(a * a + b * b);
7890 convert.lch.lab = function (lch) {
7897 hr = h / 360 * 2 * Math.PI;
7898 a = c * Math.cos(hr);
7899 b = c * Math.sin(hr);
7903 convert.rgb.ansi16 = function (args) {
7907 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
7909 value = Math.round(value / 50);
7915 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
7924 convert.hsv.ansi16 = function (args) {
7925 // optimization here; we already know the value and don't need to get
7926 // it converted for us.
7927 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
7930 convert.rgb.ansi256 = function (args) {
7933 var b = args[2]; // we use the extended greyscale palette here, with the exception of
7934 // black and white. normal palette only has 4 greyscale shades.
7936 if (r === g && g === b) {
7945 return Math.round((r - 8) / 247 * 24) + 232;
7948 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
7952 convert.ansi16.rgb = function (args) {
7953 var color = args % 10; // handle greyscale
7955 if (color === 0 || color === 7) {
7960 color = color / 10.5 * 255;
7961 return [color, color, color];
7964 var mult = (~~(args > 50) + 1) * 0.5;
7965 var r = (color & 1) * mult * 255;
7966 var g = (color >> 1 & 1) * mult * 255;
7967 var b = (color >> 2 & 1) * mult * 255;
7971 convert.ansi256.rgb = function (args) {
7974 var c = (args - 232) * 10 + 8;
7980 var r = Math.floor(args / 36) / 5 * 255;
7981 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
7982 var b = rem % 6 / 5 * 255;
7986 convert.rgb.hex = function (args) {
7987 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
7988 var string = integer.toString(16).toUpperCase();
7989 return '000000'.substring(string.length) + string;
7992 convert.hex.rgb = function (args) {
7993 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
7999 var colorString = match[0];
8001 if (match[0].length === 3) {
8002 colorString = colorString.split('').map(function (char) {
8007 var integer = parseInt(colorString, 16);
8008 var r = integer >> 16 & 0xFF;
8009 var g = integer >> 8 & 0xFF;
8010 var b = integer & 0xFF;
8014 convert.rgb.hcg = function (rgb) {
8015 var r = rgb[0] / 255;
8016 var g = rgb[1] / 255;
8017 var b = rgb[2] / 255;
8018 var max = Math.max(Math.max(r, g), b);
8019 var min = Math.min(Math.min(r, g), b);
8020 var chroma = max - min;
8025 grayscale = min / (1 - chroma);
8032 } else if (max === r) {
8033 hue = (g - b) / chroma % 6;
8034 } else if (max === g) {
8035 hue = 2 + (b - r) / chroma;
8037 hue = 4 + (r - g) / chroma + 4;
8042 return [hue * 360, chroma * 100, grayscale * 100];
8045 convert.hsl.hcg = function (hsl) {
8046 var s = hsl[1] / 100;
8047 var l = hsl[2] / 100;
8054 c = 2.0 * s * (1.0 - l);
8058 f = (l - 0.5 * c) / (1.0 - c);
8061 return [hsl[0], c * 100, f * 100];
8064 convert.hsv.hcg = function (hsv) {
8065 var s = hsv[1] / 100;
8066 var v = hsv[2] / 100;
8071 f = (v - c) / (1 - c);
8074 return [hsv[0], c * 100, f * 100];
8077 convert.hcg.rgb = function (hcg) {
8078 var h = hcg[0] / 360;
8079 var c = hcg[1] / 100;
8080 var g = hcg[2] / 100;
8083 return [g * 255, g * 255, g * 255];
8086 var pure = [0, 0, 0];
8092 switch (Math.floor(hi)) {
8130 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
8133 convert.hcg.hsv = function (hcg) {
8134 var c = hcg[1] / 100;
8135 var g = hcg[2] / 100;
8136 var v = c + g * (1.0 - c);
8143 return [hcg[0], f * 100, v * 100];
8146 convert.hcg.hsl = function (hcg) {
8147 var c = hcg[1] / 100;
8148 var g = hcg[2] / 100;
8149 var l = g * (1.0 - c) + 0.5 * c;
8152 if (l > 0.0 && l < 0.5) {
8154 } else if (l >= 0.5 && l < 1.0) {
8155 s = c / (2 * (1 - l));
8158 return [hcg[0], s * 100, l * 100];
8161 convert.hcg.hwb = function (hcg) {
8162 var c = hcg[1] / 100;
8163 var g = hcg[2] / 100;
8164 var v = c + g * (1.0 - c);
8165 return [hcg[0], (v - c) * 100, (1 - v) * 100];
8168 convert.hwb.hcg = function (hwb) {
8169 var w = hwb[1] / 100;
8170 var b = hwb[2] / 100;
8176 g = (v - c) / (1 - c);
8179 return [hwb[0], c * 100, g * 100];
8182 convert.apple.rgb = function (apple) {
8183 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
8186 convert.rgb.apple = function (rgb) {
8187 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
8190 convert.gray.rgb = function (args) {
8191 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
8194 convert.gray.hsl = convert.gray.hsv = function (args) {
8195 return [0, 0, args[0]];
8198 convert.gray.hwb = function (gray) {
8199 return [0, 100, gray[0]];
8202 convert.gray.cmyk = function (gray) {
8203 return [0, 0, 0, gray[0]];
8206 convert.gray.lab = function (gray) {
8207 return [gray[0], 0, 0];
8210 convert.gray.hex = function (gray) {
8211 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
8212 var integer = (val << 16) + (val << 8) + val;
8213 var string = integer.toString(16).toUpperCase();
8214 return '000000'.substring(string.length) + string;
8217 convert.rgb.gray = function (rgb) {
8218 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
8219 return [val / 255 * 100];
8222 var conversions_1 = conversions.rgb;
8223 var conversions_2 = conversions.hsl;
8224 var conversions_3 = conversions.hsv;
8225 var conversions_4 = conversions.hwb;
8226 var conversions_5 = conversions.cmyk;
8227 var conversions_6 = conversions.xyz;
8228 var conversions_7 = conversions.lab;
8229 var conversions_8 = conversions.lch;
8230 var conversions_9 = conversions.hex;
8231 var conversions_10 = conversions.keyword;
8232 var conversions_11 = conversions.ansi16;
8233 var conversions_12 = conversions.ansi256;
8234 var conversions_13 = conversions.hcg;
8235 var conversions_14 = conversions.apple;
8236 var conversions_15 = conversions.gray;
8239 this function routes a model to all other models.
8241 all functions that are routed have a property `.conversion` attached
8242 to the returned synthetic function. This property is an array
8243 of strings, each with the steps in between the 'from' and 'to'
8244 color models (inclusive).
8246 conversions that are not possible simply are not included.
8248 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
8250 var models = Object.keys(conversions);
8252 function buildGraph() {
8255 for (var len = models.length, i = 0; i < len; i++) {
8256 graph[models[i]] = {
8257 // http://jsperf.com/1-vs-infinity
8258 // micro-opt, but this is simple.
8265 } // https://en.wikipedia.org/wiki/Breadth-first_search
8268 function deriveBFS(fromModel) {
8269 var graph = buildGraph();
8270 var queue = [fromModel]; // unshift -> queue -> pop
8272 graph[fromModel].distance = 0;
8274 while (queue.length) {
8275 var current = queue.pop();
8276 var adjacents = Object.keys(conversions[current]);
8278 for (var len = adjacents.length, i = 0; i < len; i++) {
8279 var adjacent = adjacents[i];
8280 var node = graph[adjacent];
8282 if (node.distance === -1) {
8283 node.distance = graph[current].distance + 1;
8284 node.parent = current;
8285 queue.unshift(adjacent);
8293 function link(from, to) {
8294 return function (args) {
8295 return to(from(args));
8299 function wrapConversion(toModel, graph) {
8300 var path = [graph[toModel].parent, toModel];
8301 var fn = conversions[graph[toModel].parent][toModel];
8302 var cur = graph[toModel].parent;
8304 while (graph[cur].parent) {
8305 path.unshift(graph[cur].parent);
8306 fn = link(conversions[graph[cur].parent][cur], fn);
8307 cur = graph[cur].parent;
8310 fn.conversion = path;
8314 var route = function route(fromModel) {
8315 var graph = deriveBFS(fromModel);
8316 var conversion = {};
8317 var models = Object.keys(graph);
8319 for (var len = models.length, i = 0; i < len; i++) {
8320 var toModel = models[i];
8321 var node = graph[toModel];
8323 if (node.parent === null) {
8324 // no possible conversion, or this node is the source model.
8328 conversion[toModel] = wrapConversion(toModel, graph);
8335 var models$1 = Object.keys(conversions);
8337 function wrapRaw(fn) {
8338 var wrappedFn = function wrappedFn(args) {
8339 if (args === undefined || args === null) {
8343 if (arguments.length > 1) {
8344 args = Array.prototype.slice.call(arguments);
8348 }; // preserve .conversion property if there is one
8351 if ('conversion' in fn) {
8352 wrappedFn.conversion = fn.conversion;
8358 function wrapRounded(fn) {
8359 var wrappedFn = function wrappedFn(args) {
8360 if (args === undefined || args === null) {
8364 if (arguments.length > 1) {
8365 args = Array.prototype.slice.call(arguments);
8368 var result = fn(args); // we're assuming the result is an array here.
8369 // see notice in conversions.js; don't use box types
8370 // in conversion functions.
8372 if (_typeof(result) === 'object') {
8373 for (var len = result.length, i = 0; i < len; i++) {
8374 result[i] = Math.round(result[i]);
8379 }; // preserve .conversion property if there is one
8382 if ('conversion' in fn) {
8383 wrappedFn.conversion = fn.conversion;
8389 models$1.forEach(function (fromModel) {
8390 convert[fromModel] = {};
8391 Object.defineProperty(convert[fromModel], 'channels', {
8392 value: conversions[fromModel].channels
8394 Object.defineProperty(convert[fromModel], 'labels', {
8395 value: conversions[fromModel].labels
8397 var routes = route(fromModel);
8398 var routeModels = Object.keys(routes);
8399 routeModels.forEach(function (toModel) {
8400 var fn = routes[toModel];
8401 convert[fromModel][toModel] = wrapRounded(fn);
8402 convert[fromModel][toModel].raw = wrapRaw(fn);
8405 var colorConvert = convert;
8407 var ansiStyles = createCommonjsModule(function (module) {
8409 var wrapAnsi16 = function wrapAnsi16(fn, offset) {
8410 return function () {
8411 var code = fn.apply(colorConvert, arguments);
8412 return "\x1B[".concat(code + offset, "m");
8416 var wrapAnsi256 = function wrapAnsi256(fn, offset) {
8417 return function () {
8418 var code = fn.apply(colorConvert, arguments);
8419 return "\x1B[".concat(38 + offset, ";5;").concat(code, "m");
8423 var wrapAnsi16m = function wrapAnsi16m(fn, offset) {
8424 return function () {
8425 var rgb = fn.apply(colorConvert, arguments);
8426 return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m");
8430 function assembleStyles() {
8431 var codes = new Map();
8435 // 21 isn't widely supported and 22 does the same thing
8442 strikethrough: [9, 29]
8455 redBright: [91, 39],
8456 greenBright: [92, 39],
8457 yellowBright: [93, 39],
8458 blueBright: [94, 39],
8459 magentaBright: [95, 39],
8460 cyanBright: [96, 39],
8461 whiteBright: [97, 39]
8469 bgMagenta: [45, 49],
8473 bgBlackBright: [100, 49],
8474 bgRedBright: [101, 49],
8475 bgGreenBright: [102, 49],
8476 bgYellowBright: [103, 49],
8477 bgBlueBright: [104, 49],
8478 bgMagentaBright: [105, 49],
8479 bgCyanBright: [106, 49],
8480 bgWhiteBright: [107, 49]
8484 styles.color.grey = styles.color.gray;
8486 for (var _i = 0, _Object$keys = Object.keys(styles); _i < _Object$keys.length; _i++) {
8487 var groupName = _Object$keys[_i];
8488 var group = styles[groupName];
8490 for (var _i3 = 0, _Object$keys3 = Object.keys(group); _i3 < _Object$keys3.length; _i3++) {
8491 var styleName = _Object$keys3[_i3];
8492 var style = group[styleName];
8493 styles[styleName] = {
8494 open: "\x1B[".concat(style[0], "m"),
8495 close: "\x1B[".concat(style[1], "m")
8497 group[styleName] = styles[styleName];
8498 codes.set(style[0], style[1]);
8501 Object.defineProperty(styles, groupName, {
8505 Object.defineProperty(styles, 'codes', {
8511 var ansi2ansi = function ansi2ansi(n) {
8515 var rgb2rgb = function rgb2rgb(r, g, b) {
8519 styles.color.close = "\x1B[39m";
8520 styles.bgColor.close = "\x1B[49m";
8521 styles.color.ansi = {
8522 ansi: wrapAnsi16(ansi2ansi, 0)
8524 styles.color.ansi256 = {
8525 ansi256: wrapAnsi256(ansi2ansi, 0)
8527 styles.color.ansi16m = {
8528 rgb: wrapAnsi16m(rgb2rgb, 0)
8530 styles.bgColor.ansi = {
8531 ansi: wrapAnsi16(ansi2ansi, 10)
8533 styles.bgColor.ansi256 = {
8534 ansi256: wrapAnsi256(ansi2ansi, 10)
8536 styles.bgColor.ansi16m = {
8537 rgb: wrapAnsi16m(rgb2rgb, 10)
8540 for (var _i2 = 0, _Object$keys2 = Object.keys(colorConvert); _i2 < _Object$keys2.length; _i2++) {
8541 var key = _Object$keys2[_i2];
8543 if (_typeof(colorConvert[key]) !== 'object') {
8547 var suite = colorConvert[key];
8549 if (key === 'ansi16') {
8553 if ('ansi16' in suite) {
8554 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
8555 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
8558 if ('ansi256' in suite) {
8559 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
8560 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
8563 if ('rgb' in suite) {
8564 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
8565 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
8570 } // Make the export immutable
8573 Object.defineProperty(module, 'exports', {
8579 var require$$0$1 = {
8583 var hasFlag = function hasFlag(flag, argv) {
8584 argv = argv || process.argv;
8585 var prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
8586 var pos = argv.indexOf(prefix + flag);
8587 var terminatorPos = argv.indexOf('--');
8588 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
8591 var env$1 = process.env;
8594 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
8596 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
8600 if ('FORCE_COLOR' in env$1) {
8601 forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0;
8604 function translateLevel(level) {
8617 function supportsColor(stream) {
8618 if (forceColor === false) {
8622 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
8626 if (hasFlag('color=256')) {
8630 if (stream && !stream.isTTY && forceColor !== true) {
8634 var min = forceColor ? 1 : 0;
8636 if (process.platform === 'win32') {
8637 // Node.js 7.5.0 is the first version of Node.js to include a patch to
8638 // libuv that enables 256 color output on Windows. Anything earlier and it
8639 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
8640 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
8641 // release that supports 256 colors. Windows 10 build 14931 is the first release
8642 // that supports 16m/TrueColor.
8643 var osRelease = require$$0$1.release().split('.');
8645 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
8646 return Number(osRelease[2]) >= 14931 ? 3 : 2;
8652 if ('CI' in env$1) {
8653 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) {
8654 return sign in env$1;
8655 }) || env$1.CI_NAME === 'codeship') {
8662 if ('TEAMCITY_VERSION' in env$1) {
8663 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
8666 if (env$1.COLORTERM === 'truecolor') {
8670 if ('TERM_PROGRAM' in env$1) {
8671 var version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
8673 switch (env$1.TERM_PROGRAM) {
8675 return version >= 3 ? 3 : 2;
8677 case 'Apple_Terminal':
8683 if (/-256(color)?$/i.test(env$1.TERM)) {
8687 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
8691 if ('COLORTERM' in env$1) {
8695 if (env$1.TERM === 'dumb') {
8702 function getSupportLevel(stream) {
8703 var level = supportsColor(stream);
8704 return translateLevel(level);
8707 var supportsColor_1 = {
8708 supportsColor: getSupportLevel,
8709 stdout: getSupportLevel(process.stdout),
8710 stderr: getSupportLevel(process.stderr)
8713 var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
8714 var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
8715 var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
8716 var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
8717 var ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', "\x1B"], ['a', "\x07"]]);
8719 function unescape(c) {
8720 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
8721 return String.fromCharCode(parseInt(c.slice(1), 16));
8724 return ESCAPES.get(c) || c;
8727 function parseArguments(name, args) {
8729 var chunks = args.trim().split(/\s*,\s*/g);
8731 var _iteratorNormalCompletion = true;
8732 var _didIteratorError = false;
8733 var _iteratorError = undefined;
8736 for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
8737 var chunk = _step.value;
8739 if (!isNaN(chunk)) {
8740 results.push(Number(chunk));
8741 } else if (matches = chunk.match(STRING_REGEX)) {
8742 results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) {
8743 return escape ? unescape(escape) : chr;
8746 throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')"));
8750 _didIteratorError = true;
8751 _iteratorError = err;
8754 if (!_iteratorNormalCompletion && _iterator.return != null) {
8758 if (_didIteratorError) {
8759 throw _iteratorError;
8767 function parseStyle(style) {
8768 STYLE_REGEX.lastIndex = 0;
8772 while ((matches = STYLE_REGEX.exec(style)) !== null) {
8773 var name = matches[1];
8776 var args = parseArguments(name, matches[2]);
8777 results.push([name].concat(args));
8779 results.push([name]);
8786 function buildStyle(chalk, styles) {
8788 var _iteratorNormalCompletion2 = true;
8789 var _didIteratorError2 = false;
8790 var _iteratorError2 = undefined;
8793 for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
8794 var layer = _step2.value;
8795 var _iteratorNormalCompletion3 = true;
8796 var _didIteratorError3 = false;
8797 var _iteratorError3 = undefined;
8800 for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
8801 var style = _step3.value;
8802 enabled[style[0]] = layer.inverse ? null : style.slice(1);
8805 _didIteratorError3 = true;
8806 _iteratorError3 = err;
8809 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
8810 _iterator3.return();
8813 if (_didIteratorError3) {
8814 throw _iteratorError3;
8820 _didIteratorError2 = true;
8821 _iteratorError2 = err;
8824 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
8825 _iterator2.return();
8828 if (_didIteratorError2) {
8829 throw _iteratorError2;
8834 var current = chalk;
8836 for (var _i = 0, _Object$keys = Object.keys(enabled); _i < _Object$keys.length; _i++) {
8837 var styleName = _Object$keys[_i];
8839 if (Array.isArray(enabled[styleName])) {
8840 if (!(styleName in current)) {
8841 throw new Error("Unknown Chalk style: ".concat(styleName));
8844 if (enabled[styleName].length > 0) {
8845 current = current[styleName].apply(current, enabled[styleName]);
8847 current = current[styleName];
8855 var templates = function templates(chalk, tmp) {
8858 var chunk = []; // eslint-disable-next-line max-params
8860 tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) {
8862 chunk.push(unescape(escapeChar));
8864 var str = chunk.join('');
8866 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
8869 styles: parseStyle(style)
8872 if (styles.length === 0) {
8873 throw new Error('Found extraneous } in Chalk template literal');
8876 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
8883 chunks.push(chunk.join(''));
8885 if (styles.length > 0) {
8886 var errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)");
8887 throw new Error(errMsg);
8890 return chunks.join('');
8893 var chalk = createCommonjsModule(function (module) {
8895 var stdoutColor = supportsColor_1.stdout;
8896 var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
8898 var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
8900 var skipModels = new Set(['gray']);
8901 var styles = Object.create(null);
8903 function applyOptions(obj, options) {
8904 options = options || {}; // Detect level if not set manually
8906 var scLevel = stdoutColor ? stdoutColor.level : 0;
8907 obj.level = options.level === undefined ? scLevel : options.level;
8908 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
8911 function Chalk(options) {
8912 // We check for this.template here since calling `chalk.constructor()`
8913 // by itself will have a `this` of a previously constructed chalk object
8914 if (!this || !(this instanceof Chalk) || this.template) {
8916 applyOptions(_chalk, options);
8918 _chalk.template = function () {
8919 var args = [].slice.call(arguments);
8920 return chalkTag.apply(null, [_chalk.template].concat(args));
8923 Object.setPrototypeOf(_chalk, Chalk.prototype);
8924 Object.setPrototypeOf(_chalk.template, _chalk);
8925 _chalk.template.constructor = Chalk;
8926 return _chalk.template;
8929 applyOptions(this, options);
8930 } // Use bright blue on Windows as the normal blue color is illegible
8933 if (isSimpleWindowsTerm) {
8934 ansiStyles.blue.open = "\x1B[94m";
8937 var _loop = function _loop() {
8938 var key = _Object$keys[_i];
8939 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
8941 get: function get() {
8942 var codes = ansiStyles[key];
8943 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
8948 for (var _i = 0, _Object$keys = Object.keys(ansiStyles); _i < _Object$keys.length; _i++) {
8953 get: function get() {
8954 return build.call(this, this._styles || [], true, 'visible');
8957 ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
8959 var _loop2 = function _loop2() {
8960 var model = _Object$keys2[_i2];
8962 if (skipModels.has(model)) {
8967 get: function get() {
8968 var level = this.level;
8969 return function () {
8970 var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
8973 close: ansiStyles.color.close,
8974 closeRe: ansiStyles.color.closeRe
8976 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
8982 for (var _i2 = 0, _Object$keys2 = Object.keys(ansiStyles.color.ansi); _i2 < _Object$keys2.length; _i2++) {
8983 var _ret = _loop2();
8985 if (_ret === "continue") continue;
8988 ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
8990 var _loop3 = function _loop3() {
8991 var model = _Object$keys3[_i3];
8993 if (skipModels.has(model)) {
8997 var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
8999 get: function get() {
9000 var level = this.level;
9001 return function () {
9002 var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
9005 close: ansiStyles.bgColor.close,
9006 closeRe: ansiStyles.bgColor.closeRe
9008 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
9014 for (var _i3 = 0, _Object$keys3 = Object.keys(ansiStyles.bgColor.ansi); _i3 < _Object$keys3.length; _i3++) {
9015 var _ret2 = _loop3();
9017 if (_ret2 === "continue") continue;
9020 var proto = Object.defineProperties(function () {}, styles);
9022 function build(_styles, _empty, key) {
9023 var builder = function builder() {
9024 return applyStyle.apply(builder, arguments);
9027 builder._styles = _styles;
9028 builder._empty = _empty;
9030 Object.defineProperty(builder, 'level', {
9032 get: function get() {
9035 set: function set(level) {
9039 Object.defineProperty(builder, 'enabled', {
9041 get: function get() {
9042 return self.enabled;
9044 set: function set(enabled) {
9045 self.enabled = enabled;
9047 }); // See below for fix regarding invisible grey/dim combination on Windows
9049 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
9050 // no way to create a function with a different prototype
9052 builder.__proto__ = proto; // eslint-disable-line no-proto
9057 function applyStyle() {
9058 // Support varags, but simply cast to string in case there's only one arg
9059 var args = arguments;
9060 var argsLen = args.length;
9061 var str = String(arguments[0]);
9063 if (argsLen === 0) {
9068 // Don't slice `arguments`, it prevents V8 optimizations
9069 for (var a = 1; a < argsLen; a++) {
9070 str += ' ' + args[a];
9074 if (!this.enabled || this.level <= 0 || !str) {
9075 return this._empty ? '' : str;
9076 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
9077 // see https://github.com/chalk/chalk/issues/58
9078 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
9081 var originalDim = ansiStyles.dim.open;
9083 if (isSimpleWindowsTerm && this.hasGrey) {
9084 ansiStyles.dim.open = '';
9087 var _iteratorNormalCompletion = true;
9088 var _didIteratorError = false;
9089 var _iteratorError = undefined;
9092 for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
9093 var code = _step.value;
9094 // Replace any instances already present with a re-opening code
9095 // otherwise only the part of the string until said closing code
9096 // will be colored, and the rest will simply be 'plain'.
9097 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
9098 // after next line to fix a bleed issue on macOS
9099 // https://github.com/chalk/chalk/pull/92
9101 str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open));
9102 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
9105 _didIteratorError = true;
9106 _iteratorError = err;
9109 if (!_iteratorNormalCompletion && _iterator.return != null) {
9113 if (_didIteratorError) {
9114 throw _iteratorError;
9119 ansiStyles.dim.open = originalDim;
9123 function chalkTag(chalk, strings) {
9124 if (!Array.isArray(strings)) {
9125 // If chalk() was called by itself or with a string,
9126 // return the string itself as a string.
9127 return [].slice.call(arguments, 1).join(' ');
9130 var args = [].slice.call(arguments, 2);
9131 var parts = [strings.raw[0]];
9133 for (var i = 1; i < strings.length; i++) {
9134 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
9135 parts.push(String(strings.raw[i]));
9138 return templates(chalk, parts.join(''));
9141 Object.defineProperties(Chalk.prototype, styles);
9142 module.exports = Chalk(); // eslint-disable-line new-cap
9144 module.exports.supportsColor = stdoutColor;
9145 module.exports.default = module.exports; // For TypeScript
9147 var chalk_1 = chalk.supportsColor;
9149 var common = createCommonjsModule(function (module, exports) {
9151 Object.defineProperty(exports, "__esModule", {
9155 exports.commonDeprecatedHandler = function (keyOrPair, redirectTo, _ref) {
9156 var descriptor = _ref.descriptor;
9157 var messages = ["".concat(chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair)), " is deprecated")];
9160 messages.push("we now treat it as ".concat(chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))));
9163 return messages.join('; ') + '.';
9166 unwrapExports(common);
9167 var common_1 = common.commonDeprecatedHandler;
9169 var deprecated = createCommonjsModule(function (module, exports) {
9171 Object.defineProperty(exports, "__esModule", {
9175 tslib_1.__exportStar(common, exports);
9177 unwrapExports(deprecated);
9179 var common$1 = createCommonjsModule(function (module, exports) {
9181 Object.defineProperty(exports, "__esModule", {
9185 exports.commonInvalidHandler = function (key, value, utils) {
9186 return ["Invalid ".concat(chalk.default.red(utils.descriptor.key(key)), " value."), "Expected ".concat(chalk.default.blue(utils.schemas[key].expected(utils)), ","), "but received ".concat(chalk.default.red(utils.descriptor.value(value)), ".")].join(' ');
9189 unwrapExports(common$1);
9190 var common_1$1 = common$1.commonInvalidHandler;
9192 var invalid = createCommonjsModule(function (module, exports) {
9194 Object.defineProperty(exports, "__esModule", {
9198 tslib_1.__exportStar(common$1, exports);
9200 unwrapExports(invalid);
9202 /* eslint-disable no-nested-ternary */
9205 var charCodeCache = [];
9207 var leven = function leven(a, b) {
9212 var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
9213 // shortest & which one is the longest
9215 if (a.length > b.length) {
9220 var aLen = a.length;
9221 var bLen = b.length;
9229 } // Performing suffix trimming:
9230 // We can linearly drop suffix common to both strings since they
9231 // don't increase distance at all
9232 // Note: `~-` is the bitwise way to perform a `- 1` operation
9235 while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
9242 } // Performing prefix trimming
9243 // We can linearly drop prefix common to both strings since they
9244 // don't increase distance at all
9249 while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
9268 charCodeCache[start + i] = a.charCodeAt(start + i);
9273 bCharCode = b.charCodeAt(start + j);
9277 for (i = 0; i < aLen; i++) {
9278 tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
9280 ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
9287 var leven_1 = createCommonjsModule(function (module, exports) {
9289 Object.defineProperty(exports, "__esModule", {
9293 exports.levenUnknownHandler = function (key, value, _ref) {
9294 var descriptor = _ref.descriptor,
9295 logger = _ref.logger,
9296 schemas = _ref.schemas;
9297 var messages = ["Ignored unknown option ".concat(chalk.default.yellow(descriptor.pair({
9301 var suggestion = Object.keys(schemas).sort().find(function (knownKey) {
9302 return leven(key, knownKey) < 3;
9306 messages.push("Did you mean ".concat(chalk.default.blue(descriptor.key(suggestion)), "?"));
9309 logger.warn(messages.join(' '));
9312 unwrapExports(leven_1);
9313 var leven_2 = leven_1.levenUnknownHandler;
9315 var unknown = createCommonjsModule(function (module, exports) {
9317 Object.defineProperty(exports, "__esModule", {
9321 tslib_1.__exportStar(leven_1, exports);
9323 unwrapExports(unknown);
9325 var handlers = createCommonjsModule(function (module, exports) {
9327 Object.defineProperty(exports, "__esModule", {
9331 tslib_1.__exportStar(deprecated, exports);
9333 tslib_1.__exportStar(invalid, exports);
9335 tslib_1.__exportStar(unknown, exports);
9337 unwrapExports(handlers);
9339 var schema = createCommonjsModule(function (module, exports) {
9341 Object.defineProperty(exports, "__esModule", {
9344 var HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
9346 function createSchema(SchemaConstructor, parameters) {
9347 var schema = new SchemaConstructor(parameters);
9348 var subSchema = Object.create(schema);
9349 var _iteratorNormalCompletion = true;
9350 var _didIteratorError = false;
9351 var _iteratorError = undefined;
9354 for (var _iterator = HANDLER_KEYS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
9355 var handlerKey = _step.value;
9357 if (handlerKey in parameters) {
9358 subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
9362 _didIteratorError = true;
9363 _iteratorError = err;
9366 if (!_iteratorNormalCompletion && _iterator.return != null) {
9370 if (_didIteratorError) {
9371 throw _iteratorError;
9379 exports.createSchema = createSchema;
9384 function Schema(parameters) {
9385 _classCallCheck(this, Schema);
9387 this.name = parameters.name;
9390 _createClass(Schema, [{
9392 value: function _default(_utils) {
9394 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
9398 value: function expected(_utils) {
9400 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
9404 value: function validate(_value, _utils) {
9409 value: function deprecated(_value, _utils) {
9414 value: function forward(_value, _utils) {
9419 value: function redirect(_value, _utils) {
9424 value: function overlap(currentValue, _newValue, _utils) {
9425 return currentValue;
9429 value: function preprocess(value, _utils) {
9434 value: function postprocess(value, _utils) {
9439 value: function create(parameters) {
9440 // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
9441 return createSchema(this, parameters);
9448 exports.Schema = Schema;
9450 function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
9451 return typeof handler === 'function' ? function () {
9452 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9453 args[_key] = arguments[_key];
9456 return handler.apply(void 0, _toConsumableArray(args.slice(0, handlerArgumentsLength - 1)).concat([superSchema], _toConsumableArray(args.slice(handlerArgumentsLength - 1))));
9462 unwrapExports(schema);
9463 var schema_1 = schema.createSchema;
9464 var schema_2 = schema.Schema;
9466 var alias = createCommonjsModule(function (module, exports) {
9468 Object.defineProperty(exports, "__esModule", {
9474 function (_schema_1$Schema) {
9475 _inherits(AliasSchema, _schema_1$Schema);
9477 function AliasSchema(parameters) {
9480 _classCallCheck(this, AliasSchema);
9482 _this = _possibleConstructorReturn(this, _getPrototypeOf(AliasSchema).call(this, parameters));
9483 _this._sourceName = parameters.sourceName;
9487 _createClass(AliasSchema, [{
9489 value: function expected(utils) {
9490 return utils.schemas[this._sourceName].expected(utils);
9494 value: function validate(value, utils) {
9495 return utils.schemas[this._sourceName].validate(value, utils);
9499 value: function redirect(_value, _utils) {
9500 return this._sourceName;
9507 exports.AliasSchema = AliasSchema;
9509 unwrapExports(alias);
9510 var alias_1 = alias.AliasSchema;
9512 var any = createCommonjsModule(function (module, exports) {
9514 Object.defineProperty(exports, "__esModule", {
9520 function (_schema_1$Schema) {
9521 _inherits(AnySchema, _schema_1$Schema);
9523 function AnySchema() {
9524 _classCallCheck(this, AnySchema);
9526 return _possibleConstructorReturn(this, _getPrototypeOf(AnySchema).apply(this, arguments));
9529 _createClass(AnySchema, [{
9531 value: function expected() {
9536 value: function validate() {
9544 exports.AnySchema = AnySchema;
9547 var any_1 = any.AnySchema;
9549 var array = createCommonjsModule(function (module, exports) {
9551 Object.defineProperty(exports, "__esModule", {
9557 function (_schema_1$Schema) {
9558 _inherits(ArraySchema, _schema_1$Schema);
9560 function ArraySchema(_a) {
9563 _classCallCheck(this, ArraySchema);
9565 var valueSchema = _a.valueSchema,
9567 name = _a$name === void 0 ? valueSchema.name : _a$name,
9568 handlers = tslib_1.__rest(_a, ["valueSchema", "name"]);
9570 _this = _possibleConstructorReturn(this, _getPrototypeOf(ArraySchema).call(this, Object.assign({}, handlers, {
9573 _this._valueSchema = valueSchema;
9577 _createClass(ArraySchema, [{
9579 value: function expected(utils) {
9580 return "an array of ".concat(this._valueSchema.expected(utils));
9584 value: function validate(value, utils) {
9585 if (!Array.isArray(value)) {
9589 var invalidValues = [];
9590 var _iteratorNormalCompletion = true;
9591 var _didIteratorError = false;
9592 var _iteratorError = undefined;
9595 for (var _iterator = value[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
9596 var subValue = _step.value;
9597 var subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
9599 if (subValidateResult !== true) {
9600 invalidValues.push(subValidateResult.value);
9604 _didIteratorError = true;
9605 _iteratorError = err;
9608 if (!_iteratorNormalCompletion && _iterator.return != null) {
9612 if (_didIteratorError) {
9613 throw _iteratorError;
9618 return invalidValues.length === 0 ? true : {
9619 value: invalidValues
9624 value: function deprecated(value, utils) {
9625 var deprecatedResult = [];
9626 var _iteratorNormalCompletion2 = true;
9627 var _didIteratorError2 = false;
9628 var _iteratorError2 = undefined;
9631 for (var _iterator2 = value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
9632 var subValue = _step2.value;
9633 var subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
9635 if (subDeprecatedResult !== false) {
9636 deprecatedResult.push.apply(deprecatedResult, _toConsumableArray(subDeprecatedResult.map(function (_ref) {
9637 var deprecatedValue = _ref.value;
9639 value: [deprecatedValue]
9645 _didIteratorError2 = true;
9646 _iteratorError2 = err;
9649 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
9650 _iterator2.return();
9653 if (_didIteratorError2) {
9654 throw _iteratorError2;
9659 return deprecatedResult;
9663 value: function forward(value, utils) {
9664 var forwardResult = [];
9665 var _iteratorNormalCompletion3 = true;
9666 var _didIteratorError3 = false;
9667 var _iteratorError3 = undefined;
9670 for (var _iterator3 = value[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
9671 var subValue = _step3.value;
9672 var subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
9673 forwardResult.push.apply(forwardResult, _toConsumableArray(subForwardResult.map(wrapTransferResult)));
9676 _didIteratorError3 = true;
9677 _iteratorError3 = err;
9680 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
9681 _iterator3.return();
9684 if (_didIteratorError3) {
9685 throw _iteratorError3;
9690 return forwardResult;
9694 value: function redirect(value, utils) {
9697 var _iteratorNormalCompletion4 = true;
9698 var _didIteratorError4 = false;
9699 var _iteratorError4 = undefined;
9702 for (var _iterator4 = value[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
9703 var subValue = _step4.value;
9704 var subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
9706 if ('remain' in subRedirectResult) {
9707 remain.push(subRedirectResult.remain);
9710 redirect.push.apply(redirect, _toConsumableArray(subRedirectResult.redirect.map(wrapTransferResult)));
9713 _didIteratorError4 = true;
9714 _iteratorError4 = err;
9717 if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
9718 _iterator4.return();
9721 if (_didIteratorError4) {
9722 throw _iteratorError4;
9727 return remain.length === 0 ? {
9736 value: function overlap(currentValue, newValue) {
9737 return currentValue.concat(newValue);
9744 exports.ArraySchema = ArraySchema;
9746 function wrapTransferResult(_ref2) {
9747 var from = _ref2.from,
9755 unwrapExports(array);
9756 var array_1 = array.ArraySchema;
9758 var boolean_1 = createCommonjsModule(function (module, exports) {
9760 Object.defineProperty(exports, "__esModule", {
9766 function (_schema_1$Schema) {
9767 _inherits(BooleanSchema, _schema_1$Schema);
9769 function BooleanSchema() {
9770 _classCallCheck(this, BooleanSchema);
9772 return _possibleConstructorReturn(this, _getPrototypeOf(BooleanSchema).apply(this, arguments));
9775 _createClass(BooleanSchema, [{
9777 value: function expected() {
9778 return 'true or false';
9782 value: function validate(value) {
9783 return typeof value === 'boolean';
9787 return BooleanSchema;
9790 exports.BooleanSchema = BooleanSchema;
9792 unwrapExports(boolean_1);
9793 var boolean_2 = boolean_1.BooleanSchema;
9795 var utils = createCommonjsModule(function (module, exports) {
9797 Object.defineProperty(exports, "__esModule", {
9801 function recordFromArray(array, mainKey) {
9802 var record = Object.create(null);
9803 var _iteratorNormalCompletion = true;
9804 var _didIteratorError = false;
9805 var _iteratorError = undefined;
9808 for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
9809 var value = _step.value;
9810 var key = value[mainKey]; // istanbul ignore next
9813 throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key)));
9817 record[key] = value;
9820 _didIteratorError = true;
9821 _iteratorError = err;
9824 if (!_iteratorNormalCompletion && _iterator.return != null) {
9828 if (_didIteratorError) {
9829 throw _iteratorError;
9837 exports.recordFromArray = recordFromArray;
9839 function mapFromArray(array, mainKey) {
9840 var map = new Map();
9841 var _iteratorNormalCompletion2 = true;
9842 var _didIteratorError2 = false;
9843 var _iteratorError2 = undefined;
9846 for (var _iterator2 = array[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
9847 var value = _step2.value;
9848 var key = value[mainKey]; // istanbul ignore next
9851 throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key)));
9854 map.set(key, value);
9857 _didIteratorError2 = true;
9858 _iteratorError2 = err;
9861 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
9862 _iterator2.return();
9865 if (_didIteratorError2) {
9866 throw _iteratorError2;
9874 exports.mapFromArray = mapFromArray;
9876 function createAutoChecklist() {
9877 var map = Object.create(null);
9878 return function (id) {
9879 var idString = JSON.stringify(id);
9881 if (map[idString]) {
9885 map[idString] = true;
9890 exports.createAutoChecklist = createAutoChecklist;
9892 function partition(array, predicate) {
9894 var falseArray = [];
9895 var _iteratorNormalCompletion3 = true;
9896 var _didIteratorError3 = false;
9897 var _iteratorError3 = undefined;
9900 for (var _iterator3 = array[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
9901 var value = _step3.value;
9903 if (predicate(value)) {
9904 trueArray.push(value);
9906 falseArray.push(value);
9910 _didIteratorError3 = true;
9911 _iteratorError3 = err;
9914 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
9915 _iterator3.return();
9918 if (_didIteratorError3) {
9919 throw _iteratorError3;
9924 return [trueArray, falseArray];
9927 exports.partition = partition;
9929 function isInt(value) {
9930 return value === Math.floor(value);
9933 exports.isInt = isInt;
9935 function comparePrimitive(a, b) {
9940 var typeofA = _typeof(a);
9942 var typeofB = _typeof(b);
9944 var orders = ['undefined', 'object', 'boolean', 'number', 'string'];
9946 if (typeofA !== typeofB) {
9947 return orders.indexOf(typeofA) - orders.indexOf(typeofB);
9950 if (typeofA !== 'string') {
9951 return Number(a) - Number(b);
9954 return a.localeCompare(b);
9957 exports.comparePrimitive = comparePrimitive;
9959 function normalizeDefaultResult(result) {
9960 return result === undefined ? {} : result;
9963 exports.normalizeDefaultResult = normalizeDefaultResult;
9965 function normalizeValidateResult(result, value) {
9966 return result === true ? true : result === false ? {
9971 exports.normalizeValidateResult = normalizeValidateResult;
9973 function normalizeDeprecatedResult(result, value) {
9974 var doNotNormalizeTrue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
9975 return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
9977 }] : 'value' in result ? [result] : result.length === 0 ? false : result;
9980 exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
9982 function normalizeTransferResult(result, value) {
9983 return typeof result === 'string' || 'key' in result ? {
9986 } : 'from' in result ? {
9995 exports.normalizeTransferResult = normalizeTransferResult;
9997 function normalizeForwardResult(result, value) {
9998 return result === undefined ? [] : Array.isArray(result) ? result.map(function (transferResult) {
9999 return normalizeTransferResult(transferResult, value);
10000 }) : [normalizeTransferResult(result, value)];
10003 exports.normalizeForwardResult = normalizeForwardResult;
10005 function normalizeRedirectResult(result, value) {
10006 var redirect = normalizeForwardResult(_typeof(result) === 'object' && 'redirect' in result ? result.redirect : result, value);
10007 return redirect.length === 0 ? {
10010 } : _typeof(result) === 'object' && 'remain' in result ? {
10011 remain: result.remain,
10018 exports.normalizeRedirectResult = normalizeRedirectResult;
10020 unwrapExports(utils);
10021 var utils_1 = utils.recordFromArray;
10022 var utils_2 = utils.mapFromArray;
10023 var utils_3 = utils.createAutoChecklist;
10024 var utils_4 = utils.partition;
10025 var utils_5 = utils.isInt;
10026 var utils_6 = utils.comparePrimitive;
10027 var utils_7 = utils.normalizeDefaultResult;
10028 var utils_8 = utils.normalizeValidateResult;
10029 var utils_9 = utils.normalizeDeprecatedResult;
10030 var utils_10 = utils.normalizeTransferResult;
10031 var utils_11 = utils.normalizeForwardResult;
10032 var utils_12 = utils.normalizeRedirectResult;
10034 var choice = createCommonjsModule(function (module, exports) {
10036 Object.defineProperty(exports, "__esModule", {
10042 function (_schema_1$Schema) {
10043 _inherits(ChoiceSchema, _schema_1$Schema);
10045 function ChoiceSchema(parameters) {
10048 _classCallCheck(this, ChoiceSchema);
10050 _this = _possibleConstructorReturn(this, _getPrototypeOf(ChoiceSchema).call(this, parameters));
10051 _this._choices = utils.mapFromArray(parameters.choices.map(function (choice) {
10052 return choice && _typeof(choice) === 'object' ? choice : {
10059 _createClass(ChoiceSchema, [{
10061 value: function expected(_ref) {
10064 var descriptor = _ref.descriptor;
10065 var choiceValues = Array.from(this._choices.keys()).map(function (value) {
10066 return _this2._choices.get(value);
10067 }).filter(function (choiceInfo) {
10068 return !choiceInfo.deprecated;
10069 }).map(function (choiceInfo) {
10070 return choiceInfo.value;
10071 }).sort(utils.comparePrimitive).map(descriptor.value);
10072 var head = choiceValues.slice(0, -2);
10073 var tail = choiceValues.slice(-2);
10074 return head.concat(tail.join(' or ')).join(', ');
10078 value: function validate(value) {
10079 return this._choices.has(value);
10083 value: function deprecated(value) {
10084 var choiceInfo = this._choices.get(value);
10086 return choiceInfo && choiceInfo.deprecated ? {
10092 value: function forward(value) {
10093 var choiceInfo = this._choices.get(value);
10095 return choiceInfo ? choiceInfo.forward : undefined;
10099 value: function redirect(value) {
10100 var choiceInfo = this._choices.get(value);
10102 return choiceInfo ? choiceInfo.redirect : undefined;
10106 return ChoiceSchema;
10109 exports.ChoiceSchema = ChoiceSchema;
10111 unwrapExports(choice);
10112 var choice_1 = choice.ChoiceSchema;
10114 var number = createCommonjsModule(function (module, exports) {
10116 Object.defineProperty(exports, "__esModule", {
10122 function (_schema_1$Schema) {
10123 _inherits(NumberSchema, _schema_1$Schema);
10125 function NumberSchema() {
10126 _classCallCheck(this, NumberSchema);
10128 return _possibleConstructorReturn(this, _getPrototypeOf(NumberSchema).apply(this, arguments));
10131 _createClass(NumberSchema, [{
10133 value: function expected() {
10138 value: function validate(value, _utils) {
10139 return typeof value === 'number';
10143 return NumberSchema;
10146 exports.NumberSchema = NumberSchema;
10148 unwrapExports(number);
10149 var number_1 = number.NumberSchema;
10151 var integer = createCommonjsModule(function (module, exports) {
10153 Object.defineProperty(exports, "__esModule", {
10157 var IntegerSchema =
10159 function (_number_1$NumberSchem) {
10160 _inherits(IntegerSchema, _number_1$NumberSchem);
10162 function IntegerSchema() {
10163 _classCallCheck(this, IntegerSchema);
10165 return _possibleConstructorReturn(this, _getPrototypeOf(IntegerSchema).apply(this, arguments));
10168 _createClass(IntegerSchema, [{
10170 value: function expected() {
10171 return 'an integer';
10175 value: function validate(value, utils$1) {
10176 return utils$1.normalizeValidateResult(_get(_getPrototypeOf(IntegerSchema.prototype), "validate", this).call(this, value, utils$1), value) === true && utils.isInt(value);
10180 return IntegerSchema;
10181 }(number.NumberSchema);
10183 exports.IntegerSchema = IntegerSchema;
10185 unwrapExports(integer);
10186 var integer_1 = integer.IntegerSchema;
10188 var string = createCommonjsModule(function (module, exports) {
10190 Object.defineProperty(exports, "__esModule", {
10196 function (_schema_1$Schema) {
10197 _inherits(StringSchema, _schema_1$Schema);
10199 function StringSchema() {
10200 _classCallCheck(this, StringSchema);
10202 return _possibleConstructorReturn(this, _getPrototypeOf(StringSchema).apply(this, arguments));
10205 _createClass(StringSchema, [{
10207 value: function expected() {
10212 value: function validate(value) {
10213 return typeof value === 'string';
10217 return StringSchema;
10220 exports.StringSchema = StringSchema;
10222 unwrapExports(string);
10223 var string_1 = string.StringSchema;
10225 var schemas = createCommonjsModule(function (module, exports) {
10227 Object.defineProperty(exports, "__esModule", {
10231 tslib_1.__exportStar(alias, exports);
10233 tslib_1.__exportStar(any, exports);
10235 tslib_1.__exportStar(array, exports);
10237 tslib_1.__exportStar(boolean_1, exports);
10239 tslib_1.__exportStar(choice, exports);
10241 tslib_1.__exportStar(integer, exports);
10243 tslib_1.__exportStar(number, exports);
10245 tslib_1.__exportStar(string, exports);
10247 unwrapExports(schemas);
10249 var defaults = createCommonjsModule(function (module, exports) {
10251 Object.defineProperty(exports, "__esModule", {
10254 exports.defaultDescriptor = api.apiDescriptor;
10255 exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
10256 exports.defaultInvalidHandler = invalid.commonInvalidHandler;
10257 exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
10259 unwrapExports(defaults);
10260 var defaults_1 = defaults.defaultDescriptor;
10261 var defaults_2 = defaults.defaultUnknownHandler;
10262 var defaults_3 = defaults.defaultInvalidHandler;
10263 var defaults_4 = defaults.defaultDeprecatedHandler;
10265 var normalize = createCommonjsModule(function (module, exports) {
10267 Object.defineProperty(exports, "__esModule", {
10271 exports.normalize = function (options, schemas, opts) {
10272 return new Normalizer(schemas, opts).normalize(options);
10278 function Normalizer(schemas, opts) {
10279 _classCallCheck(this, Normalizer);
10281 // istanbul ignore next
10282 var _ref = opts || {},
10283 _ref$logger = _ref.logger,
10284 logger = _ref$logger === void 0 ? console : _ref$logger,
10285 _ref$descriptor = _ref.descriptor,
10286 descriptor = _ref$descriptor === void 0 ? defaults.defaultDescriptor : _ref$descriptor,
10287 _ref$unknown = _ref.unknown,
10288 unknown = _ref$unknown === void 0 ? defaults.defaultUnknownHandler : _ref$unknown,
10289 _ref$invalid = _ref.invalid,
10290 invalid = _ref$invalid === void 0 ? defaults.defaultInvalidHandler : _ref$invalid,
10291 _ref$deprecated = _ref.deprecated,
10292 deprecated = _ref$deprecated === void 0 ? defaults.defaultDeprecatedHandler : _ref$deprecated;
10295 descriptor: descriptor,
10297 /* istanbul ignore next */
10299 warn: function warn() {}
10301 schemas: utils.recordFromArray(schemas, 'name'),
10302 normalizeDefaultResult: utils.normalizeDefaultResult,
10303 normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
10304 normalizeForwardResult: utils.normalizeForwardResult,
10305 normalizeRedirectResult: utils.normalizeRedirectResult,
10306 normalizeValidateResult: utils.normalizeValidateResult
10308 this._unknownHandler = unknown;
10309 this._invalidHandler = invalid;
10310 this._deprecatedHandler = deprecated;
10311 this.cleanHistory();
10314 _createClass(Normalizer, [{
10315 key: "cleanHistory",
10316 value: function cleanHistory() {
10317 this._hasDeprecationWarned = utils.createAutoChecklist();
10321 value: function normalize(options) {
10324 var normalized = {};
10325 var restOptionsArray = [options];
10327 var applyNormalization = function applyNormalization() {
10328 while (restOptionsArray.length !== 0) {
10329 var currentOptions = restOptionsArray.shift();
10331 var transferredOptionsArray = _this._applyNormalization(currentOptions, normalized);
10333 restOptionsArray.push.apply(restOptionsArray, _toConsumableArray(transferredOptionsArray));
10337 applyNormalization();
10339 for (var _i = 0, _Object$keys = Object.keys(this._utils.schemas); _i < _Object$keys.length; _i++) {
10340 var key = _Object$keys[_i];
10341 var schema = this._utils.schemas[key];
10343 if (!(key in normalized)) {
10344 var defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
10346 if ('value' in defaultResult) {
10347 restOptionsArray.push(_defineProperty({}, key, defaultResult.value));
10352 applyNormalization();
10354 for (var _i2 = 0, _Object$keys2 = Object.keys(this._utils.schemas); _i2 < _Object$keys2.length; _i2++) {
10355 var _key = _Object$keys2[_i2];
10356 var _schema = this._utils.schemas[_key];
10358 if (_key in normalized) {
10359 normalized[_key] = _schema.postprocess(normalized[_key], this._utils);
10366 key: "_applyNormalization",
10367 value: function _applyNormalization(options, normalized) {
10370 var transferredOptionsArray = [];
10372 var _utils_1$partition = utils.partition(Object.keys(options), function (key) {
10373 return key in _this2._utils.schemas;
10375 _utils_1$partition2 = _slicedToArray(_utils_1$partition, 2),
10376 knownOptionNames = _utils_1$partition2[0],
10377 unknownOptionNames = _utils_1$partition2[1];
10379 var _iteratorNormalCompletion = true;
10380 var _didIteratorError = false;
10381 var _iteratorError = undefined;
10384 var _loop = function _loop() {
10385 var key = _step.value;
10386 var schema = _this2._utils.schemas[key];
10387 var value = schema.preprocess(options[key], _this2._utils);
10388 var validateResult = utils.normalizeValidateResult(schema.validate(value, _this2._utils), value);
10390 if (validateResult !== true) {
10391 var invalidValue = validateResult.value;
10393 var errorMessageOrError = _this2._invalidHandler(key, invalidValue, _this2._utils);
10395 throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
10396 /* istanbul ignore next*/
10397 errorMessageOrError;
10400 var appendTransferredOptions = function appendTransferredOptions(_ref2) {
10401 var from = _ref2.from,
10403 transferredOptionsArray.push(typeof to === 'string' ? _defineProperty({}, to, from) : _defineProperty({}, to.key, to.value));
10406 var warnDeprecated = function warnDeprecated(_ref5) {
10407 var currentValue = _ref5.value,
10408 redirectTo = _ref5.redirectTo;
10409 var deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, _this2._utils), value,
10410 /* doNotNormalizeTrue */
10413 if (deprecatedResult === false) {
10417 if (deprecatedResult === true) {
10418 if (!_this2._hasDeprecationWarned(key)) {
10419 _this2._utils.logger.warn(_this2._deprecatedHandler(key, redirectTo, _this2._utils));
10422 var _iteratorNormalCompletion3 = true;
10423 var _didIteratorError3 = false;
10424 var _iteratorError3 = undefined;
10427 for (var _iterator3 = deprecatedResult[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
10428 var deprecatedValue = _step3.value.value;
10431 value: deprecatedValue
10434 if (!_this2._hasDeprecationWarned(pair)) {
10435 var redirectToPair = typeof redirectTo === 'string' ? {
10437 value: deprecatedValue
10440 _this2._utils.logger.warn(_this2._deprecatedHandler(pair, redirectToPair, _this2._utils));
10444 _didIteratorError3 = true;
10445 _iteratorError3 = err;
10448 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
10449 _iterator3.return();
10452 if (_didIteratorError3) {
10453 throw _iteratorError3;
10460 var forwardResult = utils.normalizeForwardResult(schema.forward(value, _this2._utils), value);
10461 forwardResult.forEach(appendTransferredOptions);
10462 var redirectResult = utils.normalizeRedirectResult(schema.redirect(value, _this2._utils), value);
10463 redirectResult.redirect.forEach(appendTransferredOptions);
10465 if ('remain' in redirectResult) {
10466 var remainingValue = redirectResult.remain;
10467 normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, _this2._utils) : remainingValue;
10469 value: remainingValue
10473 var _iteratorNormalCompletion4 = true;
10474 var _didIteratorError4 = false;
10475 var _iteratorError4 = undefined;
10478 for (var _iterator4 = redirectResult.redirect[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
10479 var _step4$value = _step4.value,
10480 from = _step4$value.from,
10481 to = _step4$value.to;
10488 _didIteratorError4 = true;
10489 _iteratorError4 = err;
10492 if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
10493 _iterator4.return();
10496 if (_didIteratorError4) {
10497 throw _iteratorError4;
10503 for (var _iterator = knownOptionNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
10507 _didIteratorError = true;
10508 _iteratorError = err;
10511 if (!_iteratorNormalCompletion && _iterator.return != null) {
10512 _iterator.return();
10515 if (_didIteratorError) {
10516 throw _iteratorError;
10521 var _iteratorNormalCompletion2 = true;
10522 var _didIteratorError2 = false;
10523 var _iteratorError2 = undefined;
10526 for (var _iterator2 = unknownOptionNames[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
10527 var key = _step2.value;
10528 var value = options[key];
10530 var unknownResult = this._unknownHandler(key, value, this._utils);
10532 if (unknownResult) {
10533 for (var _i3 = 0, _Object$keys3 = Object.keys(unknownResult); _i3 < _Object$keys3.length; _i3++) {
10534 var unknownKey = _Object$keys3[_i3];
10536 var unknownOption = _defineProperty({}, unknownKey, unknownResult[unknownKey]);
10538 if (unknownKey in this._utils.schemas) {
10539 transferredOptionsArray.push(unknownOption);
10541 Object.assign(normalized, unknownOption);
10547 _didIteratorError2 = true;
10548 _iteratorError2 = err;
10551 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
10552 _iterator2.return();
10555 if (_didIteratorError2) {
10556 throw _iteratorError2;
10561 return transferredOptionsArray;
10568 exports.Normalizer = Normalizer;
10570 unwrapExports(normalize);
10571 var normalize_1 = normalize.normalize;
10572 var normalize_2 = normalize.Normalizer;
10574 var lib = createCommonjsModule(function (module, exports) {
10576 Object.defineProperty(exports, "__esModule", {
10580 tslib_1.__exportStar(descriptors, exports);
10582 tslib_1.__exportStar(handlers, exports);
10584 tslib_1.__exportStar(schemas, exports);
10586 tslib_1.__exportStar(normalize, exports);
10588 tslib_1.__exportStar(schema, exports);
10590 unwrapExports(lib);
10593 var charCodeCache$1 = [];
10595 var leven$1 = function leven(left, right) {
10596 if (left === right) {
10600 var swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the
10601 // shortest & which one is the longest
10603 if (left.length > right.length) {
10608 var leftLength = left.length;
10609 var rightLength = right.length; // Performing suffix trimming:
10610 // We can linearly drop suffix common to both strings since they
10611 // don't increase distance at all
10612 // Note: `~-` is the bitwise way to perform a `- 1` operation
10614 while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
10617 } // Performing prefix trimming
10618 // We can linearly drop prefix common to both strings since they
10619 // don't increase distance at all
10624 while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
10628 leftLength -= start;
10629 rightLength -= start;
10631 if (leftLength === 0) {
10632 return rightLength;
10642 while (i < leftLength) {
10643 charCodeCache$1[i] = left.charCodeAt(start + i);
10647 while (j < rightLength) {
10648 bCharCode = right.charCodeAt(start + j);
10652 for (i = 0; i < leftLength; i++) {
10653 temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1;
10654 temp = array$1[i]; // eslint-disable-next-line no-multi-assign
10656 result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
10663 var leven_1$1 = leven$1; // TODO: Remove this for the next major release
10665 var default_1 = leven$1;
10666 leven_1$1.default = default_1;
10668 var cliDescriptor = {
10669 key: function key(_key) {
10670 return _key.length === 1 ? "-".concat(_key) : "--".concat(_key);
10672 value: function value(_value) {
10673 return lib.apiDescriptor.value(_value);
10675 pair: function pair(_ref) {
10676 var key = _ref.key,
10677 value = _ref.value;
10678 return value === false ? "--no-".concat(key) : value === true ? cliDescriptor.key(key) : value === "" ? "".concat(cliDescriptor.key(key), " without an argument") : "".concat(cliDescriptor.key(key), "=").concat(value);
10684 function (_vnopts$ChoiceSchema) {
10685 _inherits(FlagSchema, _vnopts$ChoiceSchema);
10687 function FlagSchema(_ref2) {
10690 var name = _ref2.name,
10691 flags = _ref2.flags;
10693 _classCallCheck(this, FlagSchema);
10695 _this = _possibleConstructorReturn(this, _getPrototypeOf(FlagSchema).call(this, {
10699 _this._flags = flags.slice().sort();
10703 _createClass(FlagSchema, [{
10705 value: function preprocess(value, utils) {
10706 if (typeof value === "string" && value.length !== 0 && this._flags.indexOf(value) === -1) {
10707 var suggestion = this._flags.find(function (flag) {
10708 return leven_1$1(flag, value) < 3;
10712 utils.logger.warn(["Unknown flag ".concat(chalk.yellow(utils.descriptor.value(value)), ","), "did you mean ".concat(chalk.blue(utils.descriptor.value(suggestion)), "?")].join(" "));
10721 value: function expected() {
10727 }(lib.ChoiceSchema);
10729 var hasDeprecationWarned;
10731 function normalizeOptions(options, optionInfos) {
10732 var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
10733 logger = _ref3.logger,
10734 _ref3$isCLI = _ref3.isCLI,
10735 isCLI = _ref3$isCLI === void 0 ? false : _ref3$isCLI,
10736 _ref3$passThrough = _ref3.passThrough,
10737 passThrough = _ref3$passThrough === void 0 ? false : _ref3$passThrough;
10739 var unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? function (key, value) {
10740 return passThrough.indexOf(key) === -1 ? undefined : _defineProperty({}, key, value);
10741 } : function (key, value) {
10742 return _defineProperty({}, key, value);
10744 var descriptor = isCLI ? cliDescriptor : lib.apiDescriptor;
10745 var schemas = optionInfosToSchemas(optionInfos, {
10748 var normalizer = new lib.Normalizer(schemas, {
10751 descriptor: descriptor
10753 var shouldSuppressDuplicateDeprecationWarnings = logger !== false;
10755 if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
10756 normalizer._hasDeprecationWarned = hasDeprecationWarned;
10759 var normalized = normalizer.normalize(options);
10761 if (shouldSuppressDuplicateDeprecationWarnings) {
10762 hasDeprecationWarned = normalizer._hasDeprecationWarned;
10768 function optionInfosToSchemas(optionInfos, _ref6) {
10769 var isCLI = _ref6.isCLI;
10773 schemas.push(lib.AnySchema.create({
10778 var _iteratorNormalCompletion = true;
10779 var _didIteratorError = false;
10780 var _iteratorError = undefined;
10783 for (var _iterator = optionInfos[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
10784 var optionInfo = _step.value;
10785 schemas.push(optionInfoToSchema(optionInfo, {
10787 optionInfos: optionInfos
10790 if (optionInfo.alias && isCLI) {
10791 schemas.push(lib.AliasSchema.create({
10792 name: optionInfo.alias,
10793 sourceName: optionInfo.name
10798 _didIteratorError = true;
10799 _iteratorError = err;
10802 if (!_iteratorNormalCompletion && _iterator.return != null) {
10803 _iterator.return();
10806 if (_didIteratorError) {
10807 throw _iteratorError;
10815 function optionInfoToSchema(optionInfo, _ref7) {
10816 var isCLI = _ref7.isCLI,
10817 optionInfos = _ref7.optionInfos;
10818 var SchemaConstructor;
10820 name: optionInfo.name
10824 switch (optionInfo.type) {
10826 SchemaConstructor = lib.IntegerSchema;
10829 parameters.preprocess = function (value) {
10830 return Number(value);
10837 SchemaConstructor = lib.StringSchema;
10841 SchemaConstructor = lib.ChoiceSchema;
10842 parameters.choices = optionInfo.choices.map(function (choiceInfo) {
10843 return _typeof(choiceInfo) === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
10846 key: optionInfo.name,
10847 value: choiceInfo.redirect
10855 SchemaConstructor = lib.BooleanSchema;
10859 SchemaConstructor = FlagSchema;
10860 parameters.flags = optionInfos.map(function (optionInfo) {
10861 return [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? "no-".concat(optionInfo.name) : []);
10862 }).reduce(function (a, b) {
10863 return a.concat(b);
10868 SchemaConstructor = lib.StringSchema;
10872 throw new Error("Unexpected type ".concat(optionInfo.type));
10875 if (optionInfo.exception) {
10876 parameters.validate = function (value, schema, utils) {
10877 return optionInfo.exception(value) || schema.validate(value, utils);
10880 parameters.validate = function (value, schema, utils) {
10881 return value === undefined || schema.validate(value, utils);
10885 if (optionInfo.redirect) {
10886 handlers.redirect = function (value) {
10887 return !value ? undefined : {
10889 key: optionInfo.redirect.option,
10890 value: optionInfo.redirect.value
10896 if (optionInfo.deprecated) {
10897 handlers.deprecated = true;
10898 } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
10901 if (isCLI && !optionInfo.array) {
10902 var originalPreprocess = parameters.preprocess || function (x) {
10906 parameters.preprocess = function (value, schema, utils) {
10907 return schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
10911 return optionInfo.array ? lib.ArraySchema.create(Object.assign(isCLI ? {
10912 preprocess: function preprocess(v) {
10913 return [].concat(v);
10915 } : {}, handlers, {
10916 valueSchema: SchemaConstructor.create(parameters)
10917 })) : SchemaConstructor.create(Object.assign({}, parameters, handlers));
10920 function normalizeApiOptions(options, optionInfos, opts) {
10921 return normalizeOptions(options, optionInfos, opts);
10924 function normalizeCliOptions(options, optionInfos, opts) {
10925 return normalizeOptions(options, optionInfos, Object.assign({
10930 var optionsNormalizer = {
10931 normalizeApiOptions: normalizeApiOptions,
10932 normalizeCliOptions: normalizeCliOptions
10935 var getLast = function getLast(arr) {
10936 return arr.length > 0 ? arr[arr.length - 1] : null;
10939 function locStart(node, opts) {
10940 opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator
10942 if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) {
10943 return locStart(node.declaration.decorators[0]);
10946 if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) {
10947 return locStart(node.decorators[0]);
10950 if (node.__location) {
10951 return node.__location.startOffset;
10955 return node.range[0];
10958 if (typeof node.start === "number") {
10963 return node.loc.start;
10969 function locEnd(node) {
10970 var endNode = node.nodes && getLast(node.nodes);
10972 if (endNode && node.source && !node.source.end) {
10976 if (node.__location) {
10977 return node.__location.endOffset;
10980 var loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null;
10982 if (node.typeAnnotation) {
10983 return Math.max(loc, locEnd(node.typeAnnotation));
10986 if (node.loc && !loc) {
10987 return node.loc.end;
10994 locStart: locStart,
10998 var jsTokens = createCommonjsModule(function (module, exports) {
10999 // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
11000 // License: MIT. (See LICENSE.)
11001 Object.defineProperty(exports, "__esModule", {
11003 }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
11004 // (run `npm run build`).
11006 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;
11008 exports.matchToToken = function (match) {
11014 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";
11018 unwrapExports(jsTokens);
11019 var jsTokens_1 = jsTokens.matchToToken;
11021 var ast = createCommonjsModule(function (module) {
11023 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
11025 Redistribution and use in source and binary forms, with or without
11026 modification, are permitted provided that the following conditions are met:
11028 * Redistributions of source code must retain the above copyright
11029 notice, this list of conditions and the following disclaimer.
11030 * Redistributions in binary form must reproduce the above copyright
11031 notice, this list of conditions and the following disclaimer in the
11032 documentation and/or other materials provided with the distribution.
11034 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
11035 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
11036 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
11037 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
11038 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
11039 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
11040 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
11041 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11042 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11043 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11047 function isExpression(node) {
11048 if (node == null) {
11052 switch (node.type) {
11053 case 'ArrayExpression':
11054 case 'AssignmentExpression':
11055 case 'BinaryExpression':
11056 case 'CallExpression':
11057 case 'ConditionalExpression':
11058 case 'FunctionExpression':
11061 case 'LogicalExpression':
11062 case 'MemberExpression':
11063 case 'NewExpression':
11064 case 'ObjectExpression':
11065 case 'SequenceExpression':
11066 case 'ThisExpression':
11067 case 'UnaryExpression':
11068 case 'UpdateExpression':
11075 function isIterationStatement(node) {
11076 if (node == null) {
11080 switch (node.type) {
11081 case 'DoWhileStatement':
11082 case 'ForInStatement':
11083 case 'ForStatement':
11084 case 'WhileStatement':
11091 function isStatement(node) {
11092 if (node == null) {
11096 switch (node.type) {
11097 case 'BlockStatement':
11098 case 'BreakStatement':
11099 case 'ContinueStatement':
11100 case 'DebuggerStatement':
11101 case 'DoWhileStatement':
11102 case 'EmptyStatement':
11103 case 'ExpressionStatement':
11104 case 'ForInStatement':
11105 case 'ForStatement':
11106 case 'IfStatement':
11107 case 'LabeledStatement':
11108 case 'ReturnStatement':
11109 case 'SwitchStatement':
11110 case 'ThrowStatement':
11111 case 'TryStatement':
11112 case 'VariableDeclaration':
11113 case 'WhileStatement':
11114 case 'WithStatement':
11121 function isSourceElement(node) {
11122 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
11125 function trailingStatement(node) {
11126 switch (node.type) {
11127 case 'IfStatement':
11128 if (node.alternate != null) {
11129 return node.alternate;
11132 return node.consequent;
11134 case 'LabeledStatement':
11135 case 'ForStatement':
11136 case 'ForInStatement':
11137 case 'WhileStatement':
11138 case 'WithStatement':
11145 function isProblematicIfStatement(node) {
11148 if (node.type !== 'IfStatement') {
11152 if (node.alternate == null) {
11156 current = node.consequent;
11159 if (current.type === 'IfStatement') {
11160 if (current.alternate == null) {
11165 current = trailingStatement(current);
11172 isExpression: isExpression,
11173 isStatement: isStatement,
11174 isIterationStatement: isIterationStatement,
11175 isSourceElement: isSourceElement,
11176 isProblematicIfStatement: isProblematicIfStatement,
11177 trailingStatement: trailingStatement
11180 /* vim: set sw=4 ts=4 et tw=80 : */
11183 var ast_1 = ast.isExpression;
11184 var ast_2 = ast.isStatement;
11185 var ast_3 = ast.isIterationStatement;
11186 var ast_4 = ast.isSourceElement;
11187 var ast_5 = ast.isProblematicIfStatement;
11188 var ast_6 = ast.trailingStatement;
11190 var code = createCommonjsModule(function (module) {
11192 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
11193 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
11195 Redistribution and use in source and binary forms, with or without
11196 modification, are permitted provided that the following conditions are met:
11198 * Redistributions of source code must retain the above copyright
11199 notice, this list of conditions and the following disclaimer.
11200 * Redistributions in binary form must reproduce the above copyright
11201 notice, this list of conditions and the following disclaimer in the
11202 documentation and/or other materials provided with the distribution.
11204 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
11205 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
11206 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
11207 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
11208 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
11209 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
11210 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
11211 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11212 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11213 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11217 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
11220 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
11221 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]/,
11222 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
11223 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]/
11226 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
11227 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]/,
11228 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
11229 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]/
11232 function isDecimalDigit(ch) {
11233 return 0x30 <= ch && ch <= 0x39; // 0..9
11236 function isHexDigit(ch) {
11237 return 0x30 <= ch && ch <= 0x39 || // 0..9
11238 0x61 <= ch && ch <= 0x66 || // a..f
11239 0x41 <= ch && ch <= 0x46; // A..F
11242 function isOctalDigit(ch) {
11243 return ch >= 0x30 && ch <= 0x37; // 0..7
11244 } // 7.2 White Space
11247 NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
11249 function isWhiteSpace(ch) {
11250 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
11251 } // 7.3 Line Terminators
11254 function isLineTerminator(ch) {
11255 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
11256 } // 7.6 Identifier Names and Identifiers
11259 function fromCodePoint(cp) {
11260 if (cp <= 0xFFFF) {
11261 return String.fromCharCode(cp);
11264 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
11265 var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
11269 IDENTIFIER_START = new Array(0x80);
11271 for (ch = 0; ch < 0x80; ++ch) {
11272 IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
11273 ch >= 0x41 && ch <= 0x5A || // A..Z
11274 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
11277 IDENTIFIER_PART = new Array(0x80);
11279 for (ch = 0; ch < 0x80; ++ch) {
11280 IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
11281 ch >= 0x41 && ch <= 0x5A || // A..Z
11282 ch >= 0x30 && ch <= 0x39 || // 0..9
11283 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
11286 function isIdentifierStartES5(ch) {
11287 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
11290 function isIdentifierPartES5(ch) {
11291 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
11294 function isIdentifierStartES6(ch) {
11295 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
11298 function isIdentifierPartES6(ch) {
11299 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
11303 isDecimalDigit: isDecimalDigit,
11304 isHexDigit: isHexDigit,
11305 isOctalDigit: isOctalDigit,
11306 isWhiteSpace: isWhiteSpace,
11307 isLineTerminator: isLineTerminator,
11308 isIdentifierStartES5: isIdentifierStartES5,
11309 isIdentifierPartES5: isIdentifierPartES5,
11310 isIdentifierStartES6: isIdentifierStartES6,
11311 isIdentifierPartES6: isIdentifierPartES6
11314 /* vim: set sw=4 ts=4 et tw=80 : */
11317 var code_1 = code.isDecimalDigit;
11318 var code_2 = code.isHexDigit;
11319 var code_3 = code.isOctalDigit;
11320 var code_4 = code.isWhiteSpace;
11321 var code_5 = code.isLineTerminator;
11322 var code_6 = code.isIdentifierStartES5;
11323 var code_7 = code.isIdentifierPartES5;
11324 var code_8 = code.isIdentifierStartES6;
11325 var code_9 = code.isIdentifierPartES6;
11327 var keyword = createCommonjsModule(function (module) {
11329 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
11331 Redistribution and use in source and binary forms, with or without
11332 modification, are permitted provided that the following conditions are met:
11334 * Redistributions of source code must retain the above copyright
11335 notice, this list of conditions and the following disclaimer.
11336 * Redistributions in binary form must reproduce the above copyright
11337 notice, this list of conditions and the following disclaimer in the
11338 documentation and/or other materials provided with the distribution.
11340 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
11341 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
11342 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
11343 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
11344 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
11345 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
11346 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
11347 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11348 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11349 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11355 function isStrictModeReservedWordES6(id) {
11372 function isKeywordES5(id, strict) {
11373 // yield should not be treated as keyword under non-strict mode.
11374 if (!strict && id === 'yield') {
11378 return isKeywordES6(id, strict);
11381 function isKeywordES6(id, strict) {
11382 if (strict && isStrictModeReservedWordES6(id)) {
11386 switch (id.length) {
11388 return id === 'if' || id === 'in' || id === 'do';
11391 return id === 'var' || id === 'for' || id === 'new' || id === 'try';
11394 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
11397 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
11400 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
11403 return id === 'default' || id === 'finally' || id === 'extends';
11406 return id === 'function' || id === 'continue' || id === 'debugger';
11409 return id === 'instanceof';
11416 function isReservedWordES5(id, strict) {
11417 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
11420 function isReservedWordES6(id, strict) {
11421 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
11424 function isRestrictedWord(id) {
11425 return id === 'eval' || id === 'arguments';
11428 function isIdentifierNameES5(id) {
11431 if (id.length === 0) {
11435 ch = id.charCodeAt(0);
11437 if (!code$1.isIdentifierStartES5(ch)) {
11441 for (i = 1, iz = id.length; i < iz; ++i) {
11442 ch = id.charCodeAt(i);
11444 if (!code$1.isIdentifierPartES5(ch)) {
11452 function decodeUtf16(lead, trail) {
11453 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
11456 function isIdentifierNameES6(id) {
11457 var i, iz, ch, lowCh, check;
11459 if (id.length === 0) {
11463 check = code$1.isIdentifierStartES6;
11465 for (i = 0, iz = id.length; i < iz; ++i) {
11466 ch = id.charCodeAt(i);
11468 if (0xD800 <= ch && ch <= 0xDBFF) {
11475 lowCh = id.charCodeAt(i);
11477 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
11481 ch = decodeUtf16(ch, lowCh);
11488 check = code$1.isIdentifierPartES6;
11494 function isIdentifierES5(id, strict) {
11495 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
11498 function isIdentifierES6(id, strict) {
11499 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
11503 isKeywordES5: isKeywordES5,
11504 isKeywordES6: isKeywordES6,
11505 isReservedWordES5: isReservedWordES5,
11506 isReservedWordES6: isReservedWordES6,
11507 isRestrictedWord: isRestrictedWord,
11508 isIdentifierNameES5: isIdentifierNameES5,
11509 isIdentifierNameES6: isIdentifierNameES6,
11510 isIdentifierES5: isIdentifierES5,
11511 isIdentifierES6: isIdentifierES6
11514 /* vim: set sw=4 ts=4 et tw=80 : */
11517 var keyword_1 = keyword.isKeywordES5;
11518 var keyword_2 = keyword.isKeywordES6;
11519 var keyword_3 = keyword.isReservedWordES5;
11520 var keyword_4 = keyword.isReservedWordES6;
11521 var keyword_5 = keyword.isRestrictedWord;
11522 var keyword_6 = keyword.isIdentifierNameES5;
11523 var keyword_7 = keyword.isIdentifierNameES6;
11524 var keyword_8 = keyword.isIdentifierES5;
11525 var keyword_9 = keyword.isIdentifierES6;
11527 var utils$1 = createCommonjsModule(function (module, exports) {
11529 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
11531 Redistribution and use in source and binary forms, with or without
11532 modification, are permitted provided that the following conditions are met:
11534 * Redistributions of source code must retain the above copyright
11535 notice, this list of conditions and the following disclaimer.
11536 * Redistributions in binary form must reproduce the above copyright
11537 notice, this list of conditions and the following disclaimer in the
11538 documentation and/or other materials provided with the distribution.
11540 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
11541 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
11542 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
11543 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
11544 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
11545 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
11546 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
11547 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11548 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11549 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11554 exports.code = code;
11555 exports.keyword = keyword;
11557 /* vim: set sw=4 ts=4 et tw=80 : */
11560 var utils_1$1 = utils$1.ast;
11561 var utils_2$1 = utils$1.code;
11562 var utils_3$1 = utils$1.keyword;
11564 var lib$1 = createCommonjsModule(function (module, exports) {
11566 Object.defineProperty(exports, "__esModule", {
11569 exports.shouldHighlight = shouldHighlight;
11570 exports.getChalk = getChalk;
11571 exports.default = highlight;
11573 function _jsTokens() {
11574 var data = _interopRequireWildcard(jsTokens);
11576 _jsTokens = function _jsTokens() {
11583 function _esutils() {
11584 var data = _interopRequireDefault(utils$1);
11586 _esutils = function _esutils() {
11593 function _chalk() {
11594 var data = _interopRequireDefault(chalk);
11596 _chalk = function _chalk() {
11603 function _interopRequireDefault(obj) {
11604 return obj && obj.__esModule ? obj : {
11609 function _interopRequireWildcard(obj) {
11610 if (obj && obj.__esModule) {
11616 for (var key in obj) {
11617 if (Object.prototype.hasOwnProperty.call(obj, key)) {
11618 var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
11620 if (desc.get || desc.set) {
11621 Object.defineProperty(newObj, key, desc);
11623 newObj[key] = obj[key];
11629 newObj.default = obj;
11634 function getDefs(chalk) {
11636 keyword: chalk.cyan,
11637 capitalized: chalk.yellow,
11638 jsx_tag: chalk.yellow,
11639 punctuator: chalk.yellow,
11640 number: chalk.magenta,
11641 string: chalk.green,
11642 regex: chalk.magenta,
11643 comment: chalk.grey,
11644 invalid: chalk.white.bgRed.bold
11648 var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
11649 var JSX_TAG = /^[a-z][\w-]*$/i;
11650 var BRACKET = /^[()[\]{}]$/;
11652 function getTokenType(match) {
11653 var _match$slice = match.slice(-2),
11654 _match$slice2 = _slicedToArray(_match$slice, 2),
11655 offset = _match$slice2[0],
11656 text = _match$slice2[1];
11658 var token = (0, _jsTokens().matchToToken)(match);
11660 if (token.type === "name") {
11661 if (_esutils().default.keyword.isReservedWordES6(token.value)) {
11665 if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
11669 if (token.value[0] !== token.value[0].toLowerCase()) {
11670 return "capitalized";
11674 if (token.type === "punctuator" && BRACKET.test(token.value)) {
11678 if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
11679 return "punctuator";
11685 function highlightTokens(defs, text) {
11686 return text.replace(_jsTokens().default, function () {
11687 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
11688 args[_key] = arguments[_key];
11691 var type = getTokenType(args);
11692 var colorize = defs[type];
11695 return args[0].split(NEWLINE).map(function (str) {
11696 return colorize(str);
11704 function shouldHighlight(options) {
11705 return _chalk().default.supportsColor || options.forceColor;
11708 function getChalk(options) {
11709 var chalk = _chalk().default;
11711 if (options.forceColor) {
11712 chalk = new (_chalk().default.constructor)({
11721 function highlight(code) {
11722 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
11724 if (shouldHighlight(options)) {
11725 var chalk = getChalk(options);
11726 var defs = getDefs(chalk);
11727 return highlightTokens(defs, code);
11733 unwrapExports(lib$1);
11734 var lib_1 = lib$1.shouldHighlight;
11735 var lib_2 = lib$1.getChalk;
11737 var lib$2 = createCommonjsModule(function (module, exports) {
11739 Object.defineProperty(exports, "__esModule", {
11742 exports.codeFrameColumns = codeFrameColumns;
11743 exports.default = _default;
11745 function _highlight() {
11746 var data = _interopRequireWildcard(lib$1);
11748 _highlight = function _highlight() {
11755 function _interopRequireWildcard(obj) {
11756 if (obj && obj.__esModule) {
11762 for (var key in obj) {
11763 if (Object.prototype.hasOwnProperty.call(obj, key)) {
11764 var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
11766 if (desc.get || desc.set) {
11767 Object.defineProperty(newObj, key, desc);
11769 newObj[key] = obj[key];
11775 newObj.default = obj;
11780 var deprecationWarningShown = false;
11782 function getDefs(chalk) {
11784 gutter: chalk.grey,
11785 marker: chalk.red.bold,
11786 message: chalk.red.bold
11790 var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
11792 function getMarkerLines(loc, source, opts) {
11793 var startLoc = Object.assign({
11797 var endLoc = Object.assign({}, startLoc, loc.end);
11799 var _ref = opts || {},
11800 _ref$linesAbove = _ref.linesAbove,
11801 linesAbove = _ref$linesAbove === void 0 ? 2 : _ref$linesAbove,
11802 _ref$linesBelow = _ref.linesBelow,
11803 linesBelow = _ref$linesBelow === void 0 ? 3 : _ref$linesBelow;
11805 var startLine = startLoc.line;
11806 var startColumn = startLoc.column;
11807 var endLine = endLoc.line;
11808 var endColumn = endLoc.column;
11809 var start = Math.max(startLine - (linesAbove + 1), 0);
11810 var end = Math.min(source.length, endLine + linesBelow);
11812 if (startLine === -1) {
11816 if (endLine === -1) {
11817 end = source.length;
11820 var lineDiff = endLine - startLine;
11821 var markerLines = {};
11824 for (var i = 0; i <= lineDiff; i++) {
11825 var lineNumber = i + startLine;
11827 if (!startColumn) {
11828 markerLines[lineNumber] = true;
11829 } else if (i === 0) {
11830 var sourceLength = source[lineNumber - 1].length;
11831 markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
11832 } else if (i === lineDiff) {
11833 markerLines[lineNumber] = [0, endColumn];
11835 var _sourceLength = source[lineNumber - i].length;
11836 markerLines[lineNumber] = [0, _sourceLength];
11840 if (startColumn === endColumn) {
11842 markerLines[startLine] = [startColumn, 0];
11844 markerLines[startLine] = true;
11847 markerLines[startLine] = [startColumn, endColumn - startColumn];
11854 markerLines: markerLines
11858 function codeFrameColumns(rawLines, loc) {
11859 var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
11860 var highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts);
11861 var chalk = (0, _highlight().getChalk)(opts);
11862 var defs = getDefs(chalk);
11864 var maybeHighlight = function maybeHighlight(chalkFn, string) {
11865 return highlighted ? chalkFn(string) : string;
11868 var lines = rawLines.split(NEWLINE);
11870 var _getMarkerLines = getMarkerLines(loc, lines, opts),
11871 start = _getMarkerLines.start,
11872 end = _getMarkerLines.end,
11873 markerLines = _getMarkerLines.markerLines;
11875 var hasColumns = loc.start && typeof loc.start.column === "number";
11876 var numberMaxWidth = String(end).length;
11877 var highlightedLines = highlighted ? (0, _highlight().default)(rawLines, opts) : rawLines;
11878 var frame = highlightedLines.split(NEWLINE).slice(start, end).map(function (line, index) {
11879 var number = start + 1 + index;
11880 var paddedNumber = " ".concat(number).slice(-numberMaxWidth);
11881 var gutter = " ".concat(paddedNumber, " | ");
11882 var hasMarker = markerLines[number];
11883 var lastMarkerLine = !markerLines[number + 1];
11886 var markerLine = "";
11888 if (Array.isArray(hasMarker)) {
11889 var markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
11890 var numberOfMarkers = hasMarker[1] || 1;
11891 markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
11893 if (lastMarkerLine && opts.message) {
11894 markerLine += " " + maybeHighlight(defs.message, opts.message);
11898 return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
11900 return " ".concat(maybeHighlight(defs.gutter, gutter)).concat(line);
11904 if (opts.message && !hasColumns) {
11905 frame = "".concat(" ".repeat(numberMaxWidth + 1)).concat(opts.message, "\n").concat(frame);
11909 return chalk.reset(frame);
11915 function _default(rawLines, lineNumber, colNumber) {
11916 var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
11918 if (!deprecationWarningShown) {
11919 deprecationWarningShown = true;
11920 var message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
11922 if (process.emitWarning) {
11923 process.emitWarning(message, "DeprecationWarning");
11925 var deprecationError = new Error(message);
11926 deprecationError.name = "DeprecationWarning";
11927 console.warn(new Error(message));
11931 colNumber = Math.max(colNumber, 0);
11938 return codeFrameColumns(rawLines, location, opts);
11941 unwrapExports(lib$2);
11942 var lib_1$1 = lib$2.codeFrameColumns;
11944 var ConfigError$1 = errors.ConfigError;
11945 var locStart$1 = loc.locStart,
11946 locEnd$1 = loc.locEnd; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
11947 // triggering the parsers getters.
11949 var ownNames = Object.getOwnPropertyNames;
11950 var ownDescriptor = Object.getOwnPropertyDescriptor;
11952 function getParsers(options) {
11954 var _iteratorNormalCompletion = true;
11955 var _didIteratorError = false;
11956 var _iteratorError = undefined;
11959 for (var _iterator = options.plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
11960 var plugin = _step.value;
11962 if (!plugin.parsers) {
11966 var _iteratorNormalCompletion2 = true;
11967 var _didIteratorError2 = false;
11968 var _iteratorError2 = undefined;
11971 for (var _iterator2 = ownNames(plugin.parsers)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
11972 var name = _step2.value;
11973 Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
11976 _didIteratorError2 = true;
11977 _iteratorError2 = err;
11980 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
11981 _iterator2.return();
11984 if (_didIteratorError2) {
11985 throw _iteratorError2;
11991 _didIteratorError = true;
11992 _iteratorError = err;
11995 if (!_iteratorNormalCompletion && _iterator.return != null) {
11996 _iterator.return();
11999 if (_didIteratorError) {
12000 throw _iteratorError;
12008 function resolveParser(opts, parsers) {
12009 parsers = parsers || getParsers(opts);
12011 if (typeof opts.parser === "function") {
12012 // Custom parser API always works with JavaScript.
12014 parse: opts.parser,
12015 astFormat: "estree",
12016 locStart: locStart$1,
12021 if (typeof opts.parser === "string") {
12022 if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) {
12023 return parsers[opts.parser];
12025 /* istanbul ignore next */
12029 throw new ConfigError$1("Couldn't resolve parser \"".concat(opts.parser, "\". Parsers must be explicitly added to the standalone bundle."));
12034 function parse(text, opts) {
12035 var parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
12036 // the parsers getters when actually calling the parser `parse` function.
12038 var parsersForCustomParserApi = Object.keys(parsers).reduce(function (object, parserName) {
12039 return Object.defineProperty(object, parserName, {
12041 get: function get() {
12042 return parsers[parserName].parse;
12046 var parser = resolveParser(opts, parsers);
12049 if (parser.preprocess) {
12050 text = parser.preprocess(text, opts);
12055 ast: parser.parse(text, parsersForCustomParserApi, opts)
12058 var loc = error.loc;
12061 var codeFrame = lib$2;
12062 error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
12063 highlightCode: true
12065 error.message += "\n" + error.codeFrame;
12068 /* istanbul ignore next */
12077 resolveParser: resolveParser
12080 var UndefinedParserError$1 = errors.UndefinedParserError;
12081 var getSupportInfo$1 = support.getSupportInfo;
12082 var resolveParser$1 = parser.resolveParser;
12083 var hiddenDefaults = {
12084 astFormat: "estree",
12086 originalText: undefined,
12089 }; // Copy options and fill in default values.
12091 function normalize$1(options, opts) {
12093 var rawOptions = Object.assign({}, options);
12094 var supportOptions = getSupportInfo$1(null, {
12095 plugins: options.plugins,
12096 showUnreleased: true,
12097 showDeprecated: true
12099 var defaults = supportOptions.reduce(function (reduced, optionInfo) {
12100 return optionInfo.default !== undefined ? Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo.default)) : reduced;
12101 }, Object.assign({}, hiddenDefaults));
12103 if (!rawOptions.parser) {
12104 if (!rawOptions.filepath) {
12105 var logger = opts.logger || console;
12106 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.");
12107 rawOptions.parser = "babel";
12109 rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
12111 if (!rawOptions.parser) {
12112 throw new UndefinedParserError$1("No parser could be inferred for file: ".concat(rawOptions.filepath));
12117 var parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(function (x) {
12118 return x.name === "parser";
12123 rawOptions.astFormat = parser.astFormat;
12124 rawOptions.locEnd = parser.locEnd;
12125 rawOptions.locStart = parser.locStart;
12126 var plugin = getPlugin(rawOptions);
12127 rawOptions.printer = plugin.printers[rawOptions.astFormat];
12128 var pluginDefaults = supportOptions.filter(function (optionInfo) {
12129 return optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined;
12130 }).reduce(function (reduced, optionInfo) {
12131 return Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo.pluginDefaults[plugin.name]));
12133 var mixedDefaults = Object.assign({}, defaults, pluginDefaults);
12134 Object.keys(mixedDefaults).forEach(function (k) {
12135 if (rawOptions[k] == null) {
12136 rawOptions[k] = mixedDefaults[k];
12140 if (rawOptions.parser === "json") {
12141 rawOptions.trailingComma = "none";
12144 return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
12145 passThrough: Object.keys(hiddenDefaults)
12149 function getPlugin(options) {
12150 var astFormat = options.astFormat;
12153 throw new Error("getPlugin() requires astFormat to be set");
12156 var printerPlugin = options.plugins.find(function (plugin) {
12157 return plugin.printers && plugin.printers[astFormat];
12160 if (!printerPlugin) {
12161 throw new Error("Couldn't find plugin for AST format \"".concat(astFormat, "\""));
12164 return printerPlugin;
12167 function getInterpreter(filepath) {
12168 if (typeof filepath !== "string") {
12175 fd = fs.openSync(filepath, "r");
12181 var liner = new readlines(fd);
12182 var firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
12184 var m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
12188 } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
12191 var m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
12199 // There are some weird cases where paths are missing, causing Jest
12200 // failures. It's unclear what these correspond to in the real world.
12204 // There are some weird cases where paths are missing, causing Jest
12205 // failures. It's unclear what these correspond to in the real world.
12207 } catch (err) {// nop
12212 function inferParser(filepath, plugins) {
12213 var filepathParts = normalizePath(filepath).split("/");
12214 var filename = filepathParts[filepathParts.length - 1].toLowerCase(); // If the file has no extension, we can try to infer the language from the
12215 // interpreter in the shebang line, if any; but since this requires FS access,
12218 var language = getSupportInfo$1(null, {
12220 }).languages.find(function (language) {
12221 return language.since !== null && (language.extensions && language.extensions.some(function (extension) {
12222 return filename.endsWith(extension);
12223 }) || language.filenames && language.filenames.find(function (name) {
12224 return name.toLowerCase() === filename;
12225 }) || filename.indexOf(".") === -1 && language.interpreters && language.interpreters.indexOf(getInterpreter(filepath)) !== -1);
12227 return language && language.parsers[0];
12231 normalize: normalize$1,
12232 hiddenDefaults: hiddenDefaults,
12233 inferParser: inferParser
12236 function massageAST(ast, options, parent) {
12237 if (Array.isArray(ast)) {
12238 return ast.map(function (e) {
12239 return massageAST(e, options, parent);
12240 }).filter(function (e) {
12245 if (!ast || _typeof(ast) !== "object") {
12251 for (var _i = 0, _Object$keys = Object.keys(ast); _i < _Object$keys.length; _i++) {
12252 var key = _Object$keys[_i];
12254 if (typeof ast[key] !== "function") {
12255 newObj[key] = massageAST(ast[key], options, ast);
12259 if (options.printer.massageAstNode) {
12260 var result = options.printer.massageAstNode(ast, newObj, parent);
12262 if (result === null) {
12274 var massageAst = massageAST;
12276 function assert() {}
12278 assert.ok = function () {};
12280 assert.strictEqual = function () {};
12283 * @param {Doc[]} parts
12288 function concat(parts) {
12289 // access the internals of a document directly.
12290 // if(parts.length === 1) {
12291 // // If it's a single document, no need to concat it.
12292 // return parts[0];
12302 * @param {Doc} contents
12307 function indent(contents) {
12315 * @param {number} n
12316 * @param {Doc} contents
12321 function align(n, contents) {
12325 contents: contents,
12330 * @param {Doc} contents
12331 * @param {object} [opts] - TBD ???
12336 function group(contents, opts) {
12342 contents: contents,
12343 break: !!opts.shouldBreak,
12344 expandedStates: opts.expandedStates
12348 * @param {Doc} contents
12353 function dedentToRoot(contents) {
12354 return align(-Infinity, contents);
12357 * @param {Doc} contents
12362 function markAsRoot(contents) {
12363 // @ts-ignore - TBD ???:
12369 * @param {Doc} contents
12374 function dedent(contents) {
12375 return align(-1, contents);
12378 * @param {Doc[]} states
12379 * @param {object} [opts] - TBD ???
12384 function conditionalGroup(states, opts) {
12385 return group(states[0], Object.assign(opts || {}, {
12386 expandedStates: states
12390 * @param {Doc[]} parts
12395 function fill(parts) {
12403 * @param {Doc} [breakContents]
12404 * @param {Doc} [flatContents]
12405 * @param {object} [opts] - TBD ???
12410 function ifBreak(breakContents, flatContents, opts) {
12415 breakContents: breakContents,
12416 flatContents: flatContents,
12417 groupId: opts.groupId
12421 * @param {Doc} contents
12426 function lineSuffix(contents) {
12429 type: "line-suffix",
12434 var lineSuffixBoundary = {
12435 type: "line-suffix-boundary"
12437 var breakParent = {
12438 type: "break-parent"
12450 var hardline = concat([{
12454 var literalline = concat([{
12461 placeholder: Symbol("cursor")
12465 * @param {Doc[]} arr
12469 function join(sep, arr) {
12472 for (var i = 0; i < arr.length; i++) {
12480 return concat(res);
12484 * @param {number} size
12485 * @param {number} tabWidth
12489 function addAlignmentToDoc(doc, size, tabWidth) {
12493 // Use indent to add tabs for all the levels of tabs we need
12494 for (var i = 0; i < Math.floor(size / tabWidth); ++i) {
12495 aligned = indent(aligned);
12496 } // Use align for all the spaces that are needed
12499 aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
12500 // indentation, so we use -Infinity to reset the indentation to 0
12502 aligned = align(-Infinity, aligned);
12508 var docBuilders = {
12512 softline: softline,
12513 hardline: hardline,
12514 literalline: literalline,
12516 conditionalGroup: conditionalGroup,
12518 lineSuffix: lineSuffix,
12519 lineSuffixBoundary: lineSuffixBoundary,
12521 breakParent: breakParent,
12526 addAlignmentToDoc: addAlignmentToDoc,
12527 markAsRoot: markAsRoot,
12528 dedentToRoot: dedentToRoot,
12532 var ansiRegex = function ansiRegex(options) {
12533 options = Object.assign({
12536 var pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
12537 return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
12540 var stripAnsi = function stripAnsi(string) {
12541 return typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
12544 var stripAnsi_1 = stripAnsi;
12545 var default_1$1 = stripAnsi;
12546 stripAnsi_1.default = default_1$1;
12548 /* eslint-disable yoda */
12550 var isFullwidthCodePoint = function isFullwidthCodePoint(codePoint) {
12551 if (Number.isNaN(codePoint)) {
12553 } // Code points are derived from:
12554 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
12557 if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
12558 codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
12559 codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
12560 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
12561 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
12562 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
12563 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
12564 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
12565 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
12566 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
12567 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
12568 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
12569 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
12570 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
12571 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
12572 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
12579 var isFullwidthCodePoint_1 = isFullwidthCodePoint;
12580 var default_1$2 = isFullwidthCodePoint;
12581 isFullwidthCodePoint_1.default = default_1$2;
12583 var emojiRegex = function emojiRegex() {
12584 // https://mths.be/emoji
12585 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;
12588 var stringWidth = function stringWidth(string) {
12589 string = string.replace(emojiRegex(), ' ');
12591 if (typeof string !== 'string' || string.length === 0) {
12595 string = stripAnsi_1(string);
12598 for (var i = 0; i < string.length; i++) {
12599 var code = string.codePointAt(i); // Ignore control characters
12601 if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
12603 } // Ignore combining characters
12606 if (code >= 0x300 && code <= 0x36F) {
12611 if (code > 0xFFFF) {
12615 width += isFullwidthCodePoint_1(code) ? 2 : 1;
12621 var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
12623 var default_1$3 = stringWidth;
12624 stringWidth_1.default = default_1$3;
12626 var notAsciiRegex = /[^\x20-\x7F]/;
12628 function isExportDeclaration(node) {
12630 switch (node.type) {
12631 case "ExportDefaultDeclaration":
12632 case "ExportDefaultSpecifier":
12633 case "DeclareExportDeclaration":
12634 case "ExportNamedDeclaration":
12635 case "ExportAllDeclaration":
12643 function getParentExportDeclaration(path) {
12644 var parentNode = path.getParentNode();
12646 if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
12653 function getPenultimate(arr) {
12654 if (arr.length > 1) {
12655 return arr[arr.length - 2];
12661 * @typedef {{backwards?: boolean}} SkipOptions
12665 * @param {string | RegExp} chars
12666 * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12670 function skip(chars) {
12671 return function (text, index, opts) {
12672 var backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
12673 // to check for failures (did someone say monads?).
12675 if (index === false) {
12679 var length = text.length;
12680 var cursor = index;
12682 while (cursor >= 0 && cursor < length) {
12683 var c = text.charAt(cursor);
12685 if (chars instanceof RegExp) {
12686 if (!chars.test(c)) {
12689 } else if (chars.indexOf(c) === -1) {
12693 backwards ? cursor-- : cursor++;
12696 if (cursor === -1 || cursor === length) {
12697 // If we reached the beginning or end of the file, return the
12698 // out-of-bounds cursor. It's up to the caller to handle this
12699 // correctly. We don't want to indicate `false` though if it
12700 // actually skipped valid characters.
12708 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12712 var skipWhitespace = skip(/\s/);
12714 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12717 var skipSpaces = skip(" \t");
12719 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12722 var skipToLineEnd = skip(",; \t");
12724 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12727 var skipEverythingButNewLine = skip(/[^\r\n]/);
12729 * @param {string} text
12730 * @param {number | false} index
12731 * @returns {number | false}
12734 function skipInlineComment(text, index) {
12735 if (index === false) {
12739 if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
12740 for (var i = index + 2; i < text.length; ++i) {
12741 if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
12750 * @param {string} text
12751 * @param {number | false} index
12752 * @returns {number | false}
12756 function skipTrailingComment(text, index) {
12757 if (index === false) {
12761 if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
12762 return skipEverythingButNewLine(text, index);
12766 } // This one doesn't use the above helper function because it wants to
12767 // test \r\n in order and `skip` doesn't support ordering and we only
12768 // want to skip one newline. It's simple to implement.
12771 * @param {string} text
12772 * @param {number | false} index
12773 * @param {SkipOptions=} opts
12774 * @returns {number | false}
12778 function skipNewline(text, index, opts) {
12779 var backwards = opts && opts.backwards;
12781 if (index === false) {
12785 var atIndex = text.charAt(index);
12788 if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
12792 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
12796 if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
12800 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
12808 * @param {string} text
12809 * @param {number} index
12810 * @param {SkipOptions=} opts
12811 * @returns {boolean}
12815 function hasNewline(text, index, opts) {
12817 var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
12818 var idx2 = skipNewline(text, idx, opts);
12819 return idx !== idx2;
12822 * @param {string} text
12823 * @param {number} start
12824 * @param {number} end
12825 * @returns {boolean}
12829 function hasNewlineInRange(text, start, end) {
12830 for (var i = start; i < end; ++i) {
12831 if (text.charAt(i) === "\n") {
12837 } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
12841 * @param {string} text
12843 * @param {(node: N) => number} locStart
12847 function isPreviousLineEmpty(text, node, locStart) {
12848 /** @type {number | false} */
12849 var idx = locStart(node) - 1;
12850 idx = skipSpaces(text, idx, {
12853 idx = skipNewline(text, idx, {
12856 idx = skipSpaces(text, idx, {
12859 var idx2 = skipNewline(text, idx, {
12862 return idx !== idx2;
12865 * @param {string} text
12866 * @param {number} index
12867 * @returns {boolean}
12871 function isNextLineEmptyAfterIndex(text, index) {
12872 /** @type {number | false} */
12874 /** @type {number | false} */
12878 while (idx !== oldIdx) {
12879 // We need to skip all the potential trailing inline comments
12881 idx = skipToLineEnd(text, idx);
12882 idx = skipInlineComment(text, idx);
12883 idx = skipSpaces(text, idx);
12886 idx = skipTrailingComment(text, idx);
12887 idx = skipNewline(text, idx);
12888 return idx !== false && hasNewline(text, idx);
12892 * @param {string} text
12894 * @param {(node: N) => number} locEnd
12895 * @returns {boolean}
12899 function isNextLineEmpty(text, node, locEnd) {
12900 return isNextLineEmptyAfterIndex(text, locEnd(node));
12903 * @param {string} text
12904 * @param {number} idx
12905 * @returns {number | false}
12909 function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
12910 /** @type {number | false} */
12912 /** @type {number | false} */
12916 while (nextIdx !== oldIdx) {
12918 nextIdx = skipSpaces(text, nextIdx);
12919 nextIdx = skipInlineComment(text, nextIdx);
12920 nextIdx = skipTrailingComment(text, nextIdx);
12921 nextIdx = skipNewline(text, nextIdx);
12928 * @param {string} text
12930 * @param {(node: N) => number} locEnd
12931 * @returns {number | false}
12935 function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
12936 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
12940 * @param {string} text
12942 * @param {(node: N) => number} locEnd
12943 * @returns {string}
12947 function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
12948 return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
12949 getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
12952 * @param {string} text
12953 * @param {number} index
12954 * @param {SkipOptions=} opts
12955 * @returns {boolean}
12959 function hasSpaces(text, index, opts) {
12961 var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
12962 return idx !== index;
12965 * @param {{range?: [number, number], start?: number}} node
12966 * @param {number} index
12970 function setLocStart(node, index) {
12972 node.range[0] = index;
12974 node.start = index;
12978 * @param {{range?: [number, number], end?: number}} node
12979 * @param {number} index
12983 function setLocEnd(node, index) {
12985 node.range[1] = index;
12991 var PRECEDENCE = {};
12992 [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach(function (tier, i) {
12993 tier.forEach(function (op) {
12994 PRECEDENCE[op] = i;
12998 function getPrecedence(op) {
12999 return PRECEDENCE[op];
13002 var equalityOperators = {
13008 var multiplicativeOperators = {
13013 var bitshiftOperators = {
13019 function shouldFlatten(parentOp, nodeOp) {
13020 if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
13022 } // ** is right-associative
13023 // x ** y ** z --> x ** (y ** z)
13026 if (parentOp === "**") {
13028 } // x == y == z --> (x == y) == z
13031 if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
13033 } // x * y % z --> (x * y) % z
13036 if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
13038 } // x * y / z --> (x * y) / z
13039 // x / y * z --> (x / y) * z
13042 if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
13044 } // x << y << z --> (x << y) << z
13047 if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
13054 function isBitwiseOperator(operator) {
13055 return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
13056 } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
13057 // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
13058 // already necessary grouping parentheses.
13061 function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
13062 node = getLeftMost(node);
13064 switch (node.type) {
13065 case "FunctionExpression":
13066 case "ClassExpression":
13067 case "DoExpression":
13068 return forbidFunctionClassAndDoExpr;
13070 case "ObjectExpression":
13073 case "MemberExpression":
13074 case "OptionalMemberExpression":
13075 return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
13077 case "TaggedTemplateExpression":
13078 if (node.tag.type === "FunctionExpression") {
13079 // IIFEs are always already parenthesized
13083 return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
13085 case "CallExpression":
13086 case "OptionalCallExpression":
13087 if (node.callee.type === "FunctionExpression") {
13088 // IIFEs are always already parenthesized
13092 return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
13094 case "ConditionalExpression":
13095 return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
13097 case "UpdateExpression":
13098 return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
13100 case "BindExpression":
13101 return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
13103 case "SequenceExpression":
13104 return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
13106 case "TSAsExpression":
13107 return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
13114 function getLeftMost(node) {
13116 return getLeftMost(node.left);
13122 * @param {string} value
13123 * @param {number} tabWidth
13124 * @param {number=} startIndex
13125 * @returns {number}
13129 function getAlignmentSize(value, tabWidth, startIndex) {
13130 startIndex = startIndex || 0;
13133 for (var i = startIndex; i < value.length; ++i) {
13134 if (value[i] === "\t") {
13135 // Tabs behave in a way that they are aligned to the nearest
13136 // multiple of tabWidth:
13137 // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
13138 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
13139 size = size + tabWidth - size % tabWidth;
13148 * @param {string} value
13149 * @param {number} tabWidth
13150 * @returns {number}
13154 function getIndentSize(value, tabWidth) {
13155 var lastNewlineIndex = value.lastIndexOf("\n");
13157 if (lastNewlineIndex === -1) {
13161 return getAlignmentSize( // All the leading whitespaces
13162 value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
13165 * @typedef {'"' | "'"} Quote
13170 * @param {string} raw
13171 * @param {Quote} preferredQuote
13176 function getPreferredQuote(raw, preferredQuote) {
13177 // `rawContent` is the string exactly like it appeared in the input source
13178 // code, without its enclosing quotes.
13179 var rawContent = raw.slice(1, -1);
13180 /** @type {{ quote: '"', regex: RegExp }} */
13186 /** @type {{ quote: "'", regex: RegExp }} */
13192 var preferred = preferredQuote === "'" ? single : double;
13193 var alternate = preferred === single ? double : single;
13194 var result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
13195 // the string, we might want to enclose with the alternate quote instead, to
13196 // minimize the number of escaped quotes.
13198 if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
13199 var numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
13200 var numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
13201 result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
13207 function printString(raw, options, isDirectiveLiteral) {
13208 // `rawContent` is the string exactly like it appeared in the input source
13209 // code, without its enclosing quotes.
13210 var rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
13211 // the quotes on a DirectiveLiteral.
13213 var canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
13214 /** @type {Quote} */
13216 var enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
13217 // change the escape sequences they use.
13218 // See https://github.com/prettier/prettier/issues/1555
13219 // and https://tc39.github.io/ecma262/#directive-prologue
13221 if (isDirectiveLiteral) {
13222 if (canChangeDirectiveQuotes) {
13223 return enclosingQuote + rawContent + enclosingQuote;
13227 } // It might sound unnecessary to use `makeString` even if the string already
13228 // is enclosed with `enclosingQuote`, but it isn't. The string could contain
13229 // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
13230 // sure that we consistently output the minimum amount of escaped quotes.
13233 return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
13236 * @param {string} rawContent
13237 * @param {Quote} enclosingQuote
13238 * @param {boolean=} unescapeUnnecessaryEscapes
13239 * @returns {string}
13243 function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
13244 var otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
13246 var regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
13247 // enclose `rawContent` with `enclosingQuote`.
13249 var newContent = rawContent.replace(regex, function (match, escaped, quote) {
13250 // If we matched an escape, and the escaped character is a quote of the
13251 // other type than we intend to enclose the string with, there's no need for
13252 // it to be escaped, so return it _without_ the backslash.
13253 if (escaped === otherQuote) {
13255 } // If we matched an unescaped quote and it is of the _same_ type as we
13256 // intend to enclose the string with, it must be escaped, so return it with
13260 if (quote === enclosingQuote) {
13261 return "\\" + quote;
13266 } // Unescape any unnecessarily escaped character.
13267 // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
13270 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
13272 return enclosingQuote + newContent + enclosingQuote;
13275 function printNumber(rawNumber) {
13276 return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
13277 .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
13278 .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
13279 .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
13280 .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
13281 .replace(/\.(?=e|$)/, "");
13284 * @param {string} str
13285 * @param {string} target
13286 * @returns {number}
13290 function getMaxContinuousCount(str, target) {
13291 var results = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g"));
13293 if (results === null) {
13297 return results.reduce(function (maxCount, result) {
13298 return Math.max(maxCount, result.length / target.length);
13302 function getMinNotPresentContinuousCount(str, target) {
13303 var matches = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g"));
13305 if (matches === null) {
13309 var countPresent = new Map();
13311 var _iteratorNormalCompletion = true;
13312 var _didIteratorError = false;
13313 var _iteratorError = undefined;
13316 for (var _iterator = matches[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
13317 var match = _step.value;
13318 var count = match.length / target.length;
13319 countPresent.set(count, true);
13326 _didIteratorError = true;
13327 _iteratorError = err;
13330 if (!_iteratorNormalCompletion && _iterator.return != null) {
13331 _iterator.return();
13334 if (_didIteratorError) {
13335 throw _iteratorError;
13340 for (var i = 1; i < max; i++) {
13341 if (!countPresent.get(i)) {
13349 * @param {string} text
13350 * @returns {number}
13354 function getStringWidth(text) {
13357 } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
13360 if (!notAsciiRegex.test(text)) {
13361 return text.length;
13364 return stringWidth_1(text);
13367 function hasIgnoreComment(path) {
13368 var node = path.getValue();
13369 return hasNodeIgnoreComment(node);
13372 function hasNodeIgnoreComment(node) {
13373 return node && node.comments && node.comments.length > 0 && node.comments.some(function (comment) {
13374 return comment.value.trim() === "prettier-ignore";
13378 function matchAncestorTypes(path, types, index) {
13379 index = index || 0;
13380 types = types.slice();
13382 while (types.length) {
13383 var parent = path.getParentNode(index);
13384 var type = types.shift();
13386 if (!parent || parent.type !== type) {
13396 function addCommentHelper(node, comment) {
13397 var comments = node.comments || (node.comments = []);
13398 comments.push(comment);
13399 comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
13400 // We already "print" it via the raw text, we don't need to re-print it as a
13403 if (node.type === "JSXText") {
13404 comment.printed = true;
13408 function addLeadingComment(node, comment) {
13409 comment.leading = true;
13410 comment.trailing = false;
13411 addCommentHelper(node, comment);
13414 function addDanglingComment(node, comment) {
13415 comment.leading = false;
13416 comment.trailing = false;
13417 addCommentHelper(node, comment);
13420 function addTrailingComment(node, comment) {
13421 comment.leading = false;
13422 comment.trailing = true;
13423 addCommentHelper(node, comment);
13426 function isWithinParentArrayProperty(path, propertyName) {
13427 var node = path.getValue();
13428 var parent = path.getParentNode();
13430 if (parent == null) {
13434 if (!Array.isArray(parent[propertyName])) {
13438 var key = path.getName();
13439 return parent[propertyName][key] === node;
13442 function replaceEndOfLineWith(text, replacement) {
13444 var _iteratorNormalCompletion2 = true;
13445 var _didIteratorError2 = false;
13446 var _iteratorError2 = undefined;
13449 for (var _iterator2 = text.split("\n")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
13450 var part = _step2.value;
13452 if (parts.length !== 0) {
13453 parts.push(replacement);
13459 _didIteratorError2 = true;
13460 _iteratorError2 = err;
13463 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
13464 _iterator2.return();
13467 if (_didIteratorError2) {
13468 throw _iteratorError2;
13477 replaceEndOfLineWith: replaceEndOfLineWith,
13478 getStringWidth: getStringWidth,
13479 getMaxContinuousCount: getMaxContinuousCount,
13480 getMinNotPresentContinuousCount: getMinNotPresentContinuousCount,
13481 getPrecedence: getPrecedence,
13482 shouldFlatten: shouldFlatten,
13483 isBitwiseOperator: isBitwiseOperator,
13484 isExportDeclaration: isExportDeclaration,
13485 getParentExportDeclaration: getParentExportDeclaration,
13486 getPenultimate: getPenultimate,
13488 getNextNonSpaceNonCommentCharacterIndexWithStartIndex: getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
13489 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex,
13490 getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter,
13492 skipWhitespace: skipWhitespace,
13493 skipSpaces: skipSpaces,
13494 skipToLineEnd: skipToLineEnd,
13495 skipEverythingButNewLine: skipEverythingButNewLine,
13496 skipInlineComment: skipInlineComment,
13497 skipTrailingComment: skipTrailingComment,
13498 skipNewline: skipNewline,
13499 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex,
13500 isNextLineEmpty: isNextLineEmpty,
13501 isPreviousLineEmpty: isPreviousLineEmpty,
13502 hasNewline: hasNewline,
13503 hasNewlineInRange: hasNewlineInRange,
13504 hasSpaces: hasSpaces,
13505 setLocStart: setLocStart,
13506 setLocEnd: setLocEnd,
13507 startsWithNoLookaheadToken: startsWithNoLookaheadToken,
13508 getAlignmentSize: getAlignmentSize,
13509 getIndentSize: getIndentSize,
13510 getPreferredQuote: getPreferredQuote,
13511 printString: printString,
13512 printNumber: printNumber,
13513 hasIgnoreComment: hasIgnoreComment,
13514 hasNodeIgnoreComment: hasNodeIgnoreComment,
13515 makeString: makeString,
13516 matchAncestorTypes: matchAncestorTypes,
13517 addLeadingComment: addLeadingComment,
13518 addDanglingComment: addDanglingComment,
13519 addTrailingComment: addTrailingComment,
13520 isWithinParentArrayProperty: isWithinParentArrayProperty
13523 function guessEndOfLine(text) {
13524 var index = text.indexOf("\r");
13527 return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
13533 function convertEndOfLineToChars(value) {
13547 guessEndOfLine: guessEndOfLine,
13548 convertEndOfLineToChars: convertEndOfLineToChars
13551 var getStringWidth$1 = util.getStringWidth;
13552 var convertEndOfLineToChars$1 = endOfLine.convertEndOfLineToChars;
13553 var concat$1 = docBuilders.concat,
13554 fill$1 = docBuilders.fill,
13555 cursor$1 = docBuilders.cursor;
13556 /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
13559 var MODE_BREAK = 1;
13562 function rootIndent() {
13570 function makeIndent(ind, options) {
13571 return generateInd(ind, {
13576 function makeAlign(ind, n, options) {
13577 return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
13579 }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
13581 }) : typeof n === "string" ? generateInd(ind, {
13582 type: "stringAlign",
13584 }, options) : generateInd(ind, {
13585 type: "numberAlign",
13590 function generateInd(ind, newPart, options) {
13591 var queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
13595 var lastSpaces = 0;
13596 var _iteratorNormalCompletion = true;
13597 var _didIteratorError = false;
13598 var _iteratorError = undefined;
13601 for (var _iterator = queue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
13602 var part = _step.value;
13604 switch (part.type) {
13608 if (options.useTabs) {
13611 addSpaces(options.tabWidth);
13616 case "stringAlign":
13619 length += part.n.length;
13622 case "numberAlign":
13624 lastSpaces += part.n;
13627 /* istanbul ignore next */
13630 throw new Error("Unexpected type '".concat(part.type, "'"));
13634 _didIteratorError = true;
13635 _iteratorError = err;
13638 if (!_iteratorNormalCompletion && _iterator.return != null) {
13639 _iterator.return();
13642 if (_didIteratorError) {
13643 throw _iteratorError;
13649 return Object.assign({}, ind, {
13655 function addTabs(count) {
13656 value += "\t".repeat(count);
13657 length += options.tabWidth * count;
13660 function addSpaces(count) {
13661 value += " ".repeat(count);
13666 if (options.useTabs) {
13673 function flushTabs() {
13674 if (lastTabs > 0) {
13681 function flushSpaces() {
13682 if (lastSpaces > 0) {
13683 addSpaces(lastSpaces);
13689 function resetLast() {
13695 function trim$1(out) {
13696 if (out.length === 0) {
13700 var trimCount = 0; // Trim whitespace at the end of line
13702 while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
13703 trimCount += out.pop().length;
13706 if (out.length && typeof out[out.length - 1] === "string") {
13707 var trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
13708 trimCount += out[out.length - 1].length - trimmed.length;
13709 out[out.length - 1] = trimmed;
13715 function fits(next, restCommands, width, options, mustBeFlat) {
13716 var restIdx = restCommands.length;
13717 var cmds = [next]; // `out` is only used for width counting because `trim` requires to look
13718 // backwards for space characters.
13722 while (width >= 0) {
13723 if (cmds.length === 0) {
13724 if (restIdx === 0) {
13728 cmds.push(restCommands[restIdx - 1]);
13733 var x = cmds.pop();
13738 if (typeof doc === "string") {
13740 width -= getStringWidth$1(doc);
13742 switch (doc.type) {
13744 for (var i = doc.parts.length - 1; i >= 0; i--) {
13745 cmds.push([ind, mode, doc.parts[i]]);
13751 cmds.push([makeIndent(ind, options), mode, doc.contents]);
13755 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
13759 width += trim$1(out);
13763 if (mustBeFlat && doc.break) {
13767 cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
13770 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
13776 for (var _i = doc.parts.length - 1; _i >= 0; _i--) {
13777 cmds.push([ind, mode, doc.parts[_i]]);
13784 var groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
13786 if (groupMode === MODE_BREAK) {
13787 if (doc.breakContents) {
13788 cmds.push([ind, mode, doc.breakContents]);
13792 if (groupMode === MODE_FLAT) {
13793 if (doc.flatContents) {
13794 cmds.push([ind, mode, doc.flatContents]);
13828 function printDocToString(doc, options) {
13830 var width = options.printWidth;
13831 var newLine = convertEndOfLineToChars$1(options.endOfLine);
13832 var pos = 0; // cmds is basically a stack. We've turned a recursive call into a
13833 // while loop which is much faster. The while loop below adds new
13834 // cmds to the array instead of recursively calling `print`.
13836 var cmds = [[rootIndent(), MODE_BREAK, doc]];
13838 var shouldRemeasure = false;
13839 var lineSuffix = [];
13841 while (cmds.length !== 0) {
13842 var x = cmds.pop();
13847 if (typeof _doc === "string") {
13849 pos += getStringWidth$1(_doc);
13851 switch (_doc.type) {
13853 out.push(cursor$1.placeholder);
13857 for (var i = _doc.parts.length - 1; i >= 0; i--) {
13858 cmds.push([ind, mode, _doc.parts[i]]);
13864 cmds.push([makeIndent(ind, options), mode, _doc.contents]);
13868 cmds.push([makeAlign(ind, _doc.n, options), mode, _doc.contents]);
13872 pos -= trim$1(out);
13878 if (!shouldRemeasure) {
13879 cmds.push([ind, _doc.break ? MODE_BREAK : MODE_FLAT, _doc.contents]);
13887 shouldRemeasure = false;
13888 var next = [ind, MODE_FLAT, _doc.contents];
13889 var rem = width - pos;
13891 if (!_doc.break && fits(next, cmds, rem, options)) {
13894 // Expanded states are a rare case where a document
13895 // can manually provide multiple representations of
13896 // itself. It provides an array of documents
13897 // going from the least expanded (most flattened)
13898 // representation first to the most expanded. If a
13899 // group has these, we need to manually go through
13900 // these states and find the first one that fits.
13901 if (_doc.expandedStates) {
13902 var mostExpanded = _doc.expandedStates[_doc.expandedStates.length - 1];
13905 cmds.push([ind, MODE_BREAK, mostExpanded]);
13908 for (var _i2 = 1; _i2 < _doc.expandedStates.length + 1; _i2++) {
13909 if (_i2 >= _doc.expandedStates.length) {
13910 cmds.push([ind, MODE_BREAK, mostExpanded]);
13913 var state = _doc.expandedStates[_i2];
13914 var cmd = [ind, MODE_FLAT, state];
13916 if (fits(cmd, cmds, rem, options)) {
13924 cmds.push([ind, MODE_BREAK, _doc.contents]);
13933 groupModeMap[_doc.id] = cmds[cmds.length - 1][1];
13937 // Fills each line with as much code as possible before moving to a new
13938 // line with the same indentation.
13940 // Expects doc.parts to be an array of alternating content and
13941 // whitespace. The whitespace contains the linebreaks.
13944 // ["I", line, "love", line, "monkeys"]
13946 // [{ type: group, ... }, softline, { type: group, ... }]
13948 // It uses this parts structure to handle three main layout cases:
13949 // * The first two content items fit on the same line without
13951 // -> output the first content item and the whitespace "flat".
13952 // * Only the first content item fits on the line without breaking
13953 // -> output the first content item "flat" and the whitespace with
13955 // * Neither content item fits on the line without breaking
13956 // -> output the first content item and the whitespace with "break".
13960 var _rem = width - pos;
13962 var parts = _doc.parts;
13964 if (parts.length === 0) {
13968 var content = parts[0];
13969 var contentFlatCmd = [ind, MODE_FLAT, content];
13970 var contentBreakCmd = [ind, MODE_BREAK, content];
13971 var contentFits = fits(contentFlatCmd, [], _rem, options, true);
13973 if (parts.length === 1) {
13975 cmds.push(contentFlatCmd);
13977 cmds.push(contentBreakCmd);
13983 var whitespace = parts[1];
13984 var whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
13985 var whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
13987 if (parts.length === 2) {
13989 cmds.push(whitespaceFlatCmd);
13990 cmds.push(contentFlatCmd);
13992 cmds.push(whitespaceBreakCmd);
13993 cmds.push(contentBreakCmd);
13997 } // At this point we've handled the first pair (context, separator)
13998 // and will create a new fill doc for the rest of the content.
13999 // Ideally we wouldn't mutate the array here but coping all the
14000 // elements to a new array would make this algorithm quadratic,
14001 // which is unusable for large arrays (e.g. large texts in JSX).
14004 parts.splice(0, 2);
14005 var remainingCmd = [ind, mode, fill$1(parts)];
14006 var secondContent = parts[0];
14007 var firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
14008 var firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], _rem, options, true);
14010 if (firstAndSecondContentFits) {
14011 cmds.push(remainingCmd);
14012 cmds.push(whitespaceFlatCmd);
14013 cmds.push(contentFlatCmd);
14014 } else if (contentFits) {
14015 cmds.push(remainingCmd);
14016 cmds.push(whitespaceBreakCmd);
14017 cmds.push(contentFlatCmd);
14019 cmds.push(remainingCmd);
14020 cmds.push(whitespaceBreakCmd);
14021 cmds.push(contentBreakCmd);
14029 var groupMode = _doc.groupId ? groupModeMap[_doc.groupId] : mode;
14031 if (groupMode === MODE_BREAK) {
14032 if (_doc.breakContents) {
14033 cmds.push([ind, mode, _doc.breakContents]);
14037 if (groupMode === MODE_FLAT) {
14038 if (_doc.flatContents) {
14039 cmds.push([ind, mode, _doc.flatContents]);
14046 case "line-suffix":
14047 lineSuffix.push([ind, mode, _doc.contents]);
14050 case "line-suffix-boundary":
14051 if (lineSuffix.length > 0) {
14052 cmds.push([ind, mode, {
14071 // This line was forced into the output even if we
14072 // were in flattened mode, so we need to tell the next
14073 // group that no matter what, it needs to remeasure
14074 // because the previous measurement didn't accurately
14075 // capture the entire expression (this is necessary
14076 // for nested groups)
14077 shouldRemeasure = true;
14083 if (lineSuffix.length) {
14084 cmds.push([ind, mode, _doc]);
14085 [].push.apply(cmds, lineSuffix.reverse());
14090 if (_doc.literal) {
14092 out.push(newLine, ind.root.value);
14093 pos = ind.root.length;
14099 pos -= trim$1(out);
14100 out.push(newLine + ind.value);
14112 var cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
14114 if (cursorPlaceholderIndex !== -1) {
14115 var otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
14116 var beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
14117 var aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
14118 var afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
14120 formatted: beforeCursor + aroundCursor + afterCursor,
14121 cursorNodeStart: beforeCursor.length,
14122 cursorNodeText: aroundCursor
14127 formatted: out.join("")
14132 printDocToString: printDocToString
14135 var traverseDocOnExitStackMarker = {};
14137 function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
14138 var docsStack = [doc];
14140 while (docsStack.length !== 0) {
14141 var _doc = docsStack.pop();
14143 if (_doc === traverseDocOnExitStackMarker) {
14144 onExit(docsStack.pop());
14148 var shouldRecurse = true;
14151 if (onEnter(_doc) === false) {
14152 shouldRecurse = false;
14157 docsStack.push(_doc);
14158 docsStack.push(traverseDocOnExitStackMarker);
14161 if (shouldRecurse) {
14162 // When there are multiple parts to process,
14163 // the parts need to be pushed onto the stack in reverse order,
14164 // so that they are processed in the original order
14165 // when the stack is popped.
14166 if (_doc.type === "concat" || _doc.type === "fill") {
14167 for (var ic = _doc.parts.length, i = ic - 1; i >= 0; --i) {
14168 docsStack.push(_doc.parts[i]);
14170 } else if (_doc.type === "if-break") {
14171 if (_doc.flatContents) {
14172 docsStack.push(_doc.flatContents);
14175 if (_doc.breakContents) {
14176 docsStack.push(_doc.breakContents);
14178 } else if (_doc.type === "group" && _doc.expandedStates) {
14179 if (shouldTraverseConditionalGroups) {
14180 for (var _ic = _doc.expandedStates.length, _i = _ic - 1; _i >= 0; --_i) {
14181 docsStack.push(_doc.expandedStates[_i]);
14184 docsStack.push(_doc.contents);
14186 } else if (_doc.contents) {
14187 docsStack.push(_doc.contents);
14193 function mapDoc(doc, cb) {
14194 if (doc.type === "concat" || doc.type === "fill") {
14195 var parts = doc.parts.map(function (part) {
14196 return mapDoc(part, cb);
14198 return cb(Object.assign({}, doc, {
14201 } else if (doc.type === "if-break") {
14202 var breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
14203 var flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
14204 return cb(Object.assign({}, doc, {
14205 breakContents: breakContents,
14206 flatContents: flatContents
14208 } else if (doc.contents) {
14209 var contents = mapDoc(doc.contents, cb);
14210 return cb(Object.assign({}, doc, {
14218 function findInDoc(doc, fn, defaultValue) {
14219 var result = defaultValue;
14220 var hasStopped = false;
14222 function findInDocOnEnterFn(doc) {
14223 var maybeResult = fn(doc);
14225 if (maybeResult !== undefined) {
14227 result = maybeResult;
14235 traverseDoc(doc, findInDocOnEnterFn);
14239 function isEmpty(n) {
14240 return typeof n === "string" && n.length === 0;
14243 function isLineNextFn(doc) {
14244 if (typeof doc === "string") {
14248 if (doc.type === "line") {
14253 function isLineNext(doc) {
14254 return findInDoc(doc, isLineNextFn, false);
14257 function willBreakFn(doc) {
14258 if (doc.type === "group" && doc.break) {
14262 if (doc.type === "line" && doc.hard) {
14266 if (doc.type === "break-parent") {
14271 function willBreak(doc) {
14272 return findInDoc(doc, willBreakFn, false);
14275 function breakParentGroup(groupStack) {
14276 if (groupStack.length > 0) {
14277 var parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
14278 // the user is expected to manually handle what breaks.
14280 if (!parentGroup.expandedStates) {
14281 parentGroup.break = true;
14288 function propagateBreaks(doc) {
14289 var alreadyVisitedSet = new Set();
14290 var groupStack = [];
14292 function propagateBreaksOnEnterFn(doc) {
14293 if (doc.type === "break-parent") {
14294 breakParentGroup(groupStack);
14297 if (doc.type === "group") {
14298 groupStack.push(doc);
14300 if (alreadyVisitedSet.has(doc)) {
14304 alreadyVisitedSet.add(doc);
14308 function propagateBreaksOnExitFn(doc) {
14309 if (doc.type === "group") {
14310 var group = groupStack.pop();
14313 breakParentGroup(groupStack);
14318 traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
14319 /* shouldTraverseConditionalGroups */
14323 function removeLinesFn(doc) {
14324 // Force this doc into flat mode by statically converting all
14325 // lines into spaces (or soft lines into nothing). Hard lines
14326 // should still output because there's too great of a chance
14327 // of breaking existing assumptions otherwise.
14328 if (doc.type === "line" && !doc.hard) {
14329 return doc.soft ? "" : " ";
14330 } else if (doc.type === "if-break") {
14331 return doc.flatContents || "";
14337 function removeLines(doc) {
14338 return mapDoc(doc, removeLinesFn);
14341 function stripTrailingHardline(doc) {
14342 // HACK remove ending hardline, original PR: #1984
14343 if (doc.type === "concat" && doc.parts.length !== 0) {
14344 var lastPart = doc.parts[doc.parts.length - 1];
14346 if (lastPart.type === "concat") {
14347 if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
14350 parts: doc.parts.slice(0, -1)
14356 parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
14366 willBreak: willBreak,
14367 isLineNext: isLineNext,
14368 traverseDoc: traverseDoc,
14369 findInDoc: findInDoc,
14371 propagateBreaks: propagateBreaks,
14372 removeLines: removeLines,
14373 stripTrailingHardline: stripTrailingHardline
14376 function flattenDoc(doc) {
14377 if (doc.type === "concat") {
14380 for (var i = 0; i < doc.parts.length; ++i) {
14381 var doc2 = doc.parts[i];
14383 if (typeof doc2 !== "string" && doc2.type === "concat") {
14384 [].push.apply(res, flattenDoc(doc2).parts);
14386 var flattened = flattenDoc(doc2);
14388 if (flattened !== "") {
14389 res.push(flattened);
14394 return Object.assign({}, doc, {
14397 } else if (doc.type === "if-break") {
14398 return Object.assign({}, doc, {
14399 breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
14400 flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
14402 } else if (doc.type === "group") {
14403 return Object.assign({}, doc, {
14404 contents: flattenDoc(doc.contents),
14405 expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
14407 } else if (doc.contents) {
14408 return Object.assign({}, doc, {
14409 contents: flattenDoc(doc.contents)
14416 function printDoc(doc) {
14417 if (typeof doc === "string") {
14418 return JSON.stringify(doc);
14421 if (doc.type === "line") {
14423 return "literalline";
14437 if (doc.type === "break-parent") {
14438 return "breakParent";
14441 if (doc.type === "trim") {
14445 if (doc.type === "concat") {
14446 return "[" + doc.parts.map(printDoc).join(", ") + "]";
14449 if (doc.type === "indent") {
14450 return "indent(" + printDoc(doc.contents) + ")";
14453 if (doc.type === "align") {
14454 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) + ")";
14457 if (doc.type === "if-break") {
14458 return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
14461 if (doc.type === "group") {
14462 if (doc.expandedStates) {
14463 return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
14466 return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
14469 if (doc.type === "fill") {
14470 return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
14473 if (doc.type === "line-suffix") {
14474 return "lineSuffix(" + printDoc(doc.contents) + ")";
14477 if (doc.type === "line-suffix-boundary") {
14478 return "lineSuffixBoundary";
14481 throw new Error("Unknown doc type " + doc.type);
14485 printDocToDebug: function printDocToDebug(doc) {
14486 return printDoc(flattenDoc(doc));
14491 builders: docBuilders,
14492 printer: docPrinter,
14497 var mapDoc$1 = doc.utils.mapDoc;
14499 function isNextLineEmpty$1(text, node, options) {
14500 return util.isNextLineEmpty(text, node, options.locEnd);
14503 function isPreviousLineEmpty$1(text, node, options) {
14504 return util.isPreviousLineEmpty(text, node, options.locStart);
14507 function getNextNonSpaceNonCommentCharacterIndex$1(text, node, options) {
14508 return util.getNextNonSpaceNonCommentCharacterIndex(text, node, options.locEnd);
14512 getMaxContinuousCount: util.getMaxContinuousCount,
14513 getStringWidth: util.getStringWidth,
14514 getAlignmentSize: util.getAlignmentSize,
14515 getIndentSize: util.getIndentSize,
14517 skipWhitespace: util.skipWhitespace,
14518 skipSpaces: util.skipSpaces,
14519 skipNewline: util.skipNewline,
14520 skipToLineEnd: util.skipToLineEnd,
14521 skipEverythingButNewLine: util.skipEverythingButNewLine,
14522 skipInlineComment: util.skipInlineComment,
14523 skipTrailingComment: util.skipTrailingComment,
14524 hasNewline: util.hasNewline,
14525 hasNewlineInRange: util.hasNewlineInRange,
14526 hasSpaces: util.hasSpaces,
14527 isNextLineEmpty: isNextLineEmpty$1,
14528 isNextLineEmptyAfterIndex: util.isNextLineEmptyAfterIndex,
14529 isPreviousLineEmpty: isPreviousLineEmpty$1,
14530 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
14532 // TODO: remove in 2.0, we already exposed it in docUtils
14533 makeString: util.makeString,
14534 addLeadingComment: util.addLeadingComment,
14535 addDanglingComment: util.addDanglingComment,
14536 addTrailingComment: util.addTrailingComment
14539 var _require$$0$builders = doc.builders,
14540 concat$2 = _require$$0$builders.concat,
14541 hardline$1 = _require$$0$builders.hardline,
14542 breakParent$1 = _require$$0$builders.breakParent,
14543 indent$1 = _require$$0$builders.indent,
14544 lineSuffix$1 = _require$$0$builders.lineSuffix,
14545 join$1 = _require$$0$builders.join,
14546 cursor$2 = _require$$0$builders.cursor;
14547 var hasNewline$1 = util.hasNewline,
14548 skipNewline$1 = util.skipNewline,
14549 isPreviousLineEmpty$2 = util.isPreviousLineEmpty;
14550 var addLeadingComment$1 = utilShared.addLeadingComment,
14551 addDanglingComment$1 = utilShared.addDanglingComment,
14552 addTrailingComment$1 = utilShared.addTrailingComment;
14553 var childNodesCacheKey = Symbol("child-nodes");
14555 function getSortedChildNodes(node, options, resultArray) {
14560 var printer = options.printer,
14561 locStart = options.locStart,
14562 locEnd = options.locEnd;
14565 if (node && printer.canAttachComment && printer.canAttachComment(node)) {
14566 // This reverse insertion sort almost always takes constant
14567 // time because we almost always (maybe always?) append the
14568 // nodes in order anyway.
14571 for (i = resultArray.length - 1; i >= 0; --i) {
14572 if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
14577 resultArray.splice(i + 1, 0, node);
14580 } else if (node[childNodesCacheKey]) {
14581 return node[childNodesCacheKey];
14586 if (printer.getCommentChildNodes) {
14587 childNodes = printer.getCommentChildNodes(node);
14588 } else if (node && _typeof(node) === "object") {
14589 childNodes = Object.keys(node).filter(function (n) {
14590 return n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode";
14591 }).map(function (n) {
14600 if (!resultArray) {
14601 Object.defineProperty(node, childNodesCacheKey, {
14602 value: resultArray = [],
14607 childNodes.forEach(function (childNode) {
14608 getSortedChildNodes(childNode, options, resultArray);
14610 return resultArray;
14611 } // As efficiently as possible, decorate the comment object with
14612 // .precedingNode, .enclosingNode, and/or .followingNode properties, at
14613 // least one of which is guaranteed to be defined.
14616 function decorateComment(node, comment, options) {
14617 var locStart = options.locStart,
14618 locEnd = options.locEnd;
14619 var childNodes = getSortedChildNodes(node, options);
14621 var followingNode; // Time to dust off the old binary search robes and wizard hat.
14624 var right = childNodes.length;
14626 while (left < right) {
14627 var middle = left + right >> 1;
14628 var child = childNodes[middle];
14630 if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) {
14631 // The comment is completely contained by this child node.
14632 comment.enclosingNode = child;
14633 decorateComment(child, comment, options);
14634 return; // Abandon the binary search at this level.
14637 if (locEnd(child) - locStart(comment) <= 0) {
14638 // This child node falls completely before the comment.
14639 // Because we will never consider this node or any nodes
14640 // before it again, this node must be the closest preceding
14641 // node we have encountered so far.
14642 precedingNode = child;
14647 if (locEnd(comment) - locStart(child) <= 0) {
14648 // This child node falls completely after the comment.
14649 // Because we will never consider this node or any nodes after
14650 // it again, this node must be the closest following node we
14651 // have encountered so far.
14652 followingNode = child;
14656 /* istanbul ignore next */
14659 throw new Error("Comment location overlaps with node location");
14660 } // We don't want comments inside of different expressions inside of the same
14661 // template literal to move to another expression.
14664 if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
14665 var quasis = comment.enclosingNode.quasis;
14666 var commentIndex = findExpressionIndexForComment(quasis, comment, options);
14668 if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
14669 precedingNode = null;
14672 if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
14673 followingNode = null;
14677 if (precedingNode) {
14678 comment.precedingNode = precedingNode;
14681 if (followingNode) {
14682 comment.followingNode = followingNode;
14686 function attach(comments, ast, text, options) {
14687 if (!Array.isArray(comments)) {
14691 var tiesToBreak = [];
14692 var locStart = options.locStart,
14693 locEnd = options.locEnd;
14694 comments.forEach(function (comment, i) {
14695 if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
14696 if (locStart(comment) - locStart(ast) <= 0) {
14697 addLeadingComment$1(ast, comment);
14701 if (locEnd(comment) - locEnd(ast) >= 0) {
14702 addTrailingComment$1(ast, comment);
14707 decorateComment(ast, comment, options);
14708 var precedingNode = comment.precedingNode,
14709 enclosingNode = comment.enclosingNode,
14710 followingNode = comment.followingNode;
14711 var pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : function () {
14714 var pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : function () {
14717 var pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : function () {
14720 var isLastComment = comments.length - 1 === i;
14722 if (hasNewline$1(text, locStart(comment), {
14725 // If a comment exists on its own line, prefer a leading comment.
14726 // We also need to check if it's the first line of the file.
14727 if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) {
14728 // Always a leading comment.
14729 addLeadingComment$1(followingNode, comment);
14730 } else if (precedingNode) {
14731 addTrailingComment$1(precedingNode, comment);
14732 } else if (enclosingNode) {
14733 addDanglingComment$1(enclosingNode, comment);
14735 // There are no nodes, let's attach it to the root of the ast
14737 /* istanbul ignore next */
14738 addDanglingComment$1(ast, comment);
14740 } else if (hasNewline$1(text, locEnd(comment))) {
14741 if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) {
14742 // There is content before this comment on the same line, but
14743 // none after it, so prefer a trailing comment of the previous node.
14744 addTrailingComment$1(precedingNode, comment);
14745 } else if (followingNode) {
14746 addLeadingComment$1(followingNode, comment);
14747 } else if (enclosingNode) {
14748 addDanglingComment$1(enclosingNode, comment);
14750 // There are no nodes, let's attach it to the root of the ast
14752 /* istanbul ignore next */
14753 addDanglingComment$1(ast, comment);
14756 if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) {
14757 // Otherwise, text exists both before and after the comment on
14758 // the same line. If there is both a preceding and following
14759 // node, use a tie-breaking algorithm to determine if it should
14760 // be attached to the next or previous node. In the last case,
14761 // simply attach the right node;
14762 var tieCount = tiesToBreak.length;
14764 if (tieCount > 0) {
14765 var lastTie = tiesToBreak[tieCount - 1];
14767 if (lastTie.followingNode !== comment.followingNode) {
14768 breakTies(tiesToBreak, text, options);
14772 tiesToBreak.push(comment);
14773 } else if (precedingNode) {
14774 addTrailingComment$1(precedingNode, comment);
14775 } else if (followingNode) {
14776 addLeadingComment$1(followingNode, comment);
14777 } else if (enclosingNode) {
14778 addDanglingComment$1(enclosingNode, comment);
14780 // There are no nodes, let's attach it to the root of the ast
14782 /* istanbul ignore next */
14783 addDanglingComment$1(ast, comment);
14787 breakTies(tiesToBreak, text, options);
14788 comments.forEach(function (comment) {
14789 // These node references were useful for breaking ties, but we
14790 // don't need them anymore, and they create cycles in the AST that
14791 // may lead to infinite recursion if we don't delete them here.
14792 delete comment.precedingNode;
14793 delete comment.enclosingNode;
14794 delete comment.followingNode;
14798 function breakTies(tiesToBreak, text, options) {
14799 var tieCount = tiesToBreak.length;
14801 if (tieCount === 0) {
14805 var _tiesToBreak$ = tiesToBreak[0],
14806 precedingNode = _tiesToBreak$.precedingNode,
14807 followingNode = _tiesToBreak$.followingNode;
14808 var gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
14809 // between the tied comments. In order to qualify as leading, a
14810 // comment must be separated from followingNode by an unbroken series of
14811 // gaps (or other comments). Gaps should only contain whitespace or open
14814 var indexOfFirstLeadingComment;
14816 for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
14817 var comment = tiesToBreak[indexOfFirstLeadingComment - 1];
14818 assert.strictEqual(comment.precedingNode, precedingNode);
14819 assert.strictEqual(comment.followingNode, followingNode);
14820 var gap = text.slice(options.locEnd(comment), gapEndPos);
14822 if (/^[\s(]*$/.test(gap)) {
14823 gapEndPos = options.locStart(comment);
14825 // The gap string contained something other than whitespace or open
14831 tiesToBreak.forEach(function (comment, i) {
14832 if (i < indexOfFirstLeadingComment) {
14833 addTrailingComment$1(precedingNode, comment);
14835 addLeadingComment$1(followingNode, comment);
14838 tiesToBreak.length = 0;
14841 function printComment(commentPath, options) {
14842 var comment = commentPath.getValue();
14843 comment.printed = true;
14844 return options.printer.printComment(commentPath, options);
14847 function findExpressionIndexForComment(quasis, comment, options) {
14848 var startPos = options.locStart(comment) - 1;
14850 for (var i = 1; i < quasis.length; ++i) {
14851 if (startPos < getQuasiRange(quasis[i]).start) {
14854 } // We haven't found it, it probably means that some of the locations are off.
14855 // Let's just return the first one.
14857 /* istanbul ignore next */
14863 function getQuasiRange(expr) {
14864 if (expr.start !== undefined) {
14874 start: expr.range[0],
14879 function printLeadingComment(commentPath, print, options) {
14880 var comment = commentPath.getValue();
14881 var contents = printComment(commentPath, options);
14887 var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
14888 // same line or not.
14891 return concat$2([contents, hasNewline$1(options.originalText, options.locEnd(comment)) ? hardline$1 : " "]);
14894 return concat$2([contents, hardline$1]);
14897 function printTrailingComment(commentPath, print, options) {
14898 var comment = commentPath.getValue();
14899 var contents = printComment(commentPath, options);
14905 var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break
14906 // when the parentParentNode is a ClassDeclaration/-Expression
14907 // And the parentNode is in the superClass property
14909 var parentNode = commentPath.getNode(1);
14910 var parentParentNode = commentPath.getNode(2);
14911 var isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode;
14913 if (hasNewline$1(options.originalText, options.locStart(comment), {
14916 // This allows comments at the end of nested structures:
14922 // Those kinds of comments are almost always leading comments, but
14923 // here it doesn't go "outside" the block and turns it into a
14924 // trailing comment for `2`. We can simulate the above by checking
14925 // if this a comment on its own line; normal trailing comments are
14926 // always at the end of another expression.
14927 var isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart);
14928 return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents]));
14929 } else if (isBlock || isParentSuperClass) {
14930 // Trailing block comments never need a newline
14931 return concat$2([" ", contents]);
14934 return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]);
14937 function printDanglingComments(path, options, sameIndent, filter) {
14939 var node = path.getValue();
14941 if (!node || !node.comments) {
14945 path.each(function (commentPath) {
14946 var comment = commentPath.getValue();
14948 if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
14949 parts.push(printComment(commentPath, options));
14953 if (parts.length === 0) {
14958 return join$1(hardline$1, parts);
14961 return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)]));
14964 function prependCursorPlaceholder(path, options, printed) {
14965 if (path.getNode() === options.cursorNode && path.getValue()) {
14966 return concat$2([cursor$2, printed, cursor$2]);
14972 function printComments(path, print, options, needsSemi) {
14973 var value = path.getValue();
14974 var printed = print(path);
14975 var comments = value && value.comments;
14977 if (!comments || comments.length === 0) {
14978 return prependCursorPlaceholder(path, options, printed);
14981 var leadingParts = [];
14982 var trailingParts = [needsSemi ? ";" : "", printed];
14983 path.each(function (commentPath) {
14984 var comment = commentPath.getValue();
14985 var leading = comment.leading,
14986 trailing = comment.trailing;
14989 var contents = printLeadingComment(commentPath, print, options);
14995 leadingParts.push(contents);
14996 var text = options.originalText;
14997 var index = skipNewline$1(text, options.locEnd(comment));
14999 if (index !== false && hasNewline$1(text, index)) {
15000 leadingParts.push(hardline$1);
15002 } else if (trailing) {
15003 trailingParts.push(printTrailingComment(commentPath, print, options));
15006 return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts)));
15011 printComments: printComments,
15012 printDanglingComments: printDanglingComments,
15013 getSortedChildNodes: getSortedChildNodes
15016 function FastPath(value) {
15017 assert.ok(this instanceof FastPath);
15018 this.stack = [value];
15019 } // The name of the current property is always the penultimate element of
15020 // this.stack, and always a String.
15023 FastPath.prototype.getName = function getName() {
15024 var s = this.stack;
15025 var len = s.length;
15029 } // Since the name is always a string, null is a safe sentinel value to
15030 // return if we do not know the name of the (root) value.
15032 /* istanbul ignore next */
15036 }; // The value of the current property is always the final element of
15040 FastPath.prototype.getValue = function getValue() {
15041 var s = this.stack;
15042 return s[s.length - 1];
15045 function getNodeHelper(path, count) {
15046 var stackIndex = getNodeStackIndexHelper(path.stack, count);
15047 return stackIndex === -1 ? null : path.stack[stackIndex];
15050 function getNodeStackIndexHelper(stack, count) {
15051 for (var i = stack.length - 1; i >= 0; i -= 2) {
15052 var value = stack[i];
15054 if (value && !Array.isArray(value) && --count < 0) {
15062 FastPath.prototype.getNode = function getNode(count) {
15063 return getNodeHelper(this, ~~count);
15066 FastPath.prototype.getParentNode = function getParentNode(count) {
15067 return getNodeHelper(this, ~~count + 1);
15068 }; // Temporarily push properties named by string arguments given after the
15069 // callback function onto this.stack, then call the callback with a
15070 // reference to this (modified) FastPath object. Note that the stack will
15071 // be restored to its original state after the callback is finished, so it
15072 // is probably a mistake to retain a reference to the path.
15075 FastPath.prototype.call = function call(callback
15076 /*, name1, name2, ... */
15078 var s = this.stack;
15079 var origLen = s.length;
15080 var value = s[origLen - 1];
15081 var argc = arguments.length;
15083 for (var i = 1; i < argc; ++i) {
15084 var name = arguments[i];
15085 value = value[name];
15086 s.push(name, value);
15089 var result = callback(this);
15090 s.length = origLen;
15094 FastPath.prototype.callParent = function callParent(callback, count) {
15095 var stackIndex = getNodeStackIndexHelper(this.stack, ~~count + 1);
15096 var parentValues = this.stack.splice(stackIndex + 1);
15097 var result = callback(this);
15098 Array.prototype.push.apply(this.stack, parentValues);
15100 }; // Similar to FastPath.prototype.call, except that the value obtained by
15101 // accessing this.getValue()[name1][name2]... should be array-like. The
15102 // callback will be called with a reference to this path object for each
15103 // element of the array.
15106 FastPath.prototype.each = function each(callback
15107 /*, name1, name2, ... */
15109 var s = this.stack;
15110 var origLen = s.length;
15111 var value = s[origLen - 1];
15112 var argc = arguments.length;
15114 for (var i = 1; i < argc; ++i) {
15115 var name = arguments[i];
15116 value = value[name];
15117 s.push(name, value);
15120 for (var _i = 0; _i < value.length; ++_i) {
15122 s.push(_i, value[_i]); // If the callback needs to know the value of i, call
15123 // path.getName(), assuming path is the parameter name.
15130 s.length = origLen;
15131 }; // Similar to FastPath.prototype.each, except that the results of the
15132 // callback function invocations are stored in an array and returned at
15133 // the end of the iteration.
15136 FastPath.prototype.map = function map(callback
15137 /*, name1, name2, ... */
15139 var s = this.stack;
15140 var origLen = s.length;
15141 var value = s[origLen - 1];
15142 var argc = arguments.length;
15144 for (var i = 1; i < argc; ++i) {
15145 var name = arguments[i];
15146 value = value[name];
15147 s.push(name, value);
15150 var result = new Array(value.length);
15152 for (var _i2 = 0; _i2 < value.length; ++_i2) {
15153 if (_i2 in value) {
15154 s.push(_i2, value[_i2]);
15155 result[_i2] = callback(this, _i2);
15160 s.length = origLen;
15164 var fastPath = FastPath;
15166 var normalize$2 = options$1.normalize;
15168 function printSubtree(path, print, options, printAstToDoc) {
15169 if (options.printer.embed) {
15170 return options.printer.embed(path, print, function (text, partialNextOptions) {
15171 return textToDoc(text, partialNextOptions, options, printAstToDoc);
15176 function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) {
15177 var nextOptions = normalize$2(Object.assign({}, parentOptions, partialNextOptions, {
15178 parentParser: parentOptions.parser,
15179 embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"),
15184 var result = parser.parse(text, nextOptions);
15185 var ast = result.ast;
15186 text = result.text;
15187 var astComments = ast.comments;
15188 delete ast.comments;
15189 comments.attach(astComments, ast, text, nextOptions);
15190 return printAstToDoc(ast, nextOptions);
15193 var multiparser = {
15194 printSubtree: printSubtree
15198 var docBuilders$1 = doc$1.builders;
15199 var concat$3 = docBuilders$1.concat;
15200 var hardline$2 = docBuilders$1.hardline;
15201 var addAlignmentToDoc$1 = docBuilders$1.addAlignmentToDoc;
15202 var docUtils$1 = doc$1.utils;
15204 * Takes an abstract syntax tree (AST) and recursively converts it to a
15205 * document (series of printing primitives).
15207 * This is done by descending down the AST recursively. The recursion
15208 * involves two functions that call each other:
15210 * 1. printGenerically(), which is defined as an inner function here.
15211 * It basically takes care of node caching.
15212 * 2. callPluginPrintFunction(), which checks for some options, and
15213 * ultimately calls the print() function provided by the plugin.
15215 * The plugin function will call printGenerically() again for child nodes
15216 * of the current node, which will do its housekeeping, then call the
15217 * plugin function again, and so on.
15219 * All the while, these functions pass a "path" variable around, which
15220 * is a stack-like data structure (FastPath) that maintains the current
15221 * state of the recursion. It is called "path", because it represents
15222 * the path to the current node through the Abstract Syntax Tree.
15225 function printAstToDoc(ast, options) {
15226 var alignmentSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
15227 var printer = options.printer;
15229 if (printer.preprocess) {
15230 ast = printer.preprocess(ast, options);
15233 var cache = new Map();
15235 function printGenerically(path, args) {
15236 var node = path.getValue();
15237 var shouldCache = node && _typeof(node) === "object" && args === undefined;
15239 if (shouldCache && cache.has(node)) {
15240 return cache.get(node);
15241 } // We let JSXElement print its comments itself because it adds () around
15242 // UnionTypeAnnotation has to align the child without the comments
15247 if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) {
15248 res = callPluginPrintFunction(path, options, printGenerically, args);
15250 // printComments will call the plugin print function and check for
15251 // comments to print
15252 res = comments.printComments(path, function (p) {
15253 return callPluginPrintFunction(p, options, printGenerically, args);
15254 }, options, args && args.needsSemi);
15258 cache.set(node, res);
15264 var doc = printGenerically(new fastPath(ast));
15266 if (alignmentSize > 0) {
15267 // Add a hardline to make the indents take effect
15268 // It should be removed in index.js format()
15269 doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth);
15272 docUtils$1.propagateBreaks(doc);
15276 function callPluginPrintFunction(path, options, printPath, args) {
15277 assert.ok(path instanceof fastPath);
15278 var node = path.getValue();
15279 var printer = options.printer; // Escape hatch
15281 if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
15282 return options.originalText.slice(options.locStart(node), options.locEnd(node));
15287 // Potentially switch to a different parser
15288 var sub = multiparser.printSubtree(path, printPath, options, printAstToDoc);
15294 /* istanbul ignore if */
15295 if (commonjsGlobal.PRETTIER_DEBUG) {
15297 } // Continue with current parser
15302 return printer.print(path, options, printPath, args);
15305 var astToDoc = printAstToDoc;
15307 function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
15308 var resultStartNode = startNodeAndParents.node;
15309 var resultEndNode = endNodeAndParents.node;
15311 if (resultStartNode === resultEndNode) {
15313 startNode: resultStartNode,
15314 endNode: resultEndNode
15318 var _iteratorNormalCompletion = true;
15319 var _didIteratorError = false;
15320 var _iteratorError = undefined;
15323 for (var _iterator = endNodeAndParents.parentNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
15324 var endParent = _step.value;
15326 if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
15327 resultEndNode = endParent;
15333 _didIteratorError = true;
15334 _iteratorError = err;
15337 if (!_iteratorNormalCompletion && _iterator.return != null) {
15338 _iterator.return();
15341 if (_didIteratorError) {
15342 throw _iteratorError;
15347 var _iteratorNormalCompletion2 = true;
15348 var _didIteratorError2 = false;
15349 var _iteratorError2 = undefined;
15352 for (var _iterator2 = startNodeAndParents.parentNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
15353 var startParent = _step2.value;
15355 if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
15356 resultStartNode = startParent;
15362 _didIteratorError2 = true;
15363 _iteratorError2 = err;
15366 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
15367 _iterator2.return();
15370 if (_didIteratorError2) {
15371 throw _iteratorError2;
15377 startNode: resultStartNode,
15378 endNode: resultEndNode
15382 function findNodeAtOffset(node, offset, options, predicate, parentNodes) {
15383 predicate = predicate || function () {
15387 parentNodes = parentNodes || [];
15388 var start = options.locStart(node, options.locStart);
15389 var end = options.locEnd(node, options.locEnd);
15391 if (start <= offset && offset <= end) {
15392 var _iteratorNormalCompletion3 = true;
15393 var _didIteratorError3 = false;
15394 var _iteratorError3 = undefined;
15397 for (var _iterator3 = comments.getSortedChildNodes(node, options)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
15398 var childNode = _step3.value;
15399 var childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes));
15402 return childResult;
15406 _didIteratorError3 = true;
15407 _iteratorError3 = err;
15410 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
15411 _iterator3.return();
15414 if (_didIteratorError3) {
15415 throw _iteratorError3;
15420 if (predicate(node)) {
15423 parentNodes: parentNodes
15427 } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
15430 function isSourceElement(opts, node) {
15431 if (node == null) {
15433 } // JS and JS like to avoid repetitions
15436 var jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015
15437 "ImportDeclaration", // Module
15438 "ExportDefaultDeclaration", // Module
15439 "ExportNamedDeclaration", // Module
15440 "ExportAllDeclaration", // Module
15441 "TypeAlias", // Flow
15442 "InterfaceDeclaration", // Flow, TypeScript
15443 "TypeAliasDeclaration", // TypeScript
15444 "ExportAssignment", // TypeScript
15445 "ExportDeclaration" // TypeScript
15447 var jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"];
15448 var graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"];
15450 switch (opts.parser) {
15454 return jsSourceElements.indexOf(node.type) > -1;
15457 return jsonSourceElements.indexOf(node.type) > -1;
15460 return graphqlSourceElements.indexOf(node.kind) > -1;
15463 return node.tag !== "root";
15469 function calculateRange(text, opts, ast) {
15470 // Contract the range so that it has non-whitespace characters at its endpoints.
15471 // This ensures we can format a range that doesn't end on a node.
15472 var rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
15473 var startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
15474 var endNonWhitespace;
15476 for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
15477 if (text[endNonWhitespace - 1].match(/\S/)) {
15482 var startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, function (node) {
15483 return isSourceElement(opts, node);
15485 var endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, function (node) {
15486 return isSourceElement(opts, node);
15489 if (!startNodeAndParents || !endNodeAndParents) {
15496 var siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
15497 var startNode = siblingAncestors.startNode,
15498 endNode = siblingAncestors.endNode;
15499 var rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart));
15500 var rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd));
15502 rangeStart: rangeStart,
15508 calculateRange: calculateRange,
15509 findNodeAtOffset: findNodeAtOffset
15512 var diff = getCjsExportFromNamespace(index_es6);
15514 var normalizeOptions$1 = options$1.normalize;
15515 var guessEndOfLine$1 = endOfLine.guessEndOfLine,
15516 convertEndOfLineToChars$2 = endOfLine.convertEndOfLineToChars;
15517 var mapDoc$2 = doc.utils.mapDoc,
15518 _printDocToString = doc.printer.printDocToString,
15519 printDocToDebug = doc.debug.printDocToDebug;
15520 var UTF8BOM = 0xfeff;
15521 var CURSOR = Symbol("cursor");
15522 var PLACEHOLDERS = {
15523 cursorOffset: "<<<PRETTIER_CURSOR>>>",
15524 rangeStart: "<<<PRETTIER_RANGE_START>>>",
15525 rangeEnd: "<<<PRETTIER_RANGE_END>>>"
15528 function ensureAllCommentsPrinted(astComments) {
15529 if (!astComments) {
15533 for (var i = 0; i < astComments.length; ++i) {
15534 if (astComments[i].value.trim() === "prettier-ignore") {
15535 // If there's a prettier-ignore, we're not printing that sub-tree so we
15536 // don't know if the comments was printed or not.
15541 astComments.forEach(function (comment) {
15542 if (!comment.printed) {
15543 throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
15546 delete comment.printed;
15550 function attachComments(text, ast, opts) {
15551 var astComments = ast.comments;
15554 delete ast.comments;
15555 comments.attach(astComments, ast, text, opts);
15559 opts.originalText = opts.parser === "yaml" ? text : text.trimRight();
15560 return astComments;
15563 function coreFormat(text, opts, addAlignmentSize) {
15564 if (!text || !text.trim().length) {
15571 addAlignmentSize = addAlignmentSize || 0;
15572 var parsed = parser.parse(text, opts);
15573 var ast = parsed.ast;
15574 text = parsed.text;
15576 if (opts.cursorOffset >= 0) {
15577 var nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
15579 if (nodeResult && nodeResult.node) {
15580 opts.cursorNode = nodeResult.node;
15584 var astComments = attachComments(text, ast, opts);
15585 var doc = astToDoc(ast, opts, addAlignmentSize);
15586 var eol = convertEndOfLineToChars$2(opts.endOfLine);
15588 var result = _printDocToString(opts.endOfLine === "lf" ? doc : mapDoc$2(doc, function (currentDoc) {
15589 return typeof currentDoc === "string" && currentDoc.indexOf("\n") !== -1 ? currentDoc.replace(/\n/g, eol) : currentDoc;
15592 ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
15594 if (addAlignmentSize > 0) {
15595 var trimmed = result.formatted.trim();
15597 if (result.cursorNodeStart !== undefined) {
15598 result.cursorNodeStart -= result.formatted.indexOf(trimmed);
15601 result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine);
15604 if (opts.cursorOffset >= 0) {
15605 var oldCursorNodeStart;
15606 var oldCursorNodeText;
15607 var cursorOffsetRelativeToOldCursorNode;
15608 var newCursorNodeStart;
15609 var newCursorNodeText;
15611 if (opts.cursorNode && result.cursorNodeText) {
15612 oldCursorNodeStart = opts.locStart(opts.cursorNode);
15613 oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
15614 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
15615 newCursorNodeStart = result.cursorNodeStart;
15616 newCursorNodeText = result.cursorNodeText;
15618 oldCursorNodeStart = 0;
15619 oldCursorNodeText = text;
15620 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
15621 newCursorNodeStart = 0;
15622 newCursorNodeText = result.formatted;
15625 if (oldCursorNodeText === newCursorNodeText) {
15627 formatted: result.formatted,
15628 cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
15630 } // diff old and new cursor node texts, with a special cursor
15631 // symbol inserted to find out where it moves to
15634 var oldCursorNodeCharArray = oldCursorNodeText.split("");
15635 oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
15636 var newCursorNodeCharArray = newCursorNodeText.split("");
15637 var cursorNodeDiff = diff.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
15638 var cursorOffset = newCursorNodeStart;
15639 var _iteratorNormalCompletion = true;
15640 var _didIteratorError = false;
15641 var _iteratorError = undefined;
15644 for (var _iterator = cursorNodeDiff[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
15645 var entry = _step.value;
15647 if (entry.removed) {
15648 if (entry.value.indexOf(CURSOR) > -1) {
15652 cursorOffset += entry.count;
15656 _didIteratorError = true;
15657 _iteratorError = err;
15660 if (!_iteratorNormalCompletion && _iterator.return != null) {
15661 _iterator.return();
15664 if (_didIteratorError) {
15665 throw _iteratorError;
15671 formatted: result.formatted,
15672 cursorOffset: cursorOffset
15677 formatted: result.formatted
15681 function formatRange(text, opts) {
15682 var parsed = parser.parse(text, opts);
15683 var ast = parsed.ast;
15684 text = parsed.text;
15685 var range = rangeUtil.calculateRange(text, opts, ast);
15686 var rangeStart = range.rangeStart;
15687 var rangeEnd = range.rangeEnd;
15688 var rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
15689 // This is so we can detect indentation correctly and restore it.
15690 // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
15692 var rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
15693 var indentString = text.slice(rangeStart2, rangeStart);
15694 var alignmentSize = util.getAlignmentSize(indentString, opts.tabWidth);
15695 var rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
15697 rangeEnd: Infinity,
15698 // track the cursor offset only if it's within our range
15699 cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1
15700 }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
15701 // we need to remove the newline that was inserted by the `format` call.
15703 var rangeTrimmed = rangeResult.formatted.trimRight();
15704 var rangeLeft = text.slice(0, rangeStart);
15705 var rangeRight = text.slice(rangeEnd);
15706 var cursorOffset = opts.cursorOffset;
15708 if (opts.cursorOffset >= rangeEnd) {
15709 // handle the case where the cursor was past the end of the range
15710 cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length);
15711 } else if (rangeResult.cursorOffset !== undefined) {
15712 // handle the case where the cursor was in the range
15713 cursorOffset = rangeResult.cursorOffset + rangeStart;
15714 } // keep the cursor as it was if it was before the start of the range
15719 if (opts.endOfLine === "lf") {
15720 formatted = rangeLeft + rangeTrimmed + rangeRight;
15722 var eol = convertEndOfLineToChars$2(opts.endOfLine);
15724 if (cursorOffset >= 0) {
15725 var parts = [rangeLeft, rangeTrimmed, rangeRight];
15727 var partOffset = cursorOffset;
15729 while (partIndex < parts.length) {
15730 var part = parts[partIndex];
15732 if (partOffset < part.length) {
15733 parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset);
15738 partOffset -= part.length;
15741 var newRangeLeft = parts[0],
15742 newRangeTrimmed = parts[1],
15743 newRangeRight = parts[2];
15744 formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, function (_, index) {
15745 cursorOffset = index;
15749 formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol);
15754 formatted: formatted,
15755 cursorOffset: cursorOffset
15759 function format(text, opts) {
15760 var selectedParser = parser.resolveParser(opts);
15761 var hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
15763 if (opts.requirePragma && !hasPragma) {
15769 if (opts.endOfLine === "auto") {
15770 opts.endOfLine = guessEndOfLine$1(text);
15773 var hasCursor = opts.cursorOffset >= 0;
15774 var hasRangeStart = opts.rangeStart > 0;
15775 var hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing
15777 if (text.indexOf("\r") !== -1) {
15778 var offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort(function (aKey, bKey) {
15779 return opts[aKey] - opts[bKey];
15782 for (var i = offsetKeys.length - 1; i >= 0; i--) {
15783 var key = offsetKeys[i];
15784 text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]);
15787 text = text.replace(/\r\n?/g, "\n");
15789 var _loop = function _loop(_i) {
15790 var key = offsetKeys[_i];
15791 text = text.replace(PLACEHOLDERS[key], function (_, index) {
15797 for (var _i = 0; _i < offsetKeys.length; _i++) {
15802 var hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM;
15804 if (hasUnicodeBOM) {
15805 text = text.substring(1);
15808 opts.cursorOffset++;
15811 if (hasRangeStart) {
15821 opts.cursorOffset = -1;
15824 if (opts.rangeStart < 0) {
15825 opts.rangeStart = 0;
15828 if (opts.rangeEnd > text.length) {
15829 opts.rangeEnd = text.length;
15832 var result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts);
15834 if (hasUnicodeBOM) {
15835 result.formatted = String.fromCharCode(UTF8BOM) + result.formatted;
15838 result.cursorOffset++;
15846 formatWithCursor: function formatWithCursor(text, opts) {
15847 opts = normalizeOptions$1(opts);
15848 return format(text, opts);
15850 parse: function parse(text, opts, massage) {
15851 opts = normalizeOptions$1(opts);
15853 if (text.indexOf("\r") !== -1) {
15854 text = text.replace(/\r\n?/g, "\n");
15857 var parsed = parser.parse(text, opts);
15860 parsed.ast = massageAst(parsed.ast, opts);
15865 formatAST: function formatAST(ast, opts) {
15866 opts = normalizeOptions$1(opts);
15867 var doc = astToDoc(ast, opts);
15868 return _printDocToString(doc, opts);
15870 // Doesn't handle shebang for now
15871 formatDoc: function formatDoc(doc, opts) {
15872 var debug = printDocToDebug(doc);
15873 opts = normalizeOptions$1(Object.assign({}, opts, {
15876 return format(debug, opts).formatted;
15878 printToDoc: function printToDoc(text, opts) {
15879 opts = normalizeOptions$1(opts);
15880 var parsed = parser.parse(text, opts);
15881 var ast = parsed.ast;
15882 text = parsed.text;
15883 attachComments(text, ast, opts);
15884 return astToDoc(ast, opts);
15886 printDocToString: function printDocToString(doc, opts) {
15887 return _printDocToString(doc, normalizeOptions$1(opts));
16042 var htmlTagNames = /*#__PURE__*/Object.freeze({
16047 var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames);
16049 function clean(ast, newObj, parent) {
16050 ["raw", // front-matter
16051 "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(function (name) {
16052 delete newObj[name];
16055 if (ast.type === "yaml") {
16056 delete newObj.value;
16057 } // --insert-pragma
16060 if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment
16061 parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) {
16067 delete newObj.text; // standalone pragma
16069 if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
16074 if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
16075 delete newObj.value;
16078 if (ast.type === "css-rule") {
16079 delete newObj.params;
16082 if (ast.type === "selector-combinator") {
16083 newObj.value = newObj.value.replace(/\s+/g, " ");
16086 if (ast.type === "media-feature") {
16087 newObj.value = newObj.value.replace(/ /g, "");
16090 if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].indexOf(newObj.value.replace().toLowerCase()) !== -1) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") {
16091 newObj.value = newObj.value.toLowerCase();
16094 if (ast.type === "css-decl") {
16095 newObj.prop = newObj.prop.toLowerCase();
16098 if (ast.type === "css-atrule" || ast.type === "css-import") {
16099 newObj.name = newObj.name.toLowerCase();
16102 if (ast.type === "value-number") {
16103 newObj.unit = newObj.unit.toLowerCase();
16106 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) {
16107 newObj.value = cleanCSSStrings(newObj.value);
16110 if (ast.type === "selector-attribute") {
16111 newObj.attribute = newObj.attribute.trim();
16113 if (newObj.namespace) {
16114 if (typeof newObj.namespace === "string") {
16115 newObj.namespace = newObj.namespace.trim();
16117 if (newObj.namespace.length === 0) {
16118 newObj.namespace = true;
16123 if (newObj.value) {
16124 newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
16125 delete newObj.quoted;
16129 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) {
16130 newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, function (match, numStr, unit) {
16131 var num = Number(numStr);
16132 return isNaN(num) ? match : num + unit.toLowerCase();
16136 if (ast.type === "selector-tag") {
16137 var lowercasedValue = ast.value.toLowerCase();
16139 if (htmlTagNames$1.indexOf(lowercasedValue) !== -1) {
16140 newObj.value = lowercasedValue;
16143 if (["from", "to"].indexOf(lowercasedValue) !== -1) {
16144 newObj.value = lowercasedValue;
16146 } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
16149 if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
16150 delete newObj.value;
16151 } // Workaround for SCSS nested properties
16154 if (ast.type === "selector-unknown") {
16155 delete newObj.value;
16159 function cleanCSSStrings(value) {
16160 return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
16163 var clean_1 = clean;
16165 var _require$$0$builders$1 = doc.builders,
16166 hardline$3 = _require$$0$builders$1.hardline,
16167 literalline$1 = _require$$0$builders$1.literalline,
16168 concat$4 = _require$$0$builders$1.concat,
16169 markAsRoot$1 = _require$$0$builders$1.markAsRoot,
16170 mapDoc$3 = doc.utils.mapDoc;
16172 function embed(path, print, textToDoc
16175 var node = path.getValue();
16177 if (node.type === "yaml") {
16178 return markAsRoot$1(concat$4(["---", hardline$3, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
16180 })) : "", "---", hardline$3]));
16185 function replaceNewlinesWithLiterallines(doc) {
16186 return mapDoc$3(doc, function (currentDoc) {
16187 return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$4(currentDoc.split(/(\n)/g).map(function (v, i) {
16188 return i % 2 === 0 ? v : literalline$1;
16194 var embed_1 = embed;
16196 var detectNewline = createCommonjsModule(function (module) {
16198 module.exports = function (str) {
16199 if (typeof str !== 'string') {
16200 throw new TypeError('Expected a string');
16203 var newlines = str.match(/(?:\r?\n)/g) || [];
16205 if (newlines.length === 0) {
16209 var crlf = newlines.filter(function (el) {
16210 return el === '\r\n';
16212 var lf = newlines.length - crlf;
16213 return crlf > lf ? '\r\n' : '\n';
16216 module.exports.graceful = function (str) {
16217 return module.exports(str) || '\n';
16220 var detectNewline_1 = detectNewline.graceful;
16222 var build = createCommonjsModule(function (module, exports) {
16224 Object.defineProperty(exports, '__esModule', {
16227 exports.extract = extract;
16228 exports.strip = strip;
16229 exports.parse = parse;
16230 exports.parseWithComments = parseWithComments;
16231 exports.print = print;
16234 var data = require$$0$1;
16236 _os = function _os() {
16243 function _detectNewline() {
16244 var data = _interopRequireDefault(detectNewline);
16246 _detectNewline = function _detectNewline() {
16253 function _interopRequireDefault(obj) {
16254 return obj && obj.__esModule ? obj : {
16259 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
16261 * This source code is licensed under the MIT license found in the
16262 * LICENSE file in the root directory of this source tree.
16266 var commentEndRe = /\*\/$/;
16267 var commentStartRe = /^\/\*\*/;
16268 var docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
16269 var lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
16270 var ltrimNewlineRe = /^(\r?\n)+/;
16271 var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
16272 var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
16273 var stringStartRe = /(\r?\n|^) *\* ?/g;
16275 function extract(contents) {
16276 var match = contents.match(docblockRe);
16277 return match ? match[0].trimLeft() : '';
16280 function strip(contents) {
16281 var match = contents.match(docblockRe);
16282 return match && match[0] ? contents.substring(match[0].length) : contents;
16285 function parse(docblock) {
16286 return parseWithComments(docblock).pragmas;
16289 function parseWithComments(docblock) {
16290 var line = (0, _detectNewline().default)(docblock) || _os().EOL;
16292 docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
16296 while (prev !== docblock) {
16298 docblock = docblock.replace(multilineRe, "".concat(line, "$1 $2").concat(line));
16301 docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
16302 var result = Object.create(null);
16303 var comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
16306 while (match = propertyRe.exec(docblock)) {
16307 // strip linecomments from pragmas
16308 var nextPragma = match[2].replace(lineCommentRe, '');
16310 if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
16311 result[match[1]] = [].concat(result[match[1]], nextPragma);
16313 result[match[1]] = nextPragma;
16318 comments: comments,
16323 function print(_ref) {
16324 var _ref$comments = _ref.comments,
16325 comments = _ref$comments === void 0 ? '' : _ref$comments,
16326 _ref$pragmas = _ref.pragmas,
16327 pragmas = _ref$pragmas === void 0 ? {} : _ref$pragmas;
16329 var line = (0, _detectNewline().default)(comments) || _os().EOL;
16334 var keys = Object.keys(pragmas);
16335 var printedObject = keys.map(function (key) {
16336 return printKeyValues(key, pragmas[key]);
16337 }).reduce(function (arr, next) {
16338 return arr.concat(next);
16339 }, []).map(function (keyValue) {
16340 return start + ' ' + keyValue + line;
16344 if (keys.length === 0) {
16348 if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
16349 var value = pragmas[keys[0]];
16350 return "".concat(head, " ").concat(printKeyValues(keys[0], value)[0]).concat(tail);
16354 var printedComments = comments.split(line).map(function (textLine) {
16355 return "".concat(start, " ").concat(textLine);
16356 }).join(line) + line;
16357 return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
16360 function printKeyValues(key, valueOrArray) {
16361 return [].concat(valueOrArray).map(function (value) {
16362 return "@".concat(key, " ").concat(value).trim();
16366 unwrapExports(build);
16367 var build_1 = build.extract;
16368 var build_2 = build.strip;
16369 var build_3 = build.parse;
16370 var build_4 = build.parseWithComments;
16371 var build_5 = build.print;
16373 function hasPragma(text) {
16374 var pragmas = Object.keys(build.parse(build.extract(text)));
16375 return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1;
16378 function insertPragma(text) {
16379 var parsedDocblock = build.parseWithComments(build.extract(text));
16380 var pragmas = Object.assign({
16382 }, parsedDocblock.pragmas);
16383 var newDocblock = build.print({
16385 comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines
16387 }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock)
16389 var strippedText = build.strip(text);
16390 var separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n";
16391 return newDocblock + separatingNewlines + strippedText;
16395 hasPragma: hasPragma,
16396 insertPragma: insertPragma
16399 var DELIMITER_MAP = {
16404 function parse$1(text) {
16405 var delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|");
16406 var match = text.match( // trailing spaces after delimiters are allowed
16407 new RegExp("^(".concat(delimiterRegex, ")[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)")));
16409 if (match === null) {
16416 var raw = match[0].replace(/\n$/, "");
16417 var delimiter = match[1];
16418 var value = match[2];
16421 type: DELIMITER_MAP[delimiter],
16425 content: match[0].replace(/[^\n]/g, " ") + text.slice(match[0].length)
16429 var frontMatter = parse$1;
16431 function hasPragma$1(text) {
16432 return pragma.hasPragma(frontMatter(text).content);
16435 function insertPragma$1(text) {
16436 var _parseFrontMatter = frontMatter(text),
16437 frontMatter$1 = _parseFrontMatter.frontMatter,
16438 content = _parseFrontMatter.content;
16440 return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content);
16444 hasPragma: hasPragma$1,
16445 insertPragma: insertPragma$1
16448 var 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"];
16450 function getAncestorCounter(path, typeOrTypes) {
16451 var types = [].concat(typeOrTypes);
16455 while (ancestorNode = path.getParentNode(++counter)) {
16456 if (types.indexOf(ancestorNode.type) !== -1) {
16464 function getAncestorNode(path, typeOrTypes) {
16465 var counter = getAncestorCounter(path, typeOrTypes);
16466 return counter === -1 ? null : path.getParentNode(counter);
16469 function getPropOfDeclNode(path) {
16470 var declAncestorNode = getAncestorNode(path, "css-decl");
16471 return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
16474 function isSCSS(parser, text) {
16475 var hasExplicitParserChoice = parser === "less" || parser === "scss";
16476 var IS_POSSIBLY_SCSS = /(\w\s*: [^}:]+|#){|@import[^\n]+(url|,)/;
16477 return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
16480 function isWideKeywords(value) {
16481 return ["initial", "inherit", "unset", "revert"].indexOf(value.toLowerCase()) !== -1;
16484 function isKeyframeAtRuleKeywords(path, value) {
16485 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
16486 return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].indexOf(value.toLowerCase()) !== -1;
16489 function maybeToLowerCase(value) {
16490 return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
16493 function insideValueFunctionNode(path, functionName) {
16494 var funcAncestorNode = getAncestorNode(path, "value-func");
16495 return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
16498 function insideICSSRuleNode(path) {
16499 var ruleAncestorNode = getAncestorNode(path, "css-rule");
16500 return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
16503 function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
16504 var atRuleNames = [].concat(atRuleNameOrAtRuleNames);
16505 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
16506 return atRuleAncestorNode && atRuleNames.indexOf(atRuleAncestorNode.name.toLowerCase()) !== -1;
16509 function insideURLFunctionInImportAtRuleNode(path) {
16510 var node = path.getValue();
16511 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
16512 return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
16515 function isURLFunctionNode(node) {
16516 return node.type === "value-func" && node.value.toLowerCase() === "url";
16519 function isLastNode(path, node) {
16520 var parentNode = path.getParentNode();
16526 var nodes = parentNode.nodes;
16527 return nodes && nodes.indexOf(node) === nodes.length - 1;
16530 function isHTMLTag(value) {
16531 return htmlTagNames$1.indexOf(value.toLowerCase()) !== -1;
16534 function isDetachedRulesetDeclarationNode(node) {
16535 // If a Less file ends up being parsed with the SCSS parser, Less
16536 // variable declarations will be parsed as atrules with names ending
16537 // with a colon, so keep the original case then.
16538 if (!node.selector) {
16542 return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
16545 function isForKeywordNode(node) {
16546 return node.type === "value-word" && ["from", "through", "end"].indexOf(node.value) !== -1;
16549 function isIfElseKeywordNode(node) {
16550 return node.type === "value-word" && ["and", "or", "not"].indexOf(node.value) !== -1;
16553 function isEachKeywordNode(node) {
16554 return node.type === "value-word" && node.value === "in";
16557 function isMultiplicationNode(node) {
16558 return node.type === "value-operator" && node.value === "*";
16561 function isDivisionNode(node) {
16562 return node.type === "value-operator" && node.value === "/";
16565 function isAdditionNode(node) {
16566 return node.type === "value-operator" && node.value === "+";
16569 function isSubtractionNode(node) {
16570 return node.type === "value-operator" && node.value === "-";
16573 function isModuloNode(node) {
16574 return node.type === "value-operator" && node.value === "%";
16577 function isMathOperatorNode(node) {
16578 return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
16581 function isEqualityOperatorNode(node) {
16582 return node.type === "value-word" && ["==", "!="].indexOf(node.value) !== -1;
16585 function isRelationalOperatorNode(node) {
16586 return node.type === "value-word" && ["<", ">", "<=", ">="].indexOf(node.value) !== -1;
16589 function isSCSSControlDirectiveNode(node) {
16590 return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].indexOf(node.name) !== -1;
16593 function isSCSSNestedPropertyNode(node) {
16594 if (!node.selector) {
16598 return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
16601 function isDetachedRulesetCallNode(node) {
16602 return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
16605 function isTemplatePlaceholderNode(node) {
16606 return node.name.startsWith("prettier-placeholder");
16609 function isTemplatePropNode(node) {
16610 return node.prop.startsWith("@prettier-placeholder");
16613 function isPostcssSimpleVarNode(currentNode, nextNode) {
16614 return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
16617 function hasComposesNode(node) {
16618 return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
16621 function hasParensAroundNode(node) {
16622 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;
16625 function hasEmptyRawBefore(node) {
16626 return node.raws && node.raws.before === "";
16629 function isKeyValuePairNode(node) {
16630 return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
16633 function isKeyValuePairInParenGroupNode(node) {
16634 return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]);
16637 function isSCSSMapItemNode(path) {
16638 var node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
16640 if (node.groups.length === 0) {
16644 var parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
16646 if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
16650 var declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
16652 if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
16654 } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
16657 if (isKeyValuePairInParenGroupNode(parentParentNode)) {
16659 } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
16662 if (parentParentNode.type === "value-func") {
16669 function isInlineValueCommentNode(node) {
16670 return node.type === "value-comment" && node.inline;
16673 function isHashNode(node) {
16674 return node.type === "value-word" && node.value === "#";
16677 function isLeftCurlyBraceNode(node) {
16678 return node.type === "value-word" && node.value === "{";
16681 function isRightCurlyBraceNode(node) {
16682 return node.type === "value-word" && node.value === "}";
16685 function isWordNode(node) {
16686 return ["value-word", "value-atword"].indexOf(node.type) !== -1;
16689 function isColonNode(node) {
16690 return node.type === "value-colon";
16693 function isMediaAndSupportsKeywords(node) {
16694 return node.value && ["not", "and", "or"].indexOf(node.value.toLowerCase()) !== -1;
16697 function isColorAdjusterFuncNode(node) {
16698 if (node.type !== "value-func") {
16702 return colorAdjusterFunctions.indexOf(node.value.toLowerCase()) !== -1;
16706 getAncestorCounter: getAncestorCounter,
16707 getAncestorNode: getAncestorNode,
16708 getPropOfDeclNode: getPropOfDeclNode,
16709 maybeToLowerCase: maybeToLowerCase,
16710 insideValueFunctionNode: insideValueFunctionNode,
16711 insideICSSRuleNode: insideICSSRuleNode,
16712 insideAtRuleNode: insideAtRuleNode,
16713 insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode,
16714 isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords,
16715 isHTMLTag: isHTMLTag,
16716 isWideKeywords: isWideKeywords,
16718 isLastNode: isLastNode,
16719 isSCSSControlDirectiveNode: isSCSSControlDirectiveNode,
16720 isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode,
16721 isRelationalOperatorNode: isRelationalOperatorNode,
16722 isEqualityOperatorNode: isEqualityOperatorNode,
16723 isMultiplicationNode: isMultiplicationNode,
16724 isDivisionNode: isDivisionNode,
16725 isAdditionNode: isAdditionNode,
16726 isSubtractionNode: isSubtractionNode,
16727 isModuloNode: isModuloNode,
16728 isMathOperatorNode: isMathOperatorNode,
16729 isEachKeywordNode: isEachKeywordNode,
16730 isForKeywordNode: isForKeywordNode,
16731 isURLFunctionNode: isURLFunctionNode,
16732 isIfElseKeywordNode: isIfElseKeywordNode,
16733 hasComposesNode: hasComposesNode,
16734 hasParensAroundNode: hasParensAroundNode,
16735 hasEmptyRawBefore: hasEmptyRawBefore,
16736 isSCSSNestedPropertyNode: isSCSSNestedPropertyNode,
16737 isDetachedRulesetCallNode: isDetachedRulesetCallNode,
16738 isTemplatePlaceholderNode: isTemplatePlaceholderNode,
16739 isTemplatePropNode: isTemplatePropNode,
16740 isPostcssSimpleVarNode: isPostcssSimpleVarNode,
16741 isKeyValuePairNode: isKeyValuePairNode,
16742 isKeyValuePairInParenGroupNode: isKeyValuePairInParenGroupNode,
16743 isSCSSMapItemNode: isSCSSMapItemNode,
16744 isInlineValueCommentNode: isInlineValueCommentNode,
16745 isHashNode: isHashNode,
16746 isLeftCurlyBraceNode: isLeftCurlyBraceNode,
16747 isRightCurlyBraceNode: isRightCurlyBraceNode,
16748 isWordNode: isWordNode,
16749 isColonNode: isColonNode,
16750 isMediaAndSupportsKeywords: isMediaAndSupportsKeywords,
16751 isColorAdjusterFuncNode: isColorAdjusterFuncNode
16754 var insertPragma$2 = pragma$1.insertPragma;
16755 var printNumber$1 = util.printNumber,
16756 printString$1 = util.printString,
16757 hasIgnoreComment$1 = util.hasIgnoreComment,
16758 hasNewline$2 = util.hasNewline;
16759 var isNextLineEmpty$2 = utilShared.isNextLineEmpty;
16760 var _require$$3$builders = doc.builders,
16761 concat$5 = _require$$3$builders.concat,
16762 join$2 = _require$$3$builders.join,
16763 line$1 = _require$$3$builders.line,
16764 hardline$4 = _require$$3$builders.hardline,
16765 softline$1 = _require$$3$builders.softline,
16766 group$1 = _require$$3$builders.group,
16767 fill$2 = _require$$3$builders.fill,
16768 indent$2 = _require$$3$builders.indent,
16769 dedent$1 = _require$$3$builders.dedent,
16770 ifBreak$1 = _require$$3$builders.ifBreak,
16771 removeLines$1 = doc.utils.removeLines;
16772 var getAncestorNode$1 = utils$2.getAncestorNode,
16773 getPropOfDeclNode$1 = utils$2.getPropOfDeclNode,
16774 maybeToLowerCase$1 = utils$2.maybeToLowerCase,
16775 insideValueFunctionNode$1 = utils$2.insideValueFunctionNode,
16776 insideICSSRuleNode$1 = utils$2.insideICSSRuleNode,
16777 insideAtRuleNode$1 = utils$2.insideAtRuleNode,
16778 insideURLFunctionInImportAtRuleNode$1 = utils$2.insideURLFunctionInImportAtRuleNode,
16779 isKeyframeAtRuleKeywords$1 = utils$2.isKeyframeAtRuleKeywords,
16780 isHTMLTag$1 = utils$2.isHTMLTag,
16781 isWideKeywords$1 = utils$2.isWideKeywords,
16782 isSCSS$1 = utils$2.isSCSS,
16783 isLastNode$1 = utils$2.isLastNode,
16784 isSCSSControlDirectiveNode$1 = utils$2.isSCSSControlDirectiveNode,
16785 isDetachedRulesetDeclarationNode$1 = utils$2.isDetachedRulesetDeclarationNode,
16786 isRelationalOperatorNode$1 = utils$2.isRelationalOperatorNode,
16787 isEqualityOperatorNode$1 = utils$2.isEqualityOperatorNode,
16788 isMultiplicationNode$1 = utils$2.isMultiplicationNode,
16789 isDivisionNode$1 = utils$2.isDivisionNode,
16790 isAdditionNode$1 = utils$2.isAdditionNode,
16791 isSubtractionNode$1 = utils$2.isSubtractionNode,
16792 isMathOperatorNode$1 = utils$2.isMathOperatorNode,
16793 isEachKeywordNode$1 = utils$2.isEachKeywordNode,
16794 isForKeywordNode$1 = utils$2.isForKeywordNode,
16795 isURLFunctionNode$1 = utils$2.isURLFunctionNode,
16796 isIfElseKeywordNode$1 = utils$2.isIfElseKeywordNode,
16797 hasComposesNode$1 = utils$2.hasComposesNode,
16798 hasParensAroundNode$1 = utils$2.hasParensAroundNode,
16799 hasEmptyRawBefore$1 = utils$2.hasEmptyRawBefore,
16800 isKeyValuePairNode$1 = utils$2.isKeyValuePairNode,
16801 isDetachedRulesetCallNode$1 = utils$2.isDetachedRulesetCallNode,
16802 isTemplatePlaceholderNode$1 = utils$2.isTemplatePlaceholderNode,
16803 isTemplatePropNode$1 = utils$2.isTemplatePropNode,
16804 isPostcssSimpleVarNode$1 = utils$2.isPostcssSimpleVarNode,
16805 isSCSSMapItemNode$1 = utils$2.isSCSSMapItemNode,
16806 isInlineValueCommentNode$1 = utils$2.isInlineValueCommentNode,
16807 isHashNode$1 = utils$2.isHashNode,
16808 isLeftCurlyBraceNode$1 = utils$2.isLeftCurlyBraceNode,
16809 isRightCurlyBraceNode$1 = utils$2.isRightCurlyBraceNode,
16810 isWordNode$1 = utils$2.isWordNode,
16811 isColonNode$1 = utils$2.isColonNode,
16812 isMediaAndSupportsKeywords$1 = utils$2.isMediaAndSupportsKeywords,
16813 isColorAdjusterFuncNode$1 = utils$2.isColorAdjusterFuncNode;
16815 function shouldPrintComma(options) {
16816 switch (options.trailingComma) {
16827 function genericPrint(path, options, print) {
16828 var node = path.getValue();
16829 /* istanbul ignore if */
16835 if (typeof node === "string") {
16839 switch (node.type) {
16842 return concat$5([node.raw, hardline$4]);
16846 var nodes = printNodeSequence(path, options, print);
16848 if (nodes.parts.length) {
16849 return concat$5([nodes, hardline$4]);
16855 case "css-comment":
16857 if (node.raws.content) {
16858 return node.raws.content;
16861 var text = options.originalText.slice(options.locStart(node), options.locEnd(node));
16862 var rawText = node.raws.text || node.text; // Workaround a bug where the location is off.
16863 // https://github.com/postcss/postcss-scss/issues/63
16865 if (text.indexOf(rawText) === -1) {
16866 if (node.raws.inline) {
16867 return concat$5(["// ", rawText]);
16870 return concat$5(["/* ", rawText, " */"]);
16878 return concat$5([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$5([" {", node.nodes.length > 0 ? indent$2(concat$5([hardline$4, printNodeSequence(path, options, print)])) : "", hardline$4, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
16883 var parentNode = path.getParentNode();
16884 return concat$5([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$1(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$5([" {", indent$2(concat$5([softline$1, printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
16889 var _parentNode = path.getParentNode();
16891 return concat$5(["@", // If a Less file ends up being parsed with the SCSS parser, Less
16892 // variable declarations will be parsed as at-rules with names ending
16893 // with a colon, so keep the original case then.
16894 isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$5([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) && /^\s*\n/.test(node.raws.afterName) ? /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$5([hardline$4, hardline$4]) : hardline$4 : " ", path.call(print, "params")]) : "", node.selector ? indent$2(concat$5([" ", path.call(print, "selector")])) : "", node.value ? group$1(concat$5([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$1 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$5([isSCSSControlDirectiveNode$1(node) ? "" : " ", "{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePlaceholderNode$1(node) && !_parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
16896 // postcss-media-query-parser
16898 case "media-query-list":
16901 path.each(function (childPath) {
16902 var node = childPath.getValue();
16904 if (node.type === "media-query" && node.value === "") {
16908 parts.push(childPath.call(print));
16910 return group$1(indent$2(join$2(line$1, parts)));
16913 case "media-query":
16915 return concat$5([join$2(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
16920 return adjustNumbers(adjustStrings(node.value, options));
16923 case "media-feature-expression":
16929 return concat$5(["(", concat$5(path.map(print, "nodes")), ")"]);
16932 case "media-feature":
16934 return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
16937 case "media-colon":
16939 return concat$5([node.value, " "]);
16942 case "media-value":
16944 return adjustNumbers(adjustStrings(node.value, options));
16947 case "media-keyword":
16949 return adjustStrings(node.value, options);
16954 return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
16957 case "media-unknown":
16961 // postcss-selector-parser
16963 case "selector-root":
16965 return group$1(concat$5([insideAtRuleNode$1(path, "custom-selector") ? concat$5([getAncestorNode$1(path, "css-atrule").customSelector, line$1]) : "", join$2(concat$5([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$1 : hardline$4]), path.map(print, "nodes"))]));
16968 case "selector-selector":
16970 return group$1(indent$2(concat$5(path.map(print, "nodes"))));
16973 case "selector-comment":
16978 case "selector-string":
16980 return adjustStrings(node.value, options);
16983 case "selector-tag":
16985 var _parentNode2 = path.getParentNode();
16987 var index = _parentNode2 && _parentNode2.nodes.indexOf(node);
16989 var prevNode = index && _parentNode2.nodes[index - 1];
16990 return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isHTMLTag$1(node.value) || isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
16993 case "selector-id":
16995 return concat$5(["#", node.value]);
16998 case "selector-class":
17000 return concat$5([".", adjustNumbers(adjustStrings(node.value, options))]);
17003 case "selector-attribute":
17005 return concat$5(["[", node.namespace ? concat$5([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" : "", "]"]);
17008 case "selector-combinator":
17010 if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
17011 var _parentNode3 = path.getParentNode();
17013 var _leading = _parentNode3.type === "selector-selector" && _parentNode3.nodes[0] === node ? "" : line$1;
17015 return concat$5([_leading, node.value, isLastNode$1(path, node) ? "" : " "]);
17018 var leading = node.value.trim().startsWith("(") ? line$1 : "";
17019 var value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$1;
17020 return concat$5([leading, value]);
17023 case "selector-universal":
17025 return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
17028 case "selector-pseudo":
17030 return concat$5([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$5(["(", join$2(", ", path.map(print, "nodes")), ")"]) : ""]);
17033 case "selector-nesting":
17038 case "selector-unknown":
17040 var ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
17042 if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
17043 return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
17048 // postcss-values-parser
17050 case "value-value":
17053 return path.call(print, "group");
17056 case "value-comment":
17058 return concat$5([node.inline ? "//" : "/*", node.value, node.inline ? "" : "*/"]);
17061 case "value-comma_group":
17063 var _parentNode4 = path.getParentNode();
17065 var parentParentNode = path.getParentNode(1);
17066 var declAncestorProp = getPropOfDeclNode$1(path);
17067 var isGridValue = declAncestorProp && _parentNode4.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
17068 var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
17069 var isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
17070 var printed = path.map(print, "groups");
17072 var insideURLFunction = insideValueFunctionNode$1(path, "url");
17073 var insideSCSSInterpolationInString = false;
17074 var didBreak = false;
17076 for (var i = 0; i < node.groups.length; ++i) {
17077 _parts.push(printed[i]); // Ignore value inside `url()`
17080 if (insideURLFunction) {
17084 var iPrevNode = node.groups[i - 1];
17085 var iNode = node.groups[i];
17086 var iNextNode = node.groups[i + 1];
17087 var iNextNextNode = node.groups[i + 2]; // Ignore after latest node (i.e. before semicolon)
17091 } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
17094 var isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
17095 var isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
17097 if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
17098 insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
17102 if (insideSCSSInterpolationInString) {
17104 } // Ignore colon (i.e. `:`)
17107 if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
17109 } // Ignore `@` in Less (i.e. `@@var;`)
17112 if (iNode.type === "value-atword" && iNode.value === "") {
17114 } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
17117 if (iNode.value === "~") {
17119 } // Ignore escape `\`
17122 if (iNode.value && iNode.value.indexOf("\\") !== -1 && iNextNode && iNextNode.type !== "value-comment") {
17124 } // Ignore escaped `/`
17127 if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
17129 } // Ignore `\` (i.e. `$variable: \@small;`)
17132 if (iNode.value === "\\") {
17134 } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
17137 if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
17139 } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
17142 if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
17144 } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
17147 if (iNode.value === "--" && isHashNode$1(iNextNode)) {
17149 } // Formatting math operations
17152 var isMathOperator = isMathOperatorNode$1(iNode);
17153 var isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
17154 // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
17155 // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
17157 if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
17159 } // Print spaces before and after addition and subtraction math operators as is in `calc` function
17160 // due to the fact that it is not valid syntax
17161 // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
17164 if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
17166 } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
17167 // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
17170 var isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
17171 var requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
17172 var requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
17174 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)))) {
17176 } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
17179 if (isInlineValueCommentNode$1(iNode)) {
17180 _parts.push(hardline$4);
17183 } // Handle keywords in SCSS control directive
17186 if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
17190 } // At-rule `namespace` should be in one line
17193 if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
17197 } // Formatting `grid` property
17201 if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
17202 _parts.push(hardline$4);
17210 } // Add `space` before next math operation
17211 // Note: `grip` property have `/` delimiter and it is not math operation, so
17212 // `grid` property handles above
17215 if (isNextMathOperator) {
17219 } // Be default all values go through `line`
17222 _parts.push(line$1);
17226 _parts.unshift(hardline$4);
17229 if (isControlDirective) {
17230 return group$1(indent$2(concat$5(_parts)));
17231 } // Indent is not needed for import url when url is very long
17232 // and node has two groups
17233 // when type is value-comma_group
17234 // example @import url("verylongurl") projection,tv
17237 if (insideURLFunctionInImportAtRuleNode$1(path)) {
17238 return group$1(fill$2(_parts));
17241 return group$1(indent$2(fill$2(_parts)));
17244 case "value-paren_group":
17246 var _parentNode5 = path.getParentNode();
17248 if (_parentNode5 && isURLFunctionNode$1(_parentNode5) && (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:"))) {
17249 return concat$5([node.open ? path.call(print, "open") : "", join$2(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
17253 var _printed = path.map(print, "groups");
17257 for (var _i = 0; _i < _printed.length; _i++) {
17259 res.push(concat$5([",", line$1]));
17262 res.push(_printed[_i]);
17265 return group$1(indent$2(fill$2(res)));
17268 var isSCSSMapItem = isSCSSMapItemNode$1(path);
17269 return group$1(concat$5([node.open ? path.call(print, "open") : "", indent$2(concat$5([softline$1, join$2(concat$5([",", line$1]), path.map(function (childPath) {
17270 var node = childPath.getValue();
17271 var printed = print(childPath); // Key/Value pair in open paren already indented
17273 if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
17274 printed.contents.contents.parts[1] = group$1(printed.contents.contents.parts[1]);
17275 return group$1(dedent$1(printed));
17279 }, "groups"))])), ifBreak$1(isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$1, node.close ? path.call(print, "close") : ""]), {
17280 shouldBreak: isSCSSMapItem
17286 return concat$5([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
17289 case "value-paren":
17294 case "value-number":
17296 return concat$5([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
17299 case "value-operator":
17306 if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
17307 return node.value.toLowerCase();
17313 case "value-colon":
17315 return concat$5([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
17316 insideValueFunctionNode$1(path, "url") ? "" : line$1]);
17319 case "value-comma":
17321 return concat$5([node.value, " "]);
17324 case "value-string":
17326 return printString$1(node.raws.quote + node.value + node.raws.quote, options);
17329 case "value-atword":
17331 return concat$5(["@", node.value]);
17334 case "value-unicode-range":
17339 case "value-unknown":
17345 /* istanbul ignore next */
17346 throw new Error("Unknown postcss type ".concat(JSON.stringify(node.type)));
17350 function printNodeSequence(path, options, print) {
17351 var node = path.getValue();
17354 path.map(function (pathChild) {
17355 var prevNode = node.nodes[i - 1];
17357 if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
17358 var childNode = pathChild.getValue();
17359 parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
17361 parts.push(pathChild.call(print));
17364 if (i !== node.nodes.length - 1) {
17365 if (node.nodes[i + 1].type === "css-comment" && !hasNewline$2(options.originalText, options.locStart(node.nodes[i + 1]), {
17367 }) && 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") {
17370 parts.push(hardline$4);
17372 if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), options) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") {
17373 parts.push(hardline$4);
17380 return concat$5(parts);
17383 var STRING_REGEX$1 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
17384 var NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
17385 var STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
17386 var WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
17387 var ADJUST_NUMBERS_REGEX = RegExp(STRING_REGEX$1.source + "|" + "(".concat(WORD_PART_REGEX.source, ")?") + "(".concat(NUMBER_REGEX.source, ")") + "(".concat(STANDARD_UNIT_REGEX.source, ")?"), "g");
17389 function adjustStrings(value, options) {
17390 return value.replace(STRING_REGEX$1, function (match) {
17391 return printString$1(match, options);
17395 function quoteAttributeValue(value, options) {
17396 var quote = options.singleQuote ? "'" : '"';
17397 return value.includes('"') || value.includes("'") ? value : quote + value + quote;
17400 function adjustNumbers(value) {
17401 return value.replace(ADJUST_NUMBERS_REGEX, function (match, quote, wordPart, number, unit) {
17402 return !wordPart && number ? (wordPart || "") + printCssNumber(number) + maybeToLowerCase$1(unit || "") : match;
17406 function printCssNumber(rawNumber) {
17407 return printNumber$1(rawNumber) // Remove trailing `.0`.
17408 .replace(/\.0(?=$|e)/, "");
17411 var printerPostcss = {
17412 print: genericPrint,
17414 insertPragma: insertPragma$2,
17415 hasPrettierIgnore: hasIgnoreComment$1,
17416 massageAstNode: clean_1
17419 var CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
17421 var commonOptions = {
17424 category: CATEGORY_COMMON,
17427 description: "Print spaces between brackets.",
17428 oppositeDescription: "Do not print spaces between brackets."
17432 category: CATEGORY_COMMON,
17435 description: "Use single quotes instead of double quotes."
17439 category: CATEGORY_COMMON,
17448 description: "How to wrap prose.",
17452 description: "Wrap prose if it exceeds the print width."
17456 description: "Do not wrap prose."
17460 description: "Wrap prose as-is."
17463 deprecated: "1.9.0",
17467 deprecated: "1.9.0",
17474 singleQuote: commonOptions.singleQuote
17477 var createLanguage = function createLanguage(linguistData, transform) {
17480 for (var key in linguistData) {
17481 var newKey = key === "languageId" ? "linguistLanguageId" : key;
17482 language[newKey] = linguistData[key];
17485 return transform(language);
17488 var name$1 = "CSS";
17489 var type = "markup";
17490 var tmScope = "source.css";
17491 var aceMode = "css";
17492 var codemirrorMode = "css";
17493 var codemirrorMimeType = "text/css";
17494 var color = "#563d7c";
17498 var languageId = 50;
17504 codemirrorMode: codemirrorMode,
17505 codemirrorMimeType: codemirrorMimeType,
17507 extensions: extensions,
17508 languageId: languageId
17511 var CSS$1 = /*#__PURE__*/Object.freeze({
17517 codemirrorMode: codemirrorMode,
17518 codemirrorMimeType: codemirrorMimeType,
17520 extensions: extensions,
17521 languageId: languageId,
17525 var name$2 = "PostCSS";
17526 var type$1 = "markup";
17527 var tmScope$1 = "source.postcss";
17528 var group$2 = "CSS";
17529 var extensions$1 = [
17532 var aceMode$1 = "text";
17533 var languageId$1 = 262764437;
17537 tmScope: tmScope$1,
17539 extensions: extensions$1,
17540 aceMode: aceMode$1,
17541 languageId: languageId$1
17544 var PostCSS$1 = /*#__PURE__*/Object.freeze({
17548 tmScope: tmScope$1,
17550 extensions: extensions$1,
17551 aceMode: aceMode$1,
17552 languageId: languageId$1,
17556 var name$3 = "Less";
17557 var type$2 = "markup";
17558 var group$3 = "CSS";
17559 var extensions$2 = [
17562 var tmScope$2 = "source.css.less";
17563 var aceMode$2 = "less";
17564 var codemirrorMode$1 = "css";
17565 var codemirrorMimeType$1 = "text/css";
17566 var languageId$2 = 198;
17571 extensions: extensions$2,
17572 tmScope: tmScope$2,
17573 aceMode: aceMode$2,
17574 codemirrorMode: codemirrorMode$1,
17575 codemirrorMimeType: codemirrorMimeType$1,
17576 languageId: languageId$2
17579 var Less$1 = /*#__PURE__*/Object.freeze({
17584 extensions: extensions$2,
17585 tmScope: tmScope$2,
17586 aceMode: aceMode$2,
17587 codemirrorMode: codemirrorMode$1,
17588 codemirrorMimeType: codemirrorMimeType$1,
17589 languageId: languageId$2,
17593 var name$4 = "SCSS";
17594 var type$3 = "markup";
17595 var tmScope$3 = "source.css.scss";
17596 var group$4 = "CSS";
17597 var aceMode$3 = "scss";
17598 var codemirrorMode$2 = "css";
17599 var codemirrorMimeType$2 = "text/x-scss";
17600 var extensions$3 = [
17603 var languageId$3 = 329;
17607 tmScope: tmScope$3,
17609 aceMode: aceMode$3,
17610 codemirrorMode: codemirrorMode$2,
17611 codemirrorMimeType: codemirrorMimeType$2,
17612 extensions: extensions$3,
17613 languageId: languageId$3
17616 var SCSS$1 = /*#__PURE__*/Object.freeze({
17620 tmScope: tmScope$3,
17622 aceMode: aceMode$3,
17623 codemirrorMode: codemirrorMode$2,
17624 codemirrorMimeType: codemirrorMimeType$2,
17625 extensions: extensions$3,
17626 languageId: languageId$3,
17630 var require$$0$2 = getCjsExportFromNamespace(CSS$1);
17632 var require$$1 = getCjsExportFromNamespace(PostCSS$1);
17634 var require$$2 = getCjsExportFromNamespace(Less$1);
17636 var require$$3 = getCjsExportFromNamespace(SCSS$1);
17638 var languages = [createLanguage(require$$0$2, function (data) {
17639 return Object.assign(data, {
17642 vscodeLanguageIds: ["css"]
17644 }), createLanguage(require$$1, function (data) {
17645 return Object.assign(data, {
17648 vscodeLanguageIds: ["postcss"],
17649 extensions: data.extensions.concat(".postcss")
17651 }), createLanguage(require$$2, function (data) {
17652 return Object.assign(data, {
17655 vscodeLanguageIds: ["less"]
17657 }), createLanguage(require$$3, function (data) {
17658 return Object.assign(data, {
17661 vscodeLanguageIds: ["scss"]
17665 postcss: printerPostcss
17667 var languageCss = {
17668 languages: languages,
17669 options: options$2,
17673 function hasPragma$2(text) {
17674 return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text);
17677 function insertPragma$3(text) {
17678 return "# @format\n\n" + text;
17682 hasPragma: hasPragma$2,
17683 insertPragma: insertPragma$3
17686 var _require$$0$builders$2 = doc.builders,
17687 concat$6 = _require$$0$builders$2.concat,
17688 join$3 = _require$$0$builders$2.join,
17689 hardline$5 = _require$$0$builders$2.hardline,
17690 line$2 = _require$$0$builders$2.line,
17691 softline$2 = _require$$0$builders$2.softline,
17692 group$5 = _require$$0$builders$2.group,
17693 indent$3 = _require$$0$builders$2.indent,
17694 ifBreak$2 = _require$$0$builders$2.ifBreak;
17695 var hasIgnoreComment$2 = util.hasIgnoreComment;
17696 var isNextLineEmpty$3 = utilShared.isNextLineEmpty;
17697 var insertPragma$4 = pragma$2.insertPragma;
17699 function genericPrint$1(path, options, print) {
17700 var n = path.getValue();
17706 if (typeof n === "string") {
17714 path.map(function (pathChild, index) {
17715 parts.push(concat$6([pathChild.call(print)]));
17717 if (index !== n.definitions.length - 1) {
17718 parts.push(hardline$5);
17720 if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options)) {
17721 parts.push(hardline$5);
17725 return concat$6([concat$6(parts), hardline$5]);
17728 case "OperationDefinition":
17730 var hasOperation = options.originalText[options.locStart(n)] !== "{";
17731 var hasName = !!n.name;
17732 return concat$6([hasOperation ? n.operation : "", hasOperation && hasName ? concat$6([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
17735 case "FragmentDefinition":
17737 return concat$6(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
17740 case "SelectionSet":
17742 return concat$6(["{", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (selectionsPath) {
17743 return printSequence(selectionsPath, options, print);
17744 }, "selections"))])), hardline$5, "}"]);
17749 return group$5(concat$6([n.alias ? concat$6([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(function (argsPath) {
17750 return printSequence(argsPath, options, print);
17751 }, "arguments"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
17759 case "StringValue":
17762 return concat$6(['"""', hardline$5, join$3(hardline$5, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$5, '"""']);
17765 return concat$6(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
17775 case "BooleanValue":
17777 return n.value ? "true" : "false";
17787 return concat$6(["$", path.call(print, "name")]);
17792 return group$5(concat$6(["[", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "values"))])), softline$2, "]"]));
17795 case "ObjectValue":
17797 return group$5(concat$6(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "fields"))])), softline$2, ifBreak$2("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
17800 case "ObjectField":
17803 return concat$6([path.call(print, "name"), ": ", path.call(print, "value")]);
17808 return concat$6(["@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(function (argsPath) {
17809 return printSequence(argsPath, options, print);
17810 }, "arguments"))])), softline$2, ")"])) : ""]);
17815 return path.call(print, "name");
17818 case "VariableDefinition":
17820 return concat$6([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
17823 case "TypeExtensionDefinition":
17825 return concat$6(["extend ", path.call(print, "definition")]);
17828 case "ObjectTypeExtension":
17829 case "ObjectTypeDefinition":
17831 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$6([" implements ", join$3(determineInterfaceSeparator(options.originalText.substr(options.locStart(n), options.locEnd(n))), path.map(print, "interfaces"))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (fieldsPath) {
17832 return printSequence(fieldsPath, options, print);
17833 }, "fields"))])), hardline$5, "}"]) : ""]);
17836 case "FieldDefinition":
17838 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(function (argsPath) {
17839 return printSequence(argsPath, options, print);
17840 }, "arguments"))])), softline$2, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
17843 case "DirectiveDefinition":
17845 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(function (argsPath) {
17846 return printSequence(argsPath, options, print);
17847 }, "arguments"))])), softline$2, ")"])) : "", concat$6([" on ", join$3(" | ", path.map(print, "locations"))])]);
17850 case "EnumTypeExtension":
17851 case "EnumTypeDefinition":
17853 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (valuesPath) {
17854 return printSequence(valuesPath, options, print);
17855 }, "values"))])), hardline$5, "}"]) : ""]);
17858 case "EnumValueDefinition":
17860 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), printDirectives(path, print, n)]);
17863 case "InputValueDefinition":
17865 return concat$6([path.call(print, "description"), n.description ? n.description.block ? hardline$5 : line$2 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
17868 case "InputObjectTypeExtension":
17869 case "InputObjectTypeDefinition":
17871 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (fieldsPath) {
17872 return printSequence(fieldsPath, options, print);
17873 }, "fields"))])), hardline$5, "}"]) : ""]);
17876 case "SchemaDefinition":
17878 return concat$6(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (opsPath) {
17879 return printSequence(opsPath, options, print);
17880 }, "operationTypes"))])) : "", hardline$5, "}"]);
17883 case "OperationTypeDefinition":
17885 return concat$6([path.call(print, "operation"), ": ", path.call(print, "type")]);
17888 case "InterfaceTypeExtension":
17889 case "InterfaceTypeDefinition":
17891 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (fieldsPath) {
17892 return printSequence(fieldsPath, options, print);
17893 }, "fields"))])), hardline$5, "}"]) : ""]);
17896 case "FragmentSpread":
17898 return concat$6(["...", path.call(print, "name"), printDirectives(path, print, n)]);
17901 case "InlineFragment":
17903 return concat$6(["...", n.typeCondition ? concat$6([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
17906 case "UnionTypeExtension":
17907 case "UnionTypeDefinition":
17909 return group$5(concat$6([path.call(print, "description"), n.description ? hardline$5 : "", group$5(concat$6([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$6([" =", ifBreak$2("", " "), indent$3(concat$6([ifBreak$2(concat$6([line$2, " "])), join$3(concat$6([line$2, "| "]), path.map(print, "types"))]))]) : ""]))]));
17912 case "ScalarTypeExtension":
17913 case "ScalarTypeDefinition":
17915 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
17918 case "NonNullType":
17920 return concat$6([path.call(print, "type"), "!"]);
17925 return concat$6(["[", path.call(print, "type"), "]"]);
17929 /* istanbul ignore next */
17930 throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
17934 function printDirectives(path, print, n) {
17935 if (n.directives.length === 0) {
17939 return concat$6([" ", group$5(indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", " "), softline$2]), path.map(print, "directives"))])))]);
17942 function printSequence(sequencePath, options, print) {
17943 var count = sequencePath.getValue().length;
17944 return sequencePath.map(function (path, i) {
17945 var printed = print(path);
17947 if (isNextLineEmpty$3(options.originalText, path.getValue(), options) && i < count - 1) {
17948 return concat$6([printed, hardline$5]);
17955 function canAttachComment(node) {
17956 return node.kind && node.kind !== "Comment";
17959 function printComment$1(commentPath) {
17960 var comment = commentPath.getValue();
17962 if (comment.kind === "Comment") {
17963 return "#" + comment.value.trimRight();
17966 throw new Error("Not a comment: " + JSON.stringify(comment));
17969 function determineInterfaceSeparator(originalSource) {
17970 var start = originalSource.indexOf("implements");
17972 if (start === -1) {
17973 throw new Error("Must implement interfaces: " + originalSource);
17976 var end = originalSource.indexOf("{");
17979 end = originalSource.length;
17982 return originalSource.substr(start, end).includes("&") ? " & " : ", ";
17985 function clean$1(node, newNode
17988 delete newNode.loc;
17989 delete newNode.comments;
17992 var printerGraphql = {
17993 print: genericPrint$1,
17994 massageAstNode: clean$1,
17995 hasPrettierIgnore: hasIgnoreComment$2,
17996 insertPragma: insertPragma$4,
17997 printComment: printComment$1,
17998 canAttachComment: canAttachComment
18002 bracketSpacing: commonOptions.bracketSpacing
18005 var name$5 = "GraphQL";
18006 var type$4 = "data";
18007 var extensions$4 = [
18012 var tmScope$4 = "source.graphql";
18013 var aceMode$4 = "text";
18014 var languageId$4 = 139;
18018 extensions: extensions$4,
18019 tmScope: tmScope$4,
18020 aceMode: aceMode$4,
18021 languageId: languageId$4
18024 var GraphQL$1 = /*#__PURE__*/Object.freeze({
18028 extensions: extensions$4,
18029 tmScope: tmScope$4,
18030 aceMode: aceMode$4,
18031 languageId: languageId$4,
18035 var require$$0$3 = getCjsExportFromNamespace(GraphQL$1);
18037 var languages$1 = [createLanguage(require$$0$3, function (data) {
18038 return Object.assign(data, {
18040 parsers: ["graphql"],
18041 vscodeLanguageIds: ["graphql"]
18045 graphql: printerGraphql
18047 var languageGraphql = {
18048 languages: languages$1,
18049 options: options$3,
18050 printers: printers$1
18053 var _require$$0$builders$3 = doc.builders,
18054 concat$7 = _require$$0$builders$3.concat,
18055 join$4 = _require$$0$builders$3.join,
18056 softline$3 = _require$$0$builders$3.softline,
18057 hardline$6 = _require$$0$builders$3.hardline,
18058 line$3 = _require$$0$builders$3.line,
18059 group$6 = _require$$0$builders$3.group,
18060 indent$4 = _require$$0$builders$3.indent,
18061 ifBreak$3 = _require$$0$builders$3.ifBreak; // http://w3c.github.io/html/single-page.html#void-elements
18063 var 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:
18064 // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
18066 function printChildren(path, options, print) {
18067 return concat$7(path.map(function (childPath, childIndex) {
18068 var childNode = path.getValue();
18069 var isFirstNode = childIndex === 0;
18070 var isLastNode = childIndex == path.getParentNode(0).children.length - 1;
18071 var isLastNodeInMultiNodeList = isLastNode && !isFirstNode;
18072 var isWhitespace = isWhitespaceNode(childNode);
18074 if (isWhitespace && isLastNodeInMultiNodeList) {
18075 return print(childPath, options, print);
18076 } else if (isFirstNode) {
18077 return concat$7([softline$3, print(childPath, options, print)]);
18080 return print(childPath, options, print);
18084 function print(path, options, print) {
18085 var n = path.getValue();
18086 /* istanbul ignore if*/
18097 return group$6(concat$7(path.map(print, "body").filter(function (text) {
18098 return text !== "";
18102 case "ElementNode":
18104 var tagFirstChar = n.tag[0];
18105 var isLocal = n.tag.indexOf(".") !== -1;
18106 var isGlimmerComponent = tagFirstChar.toUpperCase() === tagFirstChar || isLocal;
18107 var hasChildren = n.children.length > 0;
18108 var hasNonWhitespaceChildren = n.children.some(function (n) {
18109 return !isWhitespaceNode(n);
18111 var isVoid = isGlimmerComponent && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.indexOf(n.tag) !== -1;
18112 var closeTagForNoBreak = isVoid ? concat$7([" />", softline$3]) : ">";
18113 var closeTagForBreak = isVoid ? "/>" : ">";
18115 var _getParams = function _getParams(path, print) {
18116 return indent$4(concat$7([n.attributes.length ? line$3 : "", join$4(line$3, path.map(print, "attributes")), n.modifiers.length ? line$3 : "", join$4(line$3, path.map(print, "modifiers")), n.comments.length ? line$3 : "", join$4(line$3, path.map(print, "comments"))]));
18119 var nextNode = getNextNode(path);
18120 return concat$7([group$6(concat$7(["<", n.tag, _getParams(path, print), n.blockParams.length ? " as |".concat(n.blockParams.join(" "), "|") : "", ifBreak$3(softline$3, ""), ifBreak$3(closeTagForBreak, closeTagForNoBreak)])), !isVoid ? group$6(concat$7([hasNonWhitespaceChildren ? indent$4(printChildren(path, options, print)) : "", ifBreak$3(hasChildren ? hardline$6 : "", ""), concat$7(["</", n.tag, ">"])])) : "", nextNode && nextNode.type === "ElementNode" ? hardline$6 : ""]);
18123 case "BlockStatement":
18125 var pp = path.getParentNode(1);
18126 var isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
18127 var hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if";
18128 var indentElse = hasElseIf ? function (a) {
18133 return concat$7([isElseIf ? concat$7(["{{else ", printPathParams(path, print), "}}"]) : printOpenBlock(path, print), indent$4(concat$7([hardline$6, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$7([hardline$6, "{{else}}"]) : "", n.inverse ? indentElse(concat$7([hardline$6, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$7([hardline$6, printCloseBlock(path, print)])]);
18134 } else if (isElseIf) {
18135 return concat$7([concat$7(["{{else ", printPathParams(path, print), "}}"]), indent$4(concat$7([hardline$6, path.call(print, "program")]))]);
18138 var _hasNonWhitespaceChildren = n.program.body.some(function (n) {
18139 return !isWhitespaceNode(n);
18142 return concat$7([printOpenBlock(path, print), group$6(concat$7([indent$4(concat$7([softline$3, path.call(print, "program")])), _hasNonWhitespaceChildren ? hardline$6 : softline$3, printCloseBlock(path, print)]))]);
18145 case "ElementModifierStatement":
18146 case "MustacheStatement":
18148 var _pp = path.getParentNode(1);
18150 var isConcat = _pp && _pp.type === "ConcatStatement";
18151 return group$6(concat$7([n.escaped === false ? "{{{" : "{{", printPathParams(path, print, {
18153 }), isConcat ? "" : softline$3, n.escaped === false ? "}}}" : "}}"]));
18156 case "SubExpression":
18158 var params = getParams(path, print);
18159 var printedParams = params.length > 0 ? indent$4(concat$7([line$3, group$6(join$4(line$3, params))])) : "";
18160 return group$6(concat$7(["(", printPath(path, print), printedParams, softline$3, ")"]));
18165 var isText = n.value.type === "TextNode";
18167 if (isText && n.value.loc.start.column === n.value.loc.end.column) {
18168 return concat$7([n.name]);
18171 var value = path.call(print, "value");
18172 var quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
18173 return concat$7([n.name, "=", quotedValue]);
18176 case "ConcatStatement":
18178 return concat$7(['"', group$6(indent$4(join$4(softline$3, path.map(function (partPath) {
18179 return print(partPath);
18180 }, "parts").filter(function (a) {
18187 return concat$7([join$4(line$3, path.map(print, "pairs"))]);
18192 return concat$7([n.key, "=", path.call(print, "value")]);
18197 var maxLineBreaksToPreserve = 2;
18198 var isFirstElement = !getPreviousNode(path);
18199 var isLastElement = !getNextNode(path);
18200 var isWhitespaceOnly = !/\S/.test(n.chars);
18201 var lineBreaksCount = countNewLines(n.chars);
18202 var hasBlockParent = path.getParentNode(0).type === "Block";
18203 var hasElementParent = path.getParentNode(0).type === "ElementNode";
18204 var hasTemplateParent = path.getParentNode(0).type === "Template";
18205 var leadingLineBreaksCount = countLeadingNewLines(n.chars);
18206 var trailingLineBreaksCount = countTrailingNewLines(n.chars);
18208 if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) {
18212 if (isWhitespaceOnly && lineBreaksCount) {
18213 leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
18214 trailingLineBreaksCount = 0;
18216 if (isNextNodeOfType(path, "ElementNode") || isNextNodeOfType(path, "BlockStatement")) {
18217 trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
18220 if (isPreviousNodeOfSomeType(path, ["ElementNode"]) || isPreviousNodeOfSomeType(path, ["BlockStatement"])) {
18221 leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
18225 var leadingSpace = "";
18226 var trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present,
18227 // when next to mustache statement.
18229 var inAttrNode = path.stack.indexOf("attributes") >= 0;
18232 var parentNode = path.getParentNode(0);
18234 var _isConcat = parentNode.type === "ConcatStatement";
18237 var parts = parentNode.parts;
18238 var partIndex = parts.indexOf(n);
18240 if (partIndex > 0) {
18241 var partType = parts[partIndex - 1].type;
18242 var isMustache = partType === "MustacheStatement";
18245 leadingSpace = " ";
18249 if (partIndex < parts.length - 1) {
18250 var _partType = parts[partIndex + 1].type;
18252 var _isMustache = _partType === "MustacheStatement";
18255 trailingSpace = " ";
18260 if (trailingLineBreaksCount === 0 && isNextNodeOfType(path, "MustacheStatement")) {
18261 trailingSpace = " ";
18264 if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType(path, ["MustacheStatement"])) {
18265 leadingSpace = " ";
18268 if (isFirstElement) {
18269 leadingLineBreaksCount = 0;
18273 if (isLastElement) {
18274 trailingLineBreaksCount = 0;
18275 trailingSpace = "";
18279 return concat$7([].concat(_toConsumableArray(generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve)), [n.chars.replace(/^[\s ]+/g, leadingSpace).replace(/[\s ]+$/, trailingSpace)], _toConsumableArray(generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve))).filter(Boolean));
18282 case "MustacheCommentStatement":
18284 var dashes = n.value.indexOf("}}") > -1 ? "--" : "";
18285 return concat$7(["{{!", dashes, n.value, dashes, "}}"]);
18288 case "PathExpression":
18293 case "BooleanLiteral":
18295 return String(n.value);
18298 case "CommentStatement":
18300 return concat$7(["<!--", n.value, "-->"]);
18303 case "StringLiteral":
18305 return printStringLiteral(n.value, options);
18308 case "NumberLiteral":
18310 return String(n.value);
18313 case "UndefinedLiteral":
18315 return "undefined";
18318 case "NullLiteral":
18323 /* istanbul ignore next */
18326 throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
18330 * Prints a string literal with the correct surrounding quotes based on
18331 * `options.singleQuote` and the number of escaped quotes contained in
18332 * the string literal. This function is the glimmer equivalent of `printString`
18333 * in `common/util`, but has differences because of the way escaped characters
18334 * are treated in hbs string literals.
18335 * @param {string} stringLiteral - the string literal value
18336 * @param {object} options - the prettier options object
18340 function printStringLiteral(stringLiteral, options) {
18349 var preferred = options.singleQuote ? single : double;
18350 var alternate = preferred === single ? double : single;
18351 var shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
18352 // enclosing the string, we might want to enclose with the alternate quote
18353 // instead, to minimize the number of escaped quotes.
18355 if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
18356 var numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
18357 var numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
18358 shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
18361 var enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
18362 var escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, "\\".concat(enclosingQuote.quote));
18363 return "".concat(enclosingQuote.quote).concat(escapedStringLiteral).concat(enclosingQuote.quote);
18366 function printPath(path, print) {
18367 return path.call(print, "path");
18370 function getParams(path, print) {
18371 var node = path.getValue();
18374 if (node.params.length > 0) {
18375 parts = parts.concat(path.map(print, "params"));
18378 if (node.hash && node.hash.pairs.length > 0) {
18379 parts.push(path.call(print, "hash"));
18385 function printPathParams(path, print, options) {
18387 options = Object.assign({
18390 parts.push(printPath(path, print));
18391 parts = parts.concat(getParams(path, print));
18393 if (!options.group) {
18394 return indent$4(join$4(line$3, parts));
18397 return indent$4(group$6(join$4(line$3, parts)));
18400 function printBlockParams(path) {
18401 var block = path.getValue();
18403 if (!block.program || !block.program.blockParams.length) {
18407 return concat$7([" as |", block.program.blockParams.join(" "), "|"]);
18410 function printOpenBlock(path, print) {
18411 return group$6(concat$7(["{{#", printPathParams(path, print), printBlockParams(path), softline$3, "}}"]));
18414 function printCloseBlock(path, print) {
18415 return concat$7(["{{/", path.call(print, "path"), "}}"]);
18418 function isWhitespaceNode(node) {
18419 return node.type === "TextNode" && !/\S/.test(node.chars);
18422 function getPreviousNode(path) {
18423 var node = path.getValue();
18424 var parentNode = path.getParentNode(0);
18425 var children = parentNode.children || parentNode.body;
18428 var nodeIndex = children.indexOf(node);
18430 if (nodeIndex > 0) {
18431 var previousNode = children[nodeIndex - 1];
18432 return previousNode;
18437 function getNextNode(path) {
18438 var node = path.getValue();
18439 var parentNode = path.getParentNode(0);
18440 var children = parentNode.children || parentNode.body;
18443 var nodeIndex = children.indexOf(node);
18445 if (nodeIndex < children.length) {
18446 var nextNode = children[nodeIndex + 1];
18452 function isPreviousNodeOfSomeType(path, types) {
18453 var previousNode = getPreviousNode(path);
18455 if (previousNode) {
18456 return types.some(function (type) {
18457 return previousNode.type === type;
18464 function isNextNodeOfType(path, type) {
18465 var nextNode = getNextNode(path);
18466 return nextNode && nextNode.type === type;
18469 function clean$2(ast, newObj) {
18471 delete newObj.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace
18473 if (ast.type === "TextNode") {
18474 if (ast.chars.replace(/\s+/, "") === "") {
18478 newObj.chars = ast.chars.replace(/^\s+/, "").replace(/\s+$/, "");
18482 function countNewLines(string) {
18483 /* istanbul ignore next */
18484 string = typeof string === "string" ? string : "";
18485 return string.split("\n").length - 1;
18488 function countLeadingNewLines(string) {
18489 /* istanbul ignore next */
18490 string = typeof string === "string" ? string : "";
18491 var newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || "";
18492 return countNewLines(newLines);
18495 function countTrailingNewLines(string) {
18496 /* istanbul ignore next */
18497 string = typeof string === "string" ? string : "";
18498 var newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || "";
18499 return countNewLines(newLines);
18502 function generateHardlines() {
18503 var number = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
18504 var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
18505 return new Array(Math.min(number, max)).fill(hardline$6);
18508 var printerGlimmer = {
18510 massageAstNode: clean$2
18513 var name$6 = "Handlebars";
18514 var type$5 = "markup";
18515 var group$7 = "HTML";
18520 var extensions$5 = [
18524 var tmScope$5 = "text.html.handlebars";
18525 var aceMode$5 = "handlebars";
18526 var languageId$5 = 155;
18532 extensions: extensions$5,
18533 tmScope: tmScope$5,
18534 aceMode: aceMode$5,
18535 languageId: languageId$5
18538 var Handlebars$1 = /*#__PURE__*/Object.freeze({
18544 extensions: extensions$5,
18545 tmScope: tmScope$5,
18546 aceMode: aceMode$5,
18547 languageId: languageId$5,
18548 'default': Handlebars
18551 var require$$0$4 = getCjsExportFromNamespace(Handlebars$1);
18553 var languages$2 = [createLanguage(require$$0$4, function (data) {
18554 return Object.assign(data, {
18557 parsers: ["glimmer"],
18558 vscodeLanguageIds: ["handlebars"]
18562 glimmer: printerGlimmer
18564 var languageHandlebars = {
18565 languages: languages$2,
18566 printers: printers$2
18569 var clean$3 = function clean(ast, newNode) {
18570 delete newNode.sourceSpan;
18571 delete newNode.startSourceSpan;
18572 delete newNode.endSourceSpan;
18573 delete newNode.nameSpan;
18574 delete newNode.valueSpan;
18576 if (ast.type === "text" || ast.type === "comment") {
18578 } // may be formatted by multiparser
18581 if (ast.type === "yaml" || ast.type === "toml") {
18585 if (ast.type === "attribute") {
18586 delete newNode.value;
18589 if (ast.type === "docType") {
18590 delete newNode.value;
18595 "CSS_DISPLAY_TAGS": {
18598 "basefont": "none",
18599 "datalist": "none",
18604 "noframes": "none",
18610 "template": "inline",
18615 "address": "block",
18616 "blockquote": "block",
18620 "figcaption": "block",
18626 "listing": "block",
18629 "plaintext": "block",
18632 "slot": "contents",
18635 "article": "block",
18645 "section": "block",
18654 "caption": "table-caption",
18655 "colgroup": "table-column-group",
18656 "col": "table-column",
18657 "thead": "table-header-group",
18658 "tbody": "table-row-group",
18659 "tfoot": "table-footer-group",
18661 "td": "table-cell",
18662 "th": "table-cell",
18663 "fieldset": "block",
18664 "button": "inline-block",
18665 "video": "inline-block",
18666 "audio": "inline-block"
18668 "CSS_DISPLAY_DEFAULT": "inline",
18669 "CSS_WHITE_SPACE_TAGS": {
18671 "plaintext": "pre",
18675 "table": "initial",
18676 "textarea": "pre-wrap"
18678 "CSS_WHITE_SPACE_DEFAULT": "normal"
18904 "allowpaymentrequest",
19286 basefont: basefont,
19288 blockquote: blockquote,
19295 colgroup: colgroup,
19305 fieldset: fieldset,
19309 frameset: frameset,
19334 optgroup: optgroup,
19340 progress: progress,
19350 textarea: textarea,
19361 var htmlElementAttributes = /*#__PURE__*/Object.freeze({
19369 basefont: basefont,
19371 blockquote: blockquote,
19378 colgroup: colgroup,
19388 fieldset: fieldset,
19392 frameset: frameset,
19417 optgroup: optgroup,
19423 progress: progress,
19433 textarea: textarea,
19445 var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes);
19447 var CSS_DISPLAY_TAGS = json.CSS_DISPLAY_TAGS,
19448 CSS_DISPLAY_DEFAULT = json.CSS_DISPLAY_DEFAULT,
19449 CSS_WHITE_SPACE_TAGS = json.CSS_WHITE_SPACE_TAGS,
19450 CSS_WHITE_SPACE_DEFAULT = json.CSS_WHITE_SPACE_DEFAULT;
19451 var HTML_TAGS = arrayToMap(htmlTagNames$1);
19452 var HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap);
19454 function arrayToMap(array) {
19455 var map = Object.create(null);
19456 var _iteratorNormalCompletion = true;
19457 var _didIteratorError = false;
19458 var _iteratorError = undefined;
19461 for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
19462 var value = _step.value;
19466 _didIteratorError = true;
19467 _iteratorError = err;
19470 if (!_iteratorNormalCompletion && _iterator.return != null) {
19471 _iterator.return();
19474 if (_didIteratorError) {
19475 throw _iteratorError;
19483 function mapObject(object, fn) {
19484 var newObject = Object.create(null);
19486 for (var _i = 0, _Object$keys = Object.keys(object); _i < _Object$keys.length; _i++) {
19487 var key = _Object$keys[_i];
19488 newObject[key] = fn(object[key], key);
19494 function shouldPreserveContent(node, options) {
19495 if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") {
19497 } // unterminated node in ie conditional comment
19498 // e.g. <!--[if lt IE 9]><html><![endif]-->
19501 if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
19503 } // incomplete html in ie conditional comment
19504 // e.g. <!--[if lt IE 9]></div><![endif]-->
19507 if (node.type === "ieConditionalComment" && !node.complete) {
19509 } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
19510 // custom blocks can be written in other languages so we should preserve them to not break the code
19513 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>
19514 "html"].indexOf(node.fullName) === -1) {
19516 } // TODO: handle non-text children in <pre>
19519 if (isPreLikeNode(node) && node.children.some(function (child) {
19520 return child.type !== "text" && child.type !== "interpolation";
19528 function hasPrettierIgnore(node) {
19529 if (node.type === "attribute" || isTextLikeNode(node)) {
19533 if (!node.parent) {
19537 if (typeof node.index !== "number" || node.index === 0) {
19541 var prevNode = node.parent.children[node.index - 1];
19542 return isPrettierIgnore(prevNode);
19545 function isPrettierIgnore(node) {
19546 return node.type === "comment" && node.value.trim() === "prettier-ignore";
19549 function getPrettierIgnoreAttributeCommentData(value) {
19550 var match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
19560 return match[1].split(/\s+/);
19562 /** there's no opening/closing tag or it's considered not breakable */
19565 function isTextLikeNode(node) {
19566 return node.type === "text" || node.type === "comment";
19569 function isScriptLikeTag(node) {
19570 return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style");
19573 function isFrontMatterNode(node) {
19574 return node.type === "yaml" || node.type === "toml";
19577 function canHaveInterpolation(node) {
19578 return node.children && !isScriptLikeTag(node);
19581 function isWhitespaceSensitiveNode(node) {
19582 return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
19585 function isIndentationSensitiveNode(node) {
19586 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
19589 function isLeadingSpaceSensitiveNode(node) {
19590 var isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
19592 if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
19593 return node.type === "interpolation";
19596 return isLeadingSpaceSensitive;
19598 function _isLeadingSpaceSensitiveNode() {
19599 if (isFrontMatterNode(node)) {
19603 if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
19607 if (!node.parent || node.parent.cssDisplay === "none") {
19611 if (isPreLikeNode(node.parent)) {
19615 if (!node.prev && (node.parent.type === "root" || isScriptLikeTag(node.parent) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
19619 if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
19627 function isTrailingSpaceSensitiveNode(node) {
19628 if (isFrontMatterNode(node)) {
19632 if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
19636 if (!node.parent || node.parent.cssDisplay === "none") {
19640 if (isPreLikeNode(node.parent)) {
19644 if (!node.next && (node.parent.type === "root" || isScriptLikeTag(node.parent) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
19648 if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
19655 function isDanglingSpaceSensitiveNode(node) {
19656 return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
19659 function forceNextEmptyLine(node) {
19660 return isFrontMatterNode(node) || node.next && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
19662 /** firstChild leadingSpaces and lastChild trailingSpaces */
19665 function forceBreakContent(node) {
19666 return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].indexOf(node.name) !== -1 || node.children.some(function (child) {
19667 return hasNonTextChild(child);
19668 })) || node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
19670 /** spaces between children */
19673 function forceBreakChildren(node) {
19674 return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].indexOf(node.name) !== -1 || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
19677 function preferHardlineAsLeadingSpaces(node) {
19678 return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
19681 function preferHardlineAsTrailingSpaces(node) {
19682 return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
19685 function hasSurroundingLineBreak(node) {
19686 return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
19689 function hasLeadingLineBreak(node) {
19690 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);
19693 function hasTrailingLineBreak(node) {
19694 return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
19697 function preferHardlineAsSurroundingSpaces(node) {
19698 switch (node.type) {
19699 case "ieConditionalComment":
19705 return ["script", "select"].indexOf(node.name) !== -1;
19711 function getLastDescendant(node) {
19712 return node.lastChild ? getLastDescendant(node.lastChild) : node;
19715 function hasNonTextChild(node) {
19716 return node.children && node.children.some(function (child) {
19717 return child.type !== "text";
19721 function inferScriptParser(node) {
19722 if (node.name === "script" && !node.attrMap.src) {
19723 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") {
19727 if (node.attrMap.type === "application/x-typescript" || node.attrMap.lang === "ts" || node.attrMap.lang === "tsx") {
19728 return "typescript";
19731 if (node.attrMap.type === "text/markdown") {
19735 if (node.attrMap.type.endsWith("json") || node.attrMap.type.endsWith("importmap")) {
19740 if (node.name === "style") {
19741 if (!node.attrMap.lang || node.attrMap.lang === "postcss" || node.attrMap.lang === "css") {
19745 if (node.attrMap.lang === "scss") {
19749 if (node.attrMap.lang === "less") {
19757 function isBlockLikeCssDisplay(cssDisplay) {
19758 return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
19761 function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
19762 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
19765 function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
19766 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
19769 function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
19770 return !isBlockLikeCssDisplay(cssDisplay);
19773 function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
19774 return !isBlockLikeCssDisplay(cssDisplay);
19777 function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
19778 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
19781 function isPreLikeNode(node) {
19782 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
19785 function countParents(path) {
19786 var predicate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
19791 for (var i = path.stack.length - 1; i >= 0; i--) {
19792 var value = path.stack[i];
19794 if (value && _typeof(value) === "object" && !Array.isArray(value) && predicate(value)) {
19802 function hasParent(node, fn) {
19803 var current = node;
19810 current = current.parent;
19816 function getNodeCssStyleDisplay(node, options) {
19817 if (node.prev && node.prev.type === "comment") {
19818 // <!-- display: block -->
19819 var match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
19826 var isInSvgForeignObject = false;
19828 if (node.type === "element" && node.namespace === "svg") {
19829 if (hasParent(node, function (parent) {
19830 return parent.fullName === "svg:foreignObject";
19832 isInSvgForeignObject = true;
19834 return node.name === "svg" ? "inline-block" : "block";
19838 switch (options.htmlWhitespaceSensitivity) {
19846 return node.type === "element" && (!node.namespace || isInSvgForeignObject) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
19850 function getNodeCssStyleWhiteSpace(node) {
19851 return node.type === "element" && !node.namespace && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
19854 function getMinIndentation(text) {
19855 var minIndentation = Infinity;
19856 var _iteratorNormalCompletion2 = true;
19857 var _didIteratorError2 = false;
19858 var _iteratorError2 = undefined;
19861 for (var _iterator2 = text.split("\n")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
19862 var lineText = _step2.value;
19864 if (lineText.length === 0) {
19868 if (/\S/.test(lineText[0])) {
19872 var indentation = lineText.match(/^\s*/)[0].length;
19874 if (lineText.length === indentation) {
19878 if (indentation < minIndentation) {
19879 minIndentation = indentation;
19883 _didIteratorError2 = true;
19884 _iteratorError2 = err;
19887 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
19888 _iterator2.return();
19891 if (_didIteratorError2) {
19892 throw _iteratorError2;
19897 return minIndentation === Infinity ? 0 : minIndentation;
19900 function dedentString(text) {
19901 var minIndent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getMinIndentation(text);
19902 return minIndent === 0 ? text : text.split("\n").map(function (lineText) {
19903 return lineText.slice(minIndent);
19907 function normalizeParts(parts) {
19909 var restParts = parts.slice();
19911 while (restParts.length !== 0) {
19912 var part = restParts.shift();
19918 if (part.type === "concat") {
19919 Array.prototype.unshift.apply(restParts, part.parts);
19923 if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
19924 newParts.push(newParts.pop() + part);
19928 newParts.push(part);
19934 function identity(x) {
19938 function shouldNotPrintClosingTag(node, options) {
19939 return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore(node) || shouldPreserveContent(node.parent, options));
19942 function countChars(text, char) {
19945 for (var i = 0; i < text.length; i++) {
19946 if (text[i] === char) {
19954 function unescapeQuoteEntities(text) {
19955 return text.replace(/'/g, "'").replace(/"/g, '"');
19959 HTML_ELEMENT_ATTRIBUTES: HTML_ELEMENT_ATTRIBUTES,
19960 HTML_TAGS: HTML_TAGS,
19961 canHaveInterpolation: canHaveInterpolation,
19962 countChars: countChars,
19963 countParents: countParents,
19964 dedentString: dedentString,
19965 forceBreakChildren: forceBreakChildren,
19966 forceBreakContent: forceBreakContent,
19967 forceNextEmptyLine: forceNextEmptyLine,
19968 getLastDescendant: getLastDescendant,
19969 getNodeCssStyleDisplay: getNodeCssStyleDisplay,
19970 getNodeCssStyleWhiteSpace: getNodeCssStyleWhiteSpace,
19971 getPrettierIgnoreAttributeCommentData: getPrettierIgnoreAttributeCommentData,
19972 hasPrettierIgnore: hasPrettierIgnore,
19973 identity: identity,
19974 inferScriptParser: inferScriptParser,
19975 isDanglingSpaceSensitiveNode: isDanglingSpaceSensitiveNode,
19976 isFrontMatterNode: isFrontMatterNode,
19977 isIndentationSensitiveNode: isIndentationSensitiveNode,
19978 isLeadingSpaceSensitiveNode: isLeadingSpaceSensitiveNode,
19979 isPreLikeNode: isPreLikeNode,
19980 isScriptLikeTag: isScriptLikeTag,
19981 isTextLikeNode: isTextLikeNode,
19982 isTrailingSpaceSensitiveNode: isTrailingSpaceSensitiveNode,
19983 isWhitespaceSensitiveNode: isWhitespaceSensitiveNode,
19984 normalizeParts: normalizeParts,
19985 preferHardlineAsLeadingSpaces: preferHardlineAsLeadingSpaces,
19986 preferHardlineAsTrailingSpaces: preferHardlineAsTrailingSpaces,
19987 shouldNotPrintClosingTag: shouldNotPrintClosingTag,
19988 shouldPreserveContent: shouldPreserveContent,
19989 unescapeQuoteEntities: unescapeQuoteEntities
19992 var canHaveInterpolation$1 = utils$3.canHaveInterpolation,
19993 getNodeCssStyleDisplay$1 = utils$3.getNodeCssStyleDisplay,
19994 isDanglingSpaceSensitiveNode$1 = utils$3.isDanglingSpaceSensitiveNode,
19995 isIndentationSensitiveNode$1 = utils$3.isIndentationSensitiveNode,
19996 isLeadingSpaceSensitiveNode$1 = utils$3.isLeadingSpaceSensitiveNode,
19997 isTrailingSpaceSensitiveNode$1 = utils$3.isTrailingSpaceSensitiveNode,
19998 isWhitespaceSensitiveNode$1 = utils$3.isWhitespaceSensitiveNode;
19999 var PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
20001 function preprocess(ast, options) {
20002 var _iteratorNormalCompletion = true;
20003 var _didIteratorError = false;
20004 var _iteratorError = undefined;
20007 for (var _iterator = PREPROCESS_PIPELINE[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
20008 var fn = _step.value;
20009 ast = fn(ast, options);
20012 _didIteratorError = true;
20013 _iteratorError = err;
20016 if (!_iteratorNormalCompletion && _iterator.return != null) {
20017 _iterator.return();
20020 if (_didIteratorError) {
20021 throw _iteratorError;
20029 function removeIgnorableFirstLf(ast
20032 return ast.map(function (node) {
20033 if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
20034 var text = node.children[0];
20035 return node.clone({
20036 children: text.value.length === 1 ? node.children.slice(1) : [].concat(text.clone({
20037 value: text.value.slice(1)
20038 }), node.children.slice(1))
20046 function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
20050 * <!--[if ...]><!--><target><!--<![endif]-->
20052 var isTarget = function isTarget(node) {
20053 return 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;
20056 return ast.map(function (node) {
20057 if (node.children) {
20058 var isTargetResults = node.children.map(isTarget);
20060 if (isTargetResults.some(Boolean)) {
20061 var newChildren = [];
20063 for (var i = 0; i < node.children.length; i++) {
20064 var child = node.children[i];
20066 if (isTargetResults[i + 1]) {
20067 // ieConditionalStartComment
20071 if (isTargetResults[i]) {
20072 var ieConditionalStartComment = child.prev;
20073 var ieConditionalEndComment = child.firstChild;
20074 var ParseSourceSpan = child.sourceSpan.constructor;
20075 var startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
20076 var sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
20077 newChildren.push(child.clone({
20078 condition: ieConditionalStartComment.condition,
20079 sourceSpan: sourceSpan,
20080 startSourceSpan: startSourceSpan,
20081 children: child.children.slice(1)
20086 newChildren.push(child);
20089 return node.clone({
20090 children: newChildren
20099 function mergeNodeIntoText(ast, shouldMerge, getValue) {
20100 return ast.map(function (node) {
20101 if (node.children) {
20102 var shouldMergeResults = node.children.map(shouldMerge);
20104 if (shouldMergeResults.some(Boolean)) {
20105 var newChildren = [];
20107 for (var i = 0; i < node.children.length; i++) {
20108 var child = node.children[i];
20110 if (child.type !== "text" && !shouldMergeResults[i]) {
20111 newChildren.push(child);
20115 var newChild = child.type === "text" ? child : child.clone({
20117 value: getValue(child)
20120 if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
20121 newChildren.push(newChild);
20125 var lastChild = newChildren.pop();
20126 var ParseSourceSpan = lastChild.sourceSpan.constructor;
20127 newChildren.push(lastChild.clone({
20128 value: lastChild.value + newChild.value,
20129 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
20133 return node.clone({
20134 children: newChildren
20143 function mergeCdataIntoText(ast
20146 return mergeNodeIntoText(ast, function (node) {
20147 return node.type === "cdata";
20148 }, function (node) {
20149 return "<![CDATA[".concat(node.value, "]]>");
20153 function mergeSimpleElementIntoText(ast
20156 var isSimpleElement = function isSimpleElement(node) {
20157 return node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && // \xA0: non-breaking whitespace
20158 !/[^\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";
20161 return ast.map(function (node) {
20162 if (node.children) {
20163 var isSimpleElementResults = node.children.map(isSimpleElement);
20165 if (isSimpleElementResults.some(Boolean)) {
20166 var newChildren = [];
20168 for (var i = 0; i < node.children.length; i++) {
20169 var child = node.children[i];
20171 if (isSimpleElementResults[i]) {
20172 var lastChild = newChildren.pop();
20173 var nextChild = node.children[++i];
20174 var ParseSourceSpan = node.sourceSpan.constructor;
20175 var isTrailingSpaceSensitive = nextChild.isTrailingSpaceSensitive,
20176 hasTrailingSpaces = nextChild.hasTrailingSpaces;
20177 newChildren.push(lastChild.clone({
20178 value: lastChild.value + "<".concat(child.rawName, ">") + child.firstChild.value + "</".concat(child.rawName, ">") + nextChild.value,
20179 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
20180 isTrailingSpaceSensitive: isTrailingSpaceSensitive,
20181 hasTrailingSpaces: hasTrailingSpaces
20184 newChildren.push(child);
20188 return node.clone({
20189 children: newChildren
20198 function extractInterpolation(ast, options) {
20199 if (options.parser === "html") {
20203 var interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
20204 return ast.map(function (node) {
20205 if (!canHaveInterpolation$1(node)) {
20209 var newChildren = [];
20210 var _iteratorNormalCompletion2 = true;
20211 var _didIteratorError2 = false;
20212 var _iteratorError2 = undefined;
20215 for (var _iterator2 = node.children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
20216 var child = _step2.value;
20218 if (child.type !== "text") {
20219 newChildren.push(child);
20223 var ParseSourceSpan = child.sourceSpan.constructor;
20224 var startSourceSpan = child.sourceSpan.start;
20225 var endSourceSpan = null;
20226 var components = child.value.split(interpolationRegex);
20228 for (var i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
20229 var value = components[i];
20232 endSourceSpan = startSourceSpan.moveBy(value.length);
20234 if (value.length !== 0) {
20238 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
20245 endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
20248 type: "interpolation",
20249 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
20250 children: value.length === 0 ? [] : [{
20253 sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
20259 _didIteratorError2 = true;
20260 _iteratorError2 = err;
20263 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
20264 _iterator2.return();
20267 if (_didIteratorError2) {
20268 throw _iteratorError2;
20273 return node.clone({
20274 children: newChildren
20279 * - add `hasLeadingSpaces` field
20280 * - add `hasTrailingSpaces` field
20281 * - add `hasDanglingSpaces` field for parent nodes
20282 * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
20283 * - remove insensitive whitespaces
20287 function extractWhitespaces(ast
20290 var TYPE_WHITESPACE = "whitespace";
20291 return ast.map(function (node) {
20292 if (!node.children) {
20296 if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && node.children[0].value.trim().length === 0) {
20297 return node.clone({
20299 hasDanglingSpaces: node.children.length !== 0
20303 var isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
20304 var isIndentationSensitive = isIndentationSensitiveNode$1(node);
20305 return node.clone({
20306 isWhitespaceSensitive: isWhitespaceSensitive,
20307 isIndentationSensitive: isIndentationSensitive,
20308 children: node.children // extract whitespace nodes
20309 .reduce(function (newChildren, child) {
20310 if (child.type !== "text" || isWhitespaceSensitive) {
20311 return newChildren.concat(child);
20314 var localChildren = [];
20316 var _child$value$match = child.value.match(/^(\s*)([\s\S]*?)(\s*)$/),
20317 _child$value$match2 = _slicedToArray(_child$value$match, 4),
20318 leadingSpaces = _child$value$match2[1],
20319 text = _child$value$match2[2],
20320 trailingSpaces = _child$value$match2[3];
20322 if (leadingSpaces) {
20323 localChildren.push({
20324 type: TYPE_WHITESPACE
20328 var ParseSourceSpan = child.sourceSpan.constructor;
20331 localChildren.push({
20334 sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length))
20338 if (trailingSpaces) {
20339 localChildren.push({
20340 type: TYPE_WHITESPACE
20344 return newChildren.concat(localChildren);
20345 }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
20346 .reduce(function (newChildren, child, i, children) {
20347 if (child.type === TYPE_WHITESPACE) {
20348 return newChildren;
20351 var hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
20352 var hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
20353 return newChildren.concat(Object.assign({}, child, {
20354 hasLeadingSpaces: hasLeadingSpaces,
20355 hasTrailingSpaces: hasTrailingSpaces
20362 function addIsSelfClosing(ast
20365 return ast.map(function (node) {
20366 return Object.assign(node, {
20367 isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
20368 node.startSourceSpan === node.endSourceSpan)
20373 function addHasHtmComponentClosingTag(ast, options) {
20374 return ast.map(function (node) {
20375 return node.type !== "element" ? node : Object.assign(node, {
20376 hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
20381 function addCssDisplay(ast, options) {
20382 return ast.map(function (node) {
20383 return Object.assign(node, {
20384 cssDisplay: getNodeCssStyleDisplay$1(node, options)
20389 * - add `isLeadingSpaceSensitive` field
20390 * - add `isTrailingSpaceSensitive` field
20391 * - add `isDanglingSpaceSensitive` field for parent nodes
20395 function addIsSpaceSensitive(ast
20398 return ast.map(function (node) {
20399 if (!node.children) {
20403 if (node.children.length === 0) {
20404 return node.clone({
20405 isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
20409 return node.clone({
20410 children: node.children.map(function (child) {
20411 return Object.assign({}, child, {
20412 isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child),
20413 isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child)
20415 }).map(function (child, index, children) {
20416 return Object.assign({}, child, {
20417 isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
20418 isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
20425 var preprocess_1 = preprocess;
20427 function hasPragma$3(text) {
20428 return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
20431 function insertPragma$5(text) {
20432 return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
20436 hasPragma: hasPragma$3,
20437 insertPragma: insertPragma$5
20440 var _require$$0$builders$4 = doc.builders,
20441 concat$8 = _require$$0$builders$4.concat,
20442 group$8 = _require$$0$builders$4.group;
20444 * v-for="... in ..."
20445 * v-for="... of ..."
20446 * v-for="(..., ...) in ..."
20447 * v-for="(..., ...) of ..."
20450 function printVueFor(value, textToDoc) {
20451 var _parseVueFor = parseVueFor(value),
20452 left = _parseVueFor.left,
20453 operator = _parseVueFor.operator,
20454 right = _parseVueFor.right;
20456 return concat$8([group$8(textToDoc("function _(".concat(left, ") {}"), {
20458 __isVueForBindingLeft: true
20459 })), " ", operator, " ", textToDoc(right, {
20460 parser: "__js_expression"
20462 } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
20465 function parseVueFor(value) {
20466 var forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
20467 var forIteratorRE = /,([^,}\]]*)(?:,([^,}\]]*))?$/;
20468 var stripParensRE = /^\(|\)$/g;
20469 var inMatch = value.match(forAliasRE);
20476 res.for = inMatch[3].trim();
20477 var alias = inMatch[1].trim().replace(stripParensRE, "");
20478 var iteratorMatch = alias.match(forIteratorRE);
20480 if (iteratorMatch) {
20481 res.alias = alias.replace(forIteratorRE, "");
20482 res.iterator1 = iteratorMatch[1].trim();
20484 if (iteratorMatch[2]) {
20485 res.iterator2 = iteratorMatch[2].trim();
20492 left: "".concat([res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")),
20493 operator: inMatch[2],
20498 function printVueSlotScope(value, textToDoc) {
20499 return textToDoc("function _(".concat(value, ") {}"), {
20501 __isVueSlotScope: true
20505 function isVueEventBindingExpression(eventBindingValue) {
20506 // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
20507 // arrow function or anonymous function
20508 var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
20510 var 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
20512 var value = eventBindingValue.trim();
20513 return fnExpRE.test(value) || simplePathRE.test(value);
20517 isVueEventBindingExpression: isVueEventBindingExpression,
20518 printVueFor: printVueFor,
20519 printVueSlotScope: printVueSlotScope
20522 var parseSrcset = createCommonjsModule(function (module) {
20526 * By Alex Bell | MIT License
20528 * JS Parser for the string value that appears in markup <img srcset="here">
20530 * @returns Array [{url: _, d: _, w: _, h:_}, ...]
20532 * Based super duper closely on the reference algorithm at:
20533 * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute
20535 * Most comments are copied in directly from the spec
20536 * (except for comments in parens).
20538 (function (root, factory) {
20539 if ( module.exports) {
20540 // Node. Does not work with strict CommonJS, but
20541 // only CommonJS-like environments that support module.exports,
20543 module.exports = factory();
20545 // Browser globals (root is window)
20546 root.parseSrcset = factory();
20548 })(commonjsGlobal, function () {
20549 // 1. Let input be the value passed to this algorithm.
20550 return function (input, options) {
20551 var logger = options && options.logger || console; // UTILITY FUNCTIONS
20552 // Manual is faster than RegEx
20553 // http://bjorn.tipling.com/state-and-regular-expressions-in-javascript
20554 // http://jsperf.com/whitespace-character/5
20556 function isSpace(c) {
20557 return c === " " || // space
20558 c === "\t" || // horizontal tab
20559 c === "\n" || // new line
20560 c === "\f" || // form feed
20561 c === "\r"; // carriage return
20564 function collectCharacters(regEx) {
20566 match = regEx.exec(input.substring(pos));
20570 pos += chars.length;
20575 var inputLength = input.length,
20576 // (Don't use \s, to avoid matching non-breaking space)
20577 regexLeadingSpaces = /^[ \t\n\r\u000c]+/,
20578 regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/,
20579 regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/,
20580 regexTrailingCommas = /[,]+$/,
20581 regexNonNegativeInteger = /^\d+$/,
20582 // ( Positive or negative or unsigned integers or decimals, without or without exponents.
20583 // Must include at least one digit.
20584 // According to spec tests any decimal point must be followed by a digit.
20585 // No leading plus sign is allowed.)
20586 // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number
20587 regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/,
20593 // 2. Let position be a pointer into input, initially pointing at the start
20596 // 3. Let candidates be an initially empty source set.
20597 candidates = []; // 4. Splitting loop: Collect a sequence of characters that are space
20598 // characters or U+002C COMMA characters. If any U+002C COMMA characters
20599 // were collected, that is a parse error.
20602 collectCharacters(regexLeadingCommasOrSpaces); // 5. If position is past the end of input, return candidates and abort these steps.
20604 if (pos >= inputLength) {
20605 return candidates; // (we're done, this is the sole return path)
20606 } // 6. Collect a sequence of characters that are not space characters,
20607 // and let that be url.
20610 url = collectCharacters(regexLeadingNotSpaces); // 7. Let descriptors be a new empty list.
20612 descriptors = []; // 8. If url ends with a U+002C COMMA character (,), follow these substeps:
20613 // (1). Remove all trailing U+002C COMMA characters from url. If this removed
20614 // more than one character, that is a parse error.
20616 if (url.slice(-1) === ",") {
20617 url = url.replace(regexTrailingCommas, ""); // (Jump ahead to step 9 to skip tokenization and just push the candidate).
20619 parseDescriptors(); // Otherwise, follow these substeps:
20622 } // (close else of step 8)
20623 // 16. Return to the step labeled splitting loop.
20625 } // (Close of big while loop.)
20628 * Tokenizes descriptor properties prior to parsing
20629 * Returns undefined.
20633 function tokenize() {
20634 // 8.1. Descriptor tokeniser: Skip whitespace
20635 collectCharacters(regexLeadingSpaces); // 8.2. Let current descriptor be the empty string.
20637 currentDescriptor = ""; // 8.3. Let state be in descriptor.
20639 state = "in descriptor";
20642 // 8.4. Let c be the character at position.
20643 c = input.charAt(pos); // Do the following depending on the value of state.
20644 // For the purpose of this step, "EOF" is a special character representing
20645 // that position is past the end of input.
20648 if (state === "in descriptor") {
20649 // Do the following, depending on the value of c:
20651 // If current descriptor is not empty, append current descriptor to
20652 // descriptors and let current descriptor be the empty string.
20653 // Set state to after descriptor.
20655 if (currentDescriptor) {
20656 descriptors.push(currentDescriptor);
20657 currentDescriptor = "";
20658 state = "after descriptor";
20659 } // U+002C COMMA (,)
20660 // Advance position to the next character in input. If current descriptor
20661 // is not empty, append current descriptor to descriptors. Jump to the step
20662 // labeled descriptor parser.
20664 } else if (c === ",") {
20667 if (currentDescriptor) {
20668 descriptors.push(currentDescriptor);
20671 parseDescriptors();
20672 return; // U+0028 LEFT PARENTHESIS (()
20673 // Append c to current descriptor. Set state to in parens.
20674 } else if (c === "(") {
20675 currentDescriptor = currentDescriptor + c;
20676 state = "in parens"; // EOF
20677 // If current descriptor is not empty, append current descriptor to
20678 // descriptors. Jump to the step labeled descriptor parser.
20679 } else if (c === "") {
20680 if (currentDescriptor) {
20681 descriptors.push(currentDescriptor);
20684 parseDescriptors();
20685 return; // Anything else
20686 // Append c to current descriptor.
20688 currentDescriptor = currentDescriptor + c;
20689 } // (end "in descriptor"
20692 } else if (state === "in parens") {
20693 // U+0029 RIGHT PARENTHESIS ())
20694 // Append c to current descriptor. Set state to in descriptor.
20696 currentDescriptor = currentDescriptor + c;
20697 state = "in descriptor"; // EOF
20698 // Append current descriptor to descriptors. Jump to the step labeled
20699 // descriptor parser.
20700 } else if (c === "") {
20701 descriptors.push(currentDescriptor);
20702 parseDescriptors();
20703 return; // Anything else
20704 // Append c to current descriptor.
20706 currentDescriptor = currentDescriptor + c;
20707 } // After descriptor
20709 } else if (state === "after descriptor") {
20710 // Do the following, depending on the value of c:
20711 // Space character: Stay in this state.
20712 if (isSpace(c)) ; else if (c === "") {
20713 parseDescriptors();
20714 return; // Anything else
20715 // Set state to in descriptor. Set position to the previous character in input.
20717 state = "in descriptor";
20720 } // Advance position to the next character in input.
20723 pos += 1; // Repeat this step.
20724 } // (close while true loop)
20728 * Adds descriptor properties to a candidate, pushes to the candidates array
20729 * @return undefined
20731 // Declared outside of the while loop so that it's only created once.
20734 function parseDescriptors() {
20735 // 9. Descriptor parser: Let error be no.
20736 var pError = false,
20737 // 10. Let width be absent.
20738 // 11. Let density be absent.
20739 // 12. Let future-compat-h be absent. (We're implementing it now as h)
20749 floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps
20750 // from the following list:
20752 for (i = 0; i < descriptors.length; i++) {
20753 desc = descriptors[i];
20754 lastChar = desc[desc.length - 1];
20755 value = desc.substring(0, desc.length - 1);
20756 intVal = parseInt(value, 10);
20757 floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by
20758 // a U+0077 LATIN SMALL LETTER W character
20760 if (regexNonNegativeInteger.test(value) && lastChar === "w") {
20761 // If width and density are not both absent, then let error be yes.
20764 } // Apply the rules for parsing non-negative integers to the descriptor.
20765 // If the result is zero, let error be yes.
20766 // Otherwise, let width be the result.
20769 if (intVal === 0) {
20773 } // If the descriptor consists of a valid floating-point number followed by
20774 // a U+0078 LATIN SMALL LETTER X character
20776 } else if (regexFloatingPoint.test(value) && lastChar === "x") {
20777 // If width, density and future-compat-h are not all absent, then let error
20781 } // Apply the rules for parsing floating-point number values to the descriptor.
20782 // If the result is less than zero, let error be yes. Otherwise, let density
20786 if (floatVal < 0) {
20790 } // If the descriptor consists of a valid non-negative integer followed by
20791 // a U+0068 LATIN SMALL LETTER H character
20793 } else if (regexNonNegativeInteger.test(value) && lastChar === "h") {
20794 // If height and density are not both absent, then let error be yes.
20797 } // Apply the rules for parsing non-negative integers to the descriptor.
20798 // If the result is zero, let error be yes. Otherwise, let future-compat-h
20802 if (intVal === 0) {
20806 } // Anything else, Let error be yes.
20811 } // (close step 13 for loop)
20812 // 15. If error is still no, then append a new image source to candidates whose
20813 // URL is url, associated with a width width if not absent and a pixel
20814 // density density if not absent. Otherwise, there is a parse error.
20818 candidate.url = url;
20832 candidates.push(candidate);
20833 } else if (logger && logger.error) {
20834 logger.error("Invalid srcset descriptor found in '" + input + "' at '" + desc + "'.");
20836 } // (close parseDescriptors fn)
20842 var _require$$0$builders$5 = doc.builders,
20843 concat$9 = _require$$0$builders$5.concat,
20844 ifBreak$4 = _require$$0$builders$5.ifBreak,
20845 join$5 = _require$$0$builders$5.join,
20846 line$4 = _require$$0$builders$5.line;
20848 function printImgSrcset(value) {
20849 var srcset = parseSrcset(value, {
20851 error: function error(message) {
20852 throw new Error(message);
20856 var hasW = srcset.some(function (src) {
20859 var hasH = srcset.some(function (src) {
20862 var hasX = srcset.some(function (src) {
20866 if (hasW + hasH + hasX !== 1) {
20867 throw new Error("Mixed descriptor in srcset is not supported");
20870 var key = hasW ? "w" : hasH ? "h" : "d";
20871 var unit = hasW ? "w" : hasH ? "h" : "x";
20873 var getMax = function getMax(values) {
20874 return Math.max.apply(Math, values);
20877 var urls = srcset.map(function (src) {
20880 var maxUrlLength = getMax(urls.map(function (url) {
20883 var descriptors = srcset.map(function (src) {
20885 }).map(function (descriptor) {
20886 return descriptor ? descriptor.toString() : "";
20888 var descriptorLeftLengths = descriptors.map(function (descriptor) {
20889 var index = descriptor.indexOf(".");
20890 return index === -1 ? descriptor.length : index;
20892 var maxDescriptorLeftLength = getMax(descriptorLeftLengths);
20893 return join$5(concat$9([",", line$4]), urls.map(function (url, index) {
20895 var descriptor = descriptors[index];
20898 var urlPadding = maxUrlLength - url.length + 1;
20899 var descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
20900 var alignment = " ".repeat(urlPadding + descriptorPadding);
20901 parts.push(ifBreak$4(alignment, " "), descriptor + unit);
20904 return concat$9(parts);
20908 var syntaxAttribute = {
20909 printImgSrcset: printImgSrcset
20912 var builders = doc.builders,
20913 _require$$0$utils = doc.utils,
20914 stripTrailingHardline$1 = _require$$0$utils.stripTrailingHardline,
20915 mapDoc$4 = _require$$0$utils.mapDoc;
20916 var breakParent$2 = builders.breakParent,
20917 dedentToRoot$1 = builders.dedentToRoot,
20918 fill$3 = builders.fill,
20919 group$9 = builders.group,
20920 hardline$7 = builders.hardline,
20921 ifBreak$5 = builders.ifBreak,
20922 indent$5 = builders.indent,
20923 join$6 = builders.join,
20924 line$5 = builders.line,
20925 literalline$2 = builders.literalline,
20926 markAsRoot$2 = builders.markAsRoot,
20927 softline$4 = builders.softline;
20928 var countChars$1 = utils$3.countChars,
20929 countParents$1 = utils$3.countParents,
20930 dedentString$1 = utils$3.dedentString,
20931 forceBreakChildren$1 = utils$3.forceBreakChildren,
20932 forceBreakContent$1 = utils$3.forceBreakContent,
20933 forceNextEmptyLine$1 = utils$3.forceNextEmptyLine,
20934 getLastDescendant$1 = utils$3.getLastDescendant,
20935 getPrettierIgnoreAttributeCommentData$1 = utils$3.getPrettierIgnoreAttributeCommentData,
20936 hasPrettierIgnore$1 = utils$3.hasPrettierIgnore,
20937 inferScriptParser$1 = utils$3.inferScriptParser,
20938 isScriptLikeTag$1 = utils$3.isScriptLikeTag,
20939 isTextLikeNode$1 = utils$3.isTextLikeNode,
20940 normalizeParts$1 = utils$3.normalizeParts,
20941 preferHardlineAsLeadingSpaces$1 = utils$3.preferHardlineAsLeadingSpaces,
20942 shouldNotPrintClosingTag$1 = utils$3.shouldNotPrintClosingTag,
20943 shouldPreserveContent$1 = utils$3.shouldPreserveContent,
20944 unescapeQuoteEntities$1 = utils$3.unescapeQuoteEntities;
20945 var replaceEndOfLineWith$1 = util.replaceEndOfLineWith;
20946 var insertPragma$6 = pragma$3.insertPragma;
20947 var printVueFor$1 = syntaxVue.printVueFor,
20948 printVueSlotScope$1 = syntaxVue.printVueSlotScope,
20949 isVueEventBindingExpression$1 = syntaxVue.isVueEventBindingExpression;
20950 var printImgSrcset$1 = syntaxAttribute.printImgSrcset;
20952 function concat$a(parts) {
20953 var newParts = normalizeParts$1(parts);
20954 return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
20957 function embed$2(path, print, textToDoc, options) {
20958 var node = path.getValue();
20960 switch (node.type) {
20963 if (isScriptLikeTag$1(node.parent)) {
20964 var parser = inferScriptParser$1(node.parent);
20967 var value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
20968 return builders.concat([concat$a([breakParent$2, printOpeningTagPrefix(node, options), stripTrailingHardline$1(textToDoc(value, {
20970 })), printClosingTagSuffix(node, options)])]);
20972 } else if (node.parent.type === "interpolation") {
20973 return concat$a([indent$5(concat$a([line$5, textToDoc(node.value, Object.assign({
20974 __isInHtmlInterpolation: true // to avoid unexpected `}}`
20976 }, options.parser === "angular" ? {
20977 parser: "__ng_interpolation",
20978 trailingComma: "none"
20979 } : options.parser === "vue" ? {
20980 parser: "__vue_expression"
20982 parser: "__js_expression"
20983 }))])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$5]);
20993 } // lit-html: html`<my-element obj=${obj}></my-element>`
20996 if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
20997 return concat$a([node.rawName, "=", node.value]);
20998 } // lwc: html`<my-element data-for={value}></my-element>`
21001 if (options.parser === "lwc") {
21002 var interpolationRegex = /^\{[\s\S]*\}$/;
21004 if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
21005 return concat$a([node.rawName, "=", node.value]);
21009 var embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, function (code, opts) {
21010 return (// strictly prefer single quote to avoid unnecessary html entity escape
21011 textToDoc(code, Object.assign({
21012 __isInHtmlAttribute: true
21017 if (embeddedAttributeValueDoc) {
21018 return concat$a([node.rawName, '="', group$9(mapDoc$4(embeddedAttributeValueDoc, function (doc) {
21019 return typeof doc === "string" ? doc.replace(/"/g, """) : doc;
21027 return markAsRoot$2(concat$a(["---", hardline$7, node.value.trim().length === 0 ? "" : textToDoc(node.value, {
21033 function genericPrint$2(path, options, print) {
21034 var node = path.getValue();
21036 switch (node.type) {
21038 // use original concat to not break stripTrailingHardline
21039 return builders.concat([group$9(printChildren$1(path, options, print)), hardline$7]);
21042 case "ieConditionalComment":
21053 * exception: break if the opening tag breaks
21064 var shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
21065 var attrGroupId = Symbol("element-attr-group-id");
21066 return concat$a([group$9(concat$a([group$9(printOpeningTag(path, options, print), {
21068 }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$5 : "" : concat$a([forceBreakContent$1(node) ? breakParent$2 : "", function (childrenDoc) {
21069 return shouldHugContent ? ifBreak$5(indent$5(childrenDoc), childrenDoc, {
21070 groupId: attrGroupId
21071 }) : isScriptLikeTag$1(node) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$5(childrenDoc);
21072 }(concat$a([shouldHugContent ? ifBreak$5(softline$4, "", {
21073 groupId: attrGroupId
21074 }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$5 : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$1(softline$4) : softline$4, printChildren$1(path, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$5(softline$4, "", {
21075 groupId: attrGroupId
21076 }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$5 : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp("\\n\\s{".concat(options.tabWidth * countParents$1(path, function (n) {
21077 return n.parent && n.parent.type !== "root";
21078 }), "}$")).test(node.lastChild.value) ?
21087 "" : softline$4])])), printClosingTag(node, options)]);
21090 case "ieConditionalStartComment":
21091 case "ieConditionalEndComment":
21092 return concat$a([printOpeningTagStart(node), printClosingTagEnd(node)]);
21094 case "interpolation":
21095 return concat$a([printOpeningTagStart(node, options), concat$a(path.map(print, "children")), printClosingTagEnd(node, options)]);
21099 if (node.parent.type === "interpolation") {
21100 // replace the trailing literalline with hardline for better readability
21101 var trailingNewlineRegex = /\n[^\S\n]*?$/;
21102 var hasTrailingNewline = trailingNewlineRegex.test(node.value);
21103 var value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
21104 return concat$a([concat$a(replaceEndOfLineWith$1(value, literalline$2)), hasTrailingNewline ? hardline$7 : ""]);
21107 return fill$3(normalizeParts$1([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
21111 return concat$a([group$9(concat$a([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
21115 return concat$a([printOpeningTagPrefix(node, options), concat$a(replaceEndOfLineWith$1(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$2)), printClosingTagSuffix(node, options)]);
21120 if (node.value === null) {
21121 return node.rawName;
21124 var _value = unescapeQuoteEntities$1(node.value);
21126 var singleQuoteCount = countChars$1(_value, "'");
21127 var doubleQuoteCount = countChars$1(_value, '"');
21128 var quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
21129 return concat$a([node.rawName, concat$a(["=", quote, concat$a(replaceEndOfLineWith$1(quote === '"' ? _value.replace(/"/g, """) : _value.replace(/'/g, "'"), literalline$2)), quote])]);
21134 return concat$a(replaceEndOfLineWith$1(node.raw, literalline$2));
21137 throw new Error("Unexpected node type ".concat(node.type));
21141 function printChildren$1(path, options, print) {
21142 var node = path.getValue();
21144 if (forceBreakChildren$1(node)) {
21145 return concat$a([breakParent$2, concat$a(path.map(function (childPath) {
21146 var childNode = childPath.getValue();
21147 var prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
21148 return concat$a([!prevBetweenLine ? "" : concat$a([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$7 : ""]), printChild(childPath)]);
21152 var groupIds = node.children.map(function () {
21155 return concat$a(path.map(function (childPath, childIndex) {
21156 var childNode = childPath.getValue();
21158 if (isTextLikeNode$1(childNode)) {
21159 if (childNode.prev && isTextLikeNode$1(childNode.prev)) {
21160 var _prevBetweenLine = printBetweenLine(childNode.prev, childNode);
21162 if (_prevBetweenLine) {
21163 if (forceNextEmptyLine$1(childNode.prev)) {
21164 return concat$a([hardline$7, hardline$7, printChild(childPath)]);
21167 return concat$a([_prevBetweenLine, printChild(childPath)]);
21171 return printChild(childPath);
21174 var prevParts = [];
21175 var leadingParts = [];
21176 var trailingParts = [];
21177 var nextParts = [];
21178 var prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
21179 var nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
21181 if (prevBetweenLine) {
21182 if (forceNextEmptyLine$1(childNode.prev)) {
21183 prevParts.push(hardline$7, hardline$7);
21184 } else if (prevBetweenLine === hardline$7) {
21185 prevParts.push(hardline$7);
21187 if (isTextLikeNode$1(childNode.prev)) {
21188 leadingParts.push(prevBetweenLine);
21190 leadingParts.push(ifBreak$5("", softline$4, {
21191 groupId: groupIds[childIndex - 1]
21197 if (nextBetweenLine) {
21198 if (forceNextEmptyLine$1(childNode)) {
21199 if (isTextLikeNode$1(childNode.next)) {
21200 nextParts.push(hardline$7, hardline$7);
21202 } else if (nextBetweenLine === hardline$7) {
21203 if (isTextLikeNode$1(childNode.next)) {
21204 nextParts.push(hardline$7);
21207 trailingParts.push(nextBetweenLine);
21211 return concat$a([].concat(prevParts, group$9(concat$a([concat$a(leadingParts), group$9(concat$a([printChild(childPath), concat$a(trailingParts)]), {
21212 id: groupIds[childIndex]
21213 })])), nextParts));
21216 function printChild(childPath) {
21217 var child = childPath.getValue();
21219 if (hasPrettierIgnore$1(child)) {
21220 return concat$a([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$1(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$2), printClosingTagSuffix(child, options)));
21223 if (shouldPreserveContent$1(child, options)) {
21224 return concat$a([].concat(printOpeningTagPrefix(child, options), group$9(printOpeningTag(childPath, options, print)), replaceEndOfLineWith$1(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$2), printClosingTag(child, options), printClosingTagSuffix(child, options)));
21227 return print(childPath);
21230 function printBetweenLine(prevNode, nextNode) {
21231 return isTextLikeNode$1(prevNode) && isTextLikeNode$1(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$7 : line$5 : "" : preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$7 : softline$4 : needsToBorrowNextOpeningTagStartMarker(prevNode) && (
21237 nextNode.firstChild ||
21243 nextNode.isSelfClosing ||
21249 nextNode.type === "element" && nextNode.attrs.length !== 0) ||
21256 prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) ||
21258 * Want to write us a letter? Use our<a
21259 * ><b><a>mailing address</a></b></a
21263 needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$7 : nextNode.hasLeadingSpaces ? line$5 : softline$4;
21267 function printOpeningTag(path, options, print) {
21268 var node = path.getValue();
21269 var forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
21270 return concat$a([printOpeningTagStart(node, options), !node.attrs || node.attrs.length === 0 ? node.isSelfClosing ?
21275 " " : "" : concat$a([indent$5(concat$a([forceNotToBreakAttrContent ? " " : line$5, join$6(line$5, function (ignoreAttributeData) {
21276 var hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? function () {
21277 return ignoreAttributeData;
21278 } : Array.isArray(ignoreAttributeData) ? function (attr) {
21279 return ignoreAttributeData.indexOf(attr.rawName) !== -1;
21283 return path.map(function (attrPath) {
21284 var attr = attrPath.getValue();
21285 return hasPrettierIgnoreAttribute(attr) ? concat$a(replaceEndOfLineWith$1(options.originalText.slice(options.locStart(attr), options.locEnd(attr)), literalline$2)) : print(attrPath);
21287 }(node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value)))])),
21294 node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
21301 node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) ? "" : node.isSelfClosing ? forceNotToBreakAttrContent ? " " : line$5 : forceNotToBreakAttrContent ? "" : softline$4]), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
21304 function printOpeningTagStart(node, options) {
21305 return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$a([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
21308 function printOpeningTagEnd(node) {
21309 return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
21312 function printClosingTag(node, options) {
21313 return concat$a([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
21316 function printClosingTagStart(node, options) {
21317 return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$a([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
21320 function printClosingTagEnd(node, options) {
21321 return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$a([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
21324 function needsToBorrowNextOpeningTagStartMarker(node) {
21330 return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
21333 function needsToBorrowParentOpeningTagEndMarker(node) {
21343 return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
21346 function needsToBorrowPrevClosingTagEndMarker(node) {
21356 return node.prev && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
21359 function needsToBorrowLastChildClosingTagEndMarker(node) {
21367 return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild));
21370 function needsToBorrowParentClosingTagStartMarker(node) {
21382 return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node));
21385 function printOpeningTagPrefix(node, options) {
21386 return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
21389 function printClosingTagPrefix(node, options) {
21390 return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
21393 function printClosingTagSuffix(node, options) {
21394 return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
21397 function printOpeningTagStartMarker(node) {
21398 switch (node.type) {
21399 case "ieConditionalComment":
21400 case "ieConditionalStartComment":
21401 return "<!--[if ".concat(node.condition);
21403 case "ieConditionalEndComment":
21406 case "interpolation":
21410 return "<!DOCTYPE";
21413 if (node.condition) {
21414 return "<!--[if ".concat(node.condition, "]><!--><").concat(node.rawName);
21420 return "<".concat(node.rawName);
21424 function printOpeningTagEndMarker(node) {
21425 assert(!node.isSelfClosing);
21427 switch (node.type) {
21428 case "ieConditionalComment":
21432 if (node.condition) {
21433 return "><!--<![endif]-->";
21443 function printClosingTagStartMarker(node, options) {
21444 assert(!node.isSelfClosing);
21446 if (shouldNotPrintClosingTag$1(node, options)) {
21450 switch (node.type) {
21451 case "ieConditionalComment":
21455 if (node.hasHtmComponentClosingTag) {
21462 return "</".concat(node.rawName);
21466 function printClosingTagEndMarker(node, options) {
21467 if (shouldNotPrintClosingTag$1(node, options)) {
21471 switch (node.type) {
21472 case "ieConditionalComment":
21473 case "ieConditionalEndComment":
21474 return "[endif]-->";
21476 case "ieConditionalStartComment":
21479 case "interpolation":
21483 if (node.isSelfClosing) {
21494 function getTextValueParts(node) {
21495 var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.value;
21496 return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$1(value, literalline$2) : replaceEndOfLineWith$1(dedentString$1(value.replace(/^\s*?\n|\n\s*?$/g, "")), hardline$7) : // https://infra.spec.whatwg.org/#ascii-whitespace
21497 join$6(line$5, value.split(/[\t\n\f\r ]+/)).parts;
21500 function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
21501 var isKeyMatched = function isKeyMatched(patterns) {
21502 return new RegExp(patterns.join("|")).test(node.fullName);
21505 var getValue = function getValue() {
21506 return unescapeQuoteEntities$1(node.value);
21509 var shouldHug = false;
21511 var __onHtmlBindingRoot = function __onHtmlBindingRoot(root) {
21512 var 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;
21514 if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression")) {
21519 var printHug = function printHug(doc) {
21520 return group$9(doc);
21523 var printExpand = function printExpand(doc) {
21524 return group$9(concat$a([indent$5(concat$a([softline$4, doc])), softline$4]));
21527 var printMaybeHug = function printMaybeHug(doc) {
21528 return shouldHug ? printHug(doc) : printExpand(doc);
21531 var textToDoc = function textToDoc(code, opts) {
21532 return originalTextToDoc(code, Object.assign({
21533 __onHtmlBindingRoot: __onHtmlBindingRoot
21537 if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
21538 return printExpand(printImgSrcset$1(getValue()));
21541 if (options.parser === "vue") {
21542 if (node.fullName === "v-for") {
21543 return printVueFor$1(getValue(), textToDoc);
21546 if (node.fullName === "slot-scope") {
21547 return printVueSlotScope$1(getValue(), textToDoc);
21550 * @click="jsStatement"
21551 * @click="jsExpression"
21552 * v-on:click="jsStatement"
21553 * v-on:click="jsExpression"
21557 var vueEventBindingPatterns = ["^@", "^v-on:"];
21559 * :class="vueExpression"
21560 * v-bind:id="vueExpression"
21563 var vueExpressionBindingPatterns = ["^:", "^v-bind:"];
21565 * v-if="jsExpression"
21568 var jsExpressionBindingPatterns = ["^v-"];
21570 if (isKeyMatched(vueEventBindingPatterns)) {
21571 var value = getValue();
21572 return printMaybeHug(isVueEventBindingExpression$1(value) ? textToDoc(value, {
21573 parser: "__js_expression"
21574 }) : stripTrailingHardline$1(textToDoc(value, {
21575 parser: "__vue_event_binding"
21579 if (isKeyMatched(vueExpressionBindingPatterns)) {
21580 return printMaybeHug(textToDoc(getValue(), {
21581 parser: "__vue_expression"
21585 if (isKeyMatched(jsExpressionBindingPatterns)) {
21586 return printMaybeHug(textToDoc(getValue(), {
21587 parser: "__js_expression"
21592 if (options.parser === "angular") {
21593 var ngTextToDoc = function ngTextToDoc(code, opts) {
21594 return (// angular does not allow trailing comma
21595 textToDoc(code, Object.assign({
21596 trailingComma: "none"
21601 * *directive="angularDirective"
21605 var ngDirectiveBindingPatterns = ["^\\*"];
21607 * (click)="angularStatement"
21608 * on-click="angularStatement"
21611 var ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
21613 * [target]="angularExpression"
21614 * bind-target="angularExpression"
21615 * [(target)]="angularExpression"
21616 * bindon-target="angularExpression"
21619 var ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-"];
21621 * i18n="longDescription"
21622 * i18n-attr="longDescription"
21625 var ngI18nPatterns = ["^i18n(-.+)?$"];
21627 if (isKeyMatched(ngStatementBindingPatterns)) {
21628 return printMaybeHug(ngTextToDoc(getValue(), {
21629 parser: "__ng_action"
21633 if (isKeyMatched(ngExpressionBindingPatterns)) {
21634 return printMaybeHug(ngTextToDoc(getValue(), {
21635 parser: "__ng_binding"
21639 if (isKeyMatched(ngI18nPatterns)) {
21640 return printExpand(fill$3(getTextValueParts(node, getValue())));
21643 if (isKeyMatched(ngDirectiveBindingPatterns)) {
21644 return printMaybeHug(ngTextToDoc(getValue(), {
21645 parser: "__ng_directive"
21649 var interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
21651 var _value2 = getValue();
21653 if (interpolationRegex.test(_value2)) {
21656 _value2.split(interpolationRegex).forEach(function (part, index) {
21657 if (index % 2 === 0) {
21658 parts.push(concat$a(replaceEndOfLineWith$1(part, literalline$2)));
21661 parts.push(group$9(concat$a(["{{", indent$5(concat$a([line$5, ngTextToDoc(part, {
21662 parser: "__ng_interpolation",
21663 __isInHtmlInterpolation: true // to avoid unexpected `}}`
21665 })])), line$5, "}}"])));
21667 parts.push("{{", concat$a(replaceEndOfLineWith$1(part, literalline$2)), "}}");
21672 return group$9(concat$a(parts));
21679 var printerHtml = {
21680 preprocess: preprocess_1,
21681 print: genericPrint$2,
21682 insertPragma: insertPragma$6,
21683 massageAstNode: clean$3,
21687 var CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
21690 htmlWhitespaceSensitivity: {
21692 category: CATEGORY_HTML,
21695 description: "How to handle whitespaces in HTML.",
21698 description: "Respect the default value of CSS display property."
21701 description: "Whitespaces are considered sensitive."
21704 description: "Whitespaces are considered insensitive."
21707 vueIndentScriptAndStyle: {
21709 category: CATEGORY_HTML,
21712 description: "Indent script and style tags in Vue files."
21716 var name$7 = "HTML";
21717 var type$6 = "markup";
21718 var tmScope$6 = "text.html.basic";
21719 var aceMode$6 = "html";
21720 var codemirrorMode$3 = "htmlmixed";
21721 var codemirrorMimeType$3 = "text/html";
21722 var color$1 = "#e34c26";
21726 var extensions$6 = [
21735 var languageId$6 = 146;
21739 tmScope: tmScope$6,
21740 aceMode: aceMode$6,
21741 codemirrorMode: codemirrorMode$3,
21742 codemirrorMimeType: codemirrorMimeType$3,
21744 aliases: aliases$1,
21745 extensions: extensions$6,
21746 languageId: languageId$6
21749 var HTML$1 = /*#__PURE__*/Object.freeze({
21753 tmScope: tmScope$6,
21754 aceMode: aceMode$6,
21755 codemirrorMode: codemirrorMode$3,
21756 codemirrorMimeType: codemirrorMimeType$3,
21758 aliases: aliases$1,
21759 extensions: extensions$6,
21760 languageId: languageId$6,
21764 var name$8 = "Vue";
21765 var type$7 = "markup";
21766 var color$2 = "#2c3e50";
21767 var extensions$7 = [
21770 var tmScope$7 = "text.html.vue";
21771 var aceMode$7 = "html";
21772 var languageId$7 = 391;
21777 extensions: extensions$7,
21778 tmScope: tmScope$7,
21779 aceMode: aceMode$7,
21780 languageId: languageId$7
21783 var Vue$1 = /*#__PURE__*/Object.freeze({
21788 extensions: extensions$7,
21789 tmScope: tmScope$7,
21790 aceMode: aceMode$7,
21791 languageId: languageId$7,
21795 var require$$0$5 = getCjsExportFromNamespace(HTML$1);
21797 var require$$1$1 = getCjsExportFromNamespace(Vue$1);
21799 var languages$3 = [createLanguage(require$$0$5, function (data) {
21800 return Object.assign(data, {
21803 parsers: ["angular"],
21804 vscodeLanguageIds: ["html"],
21805 extensions: [".component.html"],
21808 }), createLanguage(require$$0$5, function (data) {
21809 return Object.assign(data, {
21812 vscodeLanguageIds: ["html"],
21813 extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
21816 }), createLanguage(require$$0$5, function (data) {
21817 return Object.assign(data, {
21818 name: "Lightning Web Components",
21821 vscodeLanguageIds: ["html"],
21825 }), createLanguage(require$$1$1, function (data) {
21826 return Object.assign(data, {
21829 vscodeLanguageIds: ["vue"]
21835 var languageHtml = {
21836 languages: languages$3,
21837 printers: printers$3,
21841 var addLeadingComment$2 = utilShared.addLeadingComment,
21842 addTrailingComment$2 = utilShared.addTrailingComment,
21843 addDanglingComment$2 = utilShared.addDanglingComment;
21845 function handleOwnLineComment(comment, text, options, ast, isLastComment) {
21846 var precedingNode = comment.precedingNode,
21847 enclosingNode = comment.enclosingNode,
21848 followingNode = comment.followingNode;
21850 if (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)) {
21857 function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
21858 var precedingNode = comment.precedingNode,
21859 enclosingNode = comment.enclosingNode,
21860 followingNode = comment.followingNode;
21862 if (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)) {
21869 function handleRemainingComment(comment, text, options, ast, isLastComment) {
21870 var precedingNode = comment.precedingNode,
21871 enclosingNode = comment.enclosingNode,
21872 followingNode = comment.followingNode;
21874 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)) {
21881 function addBlockStatementFirstComment(node, comment) {
21882 var body = node.body.filter(function (n) {
21883 return n.type !== "EmptyStatement";
21886 if (body.length === 0) {
21887 addDanglingComment$2(node, comment);
21889 addLeadingComment$2(body[0], comment);
21893 function addBlockOrNotComment(node, comment) {
21894 if (node.type === "BlockStatement") {
21895 addBlockStatementFirstComment(node, comment);
21897 addLeadingComment$2(node, comment);
21899 } // There are often comments before the else clause of if statements like
21905 // They are being attached as leading comments of the BlockExpression which
21906 // is not well printed. What we want is to instead move the comment inside
21907 // of the block and make it leadingComment of the first element of the block
21908 // or dangling comment of the block if there is nothing inside
21917 function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
21918 if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
21920 } // We unfortunately have no way using the AST or location of nodes to know
21921 // if the comment is positioned before the condition parenthesis:
21922 // if (a /* comment */) {}
21923 // The only workaround I found is to look at the next character to see if
21927 var nextCharacter = util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
21929 if (nextCharacter === ")") {
21930 addTrailingComment$2(precedingNode, comment);
21932 } // Comments before `else`:
21933 // - treat as trailing comments of the consequent, if it's a BlockStatement
21934 // - treat as a dangling comment otherwise
21937 if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
21938 if (precedingNode.type === "BlockStatement") {
21939 addTrailingComment$2(precedingNode, comment);
21941 addDanglingComment$2(enclosingNode, comment);
21947 if (followingNode.type === "BlockStatement") {
21948 addBlockStatementFirstComment(followingNode, comment);
21952 if (followingNode.type === "IfStatement") {
21953 addBlockOrNotComment(followingNode.consequent, comment);
21955 } // For comments positioned after the condition parenthesis in an if statement
21956 // before the consequent without brackets on, such as
21957 // if (a) /* comment */ true,
21958 // we look at the next character to see if the following node
21959 // is the consequent for the if statement
21962 if (enclosingNode.consequent === followingNode) {
21963 addLeadingComment$2(followingNode, comment);
21970 function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
21971 if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
21973 } // We unfortunately have no way using the AST or location of nodes to know
21974 // if the comment is positioned before the condition parenthesis:
21975 // while (a /* comment */) {}
21976 // The only workaround I found is to look at the next character to see if
21980 var nextCharacter = util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
21982 if (nextCharacter === ")") {
21983 addTrailingComment$2(precedingNode, comment);
21987 if (followingNode.type === "BlockStatement") {
21988 addBlockStatementFirstComment(followingNode, comment);
21993 } // Same as IfStatement but for TryStatement
21996 function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) {
21997 if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
22001 if (enclosingNode.type === "CatchClause" && precedingNode) {
22002 addTrailingComment$2(precedingNode, comment);
22006 if (followingNode.type === "BlockStatement") {
22007 addBlockStatementFirstComment(followingNode, comment);
22011 if (followingNode.type === "TryStatement") {
22012 addBlockOrNotComment(followingNode.finalizer, comment);
22016 if (followingNode.type === "CatchClause") {
22017 addBlockOrNotComment(followingNode.body, comment);
22024 function handleMemberExpressionComments(enclosingNode, followingNode, comment) {
22025 if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") {
22026 addLeadingComment$2(enclosingNode, comment);
22033 function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) {
22034 var isSameLineAsPrecedingNode = precedingNode && !util.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment));
22036 if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) {
22037 addLeadingComment$2(followingNode, comment);
22044 function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
22045 if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
22046 addTrailingComment$2(enclosingNode.value.left, comment);
22053 function handleClassComments(enclosingNode, precedingNode, followingNode, comment) {
22054 if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
22055 if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) {
22056 addLeadingComment$2(enclosingNode, comment);
22058 addTrailingComment$2(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
22067 function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) {
22068 // This is only needed for estree parsers (flow, typescript) to attach
22069 // after a method name:
22070 // obj = { fn /*comment*/() {} };
22071 if (enclosingNode && precedingNode && (enclosingNode.type === "Property" || enclosingNode.type === "MethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
22072 // comment should be attached to value instead of key
22073 util.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") {
22074 addTrailingComment$2(precedingNode, comment);
22076 } // Print comments between decorators and class methods as a trailing comment
22077 // on the decorator node instead of the method node
22080 if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "MethodDefinition")) {
22081 addTrailingComment$2(precedingNode, comment);
22088 function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) {
22089 if (util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") {
22093 if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
22094 addTrailingComment$2(precedingNode, comment);
22101 function handleCommentAfterArrowParams(text, enclosingNode, comment, options) {
22102 if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
22106 var index = utilShared.getNextNonSpaceNonCommentCharacterIndex(text, comment, options);
22108 if (text.substr(index, 2) === "=>") {
22109 addDanglingComment$2(enclosingNode, comment);
22116 function handleCommentInEmptyParens(text, enclosingNode, comment, options) {
22117 if (util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") {
22119 } // Only add dangling comments to fix the case when no params are present,
22120 // i.e. a function without any argument.
22123 if (enclosingNode && ((enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ArrowFunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "ObjectMethod") && enclosingNode.params.length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) {
22124 addDanglingComment$2(enclosingNode, comment);
22128 if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) {
22129 addDanglingComment$2(enclosingNode.value, comment);
22136 function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
22137 // Type definitions functions
22138 if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
22139 addTrailingComment$2(precedingNode, comment);
22141 } // Real functions
22144 if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && (enclosingNode.type === "ArrowFunctionExpression" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "ObjectMethod" || enclosingNode.type === "ClassMethod") && util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ")") {
22145 addTrailingComment$2(precedingNode, comment);
22149 if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
22150 var functionParamRightParenIndex = function () {
22151 if (enclosingNode.params.length !== 0) {
22152 return util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(util.getLast(enclosingNode.params)));
22155 var functionParamLeftParenIndex = util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(enclosingNode.id));
22156 return util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
22159 if (options.locStart(comment) > functionParamRightParenIndex) {
22160 addBlockStatementFirstComment(followingNode, comment);
22168 function handleImportSpecifierComments(enclosingNode, comment) {
22169 if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
22170 addLeadingComment$2(enclosingNode, comment);
22177 function handleLabeledStatementComments(enclosingNode, comment) {
22178 if (enclosingNode && enclosingNode.type === "LabeledStatement") {
22179 addLeadingComment$2(enclosingNode, comment);
22186 function handleBreakAndContinueStatementComments(enclosingNode, comment) {
22187 if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
22188 addTrailingComment$2(enclosingNode, comment);
22195 function handleCallExpressionComments(precedingNode, enclosingNode, comment) {
22196 if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
22197 addLeadingComment$2(enclosingNode.arguments[0], comment);
22204 function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) {
22205 if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
22206 addTrailingComment$2(precedingNode, comment);
22213 function handlePropertyComments(enclosingNode, comment) {
22214 if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
22215 addLeadingComment$2(enclosingNode, comment);
22222 function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
22223 // With Flow the enclosingNode is undefined so use the AST instead.
22224 if (ast && ast.body && ast.body.length === 0) {
22225 if (isLastComment) {
22226 addDanglingComment$2(ast, comment);
22228 addLeadingComment$2(ast, comment);
22232 } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
22233 if (isLastComment) {
22234 addDanglingComment$2(enclosingNode, comment);
22236 addLeadingComment$2(enclosingNode, comment);
22245 function handleForComments(enclosingNode, precedingNode, comment) {
22246 if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
22247 addLeadingComment$2(enclosingNode, comment);
22254 function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) {
22255 if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && util.hasNewline(text, options.locEnd(comment))) {
22256 addTrailingComment$2(precedingNode, comment);
22263 function handleAssignmentPatternComments(enclosingNode, comment) {
22264 if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
22265 addLeadingComment$2(enclosingNode, comment);
22272 function handleTypeAliasComments(enclosingNode, followingNode, comment) {
22273 if (enclosingNode && enclosingNode.type === "TypeAlias") {
22274 addLeadingComment$2(enclosingNode, comment);
22281 function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) {
22282 if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression")) {
22283 addLeadingComment$2(followingNode, comment);
22290 function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) {
22291 if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
22295 if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
22296 addLeadingComment$2(followingNode.name, comment);
22300 if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
22301 addTrailingComment$2(precedingNode.constraint, comment);
22308 function isBlockComment(comment) {
22309 return comment.type === "Block" || comment.type === "CommentBlock";
22312 function hasLeadingComment(node) {
22313 var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
22317 if (node.leadingComments) {
22318 return node.leadingComments.some(fn);
22321 if (node.comments) {
22322 return node.comments.some(function (comment) {
22323 return comment.leading && fn(comment);
22331 handleOwnLineComment: handleOwnLineComment,
22332 handleEndOfLineComment: handleEndOfLineComment,
22333 handleRemainingComment: handleRemainingComment,
22334 hasLeadingComment: hasLeadingComment,
22335 isBlockComment: isBlockComment
22338 var isBlockComment$1 = comments$1.isBlockComment,
22339 hasLeadingComment$1 = comments$1.hasLeadingComment;
22340 var _require$$1$builders = doc.builders,
22341 indent$6 = _require$$1$builders.indent,
22342 join$7 = _require$$1$builders.join,
22343 hardline$8 = _require$$1$builders.hardline,
22344 softline$5 = _require$$1$builders.softline,
22345 literalline$3 = _require$$1$builders.literalline,
22346 concat$b = _require$$1$builders.concat,
22347 group$a = _require$$1$builders.group,
22348 dedentToRoot$2 = _require$$1$builders.dedentToRoot,
22349 _require$$1$utils = doc.utils,
22350 mapDoc$5 = _require$$1$utils.mapDoc,
22351 stripTrailingHardline$2 = _require$$1$utils.stripTrailingHardline;
22353 function embed$3(path, print, textToDoc, options) {
22354 var node = path.getValue();
22355 var parent = path.getParentNode();
22356 var parentParent = path.getParentNode(1);
22358 switch (node.type) {
22359 case "TemplateLiteral":
22361 var isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(function (isIt) {
22366 // Get full template literal with expressions replaced by placeholders
22367 var rawQuasis = node.quasis.map(function (q) {
22368 return q.value.raw;
22370 var placeholderID = 0;
22371 var text = rawQuasis.reduce(function (prevVal, currVal, idx) {
22372 return idx == 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
22374 var doc = textToDoc(text, {
22377 return transformCssDoc(doc, path, print);
22380 * react-relay and graphql-tag
22382 * graphql.experimental`...`
22385 * This intentionally excludes Relay Classic tags, as Prettier does not
22386 * support Relay Classic formatting.
22390 if (isGraphQL(path)) {
22391 var expressionDocs = node.expressions ? path.map(print, "expressions") : [];
22392 var numQuasis = node.quasis.length;
22394 if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
22400 for (var i = 0; i < numQuasis; i++) {
22401 var templateElement = node.quasis[i];
22402 var isFirst = i === 0;
22403 var isLast = i === numQuasis - 1;
22404 var _text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence
22405 // (which would make the `cooked` value be `null` or `undefined`)
22407 if (typeof _text !== "string") {
22411 var lines = _text.split("\n");
22413 var numLines = lines.length;
22414 var expressionDoc = expressionDocs[i];
22415 var startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
22416 var endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
22417 var commentsAndWhitespaceOnly = lines.every(function (line) {
22418 return /^\s*(?:#[^\r\n]*)?$/.test(line);
22419 }); // Bail out if an interpolation occurs within a comment.
22421 if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) {
22427 if (commentsAndWhitespaceOnly) {
22428 _doc = printGraphqlComments(lines);
22430 _doc = stripTrailingHardline$2(textToDoc(_text, {
22436 _doc = escapeTemplateCharacters(_doc, false);
22438 if (!isFirst && startsWithBlankLine) {
22444 if (!isLast && endsWithBlankLine) {
22447 } else if (!isFirst && !isLast && startsWithBlankLine) {
22451 if (expressionDoc) {
22452 parts.push(concat$b(["${", expressionDoc, "}"]));
22456 return concat$b(["`", indent$6(concat$b([hardline$8, join$7(hardline$8, parts)])), hardline$8, "`"]);
22459 var htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined;
22462 return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options.embeddedInHtml);
22468 case "TemplateElement":
22474 if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) {
22475 var _text2 = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, function (_, backslashes) {
22476 return "\\".repeat(backslashes.length / 2) + "`";
22479 var indentation = getIndentation(_text2);
22480 var hasIndent = indentation !== "";
22481 return concat$b([hasIndent ? indent$6(concat$b([softline$5, printMarkdown(_text2.replace(new RegExp("^".concat(indentation), "gm"), ""))])) : concat$b([literalline$3, dedentToRoot$2(printMarkdown(_text2))]), softline$5]);
22488 function printMarkdown(text) {
22489 var doc = textToDoc(text, {
22490 parser: "markdown",
22491 __inJsTemplate: true
22493 return stripTrailingHardline$2(escapeTemplateCharacters(doc, true));
22497 function getIndentation(str) {
22498 var firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
22499 return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
22502 function uncook(cookedValue) {
22503 return cookedValue.replace(/([\\`]|\$\{)/g, "\\$1");
22506 function escapeTemplateCharacters(doc, raw) {
22507 return mapDoc$5(doc, function (currentDoc) {
22508 if (!currentDoc.parts) {
22513 currentDoc.parts.forEach(function (part) {
22514 if (typeof part === "string") {
22515 parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part));
22520 return Object.assign({}, currentDoc, {
22526 function transformCssDoc(quasisDoc, path, print) {
22527 var parentNode = path.getValue();
22528 var isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
22534 var expressionDocs = parentNode.expressions ? path.map(print, "expressions") : [];
22535 var newDoc = replacePlaceholders(quasisDoc, expressionDocs);
22536 /* istanbul ignore if */
22539 throw new Error("Couldn't insert all the expressions");
22542 return concat$b(["`", indent$6(concat$b([hardline$8, stripTrailingHardline$2(newDoc)])), softline$5, "`"]);
22543 } // Search all the placeholders in the quasisDoc tree
22544 // and replace them with the expression docs one by one
22545 // returns a new doc with all the placeholders replaced,
22546 // or null if it couldn't replace any expression
22549 function replacePlaceholders(quasisDoc, expressionDocs) {
22550 if (!expressionDocs || !expressionDocs.length) {
22554 var expressions = expressionDocs.slice();
22555 var replaceCounter = 0;
22556 var newDoc = mapDoc$5(quasisDoc, function (doc) {
22557 if (!doc || !doc.parts || !doc.parts.length) {
22561 var parts = doc.parts;
22562 var atIndex = parts.indexOf("@");
22563 var placeholderIndex = atIndex + 1;
22565 if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
22566 // If placeholder is split, join it
22567 var at = parts[atIndex];
22568 var placeholder = parts[placeholderIndex];
22569 var rest = parts.slice(placeholderIndex + 1);
22570 parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
22573 var atPlaceholderIndex = parts.findIndex(function (part) {
22574 return typeof part === "string" && part.startsWith("@prettier-placeholder");
22577 if (atPlaceholderIndex > -1) {
22578 var _placeholder = parts[atPlaceholderIndex];
22580 var _rest = parts.slice(atPlaceholderIndex + 1);
22582 var placeholderMatch = _placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/);
22584 var placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:
22585 // animation: linear ${time}s ease-out;
22587 var suffix = placeholderMatch[2];
22588 var expression = expressions[placeholderID];
22590 parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(_rest);
22593 return Object.assign({}, doc, {
22597 return expressions.length === replaceCounter ? newDoc : null;
22600 function printGraphqlComments(lines) {
22602 var seenComment = false;
22603 lines.map(function (textLine) {
22604 return textLine.trim();
22605 }).forEach(function (textLine, i, array) {
22606 // Lines are either whitespace only, or a comment (with potential whitespace
22607 // around it). Drop whitespace-only lines.
22608 if (textLine === "") {
22612 if (array[i - 1] === "" && seenComment) {
22613 // If a non-first comment is preceded by a blank (whitespace only) line,
22614 // add in a blank line.
22615 parts.push(concat$b([hardline$8, textLine]));
22617 parts.push(textLine);
22620 seenComment = true;
22621 }); // If `lines` was whitespace only, return `null`.
22623 return parts.length === 0 ? null : join$7(hardline$8, parts);
22626 * Template literal in these contexts:
22627 * <style jsx>{`div{color:red}`}</style>
22634 function isStyledJsx(path) {
22635 var node = path.getValue();
22636 var parent = path.getParentNode();
22637 var parentParent = path.getParentNode(1);
22638 return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(function (attribute) {
22639 return attribute.name.name === "jsx";
22640 }) || 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");
22643 * Angular Components can have:
22644 * - Inline HTML template
22645 * - Inline CSS styles
22647 * ...which are both within template literals somewhere
22648 * inside of the Component decorator factory.
22652 * template: `<div>...</div>`,
22653 * styles: [`h1 { color: blue; }`]
22658 function isAngularComponentStyles(path) {
22659 return isPathMatch(path, [function (node) {
22660 return node.type === "TemplateLiteral";
22661 }, function (node, name) {
22662 return node.type === "ArrayExpression" && name === "elements";
22663 }, function (node, name) {
22664 return node.type === "Property" && node.key.type === "Identifier" && node.key.name === "styles" && name === "value";
22665 }].concat(getAngularComponentObjectExpressionPredicates()));
22668 function isAngularComponentTemplate(path) {
22669 return isPathMatch(path, [function (node) {
22670 return node.type === "TemplateLiteral";
22671 }, function (node, name) {
22672 return node.type === "Property" && node.key.type === "Identifier" && node.key.name === "template" && name === "value";
22673 }].concat(getAngularComponentObjectExpressionPredicates()));
22676 function getAngularComponentObjectExpressionPredicates() {
22677 return [function (node, name) {
22678 return node.type === "ObjectExpression" && name === "properties";
22679 }, function (node, name) {
22680 return node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments";
22681 }, function (node, name) {
22682 return node.type === "Decorator" && name === "expression";
22686 * styled-components template literals
22690 function isStyledComponents(path) {
22691 var parent = path.getParentNode();
22693 if (!parent || parent.type !== "TaggedTemplateExpression") {
22697 var tag = parent.tag;
22699 switch (tag.type) {
22700 case "MemberExpression":
22701 return (// styled.foo``
22702 isStyledIdentifier(tag.object) || // Component.extend``
22703 isStyledExtend(tag)
22706 case "CallExpression":
22707 return (// styled(Component)``
22708 isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})``
22709 isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})``
22710 isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})``
22711 tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
22716 return tag.name === "css";
22723 * JSX element with CSS prop
22727 function isCssProp(path) {
22728 var parent = path.getParentNode();
22729 var parentParent = path.getParentNode(1);
22730 return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
22733 function isStyledIdentifier(node) {
22734 return node.type === "Identifier" && node.name === "styled";
22737 function isStyledExtend(node) {
22738 return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
22741 * react-relay and graphql-tag
22743 * graphql.experimental`...`
22745 * GraphQL comment block
22747 * This intentionally excludes Relay Classic tags, as Prettier does not
22748 * support Relay Classic formatting.
22752 function isGraphQL(path) {
22753 var node = path.getValue();
22754 var parent = path.getParentNode();
22755 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");
22758 function hasLanguageComment(node, languageName) {
22759 // This checks for a leading comment that is exactly `/* GraphQL */`
22760 // In order to be in line with other implementations of this comment tag
22761 // we will not trim the comment value and we will expect exactly one space on
22762 // either side of the GraphQL string
22763 // Also see ./clean.js
22764 return hasLeadingComment$1(node, function (comment) {
22765 return isBlockComment$1(comment) && comment.value === " ".concat(languageName, " ");
22769 function isPathMatch(path, predicateStack) {
22770 var stack = path.stack.slice();
22772 var node = stack.pop();
22773 var _iteratorNormalCompletion = true;
22774 var _didIteratorError = false;
22775 var _iteratorError = undefined;
22778 for (var _iterator = predicateStack[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
22779 var predicate = _step.value;
22781 if (node === undefined) {
22783 } // skip index/array
22786 if (typeof name === "number") {
22787 name = stack.pop();
22788 node = stack.pop();
22791 if (!predicate(node, name)) {
22795 name = stack.pop();
22796 node = stack.pop();
22799 _didIteratorError = true;
22800 _iteratorError = err;
22803 if (!_iteratorNormalCompletion && _iterator.return != null) {
22804 _iterator.return();
22807 if (_didIteratorError) {
22808 throw _iteratorError;
22817 * - HTML comment block
22821 function isHtml(path) {
22822 var node = path.getValue();
22823 return hasLanguageComment(node, "HTML") || isPathMatch(path, [function (node) {
22824 return node.type === "TemplateLiteral";
22825 }, function (node, name) {
22826 return node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi";
22828 } // The counter is needed to distinguish nested embeds.
22831 var htmlTemplateLiteralCounter = 0;
22833 function printHtmlTemplateLiteral(path, print, textToDoc, parser, escapeClosingScriptTag) {
22834 var node = path.getValue();
22835 var counter = htmlTemplateLiteralCounter;
22836 htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0;
22838 var composePlaceholder = function composePlaceholder(index) {
22839 return "PRETTIER_HTML_PLACEHOLDER_".concat(index, "_").concat(counter, "_IN_JS");
22842 var text = node.quasis.map(function (quasi, index, quasis) {
22843 return index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index);
22845 var expressionDocs = path.map(print, "expressions");
22847 if (expressionDocs.length === 0 && text.trim().length === 0) {
22851 var placeholderRegex = RegExp(composePlaceholder("(\\d+)"), "g");
22852 var contentDoc = mapDoc$5(stripTrailingHardline$2(textToDoc(text, {
22854 })), function (doc) {
22855 if (typeof doc !== "string") {
22860 var components = doc.split(placeholderRegex);
22862 for (var i = 0; i < components.length; i++) {
22863 var component = components[i];
22867 component = uncook(component);
22869 if (escapeClosingScriptTag) {
22870 component = component.replace(/<\/(script)\b/gi, "<\\/$1");
22873 parts.push(component);
22879 var placeholderIndex = +component;
22880 parts.push(concat$b(["${", group$a(expressionDocs[placeholderIndex]), "}"]));
22883 return concat$b(parts);
22885 return group$a(concat$b(["`", indent$6(concat$b([hardline$8, group$a(contentDoc)])), softline$5, "`"]));
22888 var embed_1$1 = embed$3;
22890 function clean$4(ast, newObj, parent) {
22891 ["range", "raw", "comments", "leadingComments", "trailingComments", "extra", "start", "end", "flags", "errors"].forEach(function (name) {
22892 delete newObj[name];
22895 if (ast.type === "BigIntLiteral") {
22896 newObj.value = newObj.value.toLowerCase();
22897 } // We remove extra `;` and add them when needed
22900 if (ast.type === "EmptyStatement") {
22902 } // We move text around, including whitespaces and add {" "}
22905 if (ast.type === "JSXText") {
22909 if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") {
22911 } // We remove unneeded parens around same-operator LogicalExpressions
22914 if (isUnbalancedLogicalTree(newObj)) {
22915 return rebalanceLogicalTree(newObj);
22916 } // (TypeScript) Ignore `static` in `constructor(static p) {}`
22917 // and `export` in `constructor(export p) {}`
22920 if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) {
22922 type: "Identifier",
22923 name: ast.parameter.name,
22924 typeAnnotation: newObj.parameter.typeAnnotation,
22925 decorators: newObj.decorators
22927 } // (TypeScript) ignore empty `specifiers` array
22930 if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) {
22931 delete newObj.specifiers;
22932 } // We convert <div></div> to <div />
22935 if (ast.type === "JSXOpeningElement") {
22936 delete newObj.selfClosing;
22939 if (ast.type === "JSXElement") {
22940 delete newObj.closingElement;
22941 } // We change {'key': value} into {key: value}
22944 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")) {
22948 if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
22949 newObj.type = "MemberExpression";
22950 delete newObj.optional;
22951 } // Remove raw and cooked values from TemplateElement when it's CSS
22955 if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(function (attr) {
22956 return attr.name.name === "jsx";
22958 var templateLiterals = newObj.children.filter(function (child) {
22959 return child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral";
22960 }).map(function (container) {
22961 return container.expression;
22963 var quasis = templateLiterals.reduce(function (quasis, templateLiteral) {
22964 return quasis.concat(templateLiteral.quasis);
22966 quasis.forEach(function (q) {
22967 return delete q.value;
22969 } // CSS template literals in css prop
22972 if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
22973 newObj.value.expression.quasis.forEach(function (q) {
22974 return delete q.value;
22976 } // Angular Components: Inline HTML template and Inline CSS styles
22979 var expression = ast.expression || ast.callee;
22981 if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
22982 var astProps = ast.expression.arguments[0].properties;
22983 newObj.expression.arguments[0].properties.forEach(function (prop, index) {
22984 var templateLiteral = null;
22986 switch (astProps[index].key.name) {
22988 if (prop.value.type === "ArrayExpression") {
22989 templateLiteral = prop.value.elements[0];
22995 if (prop.value.type === "TemplateLiteral") {
22996 templateLiteral = prop.value;
23002 if (templateLiteral) {
23003 templateLiteral.quasis.forEach(function (q) {
23004 return delete q.value;
23008 } // styled-components, graphql, markdown
23011 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")) {
23012 newObj.quasi.quasis.forEach(function (quasi) {
23013 return delete quasi.value;
23017 if (ast.type === "TemplateLiteral") {
23018 // This checks for a leading comment that is exactly `/* GraphQL */`
23019 // In order to be in line with other implementations of this comment tag
23020 // we will not trim the comment value and we will expect exactly one space on
23021 // either side of the GraphQL string
23022 // Also see ./embed.js
23023 var hasLanguageComment = ast.leadingComments && ast.leadingComments.some(function (comment) {
23024 return comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(function (languageName) {
23025 return comment.value === " ".concat(languageName, " ");
23029 if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
23030 newObj.quasis.forEach(function (quasi) {
23031 return delete quasi.value;
23037 function isUnbalancedLogicalTree(newObj) {
23038 return newObj.type === "LogicalExpression" && newObj.right.type === "LogicalExpression" && newObj.operator === newObj.right.operator;
23041 function rebalanceLogicalTree(newObj) {
23042 if (isUnbalancedLogicalTree(newObj)) {
23043 return rebalanceLogicalTree({
23044 type: "LogicalExpression",
23045 operator: newObj.operator,
23046 left: rebalanceLogicalTree({
23047 type: "LogicalExpression",
23048 operator: newObj.operator,
23050 right: newObj.right.left,
23053 right: newObj.right.right,
23061 var clean_1$1 = clean$4;
23063 var getLast$1 = util.getLast,
23064 hasNewline$3 = util.hasNewline,
23065 hasNewlineInRange$1 = util.hasNewlineInRange,
23066 hasIgnoreComment$3 = util.hasIgnoreComment,
23067 hasNodeIgnoreComment$1 = util.hasNodeIgnoreComment,
23068 skipWhitespace$1 = util.skipWhitespace;
23069 var isIdentifierName = utils$1.keyword.isIdentifierNameES5; // We match any whitespace except line terminators because
23070 // Flow annotation comments cannot be split across lines. For example:
23073 // : any */).foo = 5;
23075 // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
23076 // removing the newline would create a type annotation that the user did not intend
23079 var NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
23080 var FLOW_SHORTHAND_ANNOTATION = new RegExp("^".concat(NON_LINE_TERMINATING_WHITE_SPACE, "*:"));
23081 var FLOW_ANNOTATION = new RegExp("^".concat(NON_LINE_TERMINATING_WHITE_SPACE, "*::"));
23083 function hasFlowShorthandAnnotationComment(node) {
23084 // https://flow.org/en/docs/types/comments/
23085 // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
23086 return node.extra && node.extra.parenthesized && node.trailingComments && node.trailingComments[0].value.match(FLOW_SHORTHAND_ANNOTATION);
23089 function hasFlowAnnotationComment(comments) {
23090 return comments && comments[0].value.match(FLOW_ANNOTATION);
23093 function hasNode(node, fn) {
23094 if (!node || _typeof(node) !== "object") {
23098 if (Array.isArray(node)) {
23099 return node.some(function (value) {
23100 return hasNode(value, fn);
23104 var result = fn(node);
23105 return typeof result === "boolean" ? result : Object.keys(node).some(function (key) {
23106 return hasNode(node[key], fn);
23110 function hasNakedLeftSide(node) {
23111 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";
23114 function getLeftSide(node) {
23115 if (node.expressions) {
23116 return node.expressions[0];
23119 return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
23122 function getLeftSidePathName(path, node) {
23123 if (node.expressions) {
23124 return ["expressions", 0];
23147 if (node.argument) {
23148 return ["argument"];
23151 if (node.expression) {
23152 return ["expression"];
23155 throw new Error("Unexpected node has no left side", node);
23158 function isLiteral(node) {
23159 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";
23162 function isNumericLiteral(node) {
23163 return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
23166 function isStringLiteral(node) {
23167 return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
23170 function isObjectType(n) {
23171 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
23174 function isFunctionOrArrowExpression(node) {
23175 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
23178 function isFunctionOrArrowExpressionWithBody(node) {
23179 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
23182 function isTemplateLiteral(node) {
23183 return node.type === "TemplateLiteral";
23184 } // `inject` is used in AngularJS 1.x, `async` in Angular 2+
23185 // example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
23188 function isAngularTestWrapper(node) {
23189 return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
23192 function isJSXNode(node) {
23193 return node.type === "JSXElement" || node.type === "JSXFragment";
23196 function isTheOnlyJSXElementInMarkdown(options, path) {
23197 if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
23201 var node = path.getNode();
23203 if (!node.expression || !isJSXNode(node.expression)) {
23207 var parent = path.getParentNode();
23208 return parent.type === "Program" && parent.body.length == 1;
23209 } // Detect an expression node representing `{" "}`
23212 function isJSXWhitespaceExpression(node) {
23213 return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
23216 function isMemberExpressionChain(node) {
23217 if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
23221 if (node.object.type === "Identifier") {
23225 return isMemberExpressionChain(node.object);
23228 function isGetterOrSetter(node) {
23229 return node.kind === "get" || node.kind === "set";
23232 function sameLocStart(nodeA, nodeB, options) {
23233 return options.locStart(nodeA) === options.locStart(nodeB);
23234 } // TODO: This is a bad hack and we need a better way to distinguish between
23235 // arrow functions and otherwise
23238 function isFunctionNotation(node, options) {
23239 return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
23240 } // Hack to differentiate between the following two which have the same ast
23241 // type T = { method: () => void };
23242 // type T = { method(): void };
23245 function isObjectTypePropertyAFunction(node, options) {
23246 return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
23247 } // Hack to differentiate between the following two which have the same ast
23248 // declare function f(a): void;
23249 // var f: (a) => void;
23252 function isTypeAnnotationAFunction(node, options) {
23253 return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
23256 function isBinaryish(node) {
23257 return node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression";
23260 function isMemberish(node) {
23261 return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
23264 function isSimpleFlowType(node) {
23265 var flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
23266 return node && flowTypeAnnotations.indexOf(node.type) !== -1 && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
23269 var unitTestRe = /^(skip|[fx]?(it|describe|test))$/;
23271 function isSkipOrOnlyBlock(node) {
23272 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");
23275 function isUnitTestSetUp(n) {
23276 var unitTestSetUpRe = /^(before|after)(Each|All)$/;
23277 return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
23278 } // eg; `describe("some string", (done) => {})`
23281 function isTestCall(n, parent) {
23282 if (n.type !== "CallExpression") {
23286 if (n.arguments.length === 1) {
23287 if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
23288 return isFunctionOrArrowExpression(n.arguments[0]);
23291 if (isUnitTestSetUp(n)) {
23292 return isAngularTestWrapper(n.arguments[0]);
23294 } else if (n.arguments.length === 2 || n.arguments.length === 3) {
23295 if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
23296 // it("name", () => { ... }, 2500)
23297 if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
23301 return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
23308 function hasLeadingComment$2(node) {
23309 return node.comments && node.comments.some(function (comment) {
23310 return comment.leading;
23314 function hasTrailingComment(node) {
23315 return node.comments && node.comments.some(function (comment) {
23316 return comment.trailing;
23320 function isCallOrOptionalCallExpression(node) {
23321 return node.type === "CallExpression" || node.type === "OptionalCallExpression";
23324 function hasDanglingComments(node) {
23325 return node.comments && node.comments.some(function (comment) {
23326 return !comment.leading && !comment.trailing;
23329 /** identify if an angular expression seems to have side effects */
23332 function hasNgSideEffect(path) {
23333 return hasNode(path.getValue(), function (node) {
23334 switch (node.type) {
23338 case "CallExpression":
23339 case "OptionalCallExpression":
23340 case "AssignmentExpression":
23346 function isNgForOf(node, index, parentNode) {
23347 return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
23349 /** @param node {import("estree").TemplateLiteral} */
23352 function isSimpleTemplateLiteral(node) {
23353 if (node.expressions.length === 0) {
23357 return node.expressions.every(function (expr) {
23358 // Disallow comments since printDocToString can't print them here
23359 if (expr.comments) {
23361 } // Allow `x` and `this`
23364 if (expr.type === "Identifier" || expr.type === "ThisExpression") {
23366 } // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
23369 if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") {
23372 while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") {
23373 if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") {
23377 head = head.object;
23379 if (head.comments) {
23384 if (head.type === "Identifier" || head.type === "ThisExpression") {
23395 function getFlowVariance(path) {
23396 if (!path.variance) {
23398 } // Babel 7.0 currently uses variance node type, and flow should
23399 // follow suit soon:
23400 // https://github.com/babel/babel/issues/4722
23403 var variance = path.variance.kind || path.variance;
23405 switch (variance) {
23413 /* istanbul ignore next */
23418 function classPropMayCauseASIProblems(path) {
23419 var node = path.getNode();
23421 if (node.type !== "ClassProperty") {
23425 var name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
23426 // so isn't properly tested yet.
23428 if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
23433 function classChildNeedsASIProtection(node) {
23438 if (node.static || node.accessibility // TypeScript
23443 if (!node.computed) {
23444 var name = node.key && node.key.name;
23446 if (name === "in" || name === "instanceof") {
23451 switch (node.type) {
23452 case "ClassProperty":
23453 case "TSAbstractClassProperty":
23454 return node.computed;
23456 case "MethodDefinition": // Flow
23458 case "TSAbstractMethodDefinition": // TypeScript
23460 case "ClassMethod":
23461 case "ClassPrivateMethod":
23464 var isAsync = node.value ? node.value.async : node.async;
23465 var isGenerator = node.value ? node.value.generator : node.generator;
23467 if (isAsync || node.kind === "get" || node.kind === "set") {
23471 if (node.computed || isGenerator) {
23478 case "TSIndexSignature":
23482 /* istanbul ignore next */
23487 function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
23488 if (tokenNode === "+") {
23489 return "+" + keyword;
23490 } else if (tokenNode === "-") {
23491 return "-" + keyword;
23497 function hasNewlineBetweenOrAfterDecorators(node, options) {
23498 return hasNewlineInRange$1(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$1(node.decorators))) || hasNewline$3(options.originalText, options.locEnd(getLast$1(node.decorators)));
23499 } // Only space, newline, carriage return, and tab are treated as whitespace
23503 var jsxWhitespaceChars = " \n\r\t";
23504 var matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
23505 var containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters,
23506 // or it contains whitespace without a new line.
23508 function isMeaningfulJSXText(node) {
23509 return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
23512 function hasJsxIgnoreComment(path) {
23513 var node = path.getValue();
23514 var parent = path.getParentNode();
23516 if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
23518 } // Lookup the previous sibling, ignoring any empty JSXText elements
23521 var index = parent.children.indexOf(node);
23522 var prevSibling = null;
23524 for (var i = index; i > 0; i--) {
23525 var candidate = parent.children[i - 1];
23527 if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
23531 prevSibling = candidate;
23535 return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(function (comment) {
23536 return comment.value.trim() === "prettier-ignore";
23540 function isEmptyJSXElement(node) {
23541 if (node.children.length === 0) {
23545 if (node.children.length > 1) {
23547 } // if there is one text child and does not contain any meaningful text
23548 // we can treat the element as empty.
23551 var child = node.children[0];
23552 return isLiteral(child) && !isMeaningfulJSXText(child);
23555 function hasPrettierIgnore$2(path) {
23556 return hasIgnoreComment$3(path) || hasJsxIgnoreComment(path);
23559 function isLastStatement(path) {
23560 var parent = path.getParentNode();
23566 var node = path.getValue();
23567 var body = (parent.body || parent.consequent).filter(function (stmt) {
23568 return stmt.type !== "EmptyStatement";
23570 return body && body[body.length - 1] === node;
23573 function isFlowAnnotationComment(text, typeAnnotation, options) {
23574 var start = options.locStart(typeAnnotation);
23575 var end = skipWhitespace$1(text, options.locEnd(typeAnnotation));
23576 return text.substr(start, 2) === "/*" && text.substr(end, 2) === "*/";
23579 function hasLeadingOwnLineComment(text, node, options) {
23580 if (isJSXNode(node)) {
23581 return hasNodeIgnoreComment$1(node);
23584 var res = node.comments && node.comments.some(function (comment) {
23585 return comment.leading && hasNewline$3(text, options.locEnd(comment));
23588 } // This recurses the return argument, looking for the first token
23589 // (the leftmost leaf node) and, if it (or its parents) has any
23590 // leadingComments, returns true (so it can be wrapped in parens).
23593 function returnArgumentHasLeadingComment(options, argument) {
23594 if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
23598 if (hasNakedLeftSide(argument)) {
23599 var leftMost = argument;
23602 while (newLeftMost = getLeftSide(leftMost)) {
23603 leftMost = newLeftMost;
23605 if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
23614 function isStringPropSafeToCoerceToIdentifier(node, options) {
23615 return isStringLiteral(node.key) && isIdentifierName(node.key.value) && options.parser !== "json" && !(options.parser === "typescript" && node.type === "ClassProperty");
23618 function isJestEachTemplateLiteral(node, parentNode) {
23620 * describe.each`table`(name, fn)
23621 * describe.only.each`table`(name, fn)
23622 * describe.skip.each`table`(name, fn)
23623 * test.each`table`(name, fn)
23624 * test.only.each`table`(name, fn)
23625 * test.skip.each`table`(name, fn)
23627 * Ref: https://github.com/facebook/jest/pull/6102
23629 var jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
23630 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));
23633 function templateLiteralHasNewLines(template) {
23634 return template.quasis.some(function (quasi) {
23635 return quasi.value.raw.includes("\n");
23639 function isTemplateOnItsOwnLine(n, text, options) {
23640 return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$3(text, options.locStart(n), {
23645 function needsHardlineAfterDanglingComment(node) {
23646 if (!node.comments) {
23650 var lastDanglingComment = getLast$1(node.comments.filter(function (comment) {
23651 return !comment.leading && !comment.trailing;
23653 return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment);
23654 } // If we have nested conditional expressions, we want to print them in JSX mode
23655 // if there's at least one JSXElement somewhere in the tree.
23657 // A conditional expression chain like this should be printed in normal mode,
23658 // because there aren't JSXElements anywhere in it:
23660 // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
23662 // But a conditional expression chain like this should be printed in JSX mode,
23663 // because there is a JSXElement in the last ConditionalExpression:
23665 // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
23667 // This type of ConditionalExpression chain is structured like this in the AST:
23669 // ConditionalExpression {
23671 // consequent: ...,
23672 // alternate: ConditionalExpression {
23674 // consequent: ...,
23675 // alternate: ConditionalExpression {
23677 // consequent: ...,
23683 // We want to traverse over that shape and convert it into a flat structure so
23684 // that we can find if there's a JSXElement somewhere inside.
23687 function getConditionalChainContents(node) {
23688 // Given this code:
23690 // // Using a ConditionalExpression as the consequent is uncommon, but should
23692 // A ? B : C ? D : E ? F ? G : H : I
23694 // which has this AST:
23696 // ConditionalExpression {
23697 // test: Identifier(A),
23698 // consequent: Identifier(B),
23699 // alternate: ConditionalExpression {
23700 // test: Identifier(C),
23701 // consequent: Identifier(D),
23702 // alternate: ConditionalExpression {
23703 // test: Identifier(E),
23704 // consequent: ConditionalExpression {
23705 // test: Identifier(F),
23706 // consequent: Identifier(G),
23707 // alternate: Identifier(H),
23709 // alternate: Identifier(I),
23714 // we should return this Array:
23728 // This loses the information about whether each node was the test,
23729 // consequent, or alternate, but we don't care about that here- we are only
23730 // flattening this structure to find if there's any JSXElements inside.
23731 var nonConditionalExpressions = [];
23733 function recurse(node) {
23734 if (node.type === "ConditionalExpression") {
23735 recurse(node.test);
23736 recurse(node.consequent);
23737 recurse(node.alternate);
23739 nonConditionalExpressions.push(node);
23744 return nonConditionalExpressions;
23747 function conditionalExpressionChainContainsJSX(node) {
23748 return Boolean(getConditionalChainContents(node).find(isJSXNode));
23749 } // Logic to check for args with multiple anonymous functions. For instance,
23750 // the following call should be split on multiple lines for readability:
23751 // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0))
23754 function isFunctionCompositionArgs(args) {
23755 if (args.length <= 1) {
23760 var _iteratorNormalCompletion = true;
23761 var _didIteratorError = false;
23762 var _iteratorError = undefined;
23765 for (var _iterator = args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
23766 var arg = _step.value;
23768 if (isFunctionOrArrowExpression(arg)) {
23774 } else if (isCallOrOptionalCallExpression(arg)) {
23775 var _iteratorNormalCompletion2 = true;
23776 var _didIteratorError2 = false;
23777 var _iteratorError2 = undefined;
23780 for (var _iterator2 = arg.arguments[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
23781 var childArg = _step2.value;
23783 if (isFunctionOrArrowExpression(childArg)) {
23788 _didIteratorError2 = true;
23789 _iteratorError2 = err;
23792 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
23793 _iterator2.return();
23796 if (_didIteratorError2) {
23797 throw _iteratorError2;
23804 _didIteratorError = true;
23805 _iteratorError = err;
23808 if (!_iteratorNormalCompletion && _iterator.return != null) {
23809 _iterator.return();
23812 if (_didIteratorError) {
23813 throw _iteratorError;
23819 } // Logic to determine if a call is a “long curried function call”.
23820 // See https://github.com/prettier/prettier/issues/1420.
23822 // `connect(a, b, c)(d)`
23823 // In the above call expression, the second call is the parent node and the
23824 // first call is the current node.
23827 function isLongCurriedCallExpression(path) {
23828 var node = path.getValue();
23829 var parent = path.getParentNode();
23830 return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
23833 function rawText(node) {
23834 return node.extra ? node.extra.raw : node.raw;
23837 function identity$1(x) {
23841 function isTSXFile(options) {
23842 return options.filepath && /\.tsx$/i.test(options.filepath);
23846 classChildNeedsASIProtection: classChildNeedsASIProtection,
23847 classPropMayCauseASIProblems: classPropMayCauseASIProblems,
23848 conditionalExpressionChainContainsJSX: conditionalExpressionChainContainsJSX,
23849 getFlowVariance: getFlowVariance,
23850 getLeftSidePathName: getLeftSidePathName,
23851 getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier,
23852 hasDanglingComments: hasDanglingComments,
23853 hasFlowAnnotationComment: hasFlowAnnotationComment,
23854 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment,
23855 hasLeadingComment: hasLeadingComment$2,
23856 hasLeadingOwnLineComment: hasLeadingOwnLineComment,
23857 hasNakedLeftSide: hasNakedLeftSide,
23858 hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators,
23859 hasNgSideEffect: hasNgSideEffect,
23861 hasPrettierIgnore: hasPrettierIgnore$2,
23862 hasTrailingComment: hasTrailingComment,
23863 identity: identity$1,
23864 isBinaryish: isBinaryish,
23865 isCallOrOptionalCallExpression: isCallOrOptionalCallExpression,
23866 isEmptyJSXElement: isEmptyJSXElement,
23867 isFlowAnnotationComment: isFlowAnnotationComment,
23868 isFunctionCompositionArgs: isFunctionCompositionArgs,
23869 isFunctionNotation: isFunctionNotation,
23870 isFunctionOrArrowExpression: isFunctionOrArrowExpression,
23871 isGetterOrSetter: isGetterOrSetter,
23872 isJestEachTemplateLiteral: isJestEachTemplateLiteral,
23873 isJSXNode: isJSXNode,
23874 isJSXWhitespaceExpression: isJSXWhitespaceExpression,
23875 isLastStatement: isLastStatement,
23876 isLiteral: isLiteral,
23877 isLongCurriedCallExpression: isLongCurriedCallExpression,
23878 isMeaningfulJSXText: isMeaningfulJSXText,
23879 isMemberExpressionChain: isMemberExpressionChain,
23880 isMemberish: isMemberish,
23881 isNgForOf: isNgForOf,
23882 isNumericLiteral: isNumericLiteral,
23883 isObjectType: isObjectType,
23884 isObjectTypePropertyAFunction: isObjectTypePropertyAFunction,
23885 isSimpleFlowType: isSimpleFlowType,
23886 isSimpleTemplateLiteral: isSimpleTemplateLiteral,
23887 isStringLiteral: isStringLiteral,
23888 isStringPropSafeToCoerceToIdentifier: isStringPropSafeToCoerceToIdentifier,
23889 isTemplateOnItsOwnLine: isTemplateOnItsOwnLine,
23890 isTestCall: isTestCall,
23891 isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown,
23892 isTSXFile: isTSXFile,
23893 isTypeAnnotationAFunction: isTypeAnnotationAFunction,
23894 matchJsxWhitespaceRegex: matchJsxWhitespaceRegex,
23895 needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment,
23897 returnArgumentHasLeadingComment: returnArgumentHasLeadingComment
23900 var getLeftSidePathName$1 = utils$4.getLeftSidePathName,
23901 hasFlowShorthandAnnotationComment$1 = utils$4.hasFlowShorthandAnnotationComment,
23902 hasNakedLeftSide$1 = utils$4.hasNakedLeftSide,
23903 hasNode$1 = utils$4.hasNode;
23905 function hasClosureCompilerTypeCastComment(text, path) {
23906 // https://github.com/google/closure-compiler/wiki/Annotating-Types#type-casts
23907 // Syntax example: var x = /** @type {string} */ (fruit);
23908 var n = path.getValue();
23909 return isParenthesized(n) && (hasTypeCastComment(n) || hasAncestorTypeCastComment(0)); // for sub-item: /** @type {array} */ (numberOrString).map(x => x);
23911 function hasAncestorTypeCastComment(index) {
23912 var ancestor = path.getParentNode(index);
23913 return ancestor && !isParenthesized(ancestor) ? hasTypeCastComment(ancestor) || hasAncestorTypeCastComment(index + 1) : false;
23916 function hasTypeCastComment(node) {
23917 return node.comments && node.comments.some(function (comment) {
23918 return comment.leading && comments$1.isBlockComment(comment) && isTypeCastComment(comment.value);
23922 function isParenthesized(node) {
23923 // Closure typecast comments only really make sense when _not_ using
23924 // typescript or flow parsers, so we take advantage of the babel parser's
23925 // parenthesized expressions.
23926 return node.extra && node.extra.parenthesized;
23929 function isTypeCastComment(comment) {
23930 var cleaned = comment.trim().split("\n").map(function (line) {
23931 return line.replace(/^[\s*]+/, "");
23932 }).join(" ").trim();
23934 if (!/^@type\s*\{[^]+\}$/.test(cleaned)) {
23938 var isCompletelyClosed = false;
23939 var unpairedBracketCount = 0;
23940 var _iteratorNormalCompletion = true;
23941 var _didIteratorError = false;
23942 var _iteratorError = undefined;
23945 for (var _iterator = cleaned[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
23946 var char = _step.value;
23948 if (char === "{") {
23949 if (isCompletelyClosed) {
23953 unpairedBracketCount++;
23954 } else if (char === "}") {
23955 if (unpairedBracketCount === 0) {
23959 unpairedBracketCount--;
23961 if (unpairedBracketCount === 0) {
23962 isCompletelyClosed = true;
23967 _didIteratorError = true;
23968 _iteratorError = err;
23971 if (!_iteratorNormalCompletion && _iterator.return != null) {
23972 _iterator.return();
23975 if (_didIteratorError) {
23976 throw _iteratorError;
23981 return unpairedBracketCount === 0;
23985 function needsParens(path, options) {
23986 var parent = path.getParentNode();
23992 var name = path.getName();
23993 var node = path.getNode(); // If the value of this path is some child of a Node and not a Node
23994 // itself, then it doesn't need parentheses. Only Node objects (in
23995 // fact, only Expression nodes) need parentheses.
23997 if (path.getValue() !== node) {
23999 } // to avoid unexpected `}}` in HTML interpolations
24002 if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) {
24004 } // Only statements don't need parentheses.
24007 if (isStatement(node)) {
24009 } // Closure compiler requires that type casted expressions to be surrounded by
24013 if (hasClosureCompilerTypeCastComment(options.originalText, path)) {
24017 if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
24018 // parser. The Flow parser turns Flow comments into type annotation nodes in its
24019 // AST, which we handle separately.
24020 options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) {
24022 } // Identifiers never need parentheses.
24025 if (node.type === "Identifier") {
24026 // ...unless those identifiers are embed placeholders. They might be substituted by complex
24027 // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS):
24028 // let tpl = html`<script> f((${expr}) / 2); </script>`;
24029 // If the inner JS formatter removes the parens, the expression might change its meaning:
24030 // f((a + b) / 2) vs f(a + b / 2)
24031 if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) {
24038 if (parent.type === "ParenthesizedExpression") {
24040 } // Add parens around the extends clause of a class. It is needed for almost
24041 // all expressions.
24044 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")) {
24046 } // `export default function` or `export default class` can't be followed by
24047 // anything after. So an expression like `export default (function(){}).toString()`
24048 // needs to be followed by a parentheses
24051 if (parent.type === "ExportDefaultDeclaration") {
24052 return shouldWrapFunctionForExportDefault(path, options);
24055 if (parent.type === "Decorator" && parent.expression === node) {
24056 var hasCallExpression = false;
24057 var hasMemberExpression = false;
24058 var current = node;
24061 switch (current.type) {
24062 case "MemberExpression":
24063 hasMemberExpression = true;
24064 current = current.object;
24067 case "CallExpression":
24070 hasMemberExpression ||
24072 hasCallExpression) {
24076 hasCallExpression = true;
24077 current = current.callee;
24091 if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway
24092 util.startsWithNoLookaheadToken(node,
24093 /* forbidFunctionClassAndDoExpr */
24094 false) || parent.type === "ExpressionStatement" && util.startsWithNoLookaheadToken(node,
24095 /* forbidFunctionClassAndDoExpr */
24100 switch (node.type) {
24101 case "SpreadElement":
24102 case "SpreadProperty":
24103 return parent.type === "MemberExpression" && name === "object" && parent.object === node;
24105 case "UpdateExpression":
24106 if (parent.type === "UnaryExpression") {
24107 return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
24110 // else fallthrough
24112 case "UnaryExpression":
24113 switch (parent.type) {
24114 case "UnaryExpression":
24115 return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
24117 case "BindExpression":
24120 case "MemberExpression":
24121 case "OptionalMemberExpression":
24122 return name === "object";
24124 case "TaggedTemplateExpression":
24127 case "NewExpression":
24128 case "CallExpression":
24129 case "OptionalCallExpression":
24130 return name === "callee";
24132 case "BinaryExpression":
24133 return parent.operator === "**" && name === "left";
24135 case "TSNonNullExpression":
24142 case "BinaryExpression":
24144 if (parent.type === "UpdateExpression") {
24148 var isLeftOfAForStatement = function isLeftOfAForStatement(node) {
24152 var _parent = path.getParentNode(i++);
24158 if (_parent.type === "ForStatement" && _parent.init === node) {
24168 if (node.operator === "in" && isLeftOfAForStatement(node)) {
24174 case "TSTypeAssertion":
24175 case "TSAsExpression":
24176 case "LogicalExpression":
24177 switch (parent.type) {
24178 case "ConditionalExpression":
24179 return node.type === "TSAsExpression";
24181 case "CallExpression":
24182 case "NewExpression":
24183 case "OptionalCallExpression":
24184 return name === "callee";
24186 case "ClassExpression":
24187 case "ClassDeclaration":
24188 return name === "superClass" && parent.superClass === node;
24190 case "TSTypeAssertion":
24191 case "TaggedTemplateExpression":
24192 case "UnaryExpression":
24193 case "JSXSpreadAttribute":
24194 case "SpreadElement":
24195 case "SpreadProperty":
24196 case "BindExpression":
24197 case "AwaitExpression":
24198 case "TSAsExpression":
24199 case "TSNonNullExpression":
24200 case "UpdateExpression":
24203 case "MemberExpression":
24204 case "OptionalMemberExpression":
24205 return name === "object";
24207 case "AssignmentExpression":
24208 return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
24210 case "LogicalExpression":
24211 if (node.type === "LogicalExpression") {
24212 return parent.operator !== node.operator;
24215 // else fallthrough
24217 case "BinaryExpression":
24219 if (!node.operator && node.type !== "TSTypeAssertion") {
24223 var po = parent.operator;
24224 var pp = util.getPrecedence(po);
24225 var no = node.operator;
24226 var np = util.getPrecedence(no);
24232 if (pp === np && name === "right") {
24233 assert.strictEqual(parent.right, node);
24237 if (pp === np && !util.shouldFlatten(po, no)) {
24241 if (pp < np && no === "%") {
24242 return po === "+" || po === "-";
24243 } // Add parenthesis when working with bitwise operators
24244 // It's not strictly needed but helps with code understanding
24247 if (util.isBitwiseOperator(po)) {
24258 case "SequenceExpression":
24259 switch (parent.type) {
24260 case "ReturnStatement":
24263 case "ForStatement":
24264 // Although parentheses wouldn't hurt around sequence
24265 // expressions in the head of for loops, traditional style
24266 // dictates that e.g. i++, j++ should not be wrapped with
24270 case "ExpressionStatement":
24271 return name !== "expression";
24273 case "ArrowFunctionExpression":
24274 // We do need parentheses, but SequenceExpressions are handled
24275 // specially when printing bodies of arrow functions.
24276 return name !== "body";
24279 // Otherwise err on the side of overparenthesization, adding
24280 // explicit exceptions above if this proves overzealous.
24284 case "YieldExpression":
24285 if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
24289 // else fallthrough
24291 case "AwaitExpression":
24292 switch (parent.type) {
24293 case "TaggedTemplateExpression":
24294 case "UnaryExpression":
24295 case "BinaryExpression":
24296 case "LogicalExpression":
24297 case "SpreadElement":
24298 case "SpreadProperty":
24299 case "TSAsExpression":
24300 case "TSNonNullExpression":
24301 case "BindExpression":
24304 case "MemberExpression":
24305 case "OptionalMemberExpression":
24306 return name === "object";
24308 case "NewExpression":
24309 case "CallExpression":
24310 case "OptionalCallExpression":
24311 return name === "callee";
24313 case "ConditionalExpression":
24314 return parent.test === node;
24320 case "TSConditionalType":
24321 if (parent.type === "TSConditionalType" && node === parent.extendsType) {
24327 case "TSFunctionType":
24328 case "TSConstructorType":
24329 if (parent.type === "TSConditionalType" && node === parent.checkType) {
24335 case "TSUnionType":
24336 case "TSIntersectionType":
24337 if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") {
24343 case "TSTypeOperator":
24344 case "TSInferType":
24345 return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator";
24347 case "ArrayTypeAnnotation":
24348 return parent.type === "NullableTypeAnnotation";
24350 case "IntersectionTypeAnnotation":
24351 case "UnionTypeAnnotation":
24352 return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
24354 case "NullableTypeAnnotation":
24355 return parent.type === "ArrayTypeAnnotation";
24357 case "FunctionTypeAnnotation":
24359 var ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent;
24360 return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
24361 // are really needed, but since ??T doesn't make sense this check
24362 // will almost never be true.
24363 ancestor.type === "NullableTypeAnnotation";
24366 case "StringLiteral":
24367 case "NumericLiteral":
24369 if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
24370 // See corresponding workaround in printer.js case: "Literal"
24371 options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.substr(options.locStart(node) - 1, 1) === "(")) {
24372 // To avoid becoming a directive
24373 var grandParent = path.getParentNode(1);
24374 return grandParent.type === "Program" || grandParent.type === "BlockStatement";
24377 return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node;
24379 case "AssignmentExpression":
24381 var _grandParent = path.getParentNode(1);
24383 if (parent.type === "ArrowFunctionExpression" && parent.body === node) {
24385 } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) {
24387 } else if (parent.type === "TSPropertySignature" && parent.name === node) {
24389 } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) {
24391 } else if (parent.type === "ExpressionStatement") {
24392 return node.left.type === "ObjectPattern";
24393 } else if (parent.type === "TSPropertySignature" && parent.key === node) {
24395 } else if (parent.type === "AssignmentExpression") {
24397 } else if (parent.type === "SequenceExpression" && _grandParent && _grandParent.type === "ForStatement" && (_grandParent.init === parent || _grandParent.update === parent)) {
24399 } else if (parent.type === "Property" && parent.value === node) {
24401 } else if (parent.type === "NGChainedExpression") {
24408 case "ConditionalExpression":
24409 switch (parent.type) {
24410 case "TaggedTemplateExpression":
24411 case "UnaryExpression":
24412 case "SpreadElement":
24413 case "SpreadProperty":
24414 case "BinaryExpression":
24415 case "LogicalExpression":
24416 case "NGPipeExpression":
24417 case "ExportDefaultDeclaration":
24418 case "AwaitExpression":
24419 case "JSXSpreadAttribute":
24420 case "TSTypeAssertion":
24421 case "TypeCastExpression":
24422 case "TSAsExpression":
24423 case "TSNonNullExpression":
24426 case "NewExpression":
24427 case "CallExpression":
24428 case "OptionalCallExpression":
24429 return name === "callee";
24431 case "ConditionalExpression":
24432 return name === "test" && parent.test === node;
24434 case "MemberExpression":
24435 case "OptionalMemberExpression":
24436 return name === "object";
24442 case "FunctionExpression":
24443 switch (parent.type) {
24444 case "NewExpression":
24445 case "CallExpression":
24446 case "OptionalCallExpression":
24447 // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
24448 // Is necessary if it is `expression` of `ExpressionStatement`.
24449 return name === "callee";
24451 case "TaggedTemplateExpression":
24453 // This is basically a kind of IIFE.
24459 case "ArrowFunctionExpression":
24460 switch (parent.type) {
24461 case "NewExpression":
24462 case "CallExpression":
24463 case "OptionalCallExpression":
24464 return name === "callee";
24466 case "MemberExpression":
24467 case "OptionalMemberExpression":
24468 return name === "object";
24470 case "TSAsExpression":
24471 case "BindExpression":
24472 case "TaggedTemplateExpression":
24473 case "UnaryExpression":
24474 case "LogicalExpression":
24475 case "BinaryExpression":
24476 case "AwaitExpression":
24477 case "TSTypeAssertion":
24480 case "ConditionalExpression":
24481 return name === "test";
24487 case "ClassExpression":
24488 switch (parent.type) {
24489 case "NewExpression":
24490 return name === "callee" && parent.callee === node;
24496 case "OptionalMemberExpression":
24497 case "OptionalCallExpression":
24498 if ((parent.type === "MemberExpression" && name === "object" || parent.type === "CallExpression" && name === "callee") && // workaround for https://github.com/facebook/flow/issues/8159
24499 !(options.parser === "flow" && parent.range[0] === node.range[0])) {
24505 case "CallExpression":
24506 case "MemberExpression":
24507 case "TaggedTemplateExpression":
24508 case "TSNonNullExpression":
24509 if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") {
24513 switch (object.type) {
24514 case "CallExpression":
24515 case "OptionalCallExpression":
24518 case "MemberExpression":
24519 case "OptionalMemberExpression":
24520 case "BindExpression":
24521 object = object.object;
24523 // tagged templates are basically member expressions from a grammar perspective
24524 // see https://tc39.github.io/ecma262/#prod-MemberExpression
24526 case "TaggedTemplateExpression":
24527 object = object.tag;
24530 case "TSNonNullExpression":
24531 object = object.expression;
24542 case "BindExpression":
24543 return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object";
24545 case "NGPipeExpression":
24546 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") {
24552 case "JSXFragment":
24554 return name === "callee" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "CallExpression" && 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 !== "TypeCastExpression" && parent.type !== "VariableDeclarator";
24556 case "TypeAnnotation":
24557 return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node);
24563 function isStatement(node) {
24564 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 === "ForAwaitStatement" || 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";
24567 function includesFunctionTypeInObjectType(node) {
24568 return hasNode$1(node, function (n1) {
24569 return n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, function (n2) {
24570 return n2.type === "FunctionTypeAnnotation" || undefined;
24575 function endsWithRightBracket(node) {
24576 switch (node.type) {
24577 case "ObjectExpression":
24585 function isFollowedByRightBracket(path) {
24586 var node = path.getValue();
24587 var parent = path.getParentNode();
24588 var name = path.getName();
24590 switch (parent.type) {
24591 case "NGPipeExpression":
24592 if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
24593 return path.callParent(isFollowedByRightBracket);
24598 case "ObjectProperty":
24599 if (name === "value") {
24600 var parentParent = path.getParentNode(1);
24601 return parentParent.properties[parentParent.properties.length - 1] === parent;
24606 case "BinaryExpression":
24607 case "LogicalExpression":
24608 if (name === "right") {
24609 return path.callParent(isFollowedByRightBracket);
24614 case "ConditionalExpression":
24615 if (name === "alternate") {
24616 return path.callParent(isFollowedByRightBracket);
24621 case "UnaryExpression":
24622 if (parent.prefix) {
24623 return path.callParent(isFollowedByRightBracket);
24632 function shouldWrapFunctionForExportDefault(path, options) {
24633 var node = path.getValue();
24634 var parent = path.getParentNode();
24636 if (node.type === "FunctionExpression" || node.type === "ClassExpression") {
24637 return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped
24638 // (e.g. `export default (function() {})();`)
24639 // in this case we don't need to add extra parens
24640 !needsParens(path, options);
24643 if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) {
24647 return path.call.apply(path, [function (childPath) {
24648 return shouldWrapFunctionForExportDefault(childPath, options);
24649 }].concat(getLeftSidePathName$1(path, node)));
24652 var needsParens_1 = needsParens;
24654 var _require$$0$builders$6 = doc.builders,
24655 concat$c = _require$$0$builders$6.concat,
24656 join$8 = _require$$0$builders$6.join,
24657 line$6 = _require$$0$builders$6.line;
24659 function printHtmlBinding(path, options, print) {
24660 var node = path.getValue();
24662 if (options.__onHtmlBindingRoot && path.getName() === null) {
24663 options.__onHtmlBindingRoot(node);
24666 if (node.type !== "File") {
24670 if (options.__isVueForBindingLeft) {
24671 return path.call(function (functionDeclarationPath) {
24672 var _functionDeclarationP = functionDeclarationPath.getValue(),
24673 params = _functionDeclarationP.params;
24675 return concat$c([params.length > 1 ? "(" : "", join$8(concat$c([",", line$6]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]);
24676 }, "program", "body", 0);
24679 if (options.__isVueSlotScope) {
24680 return path.call(function (functionDeclarationPath) {
24681 return join$8(concat$c([",", line$6]), functionDeclarationPath.map(print, "params"));
24682 }, "program", "body", 0);
24684 } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
24687 function isVueEventBindingExpression$2(node) {
24688 switch (node.type) {
24689 case "MemberExpression":
24690 switch (node.property.type) {
24692 case "NumericLiteral":
24693 case "StringLiteral":
24694 return isVueEventBindingExpression$2(node.object);
24707 var htmlBinding = {
24708 isVueEventBindingExpression: isVueEventBindingExpression$2,
24709 printHtmlBinding: printHtmlBinding
24712 function preprocess$1(ast, options) {
24713 switch (options.parser) {
24716 case "json-stringify":
24717 case "__js_expression":
24718 case "__vue_expression":
24719 return Object.assign({}, ast, {
24720 type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
24730 var preprocess_1$1 = preprocess$1;
24732 var getParentExportDeclaration$1 = util.getParentExportDeclaration,
24733 isExportDeclaration$1 = util.isExportDeclaration,
24734 shouldFlatten$1 = util.shouldFlatten,
24735 getNextNonSpaceNonCommentCharacter$1 = util.getNextNonSpaceNonCommentCharacter,
24736 hasNewline$4 = util.hasNewline,
24737 hasNewlineInRange$2 = util.hasNewlineInRange,
24738 getLast$2 = util.getLast,
24739 getStringWidth$2 = util.getStringWidth,
24740 printString$2 = util.printString,
24741 printNumber$2 = util.printNumber,
24742 hasIgnoreComment$4 = util.hasIgnoreComment,
24743 hasNodeIgnoreComment$2 = util.hasNodeIgnoreComment,
24744 getPenultimate$1 = util.getPenultimate,
24745 startsWithNoLookaheadToken$1 = util.startsWithNoLookaheadToken,
24746 getIndentSize$1 = util.getIndentSize,
24747 matchAncestorTypes$1 = util.matchAncestorTypes,
24748 getPreferredQuote$1 = util.getPreferredQuote;
24749 var isNextLineEmpty$4 = utilShared.isNextLineEmpty,
24750 isNextLineEmptyAfterIndex$1 = utilShared.isNextLineEmptyAfterIndex,
24751 getNextNonSpaceNonCommentCharacterIndex$2 = utilShared.getNextNonSpaceNonCommentCharacterIndex;
24752 var insertPragma$7 = pragma.insertPragma;
24753 var printHtmlBinding$1 = htmlBinding.printHtmlBinding,
24754 isVueEventBindingExpression$3 = htmlBinding.isVueEventBindingExpression;
24755 var classChildNeedsASIProtection$1 = utils$4.classChildNeedsASIProtection,
24756 classPropMayCauseASIProblems$1 = utils$4.classPropMayCauseASIProblems,
24757 conditionalExpressionChainContainsJSX$1 = utils$4.conditionalExpressionChainContainsJSX,
24758 getFlowVariance$1 = utils$4.getFlowVariance,
24759 getLeftSidePathName$2 = utils$4.getLeftSidePathName,
24760 getTypeScriptMappedTypeModifier$1 = utils$4.getTypeScriptMappedTypeModifier,
24761 hasDanglingComments$1 = utils$4.hasDanglingComments,
24762 hasFlowAnnotationComment$1 = utils$4.hasFlowAnnotationComment,
24763 hasFlowShorthandAnnotationComment$2 = utils$4.hasFlowShorthandAnnotationComment,
24764 hasLeadingComment$3 = utils$4.hasLeadingComment,
24765 hasLeadingOwnLineComment$1 = utils$4.hasLeadingOwnLineComment,
24766 hasNakedLeftSide$2 = utils$4.hasNakedLeftSide,
24767 hasNewlineBetweenOrAfterDecorators$1 = utils$4.hasNewlineBetweenOrAfterDecorators,
24768 hasNgSideEffect$1 = utils$4.hasNgSideEffect,
24769 hasPrettierIgnore$3 = utils$4.hasPrettierIgnore,
24770 hasTrailingComment$1 = utils$4.hasTrailingComment,
24771 identity$2 = utils$4.identity,
24772 isBinaryish$1 = utils$4.isBinaryish,
24773 isCallOrOptionalCallExpression$1 = utils$4.isCallOrOptionalCallExpression,
24774 isEmptyJSXElement$1 = utils$4.isEmptyJSXElement,
24775 isFlowAnnotationComment$1 = utils$4.isFlowAnnotationComment,
24776 isFunctionCompositionArgs$1 = utils$4.isFunctionCompositionArgs,
24777 isFunctionNotation$1 = utils$4.isFunctionNotation,
24778 isFunctionOrArrowExpression$1 = utils$4.isFunctionOrArrowExpression,
24779 isGetterOrSetter$1 = utils$4.isGetterOrSetter,
24780 isJestEachTemplateLiteral$1 = utils$4.isJestEachTemplateLiteral,
24781 isJSXNode$1 = utils$4.isJSXNode,
24782 isJSXWhitespaceExpression$1 = utils$4.isJSXWhitespaceExpression,
24783 isLastStatement$1 = utils$4.isLastStatement,
24784 isLiteral$1 = utils$4.isLiteral,
24785 isLongCurriedCallExpression$1 = utils$4.isLongCurriedCallExpression,
24786 isMeaningfulJSXText$1 = utils$4.isMeaningfulJSXText,
24787 isMemberExpressionChain$1 = utils$4.isMemberExpressionChain,
24788 isMemberish$1 = utils$4.isMemberish,
24789 isNgForOf$1 = utils$4.isNgForOf,
24790 isNumericLiteral$1 = utils$4.isNumericLiteral,
24791 isObjectType$1 = utils$4.isObjectType,
24792 isObjectTypePropertyAFunction$1 = utils$4.isObjectTypePropertyAFunction,
24793 isSimpleFlowType$1 = utils$4.isSimpleFlowType,
24794 isSimpleTemplateLiteral$1 = utils$4.isSimpleTemplateLiteral,
24795 isStringLiteral$1 = utils$4.isStringLiteral,
24796 isStringPropSafeToCoerceToIdentifier$1 = utils$4.isStringPropSafeToCoerceToIdentifier,
24797 isTemplateOnItsOwnLine$1 = utils$4.isTemplateOnItsOwnLine,
24798 isTestCall$1 = utils$4.isTestCall,
24799 isTheOnlyJSXElementInMarkdown$1 = utils$4.isTheOnlyJSXElementInMarkdown,
24800 isTSXFile$1 = utils$4.isTSXFile,
24801 isTypeAnnotationAFunction$1 = utils$4.isTypeAnnotationAFunction,
24802 matchJsxWhitespaceRegex$1 = utils$4.matchJsxWhitespaceRegex,
24803 needsHardlineAfterDanglingComment$1 = utils$4.needsHardlineAfterDanglingComment,
24804 rawText$1 = utils$4.rawText,
24805 returnArgumentHasLeadingComment$1 = utils$4.returnArgumentHasLeadingComment;
24806 var needsQuoteProps = new WeakMap();
24807 var _require$$5$builders = doc.builders,
24808 concat$d = _require$$5$builders.concat,
24809 join$9 = _require$$5$builders.join,
24810 line$7 = _require$$5$builders.line,
24811 hardline$9 = _require$$5$builders.hardline,
24812 softline$6 = _require$$5$builders.softline,
24813 literalline$4 = _require$$5$builders.literalline,
24814 group$b = _require$$5$builders.group,
24815 indent$7 = _require$$5$builders.indent,
24816 align$1 = _require$$5$builders.align,
24817 conditionalGroup$1 = _require$$5$builders.conditionalGroup,
24818 fill$4 = _require$$5$builders.fill,
24819 ifBreak$6 = _require$$5$builders.ifBreak,
24820 breakParent$3 = _require$$5$builders.breakParent,
24821 lineSuffixBoundary$1 = _require$$5$builders.lineSuffixBoundary,
24822 addAlignmentToDoc$2 = _require$$5$builders.addAlignmentToDoc,
24823 dedent$2 = _require$$5$builders.dedent,
24824 _require$$5$utils = doc.utils,
24825 willBreak$1 = _require$$5$utils.willBreak,
24826 isLineNext$1 = _require$$5$utils.isLineNext,
24827 isEmpty$1 = _require$$5$utils.isEmpty,
24828 removeLines$2 = _require$$5$utils.removeLines,
24829 printDocToString$1 = doc.printer.printDocToString;
24832 function shouldPrintComma$1(options, level) {
24833 level = level || "es5";
24835 switch (options.trailingComma) {
24837 if (level === "all") {
24844 if (level === "es5") {
24856 function genericPrint$3(path, options, printPath, args) {
24857 var node = path.getValue();
24858 var needsParens = false;
24859 var linesWithoutParens = printPathNoParens(path, options, printPath, args);
24861 if (!node || isEmpty$1(linesWithoutParens)) {
24862 return linesWithoutParens;
24865 var parentExportDecl = getParentExportDeclaration$1(path);
24866 var decorators = [];
24868 if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator
24869 // was written before the export, the export will be responsible
24870 // for printing the decorators.
24871 !(parentExportDecl && options.locStart(parentExportDecl, {
24872 ignoreDecorators: true
24873 }) > options.locStart(node.decorators[0]))) {
24874 var shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options);
24875 var separator = shouldBreak ? hardline$9 : line$7;
24876 path.each(function (decoratorPath) {
24877 var decorator = decoratorPath.getValue();
24879 if (decorator.expression) {
24880 decorator = decorator.expression;
24882 decorator = decorator.callee;
24885 decorators.push(printPath(decoratorPath), separator);
24888 if (parentExportDecl) {
24889 decorators.unshift(hardline$9);
24891 } 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,
24892 // otherwise they are printed by the node.declaration
24893 options.locStart(node, {
24894 ignoreDecorators: true
24895 }) > options.locStart(node.declaration.decorators[0])) {
24896 // Export declarations are responsible for printing any decorators
24897 // that logically apply to node.declaration.
24898 path.each(function (decoratorPath) {
24899 var decorator = decoratorPath.getValue();
24900 var prefix = decorator.type === "Decorator" ? "" : "@";
24901 decorators.push(prefix, printPath(decoratorPath), hardline$9);
24902 }, "declaration", "decorators");
24904 // Nodes with decorators can't have parentheses, so we can avoid
24905 // computing pathNeedsParens() except in this case.
24906 needsParens = needsParens_1(path, options);
24912 parts.unshift("(");
24915 parts.push(linesWithoutParens);
24918 var _node = path.getValue();
24920 if (hasFlowShorthandAnnotationComment$2(_node)) {
24922 parts.push(_node.trailingComments[0].value.trimLeft());
24924 _node.trailingComments[0].printed = true;
24930 if (decorators.length > 0) {
24931 return group$b(concat$d(decorators.concat(parts)));
24934 return concat$d(parts);
24937 function printDecorators(path, options, print) {
24938 var node = path.getValue();
24939 return group$b(concat$d([join$9(line$7, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$9 : line$7]));
24942 * The following is the shared logic for
24943 * ternary operators, namely ConditionalExpression
24944 * and TSConditionalType
24945 * @typedef {Object} OperatorOptions
24946 * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
24947 * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
24948 * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
24949 * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
24950 * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
24951 * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
24952 * @property {string} testNodePropertyName - The property at which the test node can be found on the main node, eg "test".
24953 * @property {boolean} breakNested - Whether to break all nested ternaries when one breaks.
24954 * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
24955 * @param {Options} options - Prettier options
24956 * @param {Function} print - Print function to call recursively
24957 * @param {OperatorOptions} operatorOptions
24962 function printTernaryOperator(path, options, print, operatorOptions) {
24963 var node = path.getValue();
24964 var testNode = node[operatorOptions.testNodePropertyName];
24965 var consequentNode = node[operatorOptions.consequentNodePropertyName];
24966 var alternateNode = node[operatorOptions.alternateNodePropertyName];
24967 var parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
24968 // See tests/jsx/conditional-expression.js for more info.
24970 var jsxMode = false;
24971 var parent = path.getParentNode();
24972 var forceNoIndent = parent.type === operatorOptions.conditionalNodeType; // Find the outermost non-ConditionalExpression parent, and the outermost
24973 // ConditionalExpression parent. We'll use these to determine if we should
24974 // print in JSX mode.
24977 var previousParent;
24981 previousParent = currentParent || node;
24982 currentParent = path.getParentNode(i);
24984 } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType);
24986 var firstNonConditionalParent = currentParent || parent;
24987 var lastConditionalParent = previousParent;
24989 if (operatorOptions.shouldCheckJsx && (isJSXNode$1(testNode) || isJSXNode$1(consequentNode) || isJSXNode$1(alternateNode) || conditionalExpressionChainContainsJSX$1(lastConditionalParent))) {
24991 forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
24992 // parens when using ?: within JSX, because the parens are analogous to
24993 // curly braces in an if statement.
24995 var wrap = function wrap(doc) {
24996 return concat$d([ifBreak$6("(", ""), indent$7(concat$d([softline$6, doc])), softline$6, ifBreak$6(")", "")]);
24997 }; // The only things we don't wrap are:
24998 // * Nested conditional expressions in alternates
25002 var isNull = function isNull(node) {
25003 return node.type === "NullLiteral" || node.type === "Literal" && node.value === null;
25006 parts.push(" ? ", isNull(consequentNode) ? path.call(print, operatorOptions.consequentNodePropertyName) : wrap(path.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNull(alternateNode) ? path.call(print, operatorOptions.alternateNodePropertyName) : wrap(path.call(print, operatorOptions.alternateNodePropertyName)));
25009 var part = concat$d([line$7, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$6("", "(") : "", align$1(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$6("", ")") : "", line$7, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path.call(print, operatorOptions.alternateNodePropertyName))]);
25010 parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node ? part : options.useTabs ? dedent$2(indent$7(part)) : align$1(Math.max(0, options.tabWidth - 2), part));
25011 } // We want a whole chain of ConditionalExpressions to all
25012 // break if any of them break. That means we should only group around the
25013 // outer-most ConditionalExpression.
25016 var maybeGroup = function maybeGroup(doc) {
25017 return operatorOptions.breakNested ? parent === firstNonConditionalParent ? group$b(doc) : doc : group$b(doc);
25018 }; // Break the closing paren to keep the chain right after it:
25025 var breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node && operatorOptions.breakNested) && !parent.computed;
25026 return maybeGroup(concat$d([].concat(function (testDoc) {
25038 parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc
25040 }(concat$d(operatorOptions.beforeParts())), forceNoIndent ? concat$d(parts) : indent$7(concat$d(parts)), operatorOptions.afterParts(breakClosingParen))));
25043 function printPathNoParens(path, options, print, args) {
25044 var n = path.getValue();
25045 var semi = options.semi ? ";" : "";
25051 if (typeof n === "string") {
25055 var htmlBinding = printHtmlBinding$1(path, options, print);
25058 return htmlBinding;
25064 case "JsExpressionRoot":
25065 return path.call(print, "node");
25068 return concat$d([path.call(print, "node"), hardline$9]);
25071 // Print @babel/parser's InterpreterDirective here so that
25072 // leading comments on the `Program` node get printed after the hashbang.
25073 if (n.program && n.program.interpreter) {
25074 parts.push(path.call(function (programPath) {
25075 return programPath.call(print, "interpreter");
25079 parts.push(path.call(print, "program"));
25080 return concat$d(parts);
25084 if (n.directives) {
25085 path.each(function (childPath) {
25086 parts.push(print(childPath), semi, hardline$9);
25088 if (isNextLineEmpty$4(options.originalText, childPath.getValue(), options)) {
25089 parts.push(hardline$9);
25094 parts.push(path.call(function (bodyPath) {
25095 return printStatementSequence(bodyPath, options, print);
25097 parts.push(comments.printDanglingComments(path, options,
25099 true)); // Only force a trailing newline if there were any contents.
25101 if (n.body.length || n.comments) {
25102 parts.push(hardline$9);
25105 return concat$d(parts);
25106 // Babel extension.
25108 case "EmptyStatement":
25111 case "ExpressionStatement":
25112 // Detect Flow-parsed directives
25114 return concat$d([nodeStr(n.expression, options, true), semi]);
25117 if (options.parser === "__vue_event_binding") {
25118 var parent = path.getParentNode();
25120 if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
25121 return concat$d([path.call(print, "expression"), isVueEventBindingExpression$3(n.expression) ? ";" : ""]);
25123 } // Do not append semicolon after the only JSX element in a program
25126 return concat$d([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]);
25127 // Babel extension.
25129 case "ParenthesizedExpression":
25130 return concat$d(["(", path.call(print, "expression"), ")"]);
25132 case "AssignmentExpression":
25133 return printAssignment(n.left, path.call(print, "left"), concat$d([" ", n.operator]), n.right, path.call(print, "right"), options);
25135 case "BinaryExpression":
25136 case "LogicalExpression":
25137 case "NGPipeExpression":
25139 var _parent = path.getParentNode();
25141 var parentParent = path.getParentNode(1);
25142 var isInsideParenthesis = n !== _parent.body && (_parent.type === "IfStatement" || _parent.type === "WhileStatement" || _parent.type === "SwitchStatement" || _parent.type === "DoWhileStatement");
25144 var _parts = printBinaryishExpressions(path, print, options,
25146 false, isInsideParenthesis); // if (
25147 // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
25150 // looks super weird, we want to break the children if the parent breaks
25153 // this.hasPlugin("dynamicImports") &&
25154 // this.lookahead().type === tt.parenLeft
25158 if (isInsideParenthesis) {
25159 return concat$d(_parts);
25160 } // Break between the parens in
25161 // unaries or in a member or specific call expression, i.e.
25170 if ((_parent.type === "CallExpression" || _parent.type === "OptionalCallExpression") && _parent.callee === n || _parent.type === "UnaryExpression" || (_parent.type === "MemberExpression" || _parent.type === "OptionalMemberExpression") && !_parent.computed) {
25171 return group$b(concat$d([indent$7(concat$d([softline$6, concat$d(_parts)])), softline$6]));
25172 } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
25173 // indented accordingly. We should indent sub-expressions where the first case isn't indented.
25176 var shouldNotIndent = _parent.type === "ReturnStatement" || _parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || 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 !== "CallExpression" && parentParent.type !== "OptionalCallExpression";
25177 var shouldIndentIfInlining = _parent.type === "AssignmentExpression" || _parent.type === "VariableDeclarator" || _parent.type === "ClassProperty" || _parent.type === "TSAbstractClassProperty" || _parent.type === "ClassPrivateProperty" || _parent.type === "ObjectProperty" || _parent.type === "Property";
25178 var samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$1(n.operator, n.left.operator);
25180 if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
25181 return group$b(concat$d(_parts));
25184 if (_parts.length === 0) {
25186 } // If the right part is a JSX node, we include it in a separate group to
25187 // prevent it breaking the whole chain, so we can print the expression like:
25196 var hasJSX = isJSXNode$1(n.right);
25197 var rest = concat$d(hasJSX ? _parts.slice(1, -1) : _parts.slice(1));
25198 var groupId = Symbol("logicalChain-" + ++uid);
25199 var chain = group$b(concat$d([// Don't include the initial expression in the indentation
25200 // level. The first item is guaranteed to be the first
25201 // left-most expression.
25202 _parts.length > 0 ? _parts[0] : "", indent$7(rest)]), {
25210 var jsxPart = getLast$2(_parts);
25211 return group$b(concat$d([chain, ifBreak$6(indent$7(jsxPart), jsxPart, {
25216 case "AssignmentPattern":
25217 return concat$d([path.call(print, "left"), " = ", path.call(print, "right")]);
25219 case "TSTypeAssertion":
25221 var shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
25222 var castGroup = group$b(concat$d(["<", indent$7(concat$d([softline$6, path.call(print, "typeAnnotation")])), softline$6, ">"]));
25223 var exprContents = concat$d([ifBreak$6("("), indent$7(concat$d([softline$6, path.call(print, "expression")])), softline$6, ifBreak$6(")")]);
25225 if (shouldBreakAfterCast) {
25226 return conditionalGroup$1([concat$d([castGroup, path.call(print, "expression")]), concat$d([castGroup, group$b(exprContents, {
25228 })]), concat$d([castGroup, path.call(print, "expression")])]);
25231 return group$b(concat$d([castGroup, path.call(print, "expression")]));
25234 case "OptionalMemberExpression":
25235 case "MemberExpression":
25237 var _parent2 = path.getParentNode();
25239 var firstNonMemberParent;
25243 firstNonMemberParent = path.getParentNode(i);
25245 } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
25247 var 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" && _parent2.type !== "MemberExpression" && _parent2.type !== "OptionalMemberExpression";
25248 return concat$d([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$b(indent$7(concat$d([softline$6, printMemberLookup(path, options, print)])))]);
25251 case "MetaProperty":
25252 return concat$d([path.call(print, "meta"), ".", path.call(print, "property")]);
25254 case "BindExpression":
25256 parts.push(path.call(print, "object"));
25259 parts.push(group$b(indent$7(concat$d([softline$6, printBindExpressionCallee(path, options, print)]))));
25260 return concat$d(parts);
25264 return concat$d([n.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]);
25267 case "V8IntrinsicIdentifier":
25268 return concat$d(["%", n.name]);
25270 case "SpreadElement":
25271 case "SpreadElementPattern":
25272 case "RestProperty":
25273 case "SpreadProperty":
25274 case "SpreadPropertyPattern":
25275 case "RestElement":
25276 case "ObjectTypeSpreadProperty":
25277 return concat$d(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]);
25279 case "FunctionDeclaration":
25280 case "FunctionExpression":
25281 parts.push(printFunctionDeclaration(path, print, options));
25287 return concat$d(parts);
25289 case "ArrowFunctionExpression":
25292 parts.push("async ");
25295 if (shouldPrintParamsWithoutParens(path, options)) {
25296 parts.push(path.call(print, "params", 0));
25298 parts.push(group$b(concat$d([printFunctionParams(path, print, options,
25300 args && (args.expandLastArg || args.expandFirstArg),
25301 /* printTypeParams */
25302 true), printReturnType(path, print, options)])));
25305 var dangling = comments.printDanglingComments(path, options,
25307 true, function (comment) {
25308 var nextCharacter = getNextNonSpaceNonCommentCharacterIndex$2(options.originalText, comment, options);
25309 return options.originalText.substr(nextCharacter, 2) === "=>";
25313 parts.push(" ", dangling);
25317 var body = path.call(function (bodyPath) {
25318 return print(bodyPath, args);
25319 }, "body"); // We want to always keep these types of nodes on the same line
25322 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")) {
25323 return group$b(concat$d([concat$d(parts), " ", body]));
25324 } // We handle sequence expressions as the body of arrows specially,
25325 // so that the required parentheses end up on their own lines.
25328 if (n.body.type === "SequenceExpression") {
25329 return group$b(concat$d([concat$d(parts), group$b(concat$d([" (", indent$7(concat$d([softline$6, body])), softline$6, ")"]))]));
25330 } // if the arrow function is expanded as last argument, we are adding a
25331 // level of indentation and need to add a softline to align the closing )
25332 // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
25333 // we should align the expression's closing } with the line with the opening {.
25336 var shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
25337 var printTrailingComma = args && args.expandLastArg && shouldPrintComma$1(options, "all"); // In order to avoid confusion between
25341 var shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body,
25342 /* forbidFunctionAndClass */
25344 return group$b(concat$d([concat$d(parts), group$b(concat$d([indent$7(concat$d([line$7, shouldAddParens ? ifBreak$6("", "(") : "", body, shouldAddParens ? ifBreak$6("", ")") : ""])), shouldAddSoftLine ? concat$d([ifBreak$6(printTrailingComma ? "," : ""), softline$6]) : ""]))]));
25347 case "YieldExpression":
25348 parts.push("yield");
25355 parts.push(" ", path.call(print, "argument"));
25358 return concat$d(parts);
25360 case "AwaitExpression":
25362 parts.push("await ", path.call(print, "argument"));
25364 var _parent3 = path.getParentNode();
25366 if ((_parent3.type === "CallExpression" || _parent3.type === "OptionalCallExpression") && _parent3.callee === n || (_parent3.type === "MemberExpression" || _parent3.type === "OptionalMemberExpression") && _parent3.object === n) {
25367 return group$b(concat$d([indent$7(concat$d([softline$6, concat$d(parts)])), softline$6]));
25370 return concat$d(parts);
25373 case "ImportSpecifier":
25374 if (n.importKind) {
25375 parts.push(path.call(print, "importKind"), " ");
25378 parts.push(path.call(print, "imported"));
25380 if (n.local && n.local.name !== n.imported.name) {
25381 parts.push(" as ", path.call(print, "local"));
25384 return concat$d(parts);
25386 case "ExportSpecifier":
25387 parts.push(path.call(print, "local"));
25389 if (n.exported && n.exported.name !== n.local.name) {
25390 parts.push(" as ", path.call(print, "exported"));
25393 return concat$d(parts);
25395 case "ImportNamespaceSpecifier":
25396 parts.push("* as ");
25397 parts.push(path.call(print, "local"));
25398 return concat$d(parts);
25400 case "ImportDefaultSpecifier":
25401 return path.call(print, "local");
25403 case "TSExportAssignment":
25404 return concat$d(["export = ", path.call(print, "expression"), semi]);
25406 case "ExportDefaultDeclaration":
25407 case "ExportNamedDeclaration":
25408 return printExportDeclaration(path, options, print);
25410 case "ExportAllDeclaration":
25411 parts.push("export ");
25413 if (n.exportKind === "type") {
25414 parts.push("type ");
25417 parts.push("* from ", path.call(print, "source"), semi);
25418 return concat$d(parts);
25420 case "ExportNamespaceSpecifier":
25421 case "ExportDefaultSpecifier":
25422 return path.call(print, "exported");
25424 case "ImportDeclaration":
25426 parts.push("import ");
25428 if (n.importKind && n.importKind !== "value") {
25429 parts.push(n.importKind + " ");
25432 var standalones = [];
25435 if (n.specifiers && n.specifiers.length > 0) {
25436 path.each(function (specifierPath) {
25437 var value = specifierPath.getValue();
25439 if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") {
25440 standalones.push(print(specifierPath));
25442 grouped.push(print(specifierPath));
25446 if (standalones.length > 0) {
25447 parts.push(join$9(", ", standalones));
25450 if (standalones.length > 0 && grouped.length > 0) {
25454 if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(function (node) {
25455 return node.comments;
25457 parts.push(concat$d(["{", options.bracketSpacing ? " " : "", concat$d(grouped), options.bracketSpacing ? " " : "", "}"]));
25458 } else if (grouped.length >= 1) {
25459 parts.push(group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$7 : softline$6, join$9(concat$d([",", line$7]), grouped)])), ifBreak$6(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$7 : softline$6, "}"])));
25462 parts.push(" from ");
25463 } else if (n.importKind && n.importKind === "type" || // import {} from 'x'
25464 /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) {
25465 parts.push("{} from ");
25468 parts.push(path.call(print, "source"), semi);
25469 return concat$d(parts);
25475 case "TSModuleBlock":
25476 case "BlockStatement":
25478 var naked = path.call(function (bodyPath) {
25479 return printStatementSequence(bodyPath, options, print);
25481 var hasContent = n.body.find(function (node) {
25482 return node.type !== "EmptyStatement";
25484 var hasDirectives = n.directives && n.directives.length > 0;
25486 var _parent4 = path.getParentNode();
25488 var _parentParent = path.getParentNode(1);
25490 if (!hasContent && !hasDirectives && !hasDanglingComments$1(n) && (_parent4.type === "ArrowFunctionExpression" || _parent4.type === "FunctionExpression" || _parent4.type === "FunctionDeclaration" || _parent4.type === "ObjectMethod" || _parent4.type === "ClassMethod" || _parent4.type === "ClassPrivateMethod" || _parent4.type === "ForStatement" || _parent4.type === "WhileStatement" || _parent4.type === "DoWhileStatement" || _parent4.type === "DoExpression" || _parent4.type === "CatchClause" && !_parentParent.finalizer || _parent4.type === "TSModuleDeclaration")) {
25494 parts.push("{"); // Babel 6
25496 if (hasDirectives) {
25497 path.each(function (childPath) {
25498 parts.push(indent$7(concat$d([hardline$9, print(childPath), semi])));
25500 if (isNextLineEmpty$4(options.originalText, childPath.getValue(), options)) {
25501 parts.push(hardline$9);
25507 parts.push(indent$7(concat$d([hardline$9, naked])));
25510 parts.push(comments.printDanglingComments(path, options));
25511 parts.push(hardline$9, "}");
25512 return concat$d(parts);
25515 case "ReturnStatement":
25516 parts.push("return");
25519 if (returnArgumentHasLeadingComment$1(options, n.argument)) {
25520 parts.push(concat$d([" (", indent$7(concat$d([hardline$9, path.call(print, "argument")])), hardline$9, ")"]));
25521 } else if (n.argument.type === "LogicalExpression" || n.argument.type === "BinaryExpression" || n.argument.type === "SequenceExpression") {
25522 parts.push(group$b(concat$d([ifBreak$6(" (", " "), indent$7(concat$d([softline$6, path.call(print, "argument")])), softline$6, ifBreak$6(")")])));
25524 parts.push(" ", path.call(print, "argument"));
25528 if (hasDanglingComments$1(n)) {
25529 parts.push(" ", comments.printDanglingComments(path, options,
25535 return concat$d(parts);
25537 case "NewExpression":
25538 case "OptionalCallExpression":
25539 case "CallExpression":
25541 var isNew = n.type === "NewExpression";
25542 var optional = printOptionalToken(path);
25544 if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
25545 // define calls, as a unit.
25546 // e.g. `define(["some/lib", (lib) => {`
25547 !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
25548 n.arguments.length === 1 && isTemplateOnItsOwnLine$1(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line
25549 // e.g. `it('long name', () => {`
25550 !isNew && isTestCall$1(n, path.getParentNode())) {
25551 return concat$d([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), concat$d(["(", join$9(", ", path.map(print, "arguments")), ")"])]);
25552 } // Inline Flow annotation comments following Identifiers in Call nodes need to
25553 // stay with the Identifier. For example:
25555 // foo /*:: <SomeGeneric> */(bar);
25557 // Here, we ensure that such comments stay between the Identifier and the Callee.
25560 var isIdentifierWithFlowAnnotation = n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments);
25562 if (isIdentifierWithFlowAnnotation) {
25563 n.callee.trailingComments[0].printed = true;
25564 } // We detect calls on member lookups and possibly print them in a
25565 // special chain format. See `printMemberChain` for more info.
25568 if (!isNew && isMemberish$1(n.callee)) {
25569 return printMemberChain(path, options, print);
25572 var contents = concat$d([isNew ? "new " : "", path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? "/*:: ".concat(n.callee.trailingComments[0].value.substring(2).trim(), " */") : "", printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]); // We group here when the callee is itself a call expression.
25573 // See `isLongCurriedCallExpression` for more info.
25575 if (isCallOrOptionalCallExpression$1(n.callee)) {
25576 return group$b(contents);
25582 case "TSInterfaceDeclaration":
25584 parts.push("declare ");
25587 parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print), "interface ", path.call(print, "id"), n.typeParameters ? path.call(print, "typeParameters") : "", " ");
25589 if (n.extends && n.extends.length) {
25590 parts.push(group$b(indent$7(concat$d([softline$6, "extends ", (n.extends.length === 1 ? identity$2 : indent$7)(join$9(concat$d([",", line$7]), path.map(print, "extends"))), " "]))));
25593 parts.push(path.call(print, "body"));
25594 return concat$d(parts);
25596 case "ObjectTypeInternalSlot":
25597 return concat$d([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken(path), n.method ? "" : ": ", path.call(print, "value")]);
25599 case "ObjectExpression":
25600 case "ObjectPattern":
25601 case "ObjectTypeAnnotation":
25602 case "TSInterfaceBody":
25603 case "TSTypeLiteral":
25605 var propertiesField;
25607 if (n.type === "TSTypeLiteral") {
25608 propertiesField = "members";
25609 } else if (n.type === "TSInterfaceBody") {
25610 propertiesField = "body";
25612 propertiesField = "properties";
25615 var isTypeAnnotation = n.type === "ObjectTypeAnnotation";
25618 if (isTypeAnnotation) {
25619 fields.push("indexers", "callProperties", "internalSlots");
25622 fields.push(propertiesField);
25623 var firstProperty = fields.map(function (field) {
25624 return n[field][0];
25625 }).sort(function (a, b) {
25626 return options.locStart(a) - options.locStart(b);
25629 var _parent5 = path.getParentNode(0);
25631 var isFlowInterfaceLikeBody = isTypeAnnotation && _parent5 && (_parent5.type === "InterfaceDeclaration" || _parent5.type === "DeclareInterface" || _parent5.type === "DeclareClass") && path.getName() === "body";
25632 var shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && _parent5.type !== "FunctionDeclaration" && _parent5.type !== "FunctionExpression" && _parent5.type !== "ArrowFunctionExpression" && _parent5.type !== "ObjectMethod" && _parent5.type !== "ClassMethod" && _parent5.type !== "ClassPrivateMethod" && _parent5.type !== "AssignmentPattern" && _parent5.type !== "CatchClause" && n.properties.some(function (property) {
25633 return property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern");
25634 }) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$2(options.originalText, options.locStart(n), options.locStart(firstProperty));
25635 var separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$6(semi, ";") : ",";
25636 var leftBrace = n.exact ? "{|" : "{";
25637 var rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
25638 // interleaved in the source code. So we need to reorder them before
25641 var propsAndLoc = [];
25642 fields.forEach(function (field) {
25643 path.each(function (childPath) {
25644 var node = childPath.getValue();
25647 printed: print(childPath),
25648 loc: options.locStart(node)
25652 var separatorParts = [];
25653 var props = propsAndLoc.sort(function (a, b) {
25654 return a.loc - b.loc;
25655 }).map(function (prop) {
25656 var result = concat$d(separatorParts.concat(group$b(prop.printed)));
25657 separatorParts = [separator, line$7];
25659 if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) {
25660 separatorParts.shift();
25663 if (isNextLineEmpty$4(options.originalText, prop.node, options)) {
25664 separatorParts.push(hardline$9);
25671 props.push(concat$d(separatorParts.concat(group$b("..."))));
25674 var lastElem = getLast$2(n[propertiesField]);
25675 var canHaveTrailingSeparator = !(lastElem && (lastElem.type === "RestProperty" || lastElem.type === "RestElement" || hasNodeIgnoreComment$2(lastElem) || n.inexact));
25678 if (props.length === 0) {
25679 if (!hasDanglingComments$1(n)) {
25680 return concat$d([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]);
25683 content = group$b(concat$d([leftBrace, comments.printDanglingComments(path, options), softline$6, rightBrace, printOptionalToken(path), printTypeAnnotation(path, options, print)]));
25685 content = concat$d([leftBrace, indent$7(concat$d([options.bracketSpacing ? line$7 : softline$6, concat$d(props)])), ifBreak$6(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$1(options)) ? separator : ""), concat$d([options.bracketSpacing ? line$7 : softline$6, rightBrace]), printOptionalToken(path), printTypeAnnotation(path, options, print)]);
25686 } // If we inline the object as first argument of the parent, we don't want
25687 // to create another group so that the object breaks before the return
25691 var parentParentParent = path.getParentNode(2);
25693 if (n.type === "ObjectPattern" && _parent5 && shouldHugArguments(_parent5) && !n.decorators && _parent5.params[0] === n || shouldHugType(n) && parentParentParent && shouldHugArguments(parentParentParent) && parentParentParent.params[0].typeAnnotation && parentParentParent.params[0].typeAnnotation.typeAnnotation === n) {
25697 return group$b(content, {
25698 shouldBreak: shouldBreak
25703 case "ObjectProperty": // Non-standard AST node type.
25706 if (n.method || n.kind === "get" || n.kind === "set") {
25707 return printMethod(path, options, print);
25711 parts.push(path.call(print, "value"));
25713 parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options));
25716 return concat$d(parts);
25719 case "ClassMethod":
25720 case "ClassPrivateMethod":
25721 case "MethodDefinition":
25722 case "TSAbstractMethodDefinition":
25723 if (n.decorators && n.decorators.length !== 0) {
25724 parts.push(printDecorators(path, options, print));
25727 if (n.accessibility) {
25728 parts.push(n.accessibility + " ");
25732 parts.push("static ");
25735 if (n.type === "TSAbstractMethodDefinition") {
25736 parts.push("abstract ");
25739 parts.push(printMethod(path, options, print));
25740 return concat$d(parts);
25742 case "ObjectMethod":
25743 return printMethod(path, options, print);
25746 return concat$d(["@", path.call(print, "expression"), path.call(print, "callee")]);
25748 case "ArrayExpression":
25749 case "ArrayPattern":
25750 if (n.elements.length === 0) {
25751 if (!hasDanglingComments$1(n)) {
25754 parts.push(group$b(concat$d(["[", comments.printDanglingComments(path, options), softline$6, "]"])));
25757 var _lastElem = getLast$2(n.elements);
25759 var canHaveTrailingComma = !(_lastElem && _lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
25760 // changes its length based on the number of commas. The algorithm
25761 // is that if the last argument is null, we need to force insert
25762 // a comma to ensure JavaScript recognizes it.
25763 // [,].length === 1
25764 // [1,].length === 1
25765 // [1,,].length === 2
25767 // Note that getLast returns null if the array is empty, but
25768 // we already check for an empty array just above so we are safe
25770 var needsForcedTrailingComma = canHaveTrailingComma && _lastElem === null;
25772 var _shouldBreak = n.elements.length > 1 && n.elements.every(function (element, i, elements) {
25773 var elementType = element && element.type;
25775 if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
25779 var nextElement = elements[i + 1];
25781 if (nextElement && elementType !== nextElement.type) {
25785 var itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
25786 return element[itemsKey] && element[itemsKey].length > 1;
25789 parts.push(group$b(concat$d(["[", indent$7(concat$d([softline$6, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$6(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma$1(options) ? "," : ""), comments.printDanglingComments(path, options,
25791 true), softline$6, "]"]), {
25792 shouldBreak: _shouldBreak
25796 parts.push(printOptionalToken(path), printTypeAnnotation(path, options, print));
25797 return concat$d(parts);
25799 case "SequenceExpression":
25801 var _parent6 = path.getParentNode(0);
25803 if (_parent6.type === "ExpressionStatement" || _parent6.type === "ForStatement") {
25804 // For ExpressionStatements and for-loop heads, which are among
25805 // the few places a SequenceExpression appears unparenthesized, we want
25806 // to indent expressions after the first.
25808 path.each(function (p) {
25809 if (p.getName() === 0) {
25810 _parts2.push(print(p));
25812 _parts2.push(",", indent$7(concat$d([line$7, print(p)])));
25815 return group$b(concat$d(_parts2));
25818 return group$b(concat$d([join$9(concat$d([",", line$7]), path.map(print, "expressions"))]));
25821 case "ThisExpression":
25827 case "NullLiteral":
25828 // Babel 6 Literal split
25831 case "RegExpLiteral":
25832 // Babel 6 Literal split
25833 return printRegex(n);
25835 case "NumericLiteral":
25836 // Babel 6 Literal split
25837 return printNumber$2(n.extra.raw);
25839 case "BigIntLiteral":
25840 // babel: n.extra.raw, typescript: n.raw, flow: n.bigint
25841 return (n.bigint || (n.extra ? n.extra.raw : n.raw)).toLowerCase();
25843 case "BooleanLiteral": // Babel 6 Literal split
25845 case "StringLiteral": // Babel 6 Literal split
25850 return printRegex(n.regex);
25853 if (typeof n.value === "number") {
25854 return printNumber$2(n.raw);
25857 if (typeof n.value !== "string") {
25858 return "" + n.value;
25859 } // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
25860 // See corresponding workaround in needs-parens.js
25863 var grandParent = path.getParentNode(1);
25864 var isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement");
25865 return nodeStr(n, options, isTypeScriptDirective);
25869 return path.call(print, "value");
25872 case "DirectiveLiteral":
25873 return nodeStr(n, options);
25875 case "UnaryExpression":
25876 parts.push(n.operator);
25878 if (/[a-z]$/.test(n.operator)) {
25882 if (n.argument.comments && n.argument.comments.length > 0) {
25883 parts.push(group$b(concat$d(["(", indent$7(concat$d([softline$6, path.call(print, "argument")])), softline$6, ")"])));
25885 parts.push(path.call(print, "argument"));
25888 return concat$d(parts);
25890 case "UpdateExpression":
25891 parts.push(path.call(print, "argument"), n.operator);
25897 return concat$d(parts);
25899 case "ConditionalExpression":
25900 return printTernaryOperator(path, options, print, {
25901 beforeParts: function beforeParts() {
25902 return [path.call(print, "test")];
25904 afterParts: function afterParts(breakClosingParen) {
25905 return [breakClosingParen ? softline$6 : ""];
25907 shouldCheckJsx: true,
25908 conditionalNodeType: "ConditionalExpression",
25909 consequentNodePropertyName: "consequent",
25910 alternateNodePropertyName: "alternate",
25911 testNodePropertyName: "test",
25915 case "VariableDeclaration":
25917 var printed = path.map(function (childPath) {
25918 return print(childPath);
25919 }, "declarations"); // We generally want to terminate all variable declarations with a
25920 // semicolon, except when they in the () part of for loops.
25922 var parentNode = path.getParentNode();
25923 var isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement" || parentNode.type === "ForAwaitStatement";
25924 var hasValue = n.declarations.some(function (decl) {
25929 if (printed.length === 1 && !n.declarations[0].comments) {
25930 firstVariable = printed[0];
25931 } else if (printed.length > 0) {
25932 // Indent first var to comply with eslint one-var rule
25933 firstVariable = indent$7(printed[0]);
25936 parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$d([" ", firstVariable]) : "", indent$7(concat$d(printed.slice(1).map(function (p) {
25937 return concat$d([",", hasValue && !isParentForLoop ? hardline$9 : line$7, p]);
25940 if (!(isParentForLoop && parentNode.body !== n)) {
25944 return group$b(concat$d(parts));
25947 case "TSTypeAliasDeclaration":
25950 parts.push("declare ");
25953 var _printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
25955 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed, semi);
25956 return group$b(concat$d(parts));
25959 case "VariableDeclarator":
25960 return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
25962 case "WithStatement":
25963 return group$b(concat$d(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))]));
25965 case "IfStatement":
25967 var con = adjustClause(n.consequent, path.call(print, "consequent"));
25968 var opening = group$b(concat$d(["if (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", con]));
25969 parts.push(opening);
25972 var commentOnOwnLine = hasTrailingComment$1(n.consequent) && n.consequent.comments.some(function (comment) {
25973 return comment.trailing && !comments$1.isBlockComment(comment);
25974 }) || needsHardlineAfterDanglingComment$1(n);
25975 var elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
25976 parts.push(elseOnSameLine ? " " : hardline$9);
25978 if (hasDanglingComments$1(n)) {
25979 parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$9 : " ");
25982 parts.push("else", group$b(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
25985 return concat$d(parts);
25988 case "ForStatement":
25990 var _body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
25991 // Any comment positioned between the for statement and the parentheses
25992 // is going to be printed before the statement.
25995 var _dangling = comments.printDanglingComments(path, options,
25999 var printedComments = _dangling ? concat$d([_dangling, softline$6]) : "";
26001 if (!n.init && !n.test && !n.update) {
26002 return concat$d([printedComments, group$b(concat$d(["for (;;)", _body]))]);
26005 return concat$d([printedComments, group$b(concat$d(["for (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "init"), ";", line$7, path.call(print, "test"), ";", line$7, path.call(print, "update")])), softline$6])), ")", _body]))]);
26008 case "WhileStatement":
26009 return group$b(concat$d(["while (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", adjustClause(n.body, path.call(print, "body"))]));
26011 case "ForInStatement":
26012 // Note: esprima can't actually parse "for each (".
26013 return group$b(concat$d([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
26015 case "ForOfStatement":
26016 case "ForAwaitStatement":
26018 // Babel 7 removed ForAwaitStatement in favor of ForOfStatement
26019 // with `"await": true`:
26020 // https://github.com/estree/estree/pull/138
26021 var isAwait = n.type === "ForAwaitStatement" || n.await;
26022 return group$b(concat$d(["for", isAwait ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
26025 case "DoWhileStatement":
26027 var clause = adjustClause(n.body, path.call(print, "body"));
26028 var doBody = group$b(concat$d(["do", clause]));
26031 if (n.body.type === "BlockStatement") {
26034 parts.push(hardline$9);
26037 parts.push("while (");
26038 parts.push(group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", semi);
26039 return concat$d(parts);
26042 case "DoExpression":
26043 return concat$d(["do ", path.call(print, "body")]);
26045 case "BreakStatement":
26046 parts.push("break");
26049 parts.push(" ", path.call(print, "label"));
26053 return concat$d(parts);
26055 case "ContinueStatement":
26056 parts.push("continue");
26059 parts.push(" ", path.call(print, "label"));
26063 return concat$d(parts);
26065 case "LabeledStatement":
26066 if (n.body.type === "EmptyStatement") {
26067 return concat$d([path.call(print, "label"), ":;"]);
26070 return concat$d([path.call(print, "label"), ": ", path.call(print, "body")]);
26072 case "TryStatement":
26073 return concat$d(["try ", path.call(print, "block"), n.handler ? concat$d([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$d([" finally ", path.call(print, "finalizer")]) : ""]);
26075 case "CatchClause":
26077 var hasComments = n.param.comments && n.param.comments.some(function (comment) {
26078 return !comments$1.isBlockComment(comment) || comment.leading && hasNewline$4(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$4(options.originalText, options.locStart(comment), {
26082 var param = path.call(print, "param");
26083 return concat$d(["catch ", hasComments ? concat$d(["(", indent$7(concat$d([softline$6, param])), softline$6, ") "]) : concat$d(["(", param, ") "]), path.call(print, "body")]);
26086 return concat$d(["catch ", path.call(print, "body")]);
26088 case "ThrowStatement":
26089 return concat$d(["throw ", path.call(print, "argument"), semi]);
26090 // Note: ignoring n.lexical because it has no printing consequences.
26092 case "SwitchStatement":
26093 return concat$d([group$b(concat$d(["switch (", indent$7(concat$d([softline$6, path.call(print, "discriminant")])), softline$6, ")"])), " {", n.cases.length > 0 ? indent$7(concat$d([hardline$9, join$9(hardline$9, path.map(function (casePath) {
26094 var caseNode = casePath.getValue();
26095 return concat$d([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$4(options.originalText, caseNode, options) ? hardline$9 : ""]);
26096 }, "cases"))])) : "", hardline$9, "}"]);
26101 parts.push("case ", path.call(print, "test"), ":");
26103 parts.push("default:");
26106 var consequent = n.consequent.filter(function (node) {
26107 return node.type !== "EmptyStatement";
26110 if (consequent.length > 0) {
26111 var cons = path.call(function (consequentPath) {
26112 return printStatementSequence(consequentPath, options, print);
26114 parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$d([" ", cons]) : indent$7(concat$d([hardline$9, cons])));
26117 return concat$d(parts);
26119 // JSX extensions below.
26121 case "DebuggerStatement":
26122 return concat$d(["debugger", semi]);
26124 case "JSXAttribute":
26125 parts.push(path.call(print, "name"));
26130 if (isStringLiteral$1(n.value)) {
26131 var raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote
26133 var final = raw.replace(/'/g, "'").replace(/"/g, '"');
26134 var quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
26136 var _escape = quote === "'" ? "'" : """;
26138 final = final.slice(1, -1).replace(new RegExp(quote, "g"), _escape);
26139 res = concat$d([quote, final, quote]);
26141 res = path.call(print, "value");
26144 parts.push("=", res);
26147 return concat$d(parts);
26149 case "JSXIdentifier":
26150 return "" + n.name;
26152 case "JSXNamespacedName":
26153 return join$9(":", [path.call(print, "namespace"), path.call(print, "name")]);
26155 case "JSXMemberExpression":
26156 return join$9(".", [path.call(print, "object"), path.call(print, "property")]);
26158 case "TSQualifiedName":
26159 return join$9(".", [path.call(print, "left"), path.call(print, "right")]);
26161 case "JSXSpreadAttribute":
26162 case "JSXSpreadChild":
26164 return concat$d(["{", path.call(function (p) {
26165 var printed = concat$d(["...", print(p)]);
26166 var n = p.getValue();
26168 if (!n.comments || !n.comments.length) {
26172 return concat$d([indent$7(concat$d([softline$6, comments.printComments(p, function () {
26174 }, options)])), softline$6]);
26175 }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
26178 case "JSXExpressionContainer":
26180 var _parent7 = path.getParentNode(0);
26182 var preventInline = _parent7.type === "JSXAttribute" && n.expression.comments && n.expression.comments.length > 0;
26184 var _shouldInline = !preventInline && (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 === "JSXEmptyExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode$1(_parent7) && (n.expression.type === "ConditionalExpression" || isBinaryish$1(n.expression)));
26186 if (_shouldInline) {
26187 return group$b(concat$d(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"]));
26190 return group$b(concat$d(["{", indent$7(concat$d([softline$6, path.call(print, "expression")])), softline$6, lineSuffixBoundary$1, "}"]));
26193 case "JSXFragment":
26196 var elem = comments.printComments(path, function () {
26197 return printJSXElement(path, options, print);
26199 return maybeWrapJSXElementInParens(path, elem, options);
26202 case "JSXOpeningElement":
26204 var _n = path.getValue();
26206 var 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
26208 if (_n.selfClosing && !_n.attributes.length && !nameHasComments) {
26209 return concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]);
26210 } // don't break up opening elements with a single long text attribute
26213 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:
26222 !nameHasComments && (!_n.attributes[0].comments || !_n.attributes[0].comments.length)) {
26223 return group$b(concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$d(path.map(print, "attributes")), _n.selfClosing ? " />" : ">"]));
26226 var lastAttrHasTrailingComments = _n.attributes.length && hasTrailingComment$1(getLast$2(_n.attributes));
26227 var bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
26228 // kept unbroken regardless of `jsxBracketSameLine`
26229 !_n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
26236 !nameHasComments || _n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
26237 // string literal with newlines
26239 var _shouldBreak2 = _n.attributes && _n.attributes.some(function (attr) {
26240 return attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n");
26243 return group$b(concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$d([indent$7(concat$d(path.map(function (attr) {
26244 return concat$d([line$7, print(attr)]);
26245 }, "attributes"))), _n.selfClosing ? line$7 : bracketSameLine ? ">" : softline$6]), _n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
26246 shouldBreak: _shouldBreak2
26250 case "JSXClosingElement":
26251 return concat$d(["</", path.call(print, "name"), ">"]);
26253 case "JSXOpeningFragment":
26254 case "JSXClosingFragment":
26256 var hasComment = n.comments && n.comments.length;
26257 var hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
26258 var isOpeningFragment = n.type === "JSXOpeningFragment";
26259 return concat$d([isOpeningFragment ? "<" : "</", indent$7(concat$d([hasOwnLineComment ? hardline$9 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$9 : "", ">"]);
26263 /* istanbul ignore next */
26264 throw new Error("JSXTest should be handled by JSXElement");
26266 case "JSXEmptyExpression":
26268 var requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
26269 return concat$d([comments.printDanglingComments(path, options,
26271 !requiresHardline), requiresHardline ? hardline$9 : ""]);
26275 if (!n.comments && n.body.length === 0) {
26279 return concat$d(["{", n.body.length > 0 ? indent$7(concat$d([hardline$9, path.call(function (bodyPath) {
26280 return printStatementSequence(bodyPath, options, print);
26281 }, "body")])) : comments.printDanglingComments(path, options), hardline$9, "}"]);
26283 case "ClassProperty":
26284 case "TSAbstractClassProperty":
26285 case "ClassPrivateProperty":
26287 if (n.decorators && n.decorators.length !== 0) {
26288 parts.push(printDecorators(path, options, print));
26291 if (n.accessibility) {
26292 parts.push(n.accessibility + " ");
26296 parts.push("declare ");
26300 parts.push("static ");
26303 if (n.type === "TSAbstractClassProperty") {
26304 parts.push("abstract ");
26308 parts.push("readonly ");
26311 var variance = getFlowVariance$1(n);
26314 parts.push(variance);
26317 parts.push(printPropertyKey(path, options, print), printOptionalToken(path), printTypeAnnotation(path, options, print));
26320 parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
26324 return group$b(concat$d(parts));
26327 case "ClassDeclaration":
26328 case "ClassExpression":
26330 parts.push("declare ");
26333 parts.push(concat$d(printClass(path, options, print)));
26334 return concat$d(parts);
26336 case "TSInterfaceHeritage":
26337 parts.push(path.call(print, "expression"));
26339 if (n.typeParameters) {
26340 parts.push(path.call(print, "typeParameters"));
26343 return concat$d(parts);
26345 case "TemplateElement":
26346 return join$9(literalline$4, n.value.raw.split(/\r?\n/g));
26348 case "TemplateLiteral":
26350 var expressions = path.map(print, "expressions");
26352 var _parentNode = path.getParentNode();
26354 if (isJestEachTemplateLiteral$1(n, _parentNode)) {
26355 var _printed2 = printJestEachTemplateLiteral(n, expressions, options);
26362 var isSimple = isSimpleTemplateLiteral$1(n);
26365 expressions = expressions.map(function (doc) {
26366 return printDocToString$1(doc, Object.assign({}, options, {
26367 printWidth: Infinity
26372 parts.push(lineSuffixBoundary$1, "`");
26373 path.each(function (childPath) {
26374 var i = childPath.getName();
26375 parts.push(print(childPath));
26377 if (i < expressions.length) {
26378 // For a template literal of the following form:
26385 // the expression is on its own line (there is a \n in the previous
26386 // quasi literal), therefore we want to indent the JavaScript
26387 // expression inside at the beginning of ${ instead of the beginning
26389 var tabWidth = options.tabWidth;
26390 var quasi = childPath.getValue();
26391 var indentSize = getIndentSize$1(quasi.value.raw, tabWidth);
26392 var _printed3 = expressions[i];
26395 // Breaks at the template element boundaries (${ and }) are preferred to breaking
26396 // in the middle of a MemberExpression
26397 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") {
26398 _printed3 = concat$d([indent$7(concat$d([softline$6, _printed3])), softline$6]);
26402 var aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, _printed3) : addAlignmentToDoc$2(_printed3, indentSize, tabWidth);
26403 parts.push(group$b(concat$d(["${", aligned, lineSuffixBoundary$1, "}"])));
26407 return concat$d(parts);
26409 // These types are unprintable because they serve as abstract
26410 // supertypes for other (printable) types.
26412 case "TaggedTemplateExpression":
26413 return concat$d([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
26417 case "SourceLocation":
26423 case "Declaration":
26425 case "NamedSpecifier":
26427 case "MemberTypeAnnotation": // Flow
26430 /* istanbul ignore next */
26431 throw new Error("unprintable type: " + JSON.stringify(n.type));
26432 // Type Annotations for Facebook Flow, typically stripped out or
26433 // transformed away before printing.
26435 case "TypeAnnotation":
26436 case "TSTypeAnnotation":
26437 if (n.typeAnnotation) {
26438 return path.call(print, "typeAnnotation");
26440 /* istanbul ignore next */
26445 case "TSTupleType":
26446 case "TupleTypeAnnotation":
26448 var typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
26449 return group$b(concat$d(["[", indent$7(concat$d([softline$6, printArrayItems(path, options, typesField, print)])), ifBreak$6(shouldPrintComma$1(options, "all") ? "," : ""), comments.printDanglingComments(path, options,
26451 true), softline$6, "]"]));
26454 case "ExistsTypeAnnotation":
26457 case "EmptyTypeAnnotation":
26460 case "AnyTypeAnnotation":
26463 case "MixedTypeAnnotation":
26466 case "ArrayTypeAnnotation":
26467 return concat$d([path.call(print, "elementType"), "[]"]);
26469 case "BooleanTypeAnnotation":
26472 case "BooleanLiteralTypeAnnotation":
26473 return "" + n.value;
26475 case "DeclareClass":
26476 return printFlowDeclaration(path, printClass(path, options, print));
26478 case "TSDeclareFunction":
26479 // For TypeScript the TSDeclareFunction node shares the AST
26480 // structure with FunctionDeclaration
26481 return concat$d([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
26483 case "DeclareFunction":
26484 return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
26486 case "DeclareModule":
26487 return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
26489 case "DeclareModuleExports":
26490 return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
26492 case "DeclareVariable":
26493 return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
26495 case "DeclareExportAllDeclaration":
26496 return concat$d(["declare export * from ", path.call(print, "source")]);
26498 case "DeclareExportDeclaration":
26499 return concat$d(["declare ", printExportDeclaration(path, options, print)]);
26501 case "DeclareOpaqueType":
26504 parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
26507 parts.push(": ", path.call(print, "supertype"));
26511 parts.push(" = ", path.call(print, "impltype"));
26516 if (n.type === "DeclareOpaqueType") {
26517 return printFlowDeclaration(path, parts);
26520 return concat$d(parts);
26523 case "EnumDeclaration":
26524 return concat$d(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
26526 case "EnumBooleanBody":
26527 case "EnumNumberBody":
26528 case "EnumStringBody":
26529 case "EnumSymbolBody":
26531 if (n.type === "EnumSymbolBody" || n.explicitType) {
26535 case "EnumBooleanBody":
26539 case "EnumNumberBody":
26543 case "EnumStringBody":
26547 case "EnumSymbolBody":
26552 parts.push("of ", type, " ");
26555 if (n.members.length === 0) {
26556 parts.push(group$b(concat$d(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
26558 parts.push(group$b(concat$d(["{", indent$7(concat$d([hardline$9, printArrayItems(path, options, "members", print), shouldPrintComma$1(options) ? "," : ""])), comments.printDanglingComments(path, options,
26560 true), hardline$9, "}"])));
26563 return concat$d(parts);
26566 case "EnumBooleanMember":
26567 case "EnumNumberMember":
26568 case "EnumStringMember":
26569 return concat$d([path.call(print, "id"), " = ", _typeof(n.init) === "object" ? path.call(print, "init") : String(n.init)]);
26571 case "EnumDefaultedMember":
26572 return path.call(print, "id");
26574 case "FunctionTypeAnnotation":
26575 case "TSFunctionType":
26577 // FunctionTypeAnnotation is ambiguous:
26578 // declare function foo(a: B): void; OR
26579 // var A: (a: B) => void;
26580 var _parent8 = path.getParentNode(0);
26582 var _parentParent2 = path.getParentNode(1);
26584 var _parentParentParent = path.getParentNode(2);
26586 var isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((_parent8.type === "ObjectTypeProperty" || _parent8.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(_parent8) && !_parent8.optional && options.locStart(_parent8) === options.locStart(n) || _parent8.type === "ObjectTypeCallProperty" || _parentParentParent && _parentParentParent.type === "DeclareFunction");
26587 var needsColon = isArrowFunctionTypeAnnotation && (_parent8.type === "TypeAnnotation" || _parent8.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
26588 // printing ":" as part of the expression and it would put parenthesis
26591 var needsParens = needsColon && isArrowFunctionTypeAnnotation && (_parent8.type === "TypeAnnotation" || _parent8.type === "TSTypeAnnotation") && _parentParent2.type === "ArrowFunctionExpression";
26593 if (isObjectTypePropertyAFunction$1(_parent8, options)) {
26594 isArrowFunctionTypeAnnotation = true;
26602 parts.push(printFunctionParams(path, print, options,
26605 /* printTypeParams */
26606 true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
26607 // needs to be added separately.
26609 if (n.returnType || n.predicate || n.typeAnnotation) {
26610 parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
26617 return group$b(concat$d(parts));
26621 return concat$d(["...", path.call(print, "typeAnnotation")]);
26623 case "TSOptionalType":
26624 return concat$d([path.call(print, "typeAnnotation"), "?"]);
26626 case "FunctionTypeParam":
26627 return concat$d([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
26629 case "GenericTypeAnnotation":
26630 return concat$d([path.call(print, "id"), path.call(print, "typeParameters")]);
26632 case "DeclareInterface":
26633 case "InterfaceDeclaration":
26634 case "InterfaceTypeAnnotation":
26636 if (n.type === "DeclareInterface" || n.declare) {
26637 parts.push("declare ");
26640 parts.push("interface");
26642 if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
26643 parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
26646 if (n["extends"].length > 0) {
26647 parts.push(group$b(indent$7(concat$d([line$7, "extends ", (n.extends.length === 1 ? identity$2 : indent$7)(join$9(concat$d([",", line$7]), path.map(print, "extends")))]))));
26650 parts.push(" ", path.call(print, "body"));
26651 return group$b(concat$d(parts));
26654 case "ClassImplements":
26655 case "InterfaceExtends":
26656 return concat$d([path.call(print, "id"), path.call(print, "typeParameters")]);
26658 case "TSClassImplements":
26659 return concat$d([path.call(print, "expression"), path.call(print, "typeParameters")]);
26661 case "TSIntersectionType":
26662 case "IntersectionTypeAnnotation":
26664 var types = path.map(print, "types");
26666 var wasIndented = false;
26668 for (var _i = 0; _i < types.length; ++_i) {
26670 result.push(types[_i]);
26671 } else if (isObjectType$1(n.types[_i - 1]) && isObjectType$1(n.types[_i])) {
26672 // If both are objects, don't indent
26673 result.push(concat$d([" & ", wasIndented ? indent$7(types[_i]) : types[_i]]));
26674 } else if (!isObjectType$1(n.types[_i - 1]) && !isObjectType$1(n.types[_i])) {
26675 // If no object is involved, go to the next line if it breaks
26676 result.push(indent$7(concat$d([" &", line$7, types[_i]])));
26678 // If you go from object to non-object or vis-versa, then inline it
26680 wasIndented = true;
26683 result.push(" & ", _i > 1 ? indent$7(types[_i]) : types[_i]);
26687 return group$b(concat$d(result));
26690 case "TSUnionType":
26691 case "UnionTypeAnnotation":
26693 // single-line variation
26695 // multi-line variation
26699 var _parent9 = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
26702 var shouldIndent = _parent9.type !== "TypeParameterInstantiation" && _parent9.type !== "TSTypeParameterInstantiation" && _parent9.type !== "GenericTypeAnnotation" && _parent9.type !== "TSTypeReference" && _parent9.type !== "TSTypeAssertion" && _parent9.type !== "TupleTypeAnnotation" && _parent9.type !== "TSTupleType" && !(_parent9.type === "FunctionTypeParam" && !_parent9.name) && !((_parent9.type === "TypeAlias" || _parent9.type === "VariableDeclarator" || _parent9.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // {
26705 // should be inlined and not be printed in the multi-line variant
26707 var shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
26712 var _printed4 = path.map(function (typePath) {
26713 var printedType = typePath.call(print);
26716 printedType = align$1(2, printedType);
26719 return comments.printComments(typePath, function () {
26720 return printedType;
26725 return join$9(" | ", _printed4);
26728 var shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
26729 var code = concat$d([ifBreak$6(concat$d([shouldAddStartLine ? line$7 : "", "| "])), join$9(concat$d([line$7, "| "]), _printed4)]);
26731 if (needsParens_1(path, options)) {
26732 return group$b(concat$d([indent$7(code), softline$6]));
26735 if (_parent9.type === "TupleTypeAnnotation" && _parent9.types.length > 1 || _parent9.type === "TSTupleType" && _parent9.elementTypes.length > 1) {
26736 return group$b(concat$d([indent$7(concat$d([ifBreak$6(concat$d(["(", softline$6])), code])), softline$6, ifBreak$6(")")]));
26739 return group$b(shouldIndent ? indent$7(code) : code);
26742 case "NullableTypeAnnotation":
26743 return concat$d(["?", path.call(print, "typeAnnotation")]);
26745 case "TSNullKeyword":
26746 case "NullLiteralTypeAnnotation":
26749 case "ThisTypeAnnotation":
26752 case "NumberTypeAnnotation":
26755 case "ObjectTypeCallProperty":
26757 parts.push("static ");
26760 parts.push(path.call(print, "value"));
26761 return concat$d(parts);
26763 case "ObjectTypeIndexer":
26765 var _variance = getFlowVariance$1(n);
26767 return concat$d([_variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
26770 case "ObjectTypeProperty":
26772 var _variance2 = getFlowVariance$1(n);
26777 modifier = "proto ";
26778 } else if (n.static) {
26779 modifier = "static ";
26782 return concat$d([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", _variance2 || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
26785 case "QualifiedTypeIdentifier":
26786 return concat$d([path.call(print, "qualification"), ".", path.call(print, "id")]);
26788 case "StringLiteralTypeAnnotation":
26789 return nodeStr(n, options);
26791 case "NumberLiteralTypeAnnotation":
26792 assert.strictEqual(_typeof(n.value), "number");
26794 if (n.extra != null) {
26795 return printNumber$2(n.extra.raw);
26798 return printNumber$2(n.raw);
26800 case "StringTypeAnnotation":
26803 case "DeclareTypeAlias":
26806 if (n.type === "DeclareTypeAlias" || n.declare) {
26807 parts.push("declare ");
26810 var _printed5 = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
26812 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed5, semi);
26813 return group$b(concat$d(parts));
26816 case "TypeCastExpression":
26818 var value = path.getValue(); // Flow supports a comment syntax for specifying type annotations: https://flow.org/en/docs/types/comments/.
26819 // Unfortunately, its parser doesn't differentiate between comment annotations and regular
26820 // annotations when producing an AST. So to preserve parentheses around type casts that use
26821 // the comment syntax, we need to hackily read the source itself to see if the code contains
26822 // a type annotation comment.
26824 // Note that we're able to use the normal whitespace regex here because the Flow parser has
26825 // already deemed this AST node to be a type cast. Only the Babel parser needs the
26826 // non-line-break whitespace regex, which is why hasFlowShorthandAnnotationComment() is
26827 // implemented differently.
26829 var commentSyntax = value && value.typeAnnotation && value.typeAnnotation.range && options.originalText.substring(value.typeAnnotation.range[0]).match(/^\/\*\s*:/);
26830 return concat$d(["(", path.call(print, "expression"), commentSyntax ? " /*" : "", ": ", path.call(print, "typeAnnotation"), commentSyntax ? " */" : "", ")"]);
26833 case "TypeParameterDeclaration":
26834 case "TypeParameterInstantiation":
26836 var _value = path.getValue();
26838 var commentStart = _value.range ? options.originalText.substring(0, _value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
26839 // because we know for sure that this is a type definition.
26841 var _commentSyntax = commentStart >= 0 && options.originalText.substring(commentStart).match(/^\/\*\s*::/);
26843 if (_commentSyntax) {
26844 return concat$d(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
26847 return printTypeParameters(path, options, print, "params");
26850 case "TSTypeParameterDeclaration":
26851 case "TSTypeParameterInstantiation":
26852 return printTypeParameters(path, options, print, "params");
26854 case "TSTypeParameter":
26855 case "TypeParameter":
26857 var _parent10 = path.getParentNode();
26859 if (_parent10.type === "TSMappedType") {
26860 parts.push("[", path.call(print, "name"));
26862 if (n.constraint) {
26863 parts.push(" in ", path.call(print, "constraint"));
26867 return concat$d(parts);
26870 var _variance3 = getFlowVariance$1(n);
26873 parts.push(_variance3);
26876 parts.push(path.call(print, "name"));
26880 parts.push(path.call(print, "bound"));
26883 if (n.constraint) {
26884 parts.push(" extends ", path.call(print, "constraint"));
26887 if (n["default"]) {
26888 parts.push(" = ", path.call(print, "default"));
26889 } // Keep comma if the file extension is .tsx and
26890 // has one type parameter that isn't extend with any types.
26891 // Because, otherwise formatted result will be invalid as tsx.
26894 var _grandParent = path.getNode(2);
26896 if (_parent10.params && _parent10.params.length === 1 && isTSXFile$1(options) && !n.constraint && _grandParent.type === "ArrowFunctionExpression") {
26900 return concat$d(parts);
26903 case "TypeofTypeAnnotation":
26904 return concat$d(["typeof ", path.call(print, "argument")]);
26906 case "VoidTypeAnnotation":
26909 case "InferredPredicate":
26911 // Unhandled types below. If encountered, nodes of these types should
26912 // be either left alone or desugared into AST types that are fully
26913 // supported by the pretty-printer.
26915 case "DeclaredPredicate":
26916 return concat$d(["%checks(", path.call(print, "value"), ")"]);
26918 case "TSAbstractKeyword":
26921 case "TSAnyKeyword":
26924 case "TSAsyncKeyword":
26927 case "TSBooleanKeyword":
26930 case "TSBigIntKeyword":
26933 case "TSConstKeyword":
26936 case "TSDeclareKeyword":
26939 case "TSExportKeyword":
26942 case "TSNeverKeyword":
26945 case "TSNumberKeyword":
26948 case "TSObjectKeyword":
26951 case "TSProtectedKeyword":
26952 return "protected";
26954 case "TSPrivateKeyword":
26957 case "TSPublicKeyword":
26960 case "TSReadonlyKeyword":
26963 case "TSSymbolKeyword":
26966 case "TSStaticKeyword":
26969 case "TSStringKeyword":
26972 case "TSUndefinedKeyword":
26973 return "undefined";
26975 case "TSUnknownKeyword":
26978 case "TSVoidKeyword":
26981 case "TSAsExpression":
26982 return concat$d([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
26984 case "TSArrayType":
26985 return concat$d([path.call(print, "elementType"), "[]"]);
26987 case "TSPropertySignature":
26990 parts.push("export ");
26993 if (n.accessibility) {
26994 parts.push(n.accessibility + " ");
26998 parts.push("static ");
27002 parts.push("readonly ");
27005 parts.push(printPropertyKey(path, options, print), printOptionalToken(path));
27007 if (n.typeAnnotation) {
27009 parts.push(path.call(print, "typeAnnotation"));
27010 } // This isn't valid semantically, but it's in the AST so we can print it.
27013 if (n.initializer) {
27014 parts.push(" = ", path.call(print, "initializer"));
27017 return concat$d(parts);
27020 case "TSParameterProperty":
27021 if (n.accessibility) {
27022 parts.push(n.accessibility + " ");
27026 parts.push("export ");
27030 parts.push("static ");
27034 parts.push("readonly ");
27037 parts.push(path.call(print, "parameter"));
27038 return concat$d(parts);
27040 case "TSTypeReference":
27041 return concat$d([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
27043 case "TSTypeQuery":
27044 return concat$d(["typeof ", path.call(print, "exprName")]);
27046 case "TSIndexSignature":
27048 var _parent11 = path.getParentNode();
27050 return concat$d([n.export ? "export " : "", n.accessibility ? concat$d([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? concat$d(path.map(print, "parameters")) : "", "]: ", path.call(print, "typeAnnotation"), _parent11.type === "ClassBody" ? semi : ""]);
27053 case "TSTypePredicate":
27054 return concat$d([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$d([" is ", path.call(print, "typeAnnotation")]) : ""]);
27056 case "TSNonNullExpression":
27057 return concat$d([path.call(print, "expression"), "!"]);
27062 case "TSImportType":
27063 return concat$d([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, "parameter"), ")", !n.qualifier ? "" : concat$d([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
27065 case "TSLiteralType":
27066 return path.call(print, "literal");
27068 case "TSIndexedAccessType":
27069 return concat$d([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
27071 case "TSConstructSignatureDeclaration":
27072 case "TSCallSignatureDeclaration":
27073 case "TSConstructorType":
27075 if (n.type !== "TSCallSignatureDeclaration") {
27076 parts.push("new ");
27079 parts.push(group$b(printFunctionParams(path, print, options,
27082 /* printTypeParams */
27085 if (n.returnType) {
27086 var isType = n.type === "TSConstructorType";
27087 parts.push(isType ? " => " : ": ", path.call(print, "returnType"));
27090 return concat$d(parts);
27093 case "TSTypeOperator":
27094 return concat$d([n.operator, " ", path.call(print, "typeAnnotation")]);
27096 case "TSMappedType":
27098 var _shouldBreak3 = hasNewlineInRange$2(options.originalText, options.locStart(n), options.locEnd(n));
27100 return group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$7 : softline$6, n.readonly ? concat$d([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", ": ", path.call(print, "typeAnnotation"), ifBreak$6(semi, "")])), comments.printDanglingComments(path, options,
27102 true), options.bracketSpacing ? line$7 : softline$6, "}"]), {
27103 shouldBreak: _shouldBreak3
27107 case "TSMethodSignature":
27108 parts.push(n.accessibility ? concat$d([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,
27111 /* printTypeParams */
27114 if (n.returnType) {
27115 parts.push(": ", path.call(print, "returnType"));
27118 return group$b(concat$d(parts));
27120 case "TSNamespaceExportDeclaration":
27121 parts.push("export as namespace ", path.call(print, "id"));
27123 if (options.semi) {
27127 return group$b(concat$d(parts));
27129 case "TSEnumDeclaration":
27131 parts.push("declare ");
27135 parts.push(printTypeScriptModifiers(path, options, print));
27139 parts.push("const ");
27142 parts.push("enum ", path.call(print, "id"), " ");
27144 if (n.members.length === 0) {
27145 parts.push(group$b(concat$d(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
27147 parts.push(group$b(concat$d(["{", indent$7(concat$d([hardline$9, printArrayItems(path, options, "members", print), shouldPrintComma$1(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
27149 true), hardline$9, "}"])));
27152 return concat$d(parts);
27154 case "TSEnumMember":
27155 parts.push(path.call(print, "id"));
27157 if (n.initializer) {
27158 parts.push(" = ", path.call(print, "initializer"));
27161 return concat$d(parts);
27163 case "TSImportEqualsDeclaration":
27165 parts.push("export ");
27168 parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
27170 if (options.semi) {
27174 return group$b(concat$d(parts));
27176 case "TSExternalModuleReference":
27177 return concat$d(["require(", path.call(print, "expression"), ")"]);
27179 case "TSModuleDeclaration":
27181 var _parent12 = path.getParentNode();
27183 var isExternalModule = isLiteral$1(n.id);
27184 var parentIsDeclaration = _parent12.type === "TSModuleDeclaration";
27185 var bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
27187 if (parentIsDeclaration) {
27191 parts.push("declare ");
27194 parts.push(printTypeScriptModifiers(path, options, print));
27195 var textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
27196 // (declare)? global { ... }
27198 var isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
27200 if (!isGlobalDeclaration) {
27201 parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
27205 parts.push(path.call(print, "id"));
27207 if (bodyIsDeclaration) {
27208 parts.push(path.call(print, "body"));
27209 } else if (n.body) {
27210 parts.push(" ", group$b(path.call(print, "body")));
27215 return concat$d(parts);
27218 case "PrivateName":
27219 return concat$d(["#", path.call(print, "id")]);
27221 case "TSConditionalType":
27222 return printTernaryOperator(path, options, print, {
27223 beforeParts: function beforeParts() {
27224 return [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")];
27226 afterParts: function afterParts() {
27229 shouldCheckJsx: false,
27230 conditionalNodeType: "TSConditionalType",
27231 consequentNodePropertyName: "trueType",
27232 alternateNodePropertyName: "falseType",
27233 testNodePropertyName: "checkType",
27237 case "TSInferType":
27238 return concat$d(["infer", " ", path.call(print, "typeParameter")]);
27240 case "InterpreterDirective":
27241 parts.push("#!", n.value, hardline$9);
27243 if (isNextLineEmpty$4(options.originalText, n, options)) {
27244 parts.push(hardline$9);
27247 return concat$d(parts);
27250 return concat$d([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$d([" //", n.node.comments[0].value.trimRight()])));
27252 case "NGChainedExpression":
27253 return group$b(join$9(concat$d([";", line$7]), path.map(function (childPath) {
27254 return hasNgSideEffect$1(childPath) ? print(childPath) : concat$d(["(", print(childPath), ")"]);
27255 }, "expressions")));
27257 case "NGEmptyExpression":
27260 case "NGQuotedExpression":
27261 return concat$d([n.prefix, ":", n.value]);
27263 case "NGMicrosyntax":
27264 return concat$d(path.map(function (childPath, index) {
27265 return concat$d([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$d([";", line$7]), print(childPath)]);
27268 case "NGMicrosyntaxKey":
27269 return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
27271 case "NGMicrosyntaxExpression":
27272 return concat$d([path.call(print, "expression"), n.alias === null ? "" : concat$d([" as ", path.call(print, "alias")])]);
27274 case "NGMicrosyntaxKeyedExpression":
27276 var index = path.getName();
27278 var _parentNode2 = path.getParentNode();
27280 var shouldNotPrintColon = isNgForOf$1(n, index, _parentNode2) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && _parentNode2.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && _parentNode2.body[index - 1].key.name === "then") && _parentNode2.body[0].type === "NGMicrosyntaxExpression";
27281 return concat$d([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
27284 case "NGMicrosyntaxLet":
27285 return concat$d(["let ", path.call(print, "key"), n.value === null ? "" : concat$d([" = ", path.call(print, "value")])]);
27287 case "NGMicrosyntaxAs":
27288 return concat$d([path.call(print, "key"), " as ", path.call(print, "alias")]);
27290 case "ArgumentPlaceholder":
27294 /* istanbul ignore next */
27295 throw new Error("unknown type: " + JSON.stringify(n.type));
27299 function printStatementSequence(path, options, print) {
27301 var bodyNode = path.getNode();
27302 var isClass = bodyNode.type === "ClassBody";
27303 path.map(function (stmtPath, i) {
27304 var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
27305 // "statements," it's safer simply to skip them.
27307 /* istanbul ignore if */
27311 } // Skip printing EmptyStatement nodes to avoid leaving stray
27312 // semicolons lying around.
27315 if (stmt.type === "EmptyStatement") {
27319 var stmtPrinted = print(stmtPath);
27320 var text = options.originalText;
27321 var parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
27322 // don't prepend the only JSX element in a program with semicolon
27324 if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
27325 if (stmt.comments && stmt.comments.some(function (comment) {
27326 return comment.leading;
27328 parts.push(print(stmtPath, {
27332 parts.push(";", stmtPrinted);
27335 parts.push(stmtPrinted);
27338 if (!options.semi && isClass) {
27339 if (classPropMayCauseASIProblems$1(stmtPath)) {
27341 } else if (stmt.type === "ClassProperty") {
27342 var nextChild = bodyNode.body[i + 1];
27344 if (classChildNeedsASIProtection$1(nextChild)) {
27350 if (isNextLineEmpty$4(text, stmt, options) && !isLastStatement$1(stmtPath)) {
27351 parts.push(hardline$9);
27354 printed.push(concat$d(parts));
27356 return join$9(hardline$9, printed);
27359 function printPropertyKey(path, options, print) {
27360 var node = path.getNode();
27362 if (node.computed) {
27363 return concat$d(["[", path.call(print, "key"), "]"]);
27366 var parent = path.getParentNode();
27367 var key = node.key;
27369 if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
27370 var objectHasStringProp = (parent.properties || parent.body || parent.members).some(function (prop) {
27371 return !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToCoerceToIdentifier$1(prop, options);
27373 needsQuoteProps.set(parent, objectHasStringProp);
27376 if (key.type === "Identifier" && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
27378 var prop = printString$2(JSON.stringify(key.name), options);
27379 return path.call(function (keyPath) {
27380 return comments.printComments(keyPath, function () {
27386 if (isStringPropSafeToCoerceToIdentifier$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
27388 return path.call(function (keyPath) {
27389 return comments.printComments(keyPath, function () {
27395 return path.call(print, "key");
27398 function printMethod(path, options, print) {
27399 var node = path.getNode();
27400 var kind = node.kind;
27401 var value = node.value || node;
27404 if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
27406 parts.push("async ");
27409 if (value.generator) {
27413 assert.ok(kind === "get" || kind === "set");
27414 parts.push(kind, " ");
27417 parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(function (path) {
27418 return printMethodInternal(path, options, print);
27420 return concat$d(parts);
27423 function printMethodInternal(path, options, print) {
27424 var parts = [printFunctionTypeParameters(path, options, print), group$b(concat$d([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
27426 if (path.getNode().body) {
27427 parts.push(" ", path.call(print, "body"));
27429 parts.push(options.semi ? ";" : "");
27432 return concat$d(parts);
27435 function couldGroupArg(arg) {
27436 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
27437 // https://github.com/prettier/prettier/issues/4070
27438 // export class Thing implements OtherThing {
27439 // do: (type: Type) => Provider<Prop> = memoize(
27440 // (type: ObjectType): Provider<Opts> => {}
27443 // https://github.com/prettier/prettier/issues/6099
27444 // app.get("/", (req, res): void => {
27445 // res.send("Hello World!");
27447 !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));
27450 function shouldGroupLastArg(args) {
27451 var lastArg = getLast$2(args);
27452 var penultimateArg = getPenultimate$1(args);
27453 return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
27454 // disable last element expansion.
27455 !penultimateArg || penultimateArg.type !== lastArg.type);
27458 function shouldGroupFirstArg(args) {
27459 if (args.length !== 2) {
27463 var firstArg = args[0];
27464 var secondArg = args[1];
27465 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);
27468 function printJestEachTemplateLiteral(node, expressions, options) {
27471 * ${1} | ${1} | ${2}
27472 * ${1} | ${2} | ${3}
27473 * ${2} | ${1} | ${3}
27475 var headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
27477 if (headerNames.length > 1 || headerNames.some(function (headerName) {
27478 return headerName.length !== 0;
27481 var stringifiedExpressions = expressions.map(function (doc) {
27482 return "${" + printDocToString$1(doc, Object.assign({}, options, {
27483 printWidth: Infinity,
27485 })).formatted + "}";
27488 hasLineBreak: false,
27492 for (var i = 1; i < node.quasis.length; i++) {
27493 var row = tableBody[tableBody.length - 1];
27494 var correspondingExpression = stringifiedExpressions[i - 1];
27495 row.cells.push(correspondingExpression);
27497 if (correspondingExpression.indexOf("\n") !== -1) {
27498 row.hasLineBreak = true;
27501 if (node.quasis[i].value.raw.indexOf("\n") !== -1) {
27503 hasLineBreak: false,
27509 var maxColumnCount = tableBody.reduce(function (maxColumnCount, row) {
27510 return Math.max(maxColumnCount, row.cells.length);
27511 }, headerNames.length);
27512 var maxColumnWidths = Array.from(new Array(maxColumnCount), function () {
27517 }].concat(tableBody.filter(function (row) {
27518 return row.cells.length !== 0;
27520 table.filter(function (row) {
27521 return !row.hasLineBreak;
27522 }).forEach(function (row) {
27523 row.cells.forEach(function (cell, index) {
27524 maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$2(cell));
27527 parts.push(lineSuffixBoundary$1, "`", indent$7(concat$d([hardline$9, join$9(hardline$9, table.map(function (row) {
27528 return join$9(" | ", row.cells.map(function (cell, index) {
27529 return row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$2(cell));
27531 }))])), hardline$9, "`");
27532 return concat$d(parts);
27536 function printArgumentsList(path, options, print) {
27537 var node = path.getValue();
27538 var args = node.arguments;
27540 if (args.length === 0) {
27541 return concat$d(["(", comments.printDanglingComments(path, options,
27544 } // useEffect(() => { ... }, [foo, bar, baz])
27547 if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(function (arg) {
27548 return arg.comments;
27550 return concat$d(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
27559 function shouldBreakForArrowFunctionInArguments(arg, argPath) {
27560 if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) {
27564 var shouldBreak = false;
27565 argPath.each(function (paramPath) {
27566 var printed = concat$d([print(paramPath)]);
27567 shouldBreak = shouldBreak || willBreak$1(printed);
27569 return shouldBreak;
27572 var anyArgEmptyLine = false;
27573 var shouldBreakForArrowFunction = false;
27574 var hasEmptyLineFollowingFirstArg = false;
27575 var lastArgIndex = args.length - 1;
27576 var printedArguments = path.map(function (argPath, index) {
27577 var arg = argPath.getNode();
27578 var parts = [print(argPath)];
27580 if (index === lastArgIndex) ; else if (isNextLineEmpty$4(options.originalText, arg, options)) {
27582 hasEmptyLineFollowingFirstArg = true;
27585 anyArgEmptyLine = true;
27586 parts.push(",", hardline$9, hardline$9);
27588 parts.push(",", line$7);
27591 shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
27592 return concat$d(parts);
27594 var maybeTrailingComma = // Dynamic imports cannot have trailing commas
27595 !(node.callee && node.callee.type === "Import") && shouldPrintComma$1(options, "all") ? "," : "";
27597 function allArgsBrokenOut() {
27598 return group$b(concat$d(["(", indent$7(concat$d([line$7, concat$d(printedArguments)])), maybeTrailingComma, line$7, ")"]), {
27603 if (isFunctionCompositionArgs$1(args)) {
27604 return allArgsBrokenOut();
27607 var shouldGroupFirst = shouldGroupFirstArg(args);
27608 var shouldGroupLast = shouldGroupLastArg(args);
27610 if (shouldGroupFirst || shouldGroupLast) {
27611 var 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
27613 var printedExpanded;
27615 path.each(function (argPath) {
27616 if (shouldGroupFirst && i === 0) {
27617 printedExpanded = [concat$d([argPath.call(function (p) {
27619 expandFirstArg: true
27621 }), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$9 : line$7, hasEmptyLineFollowingFirstArg ? hardline$9 : ""])].concat(printedArguments.slice(1));
27624 if (shouldGroupLast && i === args.length - 1) {
27625 printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(function (p) {
27627 expandLastArg: true
27634 var somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
27635 var simpleConcat = concat$d(["(", concat$d(printedExpanded), ")"]);
27636 return concat$d([somePrintedArgumentsWillBreak ? breakParent$3 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$6(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$d(["(", group$b(printedExpanded[0], {
27638 }), concat$d(printedExpanded.slice(1)), ")"]) : concat$d(["(", concat$d(printedArguments.slice(0, -1)), group$b(getLast$2(printedExpanded), {
27640 }), ")"]), allArgsBrokenOut()], {
27641 shouldBreak: shouldBreak
27645 var contents = concat$d(["(", indent$7(concat$d([softline$6, concat$d(printedArguments)])), ifBreak$6(maybeTrailingComma), softline$6, ")"]);
27647 if (isLongCurriedCallExpression$1(path)) {
27648 // By not wrapping the arguments in a group, the printer prioritizes
27649 // breaking up these arguments rather than the args of the parent call.
27653 return group$b(contents, {
27654 shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
27658 function printTypeAnnotation(path, options, print) {
27659 var node = path.getValue();
27661 if (!node.typeAnnotation) {
27665 var parentNode = path.getParentNode();
27666 var isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
27667 var isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
27669 if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
27670 return concat$d([" /*: ", path.call(print, "typeAnnotation"), " */"]);
27673 return concat$d([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
27676 function printFunctionTypeParameters(path, options, print) {
27677 var fun = path.getValue();
27679 if (fun.typeArguments) {
27680 return path.call(print, "typeArguments");
27683 if (fun.typeParameters) {
27684 return path.call(print, "typeParameters");
27690 function printFunctionParams(path, print, options, expandArg, printTypeParams) {
27691 var fun = path.getValue();
27692 var parent = path.getParentNode();
27693 var paramsField = fun.parameters ? "parameters" : "params";
27694 var isParametersInTestCall = isTestCall$1(parent);
27695 var shouldHugParameters = shouldHugArguments(fun);
27696 var shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(function (n) {
27699 var typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
27702 if (fun[paramsField]) {
27703 var lastArgIndex = fun[paramsField].length - 1;
27704 printed = path.map(function (childPath, index) {
27706 var param = childPath.getValue();
27707 parts.push(print(childPath));
27709 if (index === lastArgIndex) {
27711 parts.push(",", line$7);
27713 } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
27715 } else if (isNextLineEmpty$4(options.originalText, param, options)) {
27716 parts.push(",", hardline$9, hardline$9);
27718 parts.push(",", line$7);
27721 return concat$d(parts);
27726 printed.push(concat$d(["...", path.call(print, "rest")]));
27729 if (printed.length === 0) {
27730 return concat$d([typeParams, "(", comments.printDanglingComments(path, options,
27732 true, function (comment) {
27733 return getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")";
27737 var lastParam = getLast$2(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
27738 // params of the first/last argument, we don't want the arguments to break and instead
27739 // want the whole expression to be on a new line.
27742 // verylongcall( verylongcall((
27748 if (shouldExpandParameters) {
27749 return group$b(concat$d([removeLines$2(typeParams), "(", concat$d(printed.map(removeLines$2)), ")"]));
27750 } // Single object destructuring should hug
27759 var hasNotParameterDecorator = fun[paramsField].every(function (param) {
27760 return !param.decorators;
27763 if (shouldHugParameters && hasNotParameterDecorator) {
27764 return concat$d([typeParams, "(", concat$d(printed), ")"]);
27765 } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
27768 if (isParametersInTestCall) {
27769 return concat$d([typeParams, "(", concat$d(printed), ")"]);
27772 var 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;
27774 if (isFlowShorthandWithOneArg) {
27775 if (options.arrowParens === "always") {
27776 return concat$d(["(", concat$d(printed), ")"]);
27779 return concat$d(printed);
27782 var canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
27783 return concat$d([typeParams, "(", indent$7(concat$d([softline$6, concat$d(printed)])), ifBreak$6(canHaveTrailingComma && shouldPrintComma$1(options, "all") ? "," : ""), softline$6, ")"]);
27786 function shouldPrintParamsWithoutParens(path, options) {
27787 if (options.arrowParens === "always") {
27791 if (options.arrowParens === "avoid") {
27792 var node = path.getValue();
27793 return canPrintParamsWithoutParens(node);
27794 } // Fallback default; should be unreachable
27800 function canPrintParamsWithoutParens(node) {
27801 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;
27804 function printFunctionDeclaration(path, print, options) {
27805 var n = path.getValue();
27809 parts.push("async ");
27812 parts.push("function");
27819 parts.push(" ", path.call(print, "id"));
27822 parts.push(printFunctionTypeParameters(path, options, print), group$b(concat$d([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
27823 return concat$d(parts);
27826 function printReturnType(path, print, options) {
27827 var n = path.getValue();
27828 var returnType = path.call(print, "returnType");
27830 if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
27831 return concat$d([" /*: ", returnType, " */"]);
27834 var parts = [returnType]; // prepend colon to TypeScript type annotation
27836 if (n.returnType && n.returnType.typeAnnotation) {
27837 parts.unshift(": ");
27841 // The return type will already add the colon, but otherwise we
27842 // need to do it ourselves
27843 parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
27846 return concat$d(parts);
27849 function printExportDeclaration(path, options, print) {
27850 var decl = path.getValue();
27851 var semi = options.semi ? ";" : "";
27852 var parts = ["export "];
27853 var isDefault = decl["default"] || decl.type === "ExportDefaultDeclaration";
27856 parts.push("default ");
27859 parts.push(comments.printDanglingComments(path, options,
27863 if (needsHardlineAfterDanglingComment$1(decl)) {
27864 parts.push(hardline$9);
27867 if (decl.declaration) {
27868 parts.push(path.call(print, "declaration"));
27870 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") {
27874 if (decl.specifiers && decl.specifiers.length > 0) {
27875 var specifiers = [];
27876 var defaultSpecifiers = [];
27877 var namespaceSpecifiers = [];
27878 path.each(function (specifierPath) {
27879 var specifierType = path.getValue().type;
27881 if (specifierType === "ExportSpecifier") {
27882 specifiers.push(print(specifierPath));
27883 } else if (specifierType === "ExportDefaultSpecifier") {
27884 defaultSpecifiers.push(print(specifierPath));
27885 } else if (specifierType === "ExportNamespaceSpecifier") {
27886 namespaceSpecifiers.push(concat$d(["* as ", print(specifierPath)]));
27889 var isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
27890 var isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
27891 var canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || decl.specifiers && decl.specifiers.some(function (node) {
27892 return node.comments;
27896 if (specifiers.length !== 0) {
27898 printed = group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$7 : softline$6, join$9(concat$d([",", line$7]), specifiers)])), ifBreak$6(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$7 : softline$6, "}"]));
27900 printed = concat$d(["{", options.bracketSpacing ? " " : "", concat$d(specifiers), options.bracketSpacing ? " " : "", "}"]);
27904 parts.push(decl.exportKind === "type" ? "type " : "", concat$d(defaultSpecifiers), concat$d([isDefaultFollowed ? ", " : ""]), concat$d(namespaceSpecifiers), concat$d([isNamespaceFollowed ? ", " : ""]), printed);
27910 parts.push(" from ", path.call(print, "source"));
27916 return concat$d(parts);
27919 function printFlowDeclaration(path, parts) {
27920 var parentExportDecl = getParentExportDeclaration$1(path);
27922 if (parentExportDecl) {
27923 assert.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
27925 // If the parent node has type DeclareExportDeclaration, then it
27926 // will be responsible for printing the "declare" token. Otherwise
27927 // it needs to be printed with this non-exported declaration node.
27928 parts.unshift("declare ");
27931 return concat$d(parts);
27934 function printTypeScriptModifiers(path, options, print) {
27935 var n = path.getValue();
27937 if (!n.modifiers || !n.modifiers.length) {
27941 return concat$d([join$9(" ", path.map(print, "modifiers")), " "]);
27944 function printTypeParameters(path, options, print, paramsKey) {
27945 var n = path.getValue();
27947 if (!n[paramsKey]) {
27949 } // for TypeParameterDeclaration typeParameters is a single node
27952 if (!Array.isArray(n[paramsKey])) {
27953 return path.call(print, paramsKey);
27956 var grandparent = path.getNode(2);
27957 var greatGreatGrandParent = path.getNode(4);
27958 var isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
27959 var 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.
27960 greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent && grandparent.type === "TSTypeAnnotation" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType");
27962 if (shouldInline) {
27963 return concat$d(["<", join$9(", ", path.map(print, paramsKey)), ">"]);
27966 return group$b(concat$d(["<", indent$7(concat$d([softline$6, join$9(concat$d([",", line$7]), path.map(print, paramsKey))])), ifBreak$6(options.parser !== "typescript" && shouldPrintComma$1(options, "all") ? "," : ""), softline$6, ">"]));
27969 function printClass(path, options, print) {
27970 var n = path.getValue();
27974 parts.push("abstract ");
27977 parts.push("class");
27980 parts.push(" ", path.call(print, "id"));
27983 parts.push(path.call(print, "typeParameters"));
27984 var partsGroup = [];
27986 if (n.superClass) {
27987 var printed = concat$d(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
27988 // If there is only on extends and there are not comments
27990 if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
27991 parts.push(concat$d([" ", path.call(function (superClass) {
27992 return comments.printComments(superClass, function () {
27995 }, "superClass")]));
27997 partsGroup.push(group$b(concat$d([line$7, path.call(function (superClass) {
27998 return comments.printComments(superClass, function () {
28001 }, "superClass")])));
28003 } else if (n.extends && n.extends.length > 0) {
28004 parts.push(" extends ", join$9(", ", path.map(print, "extends")));
28007 if (n["mixins"] && n["mixins"].length > 0) {
28008 partsGroup.push(line$7, "mixins ", group$b(indent$7(join$9(concat$d([",", line$7]), path.map(print, "mixins")))));
28011 if (n["implements"] && n["implements"].length > 0) {
28012 partsGroup.push(line$7, "implements", group$b(indent$7(concat$d([line$7, join$9(concat$d([",", line$7]), path.map(print, "implements"))]))));
28015 if (partsGroup.length > 0) {
28016 parts.push(group$b(indent$7(concat$d(partsGroup))));
28019 if (n.body && n.body.comments && hasLeadingOwnLineComment$1(options.originalText, n.body, options)) {
28020 parts.push(hardline$9);
28025 parts.push(path.call(print, "body"));
28029 function printOptionalToken(path) {
28030 var node = path.getValue();
28032 if (!node.optional || // It's an optional computed method parsed by typescript-estree.
28033 // "?" is printed in `printMethod`.
28034 node.type === "Identifier" && node === path.getParentNode().key) {
28038 if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
28045 function printMemberLookup(path, options, print) {
28046 var property = path.call(print, "property");
28047 var n = path.getValue();
28048 var optional = printOptionalToken(path);
28051 return concat$d([optional, ".", property]);
28054 if (!n.property || isNumericLiteral$1(n.property)) {
28055 return concat$d([optional, "[", property, "]"]);
28058 return group$b(concat$d([optional, "[", indent$7(concat$d([softline$6, property])), softline$6, "]"]));
28061 function printBindExpressionCallee(path, options, print) {
28062 return concat$d(["::", path.call(print, "callee")]);
28063 } // We detect calls on member expressions specially to format a
28064 // common pattern better. The pattern we are looking for is this:
28067 // .map(x => x + 1)
28068 // .filter(x => x > 10)
28069 // .some(x => x % 2)
28071 // The way it is structured in the AST is via a nested sequence of
28072 // MemberExpression and CallExpression. We need to traverse the AST
28073 // and make groups out of it to print it in the desired way.
28076 function printMemberChain(path, options, print) {
28077 // The first phase is to linearize the AST by traversing it down.
28080 // has the following AST structure:
28081 // CallExpression(MemberExpression(CallExpression(Identifier)))
28082 // and we transform it into
28083 // [Identifier, CallExpression, MemberExpression, CallExpression]
28084 var printedNodes = []; // Here we try to retain one typed empty line after each call expression or
28085 // the first group whether it is in parentheses or not
28087 function shouldInsertEmptyLineAfter(node) {
28088 var originalText = options.originalText;
28089 var nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$2(originalText, node, options);
28090 var nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
28091 // line after that parenthesis
28093 if (nextChar == ")") {
28094 return isNextLineEmptyAfterIndex$1(originalText, nextCharIndex + 1, options);
28097 return isNextLineEmpty$4(originalText, node, options);
28100 function rec(path) {
28101 var node = path.getValue();
28103 if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish$1(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
28104 printedNodes.unshift({
28106 printed: concat$d([comments.printComments(path, function () {
28107 return concat$d([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]);
28108 }, options), shouldInsertEmptyLineAfter(node) ? hardline$9 : ""])
28110 path.call(function (callee) {
28111 return rec(callee);
28113 } else if (isMemberish$1(node)) {
28114 printedNodes.unshift({
28116 needsParens: needsParens_1(path, options),
28117 printed: comments.printComments(path, function () {
28118 return node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print);
28121 path.call(function (object) {
28122 return rec(object);
28124 } else if (node.type === "TSNonNullExpression") {
28125 printedNodes.unshift({
28127 printed: comments.printComments(path, function () {
28131 path.call(function (expression) {
28132 return rec(expression);
28135 printedNodes.unshift({
28137 printed: path.call(print)
28140 } // Note: the comments of the root node have already been printed, so we
28141 // need to extract this first call without printing them as they would
28142 // if handled inside of the recursive call.
28145 var node = path.getValue();
28146 printedNodes.unshift({
28148 printed: concat$d([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)])
28150 path.call(function (callee) {
28151 return rec(callee);
28152 }, "callee"); // Once we have a linear list of printed nodes, we want to create groups out
28156 // will be grouped as
28158 // [Identifier, CallExpression],
28159 // [MemberExpression, MemberExpression, CallExpression],
28160 // [MemberExpression, CallExpression],
28161 // [MemberExpression],
28163 // so that we can print it as
28168 // The first group is the first node followed by
28169 // - as many CallExpression as possible
28170 // < fn()()() >.something()
28171 // - as many array accessors as possible
28172 // < fn()[0][1][2] >.something()
28173 // - then, as many MemberExpression as possible but the last one
28174 // < this.items >.something()
28177 var currentGroup = [printedNodes[0]];
28180 for (; i < printedNodes.length; ++i) {
28181 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)) {
28182 currentGroup.push(printedNodes[i]);
28188 if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
28189 for (; i + 1 < printedNodes.length; ++i) {
28190 if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
28191 currentGroup.push(printedNodes[i]);
28198 groups.push(currentGroup);
28199 currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
28200 // a sequence of CallExpression. To compute it, we keep adding things to the
28201 // group until we has seen a CallExpression in the past and reach a
28202 // MemberExpression
28204 var hasSeenCallExpression = false;
28206 for (; i < printedNodes.length; ++i) {
28207 if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
28208 // [0] should be appended at the end of the group instead of the
28209 // beginning of the next one
28210 if (printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
28211 currentGroup.push(printedNodes[i]);
28215 groups.push(currentGroup);
28217 hasSeenCallExpression = false;
28220 if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
28221 hasSeenCallExpression = true;
28224 currentGroup.push(printedNodes[i]);
28226 if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(function (comment) {
28227 return comment.trailing;
28229 groups.push(currentGroup);
28231 hasSeenCallExpression = false;
28235 if (currentGroup.length > 0) {
28236 groups.push(currentGroup);
28237 } // There are cases like Object.keys(), Observable.of(), _.values() where
28238 // they are the subject of all the chained calls and therefore should
28239 // be kept on the same line:
28241 // Object.keys(items)
28245 // In order to detect those cases, we use an heuristic: if the first
28246 // node is an identifier with the name starting with a capital
28247 // letter or just a sequence of _$. The rationale is that they are
28248 // likely to be factories.
28251 function isFactory(name) {
28252 return /^[A-Z]|^[_$]+$/.test(name);
28253 } // In case the Identifier is shorter than tab width, we can keep the
28254 // first call in a single line, if it's an ExpressionStatement.
28256 // d3.scaleLinear()
28257 // .domain([0, 100])
28258 // .range([0, width]);
28262 function isShort(name) {
28263 return name.length <= options.tabWidth;
28266 function shouldNotWrap(groups) {
28267 var parent = path.getParentNode();
28268 var isExpression = parent && parent.type === "ExpressionStatement";
28269 var hasComputed = groups[1].length && groups[1][0].node.computed;
28271 if (groups[0].length === 1) {
28272 var firstNode = groups[0][0].node;
28273 return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
28276 var lastNode = getLast$2(groups[0]).node;
28277 return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
28280 var shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
28282 function printGroup(printedGroup) {
28283 var printed = printedGroup.map(function (tuple) {
28284 return tuple.printed;
28285 }); // Checks if the last node (i.e. the parent node) needs parens and print
28288 if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
28289 return concat$d(["("].concat(_toConsumableArray(printed), [")"]));
28292 return concat$d(printed);
28295 function printIndentedGroup(groups) {
28296 if (groups.length === 0) {
28300 return indent$7(group$b(concat$d([hardline$9, join$9(hardline$9, groups.map(printGroup))])));
28303 var printedGroups = groups.map(printGroup);
28304 var oneLine = concat$d(printedGroups);
28305 var cutoff = shouldMerge ? 3 : 2;
28306 var flatGroups = groups.slice(0, cutoff).reduce(function (res, group) {
28307 return res.concat(group);
28309 var hasComment = flatGroups.slice(1, -1).some(function (node) {
28310 return hasLeadingComment$3(node.node);
28311 }) || flatGroups.slice(0, -1).some(function (node) {
28312 return hasTrailingComment$1(node.node);
28313 }) || groups[cutoff] && hasLeadingComment$3(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
28314 // render everything concatenated together.
28316 if (groups.length <= cutoff && !hasComment) {
28317 if (isLongCurriedCallExpression$1(path)) {
28321 return group$b(oneLine);
28322 } // Find out the last node in the first group and check if it has an
28323 // empty line after
28326 var lastNodeBeforeIndent = getLast$2(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
28327 var shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
28328 var expanded = concat$d([printGroup(groups[0]), shouldMerge ? concat$d(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$9 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
28329 var callExpressions = printedNodes.map(function (_ref) {
28330 var node = _ref.node;
28332 }).filter(isCallOrOptionalCallExpression$1); // We don't want to print in one line if there's:
28334 // * 3 or more chained calls.
28335 // * Any group but the last one has a hard line.
28336 // If the last group is a function it's okay to inline if it fits.
28338 if (hasComment || callExpressions.length >= 3 || printedGroups.slice(0, -1).some(willBreak$1) ||
28340 * scopes.filter(scope => scope.value !== '').map((scope, i) => {
28341 * // multi line content
28344 function (lastGroupDoc, lastGroupNode) {
28345 return isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$1(lastGroupDoc);
28346 }(getLast$2(printedGroups), getLast$2(getLast$2(groups)).node) && callExpressions.slice(0, -1).some(function (n) {
28347 return n.arguments.some(isFunctionOrArrowExpression$1);
28349 return group$b(expanded);
28352 return concat$d([// We only need to check `oneLine` because if `expanded` is chosen
28353 // that means that the parent group has already been broken
28355 willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$3 : "", conditionalGroup$1([oneLine, expanded])]);
28358 function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
28359 if (isFacebookTranslationTag) {
28363 if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
28364 return child.length === 1 ? softline$6 : hardline$9;
28370 function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
28371 if (isFacebookTranslationTag) {
28375 if (child.length === 1) {
28376 return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$9 : softline$6;
28380 } // JSX Children are strange, mostly for two reasons:
28381 // 1. JSX reads newlines into string values, instead of skipping them like JS
28382 // 2. up to one whitespace between elements within a line is significant,
28383 // but not between lines.
28385 // Leading, trailing, and lone whitespace all need to
28386 // turn themselves into the rather ugly `{' '}` when breaking.
28388 // We print JSX using the `fill` doc primitive.
28389 // This requires that we give it an array of alternating
28390 // content and whitespace elements.
28391 // To ensure this we add dummy `""` content elements as needed.
28394 function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
28395 var n = path.getValue();
28396 var children = []; // using `map` instead of `each` because it provides `i`
28398 path.map(function (childPath, i) {
28399 var child = childPath.getValue();
28401 if (isLiteral$1(child)) {
28402 var text = rawText$1(child); // Contains a non-whitespace character
28404 if (isMeaningfulJSXText$1(child)) {
28405 var words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
28407 if (words[0] === "") {
28411 if (/\n/.test(words[0])) {
28412 var next = n.children[i + 1];
28413 children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
28415 children.push(jsxWhitespace);
28421 var endWhitespace; // Ends with whitespace
28423 if (getLast$2(words) === "") {
28425 endWhitespace = words.pop();
28426 } // This was whitespace only without a new line.
28429 if (words.length === 0) {
28433 words.forEach(function (word, i) {
28435 children.push(line$7);
28437 children.push(word);
28441 if (endWhitespace !== undefined) {
28442 if (/\n/.test(endWhitespace)) {
28443 var _next = n.children[i + 1];
28444 children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$2(children), child, _next));
28446 children.push(jsxWhitespace);
28449 var _next2 = n.children[i + 1];
28450 children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$2(children), child, _next2));
28452 } else if (/\n/.test(text)) {
28453 // Keep (up to one) blank line between tags/expressions/text.
28454 // Note: We don't keep blank lines between text elements.
28455 if (text.match(/\n/g).length > 1) {
28457 children.push(hardline$9);
28461 children.push(jsxWhitespace);
28464 var printedChild = print(childPath);
28465 children.push(printedChild);
28466 var _next3 = n.children[i + 1];
28468 var directlyFollowedByMeaningfulText = _next3 && isMeaningfulJSXText$1(_next3);
28470 if (directlyFollowedByMeaningfulText) {
28471 var firstWord = rawText$1(_next3).trim().split(matchJsxWhitespaceRegex$1)[0];
28472 children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, _next3));
28474 children.push(hardline$9);
28479 } // JSX expands children from the inside-out, instead of the outside-in.
28480 // This is both to break children before attributes,
28481 // and to ensure that when children break, their parents do as well.
28483 // Any element that is written without any newlines and fits on a single line
28484 // is left that way.
28485 // Not only that, any user-written-line containing multiple JSX siblings
28486 // should also be kept on one line if possible,
28487 // so each user-written-line is wrapped in its own group.
28489 // Elements that contain newlines or don't fit on a single line (recursively)
28490 // are fully-split, using hardline and shouldBreak: true.
28492 // To support that case properly, all leading and trailing spaces
28493 // are stripped from the list of children, and replaced with a single hardline.
28496 function printJSXElement(path, options, print) {
28497 var n = path.getValue();
28499 if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
28500 return concat$d([path.call(print, "openingElement"), path.call(print, "closingElement")]);
28503 var openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
28504 var closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
28506 if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
28507 return concat$d([openingLines, concat$d(path.map(print, "children")), closingLines]);
28508 } // Convert `{" "}` to text nodes containing a space.
28509 // This makes it easy to turn them into `jsxWhitespace` which
28510 // can then print as either a space or `{" "}` when breaking.
28513 n.children = n.children.map(function (child) {
28514 if (isJSXWhitespaceExpression$1(child)) {
28524 var containsTag = n.children.filter(isJSXNode$1).length > 0;
28525 var containsMultipleExpressions = n.children.filter(function (child) {
28526 return child.type === "JSXExpressionContainer";
28528 var containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
28530 var forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
28531 var rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
28532 var jsxWhitespace = ifBreak$6(concat$d([rawJsxWhitespace, softline$6]), " ");
28533 var isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
28534 var children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
28535 var containsText = n.children.filter(function (child) {
28536 return isMeaningfulJSXText$1(child);
28537 }).length > 0; // We can end up we multiple whitespace elements with empty string
28538 // content between them.
28539 // We need to remove empty whitespace and softlines before JSX whitespace
28540 // to get the correct output.
28542 for (var i = children.length - 2; i >= 0; i--) {
28543 var isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
28544 var isPairOfHardlines = children[i] === hardline$9 && children[i + 1] === "" && children[i + 2] === hardline$9;
28545 var isLineFollowedByJSXWhitespace = (children[i] === softline$6 || children[i] === hardline$9) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
28546 var isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$6 || children[i + 2] === hardline$9);
28547 var isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
28548 var isPairOfHardOrSoftLines = children[i] === softline$6 && children[i + 1] === "" && children[i + 2] === hardline$9 || children[i] === hardline$9 && children[i + 1] === "" && children[i + 2] === softline$6;
28550 if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
28551 children.splice(i, 2);
28552 } else if (isJSXWhitespaceFollowedByLine) {
28553 children.splice(i + 1, 2);
28555 } // Trim trailing lines (or empty strings)
28558 while (children.length && (isLineNext$1(getLast$2(children)) || isEmpty$1(getLast$2(children)))) {
28560 } // Trim leading lines (or empty strings)
28563 while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
28566 } // Tweak how we format children if outputting this element over multiple lines.
28567 // Also detect whether we will force this element to output over multiple lines.
28570 var multilineChildren = [];
28571 children.forEach(function (child, i) {
28572 // There are a number of situations where we need to ensure we display
28573 // whitespace as `{" "}` when outputting this element over multiple lines.
28574 if (child === jsxWhitespace) {
28575 if (i === 1 && children[i - 1] === "") {
28576 if (children.length === 2) {
28577 // Solitary whitespace
28578 multilineChildren.push(rawJsxWhitespace);
28580 } // Leading whitespace
28583 multilineChildren.push(concat$d([rawJsxWhitespace, hardline$9]));
28585 } else if (i === children.length - 1) {
28586 // Trailing whitespace
28587 multilineChildren.push(rawJsxWhitespace);
28589 } else if (children[i - 1] === "" && children[i - 2] === hardline$9) {
28590 // Whitespace after line break
28591 multilineChildren.push(rawJsxWhitespace);
28596 multilineChildren.push(child);
28598 if (willBreak$1(child)) {
28599 forcedBreak = true;
28601 }); // If there is text we use `fill` to fit as much onto each line as possible.
28602 // When there is no text (just tags and expressions) we use `group`
28603 // to output each on a separate line.
28605 var content = containsText ? fill$4(multilineChildren) : group$b(concat$d(multilineChildren), {
28608 var multiLineElem = group$b(concat$d([openingLines, indent$7(concat$d([hardline$9, content])), hardline$9, closingLines]));
28611 return multiLineElem;
28614 return conditionalGroup$1([group$b(concat$d([openingLines, concat$d(children), closingLines])), multiLineElem]);
28617 function maybeWrapJSXElementInParens(path, elem, options) {
28618 var parent = path.getParentNode();
28624 var NO_WRAP_PARENTS = {
28625 ArrayExpression: true,
28626 JSXAttribute: true,
28628 JSXExpressionContainer: true,
28630 ExpressionStatement: true,
28631 CallExpression: true,
28632 OptionalCallExpression: true,
28633 ConditionalExpression: true,
28634 JsExpressionRoot: true
28637 if (NO_WRAP_PARENTS[parent.type]) {
28641 var shouldBreak = matchAncestorTypes$1(path, ["ArrowFunctionExpression", "CallExpression", "JSXExpressionContainer"]) || matchAncestorTypes$1(path, ["ArrowFunctionExpression", "OptionalCallExpression", "JSXExpressionContainer"]);
28642 var needsParens = needsParens_1(path, options);
28643 return group$b(concat$d([needsParens ? "" : ifBreak$6("("), indent$7(concat$d([softline$6, elem])), softline$6, needsParens ? "" : ifBreak$6(")")]), {
28644 shouldBreak: shouldBreak
28648 function shouldInlineLogicalExpression(node) {
28649 if (node.type !== "LogicalExpression") {
28653 if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
28657 if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
28661 if (isJSXNode$1(node.right)) {
28666 } // For binary expressions to be consistent, we need to group
28667 // subsequent operators with the same precedence level under a single
28668 // group. Otherwise they will be nested such that some of them break
28669 // onto new lines but not all. Operators with the same precedence
28670 // level should either all break or not. Because we group them by
28671 // precedence level and the AST is structured based on precedence
28672 // level, things are naturally broken up correctly, i.e. `&&` is
28673 // broken before `+`.
28676 function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
28678 var node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
28680 if (isBinaryish$1(node)) {
28681 // Put all operators with the same precedence level in the same
28682 // group. The reason we only need to do this with the `left`
28683 // expression is because given an expression like `1 + 2 - 3`, it
28684 // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
28685 // is where the rest of the expression will exist. Binary
28686 // expressions on the right side mean they have a difference
28687 // precedence level and should be treated as a separate group, so
28688 // print them normally. (This doesn't hold for the `**` operator,
28689 // which is unique in that it is right-associative.)
28690 if (shouldFlatten$1(node.operator, node.left.operator)) {
28691 // Flatten them out by recursively calling this function.
28692 parts = parts.concat(path.call(function (left) {
28693 return printBinaryishExpressions(left, print, options,
28695 true, isInsideParenthesis);
28698 parts.push(path.call(print, "left"));
28701 var shouldInline = shouldInlineLogicalExpression(node);
28702 var lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
28703 var operator = node.type === "NGPipeExpression" ? "|" : node.operator;
28704 var rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$b(indent$7(concat$d([softline$6, ": ", join$9(concat$d([softline$6, ":", ifBreak$6(" ")]), path.map(print, "arguments").map(function (arg) {
28705 return align$1(2, group$b(arg));
28707 var right = shouldInline ? concat$d([operator, " ", path.call(print, "right"), rightSuffix]) : concat$d([lineBeforeOperator ? softline$6 : "", operator, lineBeforeOperator ? " " : line$7, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
28708 // in order to avoid having a small right part like -1 be on its own line.
28710 var parent = path.getParentNode();
28711 var shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
28712 parts.push(" ", shouldGroup ? group$b(right) : right); // The root comments are already printed, but we need to manually print
28713 // the other ones since we don't call the normal print on BinaryExpression,
28714 // only for the left and right parts
28716 if (isNested && node.comments) {
28717 parts = comments.printComments(path, function () {
28718 return concat$d(parts);
28722 // Our stopping case. Simply print the node normally.
28723 parts.push(path.call(print));
28729 function printAssignmentRight(leftNode, rightNode, printedRight, options) {
28730 if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
28731 return indent$7(concat$d([hardline$9, printedRight]));
28734 var 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
28735 options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
28738 return group$b(indent$7(concat$d([line$7, printedRight])));
28741 return concat$d([" ", printedRight]);
28744 function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
28746 return printedLeft;
28749 var printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
28750 return group$b(concat$d([printedLeft, operator, printed]));
28753 function adjustClause(node, clause, forceSpace) {
28754 if (node.type === "EmptyStatement") {
28758 if (node.type === "BlockStatement" || forceSpace) {
28759 return concat$d([" ", clause]);
28762 return indent$7(concat$d([line$7, clause]));
28765 function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
28766 var raw = rawText$1(node);
28767 var isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
28768 return printString$2(raw, options, isDirectiveLiteral);
28771 function printRegex(node) {
28772 var flags = node.flags.split("").sort().join("");
28773 return "/".concat(node.pattern, "/").concat(flags);
28776 function exprNeedsASIProtection(path, options) {
28777 var node = path.getValue();
28778 var 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;
28780 if (maybeASIProblem) {
28784 if (!hasNakedLeftSide$2(node)) {
28788 return path.call.apply(path, [function (childPath) {
28789 return exprNeedsASIProtection(childPath, options);
28790 }].concat(getLeftSidePathName$2(path, node)));
28793 function stmtNeedsASIProtection(path, options) {
28794 var node = path.getNode();
28796 if (node.type !== "ExpressionStatement") {
28800 return path.call(function (childPath) {
28801 return exprNeedsASIProtection(childPath, options);
28805 function shouldHugType(node) {
28806 if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
28810 if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
28811 var voidCount = node.types.filter(function (n) {
28812 return n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword";
28814 var objectCount = node.types.filter(function (n) {
28815 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
28816 n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference";
28819 if (node.types.length - 1 === voidCount && objectCount > 0) {
28827 function shouldHugArguments(fun) {
28828 return fun && fun.params && fun.params.length === 1 && !fun.params[0].comments && (fun.params[0].type === "ObjectPattern" || fun.params[0].type === "ArrayPattern" || fun.params[0].type === "Identifier" && fun.params[0].typeAnnotation && (fun.params[0].typeAnnotation.type === "TypeAnnotation" || fun.params[0].typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(fun.params[0].typeAnnotation.typeAnnotation) || fun.params[0].type === "FunctionTypeParam" && isObjectType$1(fun.params[0].typeAnnotation) || fun.params[0].type === "AssignmentPattern" && (fun.params[0].left.type === "ObjectPattern" || fun.params[0].left.type === "ArrayPattern") && (fun.params[0].right.type === "Identifier" || fun.params[0].right.type === "ObjectExpression" && fun.params[0].right.properties.length === 0 || fun.params[0].right.type === "ArrayExpression" && fun.params[0].right.elements.length === 0)) && !fun.rest;
28831 function printArrayItems(path, options, printPath, print) {
28832 var printedElements = [];
28833 var separatorParts = [];
28834 path.each(function (childPath) {
28835 printedElements.push(concat$d(separatorParts));
28836 printedElements.push(group$b(print(childPath)));
28837 separatorParts = [",", line$7];
28839 if (childPath.getValue() && isNextLineEmpty$4(options.originalText, childPath.getValue(), options)) {
28840 separatorParts.push(softline$6);
28843 return concat$d(printedElements);
28846 function willPrintOwnComments(path
28849 var node = path.getValue();
28850 var parent = path.getParentNode();
28851 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$4(path);
28854 function canAttachComment$1(node) {
28855 return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
28858 function printComment$2(commentPath, options) {
28859 var comment = commentPath.getValue();
28861 switch (comment.type) {
28862 case "CommentBlock":
28865 if (isIndentableBlockComment(comment)) {
28866 var printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
28867 // printed as a `lineSuffix` which causes the comments to be
28868 // interleaved. See https://github.com/prettier/prettier/issues/4412
28870 if (comment.trailing && !hasNewline$4(options.originalText, options.locStart(comment), {
28873 return concat$d([hardline$9, printed]);
28879 var isInsideFlowComment = options.originalText.substr(options.locEnd(comment) - 3, 3) === "*-/";
28880 return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
28883 case "CommentLine":
28885 // Print shebangs with the proper comment characters
28886 if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
28887 return "#!" + comment.value.trimRight();
28890 return "//" + comment.value.trimRight();
28893 throw new Error("Not a comment: " + JSON.stringify(comment));
28897 function isIndentableBlockComment(comment) {
28898 // If the comment has multiple lines and every line starts with a star
28899 // we can fix the indentation of each line. The stars in the `/*` and
28900 // `*/` delimiters are not included in the comment value, so add them
28902 var lines = "*".concat(comment.value, "*").split("\n");
28903 return lines.length > 1 && lines.every(function (line) {
28904 return line.trim()[0] === "*";
28908 function printIndentableBlockComment(comment) {
28909 var lines = comment.value.split("\n");
28910 return concat$d(["/*", join$9(hardline$9, lines.map(function (line, index) {
28911 return index === 0 ? line.trimRight() : " " + (index < lines.length - 1 ? line.trim() : line.trimLeft());
28915 var printerEstree = {
28916 preprocess: preprocess_1$1,
28917 print: genericPrint$3,
28919 insertPragma: insertPragma$7,
28920 massageAstNode: clean_1$1,
28921 hasPrettierIgnore: hasPrettierIgnore$3,
28922 willPrintOwnComments: willPrintOwnComments,
28923 canAttachComment: canAttachComment$1,
28924 printComment: printComment$2,
28925 isBlockComment: comments$1.isBlockComment,
28927 ownLine: comments$1.handleOwnLineComment,
28928 endOfLine: comments$1.handleEndOfLineComment,
28929 remaining: comments$1.handleRemainingComment
28933 var _require$$0$builders$7 = doc.builders,
28934 concat$e = _require$$0$builders$7.concat,
28935 hardline$a = _require$$0$builders$7.hardline,
28936 indent$8 = _require$$0$builders$7.indent,
28937 join$a = _require$$0$builders$7.join;
28939 function genericPrint$4(path, options, print) {
28940 var node = path.getValue();
28942 switch (node.type) {
28944 return concat$e([path.call(print, "node"), hardline$a]);
28946 case "ArrayExpression":
28947 return node.elements.length === 0 ? "[]" : concat$e(["[", indent$8(concat$e([hardline$a, join$a(concat$e([",", hardline$a]), path.map(print, "elements"))])), hardline$a, "]"]);
28949 case "ObjectExpression":
28950 return node.properties.length === 0 ? "{}" : concat$e(["{", indent$8(concat$e([hardline$a, join$a(concat$e([",", hardline$a]), path.map(print, "properties"))])), hardline$a, "}"]);
28952 case "ObjectProperty":
28953 return concat$e([path.call(print, "key"), ": ", path.call(print, "value")]);
28955 case "UnaryExpression":
28956 return concat$e([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
28958 case "NullLiteral":
28961 case "BooleanLiteral":
28962 return node.value ? "true" : "false";
28964 case "StringLiteral":
28965 case "NumericLiteral":
28966 return JSON.stringify(node.value);
28969 return JSON.stringify(node.name);
28972 /* istanbul ignore next */
28973 throw new Error("unknown type: " + JSON.stringify(node.type));
28977 function clean$5(node, newNode
28980 delete newNode.start;
28981 delete newNode.end;
28982 delete newNode.extra;
28983 delete newNode.loc;
28984 delete newNode.comments;
28985 delete newNode.errors;
28987 if (node.type === "Identifier") {
28989 type: "StringLiteral",
28994 if (node.type === "UnaryExpression" && node.operator === "+") {
28995 return newNode.argument;
28999 var printerEstreeJson = {
29000 preprocess: preprocess_1$1,
29001 print: genericPrint$4,
29002 massageAstNode: clean$5
29005 var CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
29010 category: CATEGORY_JAVASCRIPT,
29013 description: "Include parentheses around a sole arrow function parameter.",
29016 description: "Omit parens when possible. Example: `x => x`"
29019 description: "Always include parens. Example: `(x) => x`"
29022 bracketSpacing: commonOptions.bracketSpacing,
29023 jsxBracketSameLine: {
29025 category: CATEGORY_JAVASCRIPT,
29028 description: "Put > on the last line instead of at a new line."
29032 category: CATEGORY_JAVASCRIPT,
29035 description: "Print semicolons.",
29036 oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
29038 singleQuote: commonOptions.singleQuote,
29041 category: CATEGORY_JAVASCRIPT,
29044 description: "Use single quotes in JSX."
29048 category: CATEGORY_JAVASCRIPT,
29050 default: "as-needed",
29051 description: "Change when properties in objects are quoted.",
29053 value: "as-needed",
29054 description: "Only add quotes around object properties where required."
29056 value: "consistent",
29057 description: "If at least one property in an object requires quotes, quote all properties."
29060 description: "Respect the input use of quotes in object properties."
29065 category: CATEGORY_JAVASCRIPT,
29074 description: "Print trailing commas wherever possible when multi-line.",
29077 description: "No trailing commas."
29080 description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
29083 description: "Trailing commas wherever possible (including function arguments)."
29086 deprecated: "0.19.0",
29090 deprecated: "0.19.0",
29096 var name$9 = "JavaScript";
29097 var type$8 = "programming";
29098 var tmScope$8 = "source.js";
29099 var aceMode$8 = "javascript";
29100 var codemirrorMode$4 = "javascript";
29101 var codemirrorMimeType$4 = "text/javascript";
29102 var color$3 = "#f1e05a";
29107 var extensions$8 = [
29132 var interpreters = [
29141 var languageId$8 = 183;
29145 tmScope: tmScope$8,
29146 aceMode: aceMode$8,
29147 codemirrorMode: codemirrorMode$4,
29148 codemirrorMimeType: codemirrorMimeType$4,
29150 aliases: aliases$2,
29151 extensions: extensions$8,
29152 filenames: filenames,
29153 interpreters: interpreters,
29154 languageId: languageId$8
29157 var JavaScript$1 = /*#__PURE__*/Object.freeze({
29161 tmScope: tmScope$8,
29162 aceMode: aceMode$8,
29163 codemirrorMode: codemirrorMode$4,
29164 codemirrorMimeType: codemirrorMimeType$4,
29166 aliases: aliases$2,
29167 extensions: extensions$8,
29168 filenames: filenames,
29169 interpreters: interpreters,
29170 languageId: languageId$8,
29171 'default': JavaScript
29174 var name$a = "JSX";
29175 var type$9 = "programming";
29176 var group$c = "JavaScript";
29177 var extensions$9 = [
29180 var tmScope$9 = "source.js.jsx";
29181 var aceMode$9 = "javascript";
29182 var codemirrorMode$5 = "jsx";
29183 var codemirrorMimeType$5 = "text/jsx";
29184 var languageId$9 = 178;
29189 extensions: extensions$9,
29190 tmScope: tmScope$9,
29191 aceMode: aceMode$9,
29192 codemirrorMode: codemirrorMode$5,
29193 codemirrorMimeType: codemirrorMimeType$5,
29194 languageId: languageId$9
29197 var JSX$1 = /*#__PURE__*/Object.freeze({
29202 extensions: extensions$9,
29203 tmScope: tmScope$9,
29204 aceMode: aceMode$9,
29205 codemirrorMode: codemirrorMode$5,
29206 codemirrorMimeType: codemirrorMimeType$5,
29207 languageId: languageId$9,
29211 var name$b = "TypeScript";
29212 var type$a = "programming";
29213 var color$4 = "#2b7489";
29217 var interpreters$1 = [
29221 var extensions$a = [
29224 var tmScope$a = "source.ts";
29225 var aceMode$a = "typescript";
29226 var codemirrorMode$6 = "javascript";
29227 var codemirrorMimeType$6 = "application/typescript";
29228 var languageId$a = 378;
29233 aliases: aliases$3,
29234 interpreters: interpreters$1,
29235 extensions: extensions$a,
29236 tmScope: tmScope$a,
29237 aceMode: aceMode$a,
29238 codemirrorMode: codemirrorMode$6,
29239 codemirrorMimeType: codemirrorMimeType$6,
29240 languageId: languageId$a
29243 var TypeScript$1 = /*#__PURE__*/Object.freeze({
29248 aliases: aliases$3,
29249 interpreters: interpreters$1,
29250 extensions: extensions$a,
29251 tmScope: tmScope$a,
29252 aceMode: aceMode$a,
29253 codemirrorMode: codemirrorMode$6,
29254 codemirrorMimeType: codemirrorMimeType$6,
29255 languageId: languageId$a,
29256 'default': TypeScript
29259 var name$c = "TSX";
29260 var type$b = "programming";
29261 var group$d = "TypeScript";
29262 var extensions$b = [
29265 var tmScope$b = "source.tsx";
29266 var aceMode$b = "javascript";
29267 var codemirrorMode$7 = "jsx";
29268 var codemirrorMimeType$7 = "text/jsx";
29269 var languageId$b = 94901924;
29274 extensions: extensions$b,
29275 tmScope: tmScope$b,
29276 aceMode: aceMode$b,
29277 codemirrorMode: codemirrorMode$7,
29278 codemirrorMimeType: codemirrorMimeType$7,
29279 languageId: languageId$b
29282 var TSX$1 = /*#__PURE__*/Object.freeze({
29287 extensions: extensions$b,
29288 tmScope: tmScope$b,
29289 aceMode: aceMode$b,
29290 codemirrorMode: codemirrorMode$7,
29291 codemirrorMimeType: codemirrorMimeType$7,
29292 languageId: languageId$b,
29296 var name$d = "JSON";
29297 var type$c = "data";
29298 var tmScope$c = "source.json";
29299 var aceMode$c = "json";
29300 var codemirrorMode$8 = "javascript";
29301 var codemirrorMimeType$8 = "application/json";
29302 var searchable = false;
29303 var extensions$c = [
29310 ".JSON-tmLanguage",
29321 var filenames$1 = [
29330 var languageId$c = 174;
29334 tmScope: tmScope$c,
29335 aceMode: aceMode$c,
29336 codemirrorMode: codemirrorMode$8,
29337 codemirrorMimeType: codemirrorMimeType$8,
29338 searchable: searchable,
29339 extensions: extensions$c,
29340 filenames: filenames$1,
29341 languageId: languageId$c
29344 var _JSON$1 = /*#__PURE__*/Object.freeze({
29348 tmScope: tmScope$c,
29349 aceMode: aceMode$c,
29350 codemirrorMode: codemirrorMode$8,
29351 codemirrorMimeType: codemirrorMimeType$8,
29352 searchable: searchable,
29353 extensions: extensions$c,
29354 filenames: filenames$1,
29355 languageId: languageId$c,
29359 var name$e = "JSON with Comments";
29360 var type$d = "data";
29361 var group$e = "JSON";
29362 var tmScope$d = "source.js";
29363 var aceMode$d = "javascript";
29364 var codemirrorMode$9 = "javascript";
29365 var codemirrorMimeType$9 = "text/javascript";
29369 var extensions$d = [
29371 ".sublime-commands",
29372 ".sublime-completions",
29376 ".sublime-mousemap",
29377 ".sublime-project",
29378 ".sublime-settings",
29380 ".sublime-workspace",
29381 ".sublime_metrics",
29384 var filenames$2 = [
29391 "language-configuration.json",
29394 var languageId$d = 423;
29395 var JSON_with_Comments = {
29399 tmScope: tmScope$d,
29400 aceMode: aceMode$d,
29401 codemirrorMode: codemirrorMode$9,
29402 codemirrorMimeType: codemirrorMimeType$9,
29403 aliases: aliases$4,
29404 extensions: extensions$d,
29405 filenames: filenames$2,
29406 languageId: languageId$d
29409 var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
29414 tmScope: tmScope$d,
29415 aceMode: aceMode$d,
29416 codemirrorMode: codemirrorMode$9,
29417 codemirrorMimeType: codemirrorMimeType$9,
29418 aliases: aliases$4,
29419 extensions: extensions$d,
29420 filenames: filenames$2,
29421 languageId: languageId$d,
29422 'default': JSON_with_Comments
29425 var name$f = "JSON5";
29426 var type$e = "data";
29427 var extensions$e = [
29430 var tmScope$e = "source.js";
29431 var aceMode$e = "javascript";
29432 var codemirrorMode$a = "javascript";
29433 var codemirrorMimeType$a = "application/json";
29434 var languageId$e = 175;
29438 extensions: extensions$e,
29439 tmScope: tmScope$e,
29440 aceMode: aceMode$e,
29441 codemirrorMode: codemirrorMode$a,
29442 codemirrorMimeType: codemirrorMimeType$a,
29443 languageId: languageId$e
29446 var JSON5$1 = /*#__PURE__*/Object.freeze({
29450 extensions: extensions$e,
29451 tmScope: tmScope$e,
29452 aceMode: aceMode$e,
29453 codemirrorMode: codemirrorMode$a,
29454 codemirrorMimeType: codemirrorMimeType$a,
29455 languageId: languageId$e,
29459 var require$$0$6 = getCjsExportFromNamespace(JavaScript$1);
29461 var require$$1$2 = getCjsExportFromNamespace(JSX$1);
29463 var require$$2$1 = getCjsExportFromNamespace(TypeScript$1);
29465 var require$$3$1 = getCjsExportFromNamespace(TSX$1);
29467 var require$$4 = getCjsExportFromNamespace(_JSON$1);
29469 var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
29471 var require$$6 = getCjsExportFromNamespace(JSON5$1);
29473 var languages$4 = [createLanguage(require$$0$6, function (data) {
29474 return Object.assign(data, {
29476 parsers: ["babel", "flow"],
29477 vscodeLanguageIds: ["javascript", "mongo"],
29478 interpreters: data.interpreters.concat(["nodejs"])
29480 }), createLanguage(require$$0$6, function (data) {
29481 return Object.assign(data, {
29484 parsers: ["babel", "flow"],
29485 vscodeLanguageIds: ["javascript"],
29488 extensions: [".js.flow"]
29490 }), createLanguage(require$$1$2, function (data) {
29491 return Object.assign(data, {
29493 parsers: ["babel", "flow"],
29494 vscodeLanguageIds: ["javascriptreact"]
29496 }), createLanguage(require$$2$1, function (data) {
29497 return Object.assign(data, {
29499 parsers: ["typescript"],
29500 vscodeLanguageIds: ["typescript"]
29502 }), createLanguage(require$$3$1, function (data) {
29503 return Object.assign(data, {
29505 parsers: ["typescript"],
29506 vscodeLanguageIds: ["typescriptreact"]
29508 }), createLanguage(require$$4, function (data) {
29509 return Object.assign(data, {
29510 name: "JSON.stringify",
29512 parsers: ["json-stringify"],
29513 vscodeLanguageIds: ["json"],
29515 // .json file defaults to json instead of json-stringify
29516 filenames: ["package.json", "package-lock.json", "composer.json"]
29518 }), createLanguage(require$$4, function (data) {
29519 return Object.assign(data, {
29522 vscodeLanguageIds: ["json"],
29523 filenames: data.filenames.concat([".prettierrc"])
29525 }), createLanguage(require$$5, function (data) {
29526 return Object.assign(data, {
29529 vscodeLanguageIds: ["jsonc"],
29530 filenames: data.filenames.concat([".eslintrc"])
29532 }), createLanguage(require$$6, function (data) {
29533 return Object.assign(data, {
29535 parsers: ["json5"],
29536 vscodeLanguageIds: ["json5"]
29540 estree: printerEstree,
29541 "estree-json": printerEstreeJson
29544 languages: languages$4,
29545 options: options$5,
29546 printers: printers$4
29550 "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]",
29551 "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]",
29552 "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]"
29555 var cjkPattern = json$1.cjkPattern,
29556 kPattern = json$1.kPattern,
29557 punctuationPattern = json$1.punctuationPattern;
29558 var getLast$3 = util.getLast;
29559 var INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
29560 var INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
29561 var kRegex = new RegExp(kPattern);
29562 var punctuationRegex = new RegExp(punctuationPattern);
29564 * split text into whitespaces and words
29565 * @param {string} text
29566 * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
29569 function splitText(text, options) {
29570 var KIND_NON_CJK = "non-cjk";
29571 var KIND_CJ_LETTER = "cj-letter";
29572 var KIND_K_LETTER = "k-letter";
29573 var KIND_CJK_PUNCTUATION = "cjk-punctuation";
29575 (options.proseWrap === "preserve" ? text : text.replace(new RegExp("(".concat(cjkPattern, ")\n(").concat(cjkPattern, ")"), "g"), "$1$2")).split(/([ \t\n]+)/).forEach(function (token, index, tokens) {
29577 if (index % 2 === 1) {
29579 type: "whitespace",
29580 value: /\n/.test(token) ? "\n" : " "
29583 } // word separated by whitespace
29586 if ((index === 0 || index === tokens.length - 1) && token === "") {
29590 token.split(new RegExp("(".concat(cjkPattern, ")"))).forEach(function (innerToken, innerIndex, innerTokens) {
29591 if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
29596 if (innerIndex % 2 === 0) {
29597 if (innerToken !== "") {
29601 kind: KIND_NON_CJK,
29602 hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
29603 hasTrailingPunctuation: punctuationRegex.test(getLast$3(innerToken))
29611 appendNode(punctuationRegex.test(innerToken) ? {
29614 kind: KIND_CJK_PUNCTUATION,
29615 hasLeadingPunctuation: true,
29616 hasTrailingPunctuation: true
29620 kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
29621 hasLeadingPunctuation: false,
29622 hasTrailingPunctuation: false
29628 function appendNode(node) {
29629 var lastNode = getLast$3(nodes);
29631 if (lastNode && lastNode.type === "word") {
29632 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) {
29634 type: "whitespace",
29637 } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
29638 ![lastNode.value, node.value].some(function (value) {
29639 return /\u3000/.test(value);
29642 type: "whitespace",
29650 function isBetween(kind1, kind2) {
29651 return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
29656 function getOrderedListItemInfo(orderListItem, originalText) {
29657 var _originalText$slice$m = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/),
29658 _originalText$slice$m2 = _slicedToArray(_originalText$slice$m, 4),
29659 numberText = _originalText$slice$m2[1],
29660 marker = _originalText$slice$m2[2],
29661 leadingSpaces = _originalText$slice$m2[3];
29664 numberText: numberText,
29666 leadingSpaces: leadingSpaces
29668 } // workaround for https://github.com/remarkjs/remark/issues/351
29669 // leading and trailing newlines are stripped by remark
29672 function getFencedCodeBlockValue(node, originalText) {
29673 var text = originalText.slice(node.position.start.offset, node.position.end.offset);
29674 var leadingSpaceCount = text.match(/^\s*/)[0].length;
29675 var replaceRegex = new RegExp("^\\s{0,".concat(leadingSpaceCount, "}"));
29676 var lineContents = text.split("\n");
29677 var markerStyle = text[leadingSpaceCount]; // ` or ~
29679 var marker = text.slice(leadingSpaceCount).match(new RegExp("^[".concat(markerStyle, "]+")))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
29680 // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
29682 var hasEndMarker = new RegExp("^\\s{0,3}".concat(marker)).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
29683 return lineContents.slice(1, hasEndMarker ? -1 : undefined).map(function (x, i) {
29684 return x.slice(getIndent(i + 1)).replace(replaceRegex, "");
29687 function getIndent(lineIndex) {
29688 return node.position.indent[lineIndex - 1] - 1;
29692 function mapAst(ast, handler) {
29693 return function preorder(node, index, parentStack) {
29694 parentStack = parentStack || [];
29695 var newNode = handler(node, index, parentStack);
29697 if (Array.isArray(newNode)) {
29701 newNode = Object.assign({}, newNode);
29703 if (newNode.children) {
29704 newNode.children = newNode.children.reduce(function (nodes, child, index) {
29705 var newNodes = preorder(child, index, [newNode].concat(parentStack));
29707 if (!Array.isArray(newNodes)) {
29708 newNodes = [newNodes];
29711 nodes.push.apply(nodes, newNodes);
29717 }(ast, null, null);
29722 splitText: splitText,
29723 punctuationPattern: punctuationPattern,
29724 getFencedCodeBlockValue: getFencedCodeBlockValue,
29725 getOrderedListItemInfo: getOrderedListItemInfo,
29726 INLINE_NODE_TYPES: INLINE_NODE_TYPES,
29727 INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES
29730 var _require$$0$builders$8 = doc.builders,
29731 hardline$b = _require$$0$builders$8.hardline,
29732 literalline$5 = _require$$0$builders$8.literalline,
29733 concat$f = _require$$0$builders$8.concat,
29734 markAsRoot$3 = _require$$0$builders$8.markAsRoot,
29735 mapDoc$6 = doc.utils.mapDoc;
29736 var getFencedCodeBlockValue$1 = utils$5.getFencedCodeBlockValue;
29738 function embed$4(path, print, textToDoc, options) {
29739 var node = path.getValue();
29741 if (node.type === "code" && node.lang !== null) {
29742 // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
29743 var langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
29744 var lang = langMatch ? langMatch[0] : "";
29745 var parser = getParserName(lang);
29748 var styleUnit = options.__inJsTemplate ? "~" : "`";
29749 var style = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
29750 var doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
29753 return markAsRoot$3(concat$f([style, node.lang, hardline$b, replaceNewlinesWithLiterallines(doc), style]));
29757 if (node.type === "yaml") {
29758 return markAsRoot$3(concat$f(["---", hardline$b, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
29760 })) : "", "---"]));
29764 switch (node.type) {
29765 case "importExport":
29766 return textToDoc(node.value, {
29771 return textToDoc(node.value, {
29772 parser: "__js_expression"
29778 function getParserName(lang) {
29779 var supportInfo = support.getSupportInfo(null, {
29780 plugins: options.plugins
29782 var language = supportInfo.languages.find(function (language) {
29783 return language.name.toLowerCase() === lang || language.aliases && language.aliases.indexOf(lang) !== -1 || language.extensions && language.extensions.find(function (ext) {
29784 return ext.substring(1) === lang;
29789 return language.parsers[0];
29795 function replaceNewlinesWithLiterallines(doc) {
29796 return mapDoc$6(doc, function (currentDoc) {
29797 return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$f(currentDoc.split(/(\n)/g).map(function (v, i) {
29798 return i % 2 === 0 ? v : literalline$5;
29804 var embed_1$2 = embed$4;
29806 var pragmas = ["format", "prettier"];
29808 function startWithPragma(text) {
29809 var pragma = "@(".concat(pragmas.join("|"), ")");
29810 var regex = new RegExp(["<!--\\s*".concat(pragma, "\\s*-->"), "<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*".concat(pragma, "[^\\S\n]*($|\n)[\\s\\S]*\n.*-->")].join("|"), "m");
29811 var matched = text.match(regex);
29812 return matched && matched.index === 0;
29816 startWithPragma: startWithPragma,
29817 hasPragma: function hasPragma(text) {
29818 return startWithPragma(frontMatter(text).content.trimLeft());
29820 insertPragma: function insertPragma(text) {
29821 var extracted = frontMatter(text);
29822 var pragma = "<!-- @".concat(pragmas[0], " -->");
29823 return extracted.frontMatter ? "".concat(extracted.frontMatter.raw, "\n\n").concat(pragma, "\n\n").concat(extracted.content) : "".concat(pragma, "\n\n").concat(extracted.content);
29827 var getOrderedListItemInfo$1 = utils$5.getOrderedListItemInfo,
29828 mapAst$1 = utils$5.mapAst,
29829 splitText$1 = utils$5.splitText; // 0x0 ~ 0x10ffff
29830 // eslint-disable-next-line no-control-regex
29832 var isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
29834 function preprocess$2(ast, options) {
29835 ast = restoreUnescapedCharacter(ast, options);
29836 ast = mergeContinuousTexts(ast);
29837 ast = transformInlineCode(ast);
29838 ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
29839 ast = markAlignedList(ast, options);
29840 ast = splitTextIntoSentences(ast, options);
29841 ast = transformImportExport(ast);
29842 ast = mergeContinuousImportExport(ast);
29846 function transformImportExport(ast) {
29847 return mapAst$1(ast, function (node) {
29848 if (node.type !== "import" && node.type !== "export") {
29852 return Object.assign({}, node, {
29853 type: "importExport"
29858 function transformInlineCode(ast) {
29859 return mapAst$1(ast, function (node) {
29860 if (node.type !== "inlineCode") {
29864 return Object.assign({}, node, {
29865 value: node.value.replace(/\s+/g, " ")
29870 function restoreUnescapedCharacter(ast, options) {
29871 return mapAst$1(ast, function (node) {
29872 return node.type !== "text" ? node : Object.assign({}, node, {
29873 value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
29874 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
29879 function mergeContinuousImportExport(ast) {
29880 return mergeChildren(ast, function (prevNode, node) {
29881 return prevNode.type === "importExport" && node.type === "importExport";
29882 }, function (prevNode, node) {
29884 type: "importExport",
29885 value: prevNode.value + "\n\n" + node.value,
29887 start: prevNode.position.start,
29888 end: node.position.end
29894 function mergeChildren(ast, shouldMerge, mergeNode) {
29895 return mapAst$1(ast, function (node) {
29896 if (!node.children) {
29900 var children = node.children.reduce(function (current, child) {
29901 var lastChild = current[current.length - 1];
29903 if (lastChild && shouldMerge(lastChild, child)) {
29904 current.splice(-1, 1, mergeNode(lastChild, child));
29906 current.push(child);
29911 return Object.assign({}, node, {
29917 function mergeContinuousTexts(ast) {
29918 return mergeChildren(ast, function (prevNode, node) {
29919 return prevNode.type === "text" && node.type === "text";
29920 }, function (prevNode, node) {
29923 value: prevNode.value + node.value,
29925 start: prevNode.position.start,
29926 end: node.position.end
29932 function splitTextIntoSentences(ast, options) {
29933 return mapAst$1(ast, function (node, index, _ref) {
29934 var _ref2 = _slicedToArray(_ref, 1),
29935 parentNode = _ref2[0];
29937 if (node.type !== "text") {
29941 var value = node.value;
29943 if (parentNode.type === "paragraph") {
29945 value = value.trimLeft();
29948 if (index === parentNode.children.length - 1) {
29949 value = value.trimRight();
29955 position: node.position,
29956 children: splitText$1(value, options)
29961 function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
29962 return mapAst$1(ast, function (node, index, parentStack) {
29963 if (node.type === "code") {
29964 // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
29965 var isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
29966 node.isIndented = isIndented;
29969 for (var i = 0; i < parentStack.length; i++) {
29970 var parent = parentStack[i]; // no need to check checked items
29972 if (parent.hasIndentedCodeblock) {
29976 if (parent.type === "list") {
29977 parent.hasIndentedCodeblock = true;
29987 function markAlignedList(ast, options) {
29988 return mapAst$1(ast, function (node, index, parentStack) {
29989 if (node.type === "list" && node.children.length !== 0) {
29990 // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
29991 for (var i = 0; i < parentStack.length; i++) {
29992 var parent = parentStack[i];
29994 if (parent.type === "list" && !parent.isAligned) {
29995 node.isAligned = false;
30000 node.isAligned = isAligned(node);
30006 function getListItemStart(listItem) {
30007 return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
30010 function isAligned(list) {
30011 if (!list.ordered) {
30019 var _list$children = _slicedToArray(list.children, 2),
30020 firstItem = _list$children[0],
30021 secondItem = _list$children[1];
30023 var firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
30025 if (firstInfo.leadingSpaces.length > 1) {
30035 var firstStart = getListItemStart(firstItem);
30037 if (firstStart === -1) {
30047 if (list.children.length === 1) {
30057 return firstStart % options.tabWidth === 0;
30060 var secondStart = getListItemStart(secondItem);
30062 if (firstStart !== secondStart) {
30073 if (firstStart % options.tabWidth === 0) {
30093 var secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
30094 return secondInfo.leadingSpaces.length > 1;
30098 var preprocess_1$2 = preprocess$2;
30100 var _require$$0$builders$9 = doc.builders,
30101 breakParent$4 = _require$$0$builders$9.breakParent,
30102 concat$g = _require$$0$builders$9.concat,
30103 join$b = _require$$0$builders$9.join,
30104 line$8 = _require$$0$builders$9.line,
30105 literalline$6 = _require$$0$builders$9.literalline,
30106 markAsRoot$4 = _require$$0$builders$9.markAsRoot,
30107 hardline$c = _require$$0$builders$9.hardline,
30108 softline$7 = _require$$0$builders$9.softline,
30109 ifBreak$7 = _require$$0$builders$9.ifBreak,
30110 fill$5 = _require$$0$builders$9.fill,
30111 align$2 = _require$$0$builders$9.align,
30112 indent$9 = _require$$0$builders$9.indent,
30113 group$f = _require$$0$builders$9.group,
30114 mapDoc$7 = doc.utils.mapDoc,
30115 printDocToString$2 = doc.printer.printDocToString;
30116 var getFencedCodeBlockValue$2 = utils$5.getFencedCodeBlockValue,
30117 getOrderedListItemInfo$2 = utils$5.getOrderedListItemInfo,
30118 splitText$2 = utils$5.splitText,
30119 punctuationPattern$1 = utils$5.punctuationPattern,
30120 INLINE_NODE_TYPES$1 = utils$5.INLINE_NODE_TYPES,
30121 INLINE_NODE_WRAPPER_TYPES$1 = utils$5.INLINE_NODE_WRAPPER_TYPES;
30122 var replaceEndOfLineWith$2 = util.replaceEndOfLineWith;
30123 var TRAILING_HARDLINE_NODES = ["importExport"];
30124 var SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
30125 var SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition", "jsx"];
30127 function genericPrint$5(path, options, print) {
30128 var node = path.getValue();
30130 if (shouldRemainTheSameContent(path)) {
30131 return concat$g(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(function (node) {
30132 return node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options);
30136 switch (node.type) {
30138 if (node.children.length === 0) {
30142 return concat$g([normalizeDoc(printRoot(path, options, print)), TRAILING_HARDLINE_NODES.indexOf(getLastDescendantNode(node).type) === -1 ? hardline$c : ""]);
30145 return printChildren$2(path, options, print, {
30146 postprocessor: fill$5
30150 return printChildren$2(path, options, print);
30153 return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
30154 .replace(new RegExp(["(^|".concat(punctuationPattern$1, ")(_+)"), "(_+)(".concat(punctuationPattern$1, "|$)")].join("|"), "g"), function (_, text1, underscore1, underscore2, text2) {
30155 return (underscore1 ? "".concat(text1).concat(underscore1) : "".concat(underscore2).concat(text2)).replace(/_/g, "\\_");
30157 // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
30161 var parentNode = path.getParentNode();
30162 var index = parentNode.children.indexOf(node);
30163 var nextNode = parentNode.children[index + 1];
30164 var proseWrap = // leading char that may cause different syntax
30165 nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
30166 return printLine(path, node.value, {
30167 proseWrap: proseWrap
30173 var _parentNode = path.getParentNode();
30175 var _index = _parentNode.children.indexOf(node);
30177 var prevNode = _parentNode.children[_index - 1];
30178 var _nextNode = _parentNode.children[_index + 1];
30179 var hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
30180 prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util.getLast(prevNode.children).type === "word" && !util.getLast(prevNode.children).hasTrailingPunctuation || _nextNode && _nextNode.type === "sentence" && _nextNode.children.length > 0 && _nextNode.children[0].type === "word" && !_nextNode.children[0].hasLeadingPunctuation;
30181 var style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
30182 return concat$g([style, printChildren$2(path, options, print), style]);
30186 return concat$g(["**", printChildren$2(path, options, print), "**"]);
30189 return concat$g(["~~", printChildren$2(path, options, print), "~~"]);
30193 var backtickCount = util.getMinNotPresentContinuousCount(node.value, "`");
30195 var _style = "`".repeat(backtickCount || 1);
30197 var gap = backtickCount ? " " : "";
30198 return concat$g([_style, gap, node.value, gap, _style]);
30202 switch (options.originalText[node.position.start.offset]) {
30205 var mailto = "mailto:";
30206 var url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
30207 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;
30208 return concat$g(["<", url, ">"]);
30212 return concat$g(["[", printChildren$2(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
30215 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
30219 return concat$g(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
30222 return concat$g(["> ", align$2("> ", printChildren$2(path, options, print))]);
30225 return concat$g(["#".repeat(node.depth) + " ", printChildren$2(path, options, print)]);
30229 if (node.isIndented) {
30230 // indented code block
30231 var alignment = " ".repeat(4);
30232 return align$2(alignment, concat$g([alignment, concat$g(replaceEndOfLineWith$2(node.value, hardline$c))]));
30233 } // fenced code block
30236 var styleUnit = options.__inJsTemplate ? "~" : "`";
30238 var _style2 = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
30240 return concat$g([_style2, node.lang || "", hardline$c, concat$g(replaceEndOfLineWith$2(getFencedCodeBlockValue$2(node, options.originalText), hardline$c)), hardline$c, _style2]);
30245 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
30249 var _parentNode2 = path.getParentNode();
30251 var value = _parentNode2.type === "root" && util.getLast(_parentNode2.children) === node ? node.value.trimRight() : node.value;
30252 var isHtmlComment = /^<!--[\s\S]*-->$/.test(value);
30253 return concat$g(replaceEndOfLineWith$2(value, isHtmlComment ? hardline$c : markAsRoot$4(literalline$6)));
30258 var nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
30259 var isGitDiffFriendlyOrderedList = node.ordered && node.children.length > 1 && +getOrderedListItemInfo$2(node.children[1], options.originalText).numberText === 1;
30260 return printChildren$2(path, options, print, {
30261 processor: function processor(childPath, index) {
30262 var prefix = getPrefix();
30263 return concat$g([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
30265 function getPrefix() {
30266 var rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
30267 return node.isAligned ||
30268 /* workaround for https://github.com/remarkjs/remark/issues/315 */
30269 node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
30275 case "thematicBreak":
30277 var counter = getAncestorCounter$1(path, "list");
30279 if (counter === -1) {
30283 var _nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
30285 return _nthSiblingIndex % 2 === 0 ? "***" : "---";
30288 case "linkReference":
30289 return concat$g(["[", printChildren$2(path, options, print), "]", node.referenceType === "full" ? concat$g(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
30291 case "imageReference":
30292 switch (node.referenceType) {
30294 return concat$g(["![", node.alt || "", "][", node.identifier, "]"]);
30297 return concat$g(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
30302 var lineOrSpace = options.proseWrap === "always" ? line$8 : " ";
30303 return group$f(concat$g([concat$g(["[", node.identifier, "]:"]), indent$9(concat$g([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$g([lineOrSpace, printTitle(node.title, options, false)])]))]));
30307 return concat$g(["[^", printChildren$2(path, options, print), "]"]);
30309 case "footnoteReference":
30310 return concat$g(["[^", node.identifier, "]"]);
30312 case "footnoteDefinition":
30314 var _nextNode2 = path.getParentNode().children[path.getName() + 1];
30315 var 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);
30316 return concat$g(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$2(path, options, print) : group$f(concat$g([align$2(" ".repeat(options.tabWidth), printChildren$2(path, options, print, {
30317 processor: function processor(childPath, index) {
30318 return index === 0 ? group$f(concat$g([softline$7, softline$7, childPath.call(print)])) : childPath.call(print);
30320 })), _nextNode2 && _nextNode2.type === "footnoteDefinition" ? softline$7 : ""]))]);
30324 return printTable(path, options, print);
30327 return printChildren$2(path, options, print);
30330 return /\s/.test(options.originalText[node.position.start.offset]) ? concat$g([" ", markAsRoot$4(literalline$6)]) : concat$g(["\\", hardline$c]);
30333 return concat$g(replaceEndOfLineWith$2(node.value, hardline$c));
30336 case "importExport":
30339 // fallback to the original text if multiparser failed
30342 return concat$g(["$$", hardline$c, node.value ? concat$g([concat$g(replaceEndOfLineWith$2(node.value, hardline$c)), hardline$c]) : "", "$$"]);
30346 // remark-math trims content but we don't want to remove whitespaces
30347 // since it's very possible that it's recognized as math accidentally
30348 return options.originalText.slice(options.locStart(node), options.locEnd(node));
30351 case "tableRow": // handled in "table"
30353 case "listItem": // handled in "list"
30356 throw new Error("Unknown markdown type ".concat(JSON.stringify(node.type)));
30360 function printListItem(path, options, print, listPrefix) {
30361 var node = path.getValue();
30362 var prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
30363 return concat$g([prefix, printChildren$2(path, options, print, {
30364 processor: function processor(childPath, index) {
30365 if (index === 0 && childPath.getValue().type !== "list") {
30366 return align$2(" ".repeat(prefix.length), childPath.call(print));
30369 var alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
30371 return concat$g([alignment, align$2(alignment, childPath.call(print))]);
30376 function alignListPrefix(prefix, options) {
30377 var additionalSpaces = getAdditionalSpaces();
30378 return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
30381 function getAdditionalSpaces() {
30382 var restSpaces = prefix.length % options.tabWidth;
30383 return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
30387 function getNthListSiblingIndex(node, parentNode) {
30388 return getNthSiblingIndex(node, parentNode, function (siblingNode) {
30389 return siblingNode.ordered === node.ordered;
30393 function getNthSiblingIndex(node, parentNode, condition) {
30394 condition = condition || function () {
30399 var _iteratorNormalCompletion = true;
30400 var _didIteratorError = false;
30401 var _iteratorError = undefined;
30404 for (var _iterator = parentNode.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
30405 var childNode = _step.value;
30407 if (childNode.type === node.type && condition(childNode)) {
30413 if (childNode === node) {
30418 _didIteratorError = true;
30419 _iteratorError = err;
30422 if (!_iteratorNormalCompletion && _iterator.return != null) {
30423 _iterator.return();
30426 if (_didIteratorError) {
30427 throw _iteratorError;
30433 function getAncestorCounter$1(path, typeOrTypes) {
30434 var types = [].concat(typeOrTypes);
30438 while (ancestorNode = path.getParentNode(++counter)) {
30439 if (types.indexOf(ancestorNode.type) !== -1) {
30447 function getAncestorNode$2(path, typeOrTypes) {
30448 var counter = getAncestorCounter$1(path, typeOrTypes);
30449 return counter === -1 ? null : path.getParentNode(counter);
30452 function printLine(path, value, options) {
30453 if (options.proseWrap === "preserve" && value === "\n") {
30457 var isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
30458 return value !== "" ? isBreakable ? line$8 : " " : isBreakable ? softline$7 : "";
30461 function printTable(path, options, print) {
30462 var hardlineWithoutBreakParent = hardline$c.parts[0];
30463 var node = path.getValue();
30464 var contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
30466 path.map(function (rowPath) {
30467 var rowContents = [];
30468 rowPath.map(function (cellPath) {
30469 rowContents.push(printDocToString$2(cellPath.call(print), options).formatted);
30471 contents.push(rowContents);
30472 }, "children"); // Get the width of each column
30474 var columnMaxWidths = contents.reduce(function (currentWidths, rowContents) {
30475 return currentWidths.map(function (width, columnIndex) {
30476 return Math.max(width, util.getStringWidth(rowContents[columnIndex]));
30478 }, contents[0].map(function () {
30480 }) // minimum width = 3 (---, :--, :-:, --:)
30482 var alignedTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$b(hardlineWithoutBreakParent, contents.slice(1).map(function (rowContents) {
30483 return printRow(rowContents);
30486 if (options.proseWrap !== "never") {
30487 return concat$g([breakParent$4, alignedTable]);
30488 } // Only if the --prose-wrap never is set and it exceeds the print width.
30491 var compactTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0],
30493 true), printSeparator(
30495 true), join$b(hardlineWithoutBreakParent, contents.slice(1).map(function (rowContents) {
30496 return printRow(rowContents,
30500 return concat$g([breakParent$4, group$f(ifBreak$7(compactTable, alignedTable))]);
30502 function printSeparator(isCompact) {
30503 return concat$g(["| ", join$b(" | ", columnMaxWidths.map(function (width, index) {
30504 var spaces = isCompact ? 3 : width;
30506 switch (node.align[index]) {
30508 return ":" + "-".repeat(spaces - 1);
30511 return "-".repeat(spaces - 1) + ":";
30514 return ":" + "-".repeat(spaces - 2) + ":";
30517 return "-".repeat(spaces);
30522 function printRow(rowContents, isCompact) {
30523 return concat$g(["| ", join$b(" | ", isCompact ? rowContents : rowContents.map(function (rowContent, columnIndex) {
30524 switch (node.align[columnIndex]) {
30526 return alignRight(rowContent, columnMaxWidths[columnIndex]);
30529 return alignCenter(rowContent, columnMaxWidths[columnIndex]);
30532 return alignLeft(rowContent, columnMaxWidths[columnIndex]);
30537 function alignLeft(text, width) {
30538 var spaces = width - util.getStringWidth(text);
30539 return concat$g([text, " ".repeat(spaces)]);
30542 function alignRight(text, width) {
30543 var spaces = width - util.getStringWidth(text);
30544 return concat$g([" ".repeat(spaces), text]);
30547 function alignCenter(text, width) {
30548 var spaces = width - util.getStringWidth(text);
30549 var left = Math.floor(spaces / 2);
30550 var right = spaces - left;
30551 return concat$g([" ".repeat(left), text, " ".repeat(right)]);
30555 function printRoot(path, options, print) {
30556 /** @typedef {{ index: number, offset: number }} IgnorePosition */
30558 /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
30559 var ignoreRanges = [];
30560 /** @type {IgnorePosition | null} */
30562 var ignoreStart = null;
30563 var children = path.getValue().children;
30564 children.forEach(function (childNode, index) {
30565 switch (isPrettierIgnore$1(childNode)) {
30567 if (ignoreStart === null) {
30570 offset: childNode.position.end.offset
30577 if (ignoreStart !== null) {
30578 ignoreRanges.push({
30579 start: ignoreStart,
30582 offset: childNode.position.start.offset
30585 ignoreStart = null;
30591 return printChildren$2(path, options, print, {
30592 processor: function processor(childPath, index) {
30593 if (ignoreRanges.length !== 0) {
30594 var ignoreRange = ignoreRanges[0];
30596 if (index === ignoreRange.start.index) {
30597 return concat$g([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
30600 if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
30604 if (index === ignoreRange.end.index) {
30605 ignoreRanges.shift();
30610 return childPath.call(print);
30615 function printChildren$2(path, options, print, events) {
30616 events = events || {};
30617 var postprocessor = events.postprocessor || concat$g;
30619 var processor = events.processor || function (childPath) {
30620 return childPath.call(print);
30623 var node = path.getValue();
30626 path.map(function (childPath, index) {
30627 var childNode = childPath.getValue();
30628 var result = processor(childPath, index);
30630 if (result !== false) {
30633 prevNode: lastChildNode,
30638 if (!shouldNotPrePrintHardline(childNode, data)) {
30639 parts.push(hardline$c);
30641 if (lastChildNode && TRAILING_HARDLINE_NODES.indexOf(lastChildNode.type) !== -1) {
30642 if (shouldPrePrintTripleHardline(childNode, data)) {
30643 parts.push(hardline$c);
30646 if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
30647 parts.push(hardline$c);
30650 if (shouldPrePrintTripleHardline(childNode, data)) {
30651 parts.push(hardline$c);
30656 parts.push(result);
30657 lastChildNode = childNode;
30660 return postprocessor(parts);
30663 function getLastDescendantNode(node) {
30664 var current = node;
30666 while (current.children && current.children.length !== 0) {
30667 current = current.children[current.children.length - 1];
30672 /** @return {false | 'next' | 'start' | 'end'} */
30675 function isPrettierIgnore$1(node) {
30676 if (node.type !== "html") {
30680 var match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
30681 return match === null ? false : match[1] ? match[1] : "next";
30684 function isInlineNode(node) {
30685 return node && INLINE_NODE_TYPES$1.indexOf(node.type) !== -1;
30688 function isEndsWithHardLine(node) {
30689 return node && /\n+$/.test(node.value);
30692 function last(nodes) {
30693 return nodes && nodes[nodes.length - 1];
30696 function shouldNotPrePrintHardline(node, _ref) {
30697 var parentNode = _ref.parentNode,
30698 parts = _ref.parts,
30699 prevNode = _ref.prevNode;
30700 var isFirstNode = parts.length === 0;
30701 var isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.indexOf(parentNode.type) !== -1;
30702 var isAfterHardlineNode = prevNode && (isEndsWithHardLine(prevNode) || isEndsWithHardLine(last(prevNode.children)));
30703 return isFirstNode || isInlineNode(node) || isInlineHTML || isAfterHardlineNode;
30706 function shouldPrePrintDoubleHardline(node, _ref2) {
30707 var parentNode = _ref2.parentNode,
30708 prevNode = _ref2.prevNode;
30709 var prevNodeType = prevNode && prevNode.type;
30710 var nodeType = node.type;
30711 var isSequence = prevNodeType === nodeType;
30712 var isSiblingNode = isSequence && SIBLING_NODE_TYPES.indexOf(nodeType) !== -1;
30713 var isInTightListItem = parentNode.type === "listItem" && !parentNode.loose;
30714 var isPrevNodeLooseListItem = prevNodeType === "listItem" && prevNode.loose;
30715 var isPrevNodePrettierIgnore = isPrettierIgnore$1(prevNode) === "next";
30716 var isBlockHtmlWithoutBlankLineBetweenPrevHtml = nodeType === "html" && prevNodeType === "html" && prevNode.position.end.line + 1 === node.position.start.line;
30717 var isJsxInlineSibling = prevNodeType === "jsx" && isInlineNode(node) || nodeType === "jsx" && isInlineNode(prevNode);
30718 return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isJsxInlineSibling);
30721 function shouldPrePrintTripleHardline(node, data) {
30722 var isPrevNodeList = data.prevNode && data.prevNode.type === "list";
30723 var isIndentedCode = node.type === "code" && node.isIndented;
30724 return isPrevNodeList && isIndentedCode;
30727 function shouldRemainTheSameContent(path) {
30728 var ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
30729 return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
30732 function normalizeDoc(doc) {
30733 return mapDoc$7(doc, function (currentDoc) {
30734 if (!currentDoc.parts) {
30738 if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
30739 return currentDoc.parts[0];
30743 currentDoc.parts.forEach(function (part) {
30744 if (part.type === "concat") {
30745 parts.push.apply(parts, part.parts);
30746 } else if (part !== "") {
30750 return Object.assign({}, currentDoc, {
30751 parts: normalizeParts$2(parts)
30756 function printUrl(url, dangerousCharOrChars) {
30757 var dangerousChars = [" "].concat(dangerousCharOrChars || []);
30758 return new RegExp(dangerousChars.map(function (x) {
30759 return "\\".concat(x);
30760 }).join("|")).test(url) ? "<".concat(url, ">") : url;
30763 function printTitle(title, options, printSpace) {
30764 if (printSpace == null) {
30773 return " " + printTitle(title, options, false);
30776 if (title.includes('"') && title.includes("'") && !title.includes(")")) {
30777 return "(".concat(title, ")"); // avoid escaped quotes
30778 } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
30781 var singleCount = title.split("'").length - 1;
30782 var doubleCount = title.split('"').length - 1;
30783 var quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
30784 title = title.replace(new RegExp("(".concat(quote, ")"), "g"), "\\$1");
30785 return "".concat(quote).concat(title).concat(quote);
30788 function normalizeParts$2(parts) {
30789 return parts.reduce(function (current, part) {
30790 var lastPart = util.getLast(current);
30792 if (typeof lastPart === "string" && typeof part === "string") {
30793 current.splice(-1, 1, lastPart + part);
30795 current.push(part);
30802 function clamp(value, min, max) {
30803 return value < min ? min : value > max ? max : value;
30806 function clean$6(ast, newObj, parent) {
30807 delete newObj.position;
30808 delete newObj.raw; // front-matter
30811 if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
30812 delete newObj.value;
30815 if (ast.type === "list") {
30816 delete newObj.isAligned;
30817 } // texts can be splitted or merged
30820 if (ast.type === "text") {
30824 if (ast.type === "inlineCode") {
30825 newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
30826 } // for insert pragma
30829 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$4.startWithPragma(ast.value)) {
30834 function hasPrettierIgnore$4(path) {
30835 var index = +path.getName();
30841 var prevNode = path.getParentNode().children[index - 1];
30842 return isPrettierIgnore$1(prevNode) === "next";
30845 var printerMarkdown = {
30846 preprocess: preprocess_1$2,
30847 print: genericPrint$5,
30849 massageAstNode: clean$6,
30850 hasPrettierIgnore: hasPrettierIgnore$4,
30851 insertPragma: pragma$4.insertPragma
30855 proseWrap: commonOptions.proseWrap,
30856 singleQuote: commonOptions.singleQuote
30859 var name$g = "Markdown";
30860 var type$f = "prose";
30864 var aceMode$f = "markdown";
30865 var codemirrorMode$b = "gfm";
30866 var codemirrorMimeType$b = "text/x-gfm";
30868 var extensions$f = [
30880 var filenames$3 = [
30883 var tmScope$f = "source.gfm";
30884 var languageId$f = 222;
30888 aliases: aliases$5,
30889 aceMode: aceMode$f,
30890 codemirrorMode: codemirrorMode$b,
30891 codemirrorMimeType: codemirrorMimeType$b,
30893 extensions: extensions$f,
30894 filenames: filenames$3,
30895 tmScope: tmScope$f,
30896 languageId: languageId$f
30899 var Markdown$1 = /*#__PURE__*/Object.freeze({
30903 aliases: aliases$5,
30904 aceMode: aceMode$f,
30905 codemirrorMode: codemirrorMode$b,
30906 codemirrorMimeType: codemirrorMimeType$b,
30908 extensions: extensions$f,
30909 filenames: filenames$3,
30910 tmScope: tmScope$f,
30911 languageId: languageId$f,
30912 'default': Markdown
30915 var require$$0$7 = getCjsExportFromNamespace(Markdown$1);
30917 var languages$5 = [createLanguage(require$$0$7, function (data) {
30918 return Object.assign(data, {
30920 parsers: ["remark"],
30921 vscodeLanguageIds: ["markdown"],
30922 filenames: data.filenames.concat(["README"]),
30923 extensions: data.extensions.filter(function (extension) {
30924 return extension !== ".mdx";
30927 }), createLanguage(require$$0$7, function (data) {
30928 return Object.assign(data, {
30932 vscodeLanguageIds: ["mdx"],
30934 extensions: [".mdx"]
30938 mdast: printerMarkdown
30940 var languageMarkdown = {
30941 languages: languages$5,
30942 options: options$6,
30943 printers: printers$5
30946 function isPragma(text) {
30947 return /^\s*@(prettier|format)\s*$/.test(text);
30950 function hasPragma$4(text) {
30951 return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
30954 function insertPragma$8(text) {
30955 return "# @format\n\n".concat(text);
30959 isPragma: isPragma,
30960 hasPragma: hasPragma$4,
30961 insertPragma: insertPragma$8
30964 var getLast$4 = util.getLast;
30966 function getAncestorCount(path, filter) {
30968 var pathStackLength = path.stack.length - 1;
30970 for (var i = 0; i < pathStackLength; i++) {
30971 var value = path.stack[i];
30973 if (isNode(value) && filter(value)) {
30981 * @param {any} value
30982 * @param {string[]=} types
30986 function isNode(value, types) {
30987 return value && typeof value.type === "string" && (!types || types.indexOf(value.type) !== -1);
30990 function mapNode(node, callback, parent) {
30991 return callback("children" in node ? Object.assign({}, node, {
30992 children: node.children.map(function (childNode) {
30993 return mapNode(childNode, callback, node);
30995 }) : node, parent);
30998 function defineShortcut(x, key, getter) {
30999 Object.defineProperty(x, key, {
31005 function isNextLineEmpty$5(node, text) {
31006 var newlineCount = 0;
31007 var textLength = text.length;
31009 for (var i = node.position.end.offset - 1; i < textLength; i++) {
31010 var char = text[i];
31012 if (char === "\n") {
31016 if (newlineCount === 1 && /\S/.test(char)) {
31020 if (newlineCount === 2) {
31028 function isLastDescendantNode(path) {
31029 var node = path.getValue();
31031 switch (node.type) {
31038 var pathStackLength = path.stack.length;
31040 for (var i = 1; i < pathStackLength; i++) {
31041 var item = path.stack[i];
31042 var parentItem = path.stack[i - 1];
31044 if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
31052 function getLastDescendantNode$1(node) {
31053 return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$4(node.children)) : node;
31056 function isPrettierIgnore$2(comment) {
31057 return comment.value.trim() === "prettier-ignore";
31060 function hasPrettierIgnore$5(path) {
31061 var node = path.getValue();
31063 if (node.type === "documentBody") {
31064 var document = path.getParentNode();
31065 return hasEndComments(document.head) && isPrettierIgnore$2(getLast$4(document.head.endComments));
31068 return hasLeadingComments(node) && isPrettierIgnore$2(getLast$4(node.leadingComments));
31071 function isEmptyNode(node) {
31072 return (!node.children || node.children.length === 0) && !hasComments(node);
31075 function hasComments(node) {
31076 return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$2(node) || hasEndComments(node);
31079 function hasLeadingComments(node) {
31080 return node && node.leadingComments && node.leadingComments.length !== 0;
31083 function hasMiddleComments(node) {
31084 return node && node.middleComments && node.middleComments.length !== 0;
31087 function hasIndicatorComment(node) {
31088 return node && node.indicatorComment;
31091 function hasTrailingComment$2(node) {
31092 return node && node.trailingComment;
31095 function hasEndComments(node) {
31096 return node && node.endComments && node.endComments.length !== 0;
31099 * " a b c d e f " -> [" a b", "c d", "e f "]
31103 function splitWithSingleSpace(text) {
31105 var lastPart = undefined;
31106 var _iteratorNormalCompletion = true;
31107 var _didIteratorError = false;
31108 var _iteratorError = undefined;
31111 for (var _iterator = text.split(/( +)/g)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
31112 var part = _step.value;
31114 if (part !== " ") {
31115 if (lastPart === " ") {
31118 parts.push((parts.pop() || "") + part);
31120 } else if (lastPart === undefined) {
31127 _didIteratorError = true;
31128 _iteratorError = err;
31131 if (!_iteratorNormalCompletion && _iterator.return != null) {
31132 _iterator.return();
31135 if (_didIteratorError) {
31136 throw _iteratorError;
31141 if (lastPart === " ") {
31142 parts.push((parts.pop() || "") + " ");
31145 if (parts[0] === "") {
31147 parts.unshift(" " + (parts.shift() || ""));
31153 function getFlowScalarLineContents(nodeType, content, options) {
31154 var rawLineContents = content.split("\n").map(function (lineContent, index, lineContents) {
31155 return index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimRight() : lineContent.trimLeft();
31158 if (options.proseWrap === "preserve") {
31159 return rawLineContents.map(function (lineContent) {
31160 return lineContent.length === 0 ? [] : [lineContent];
31164 return rawLineContents.map(function (lineContent) {
31165 return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
31166 }).reduce(function (reduced, lineContentWords, index) {
31167 return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
31168 nodeType === "quoteDouble" && getLast$4(getLast$4(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
31169 }, []).map(function (lineContentWords) {
31170 return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
31174 function getBlockValueLineContents(node, _ref) {
31175 var parentIndent = _ref.parentIndent,
31176 isLastDescendant = _ref.isLastDescendant,
31177 options = _ref.options;
31178 var content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
31179 .match(/^[^\n]*?\n([\s\S]*)$/)[1];
31180 var leadingSpaceCount = node.indent === null ? function (match) {
31181 return match ? match[1].length : Infinity;
31182 }(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
31183 var rawLineContents = content.split("\n").map(function (lineContent) {
31184 return lineContent.slice(leadingSpaceCount);
31187 if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
31188 return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
31189 return lineContent.length === 0 ? [] : [lineContent];
31193 return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
31194 return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
31195 }).reduce(function (reduced, lineContentWords, index) {
31196 return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$4(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
31197 }, []).map(function (lineContentWords) {
31198 return lineContentWords.reduce(function (reduced, word) {
31199 return (// disallow trailing spaces
31200 reduced.length !== 0 && /\s$/.test(getLast$4(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word)
31203 }).map(function (lineContentWords) {
31204 return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
31207 function removeUnnecessaryTrailingNewlines(lineContents) {
31208 if (node.chomping === "keep") {
31209 return getLast$4(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
31212 var trailingNewlineCount = 0;
31214 for (var i = lineContents.length - 1; i >= 0; i--) {
31215 if (lineContents[i].length === 0) {
31216 trailingNewlineCount++;
31222 return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
31223 lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
31228 getLast: getLast$4,
31229 getAncestorCount: getAncestorCount,
31231 isEmptyNode: isEmptyNode,
31233 defineShortcut: defineShortcut,
31234 isNextLineEmpty: isNextLineEmpty$5,
31235 isLastDescendantNode: isLastDescendantNode,
31236 getBlockValueLineContents: getBlockValueLineContents,
31237 getFlowScalarLineContents: getFlowScalarLineContents,
31238 getLastDescendantNode: getLastDescendantNode$1,
31239 hasPrettierIgnore: hasPrettierIgnore$5,
31240 hasLeadingComments: hasLeadingComments,
31241 hasMiddleComments: hasMiddleComments,
31242 hasIndicatorComment: hasIndicatorComment,
31243 hasTrailingComment: hasTrailingComment$2,
31244 hasEndComments: hasEndComments
31247 var insertPragma$9 = pragma$5.insertPragma,
31248 isPragma$1 = pragma$5.isPragma;
31249 var getAncestorCount$1 = utils$6.getAncestorCount,
31250 getBlockValueLineContents$1 = utils$6.getBlockValueLineContents,
31251 getFlowScalarLineContents$1 = utils$6.getFlowScalarLineContents,
31252 getLast$5 = utils$6.getLast,
31253 getLastDescendantNode$2 = utils$6.getLastDescendantNode,
31254 hasLeadingComments$1 = utils$6.hasLeadingComments,
31255 hasMiddleComments$1 = utils$6.hasMiddleComments,
31256 hasIndicatorComment$1 = utils$6.hasIndicatorComment,
31257 hasTrailingComment$3 = utils$6.hasTrailingComment,
31258 hasEndComments$1 = utils$6.hasEndComments,
31259 hasPrettierIgnore$6 = utils$6.hasPrettierIgnore,
31260 isLastDescendantNode$1 = utils$6.isLastDescendantNode,
31261 isNextLineEmpty$6 = utils$6.isNextLineEmpty,
31262 isNode$1 = utils$6.isNode,
31263 isEmptyNode$1 = utils$6.isEmptyNode,
31264 defineShortcut$1 = utils$6.defineShortcut,
31265 mapNode$1 = utils$6.mapNode;
31266 var docBuilders$2 = doc.builders;
31267 var conditionalGroup$2 = docBuilders$2.conditionalGroup,
31268 breakParent$5 = docBuilders$2.breakParent,
31269 concat$h = docBuilders$2.concat,
31270 dedent$3 = docBuilders$2.dedent,
31271 dedentToRoot$3 = docBuilders$2.dedentToRoot,
31272 fill$6 = docBuilders$2.fill,
31273 group$g = docBuilders$2.group,
31274 hardline$d = docBuilders$2.hardline,
31275 ifBreak$8 = docBuilders$2.ifBreak,
31276 join$c = docBuilders$2.join,
31277 line$9 = docBuilders$2.line,
31278 lineSuffix$2 = docBuilders$2.lineSuffix,
31279 literalline$7 = docBuilders$2.literalline,
31280 markAsRoot$5 = docBuilders$2.markAsRoot,
31281 softline$8 = docBuilders$2.softline;
31282 var replaceEndOfLineWith$3 = util.replaceEndOfLineWith;
31284 function preprocess$3(ast) {
31285 return mapNode$1(ast, defineShortcuts);
31288 function defineShortcuts(node) {
31289 switch (node.type) {
31291 defineShortcut$1(node, "head", function () {
31292 return node.children[0];
31294 defineShortcut$1(node, "body", function () {
31295 return node.children[1];
31299 case "documentBody":
31300 case "sequenceItem":
31301 case "flowSequenceItem":
31303 case "mappingValue":
31304 defineShortcut$1(node, "content", function () {
31305 return node.children[0];
31309 case "mappingItem":
31310 case "flowMappingItem":
31311 defineShortcut$1(node, "key", function () {
31312 return node.children[0];
31314 defineShortcut$1(node, "value", function () {
31315 return node.children[1];
31323 function genericPrint$6(path, options, print) {
31324 var node = path.getValue();
31325 var parentNode = path.getParentNode();
31326 var tag = !node.tag ? "" : path.call(print, "tag");
31327 var anchor = !node.anchor ? "" : path.call(print, "anchor");
31328 var nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
31329 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$6(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$1(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"))])) : ""]);
31332 function _print(node, parentNode, path, options, print) {
31333 switch (node.type) {
31335 return concat$h([join$c(hardline$d, path.map(function (childPath, index) {
31336 var document = node.children[index];
31337 var nextDocument = node.children[index + 1];
31338 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, "---"])]);
31339 }, "children")), node.children.length === 0 || function (lastDescendantNode) {
31340 return isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep";
31341 }(getLastDescendantNode$2(node)) ? "" : hardline$d]);
31345 var nextDocument = parentNode.children[path.getName() + 1];
31346 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));
31349 case "documentHead":
31350 return join$c(hardline$d, [].concat(path.map(print, "children"), path.map(print, "endComments")));
31352 case "documentBody":
31354 var children = join$c(hardline$d, path.map(print, "children")).parts;
31355 var endComments = join$c(hardline$d, path.map(print, "endComments")).parts;
31356 var separator = children.length === 0 || endComments.length === 0 ? "" : function (lastDescendantNode) {
31357 return isNode$1(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
31358 "" : // an extra newline for better readability
31359 concat$h([hardline$d, hardline$d]) : hardline$d;
31360 }(getLastDescendantNode$2(node));
31361 return concat$h([].concat(children, separator, endComments));
31365 return concat$h(["%", join$c(" ", [node.name].concat(node.parameters))]);
31368 return concat$h(["#", node.value]);
31371 return concat$h(["*", node.value]);
31374 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
31377 return concat$h(["&", node.value]);
31380 return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
31382 case "quoteDouble":
31383 case "quoteSingle":
31385 var singleQuote = "'";
31386 var doubleQuote = '"';
31387 var raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
31389 if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
31390 // only quoteDouble can use escape chars
31391 // and quoteSingle do not need to escape backslashes
31392 var originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
31393 return concat$h([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
31394 } else if (raw.includes(doubleQuote)) {
31395 return concat$h([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
31396 .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
31399 if (raw.includes(singleQuote)) {
31400 return concat$h([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
31401 raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
31404 var quote = options.singleQuote ? singleQuote : doubleQuote;
31405 return concat$h([quote, printFlowScalarContent(node.type, raw, options), quote]);
31408 case "blockFolded":
31409 case "blockLiteral":
31411 var parentIndent = getAncestorCount$1(path, function (ancestorNode) {
31412 return isNode$1(ancestorNode, ["sequence", "mapping"]);
31414 var isLastDescendant = isLastDescendantNode$1(path);
31415 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, {
31416 parentIndent: parentIndent,
31417 isLastDescendant: isLastDescendant,
31419 }).reduce(function (reduced, lineWords, index, lineContents) {
31420 return reduced.concat(index === 0 ? hardline$d : "", fill$6(join$c(line$9, 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) : "");
31425 return join$c(hardline$d, path.map(print, "children"));
31427 case "sequenceItem":
31428 return concat$h(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]);
31431 return !node.content ? "" : path.call(print, "content");
31433 case "mappingValue":
31434 return !node.content ? "" : path.call(print, "content");
31437 return join$c(hardline$d, path.map(print, "children"));
31439 case "mappingItem":
31440 case "flowMappingItem":
31442 var isEmptyMappingKey = isEmptyNode$1(node.key);
31443 var isEmptyMappingValue = isEmptyNode$1(node.value);
31445 if (isEmptyMappingKey && isEmptyMappingValue) {
31446 return concat$h([": "]);
31449 var key = path.call(print, "key");
31450 var value = path.call(print, "value");
31452 if (isEmptyMappingValue) {
31453 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)]);
31456 if (isEmptyMappingKey) {
31457 return concat$h([": ", align$3(2, value)]);
31460 var groupId = Symbol("mappingKey");
31461 var forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode$1(node.key.content);
31462 return forceExplicitKey ? concat$h(["? ", align$3(2, key), hardline$d, join$c("", path.map(print, "value", "leadingComments").map(function (comment) {
31463 return concat$h([comment, hardline$d]);
31464 })), ": ", align$3(2, value)]) : // force singleline
31465 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), {
31467 })])), 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$1(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$9, value])), {
31472 case "flowMapping":
31473 case "flowSequence":
31475 var openMarker = node.type === "flowMapping" ? "{" : "[";
31476 var closeMarker = node.type === "flowMapping" ? "}" : "]";
31477 var bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$9 : softline$8;
31479 var isLastItemEmptyMappingItem = node.children.length !== 0 && function (lastItem) {
31480 return lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value);
31481 }(getLast$5(node.children));
31483 return concat$h([openMarker, indent(concat$h([bracketSpacing, concat$h(path.map(function (childPath, index) {
31484 return concat$h([print(childPath), index === node.children.length - 1 ? "" : concat$h([",", line$9, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]);
31485 }, "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
31488 case "flowSequenceItem":
31489 return path.call(print, "content");
31490 // istanbul ignore next
31493 throw new Error("Unexpected node type ".concat(node.type));
31496 function indent(doc) {
31497 return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
31501 function align$3(n, doc) {
31502 return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
31505 function isInlineNode$1(node) {
31510 switch (node.type) {
31512 case "quoteDouble":
31513 case "quoteSingle":
31515 case "flowMapping":
31516 case "flowSequence":
31524 function isSingleLineNode(node) {
31529 switch (node.type) {
31531 case "quoteDouble":
31532 case "quoteSingle":
31533 return node.position.start.line === node.position.end.line;
31543 function shouldPrintDocumentBody(document) {
31544 return document.body.children.length !== 0 || hasEndComments$1(document.body);
31547 function shouldPrintDocumentEndMarker(document, nextDocument) {
31550 *... # trailingComment
31552 hasTrailingComment$3(document) || nextDocument && (
31558 nextDocument.head.children.length !== 0 ||
31564 hasEndComments$1(nextDocument.head))
31568 function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
31572 * preserve the first document head end marker
31574 root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
31579 document.head.children.length !== 0 ||
31584 hasEndComments$1(document.head) ||
31586 * --- # trailing comment
31588 hasTrailingComment$3(document.head)) {
31592 if (shouldPrintDocumentEndMarker(document, nextDocument)) {
31596 return nextDocument ? "root" : false;
31599 function isAbsolutelyPrintedAsSingleLineNode(node, options) {
31604 switch (node.type) {
31606 case "quoteSingle":
31607 case "quoteDouble":
31617 if (options.proseWrap === "preserve") {
31618 return node.position.start.line === node.position.end.line;
31621 if ( // backslash-newline
31622 /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
31626 switch (options.proseWrap) {
31628 return node.value.indexOf("\n") === -1;
31631 return !/[\n ]/.test(node.value);
31632 // istanbul ignore next
31639 function needsSpaceInFrontOfMappingValue(node) {
31640 return node.key.content && node.key.content.type === "alias";
31643 function printNextEmptyLine(path, originalText) {
31644 var node = path.getValue();
31645 var root = path.stack[0];
31646 root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
31648 if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
31649 if (isNextLineEmpty$6(node, originalText)) {
31650 root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
31658 function printFlowScalarContent(nodeType, content, options) {
31659 var lineContents = getFlowScalarLineContents$1(nodeType, content, options);
31660 return join$c(hardline$d, lineContents.map(function (lineContentWords) {
31661 return fill$6(join$c(line$9, lineContentWords).parts);
31665 function clean$7(node, newNode
31668 if (isNode$1(newNode)) {
31669 delete newNode.position;
31671 switch (newNode.type) {
31674 if (isPragma$1(newNode.value)) {
31680 case "quoteDouble":
31681 case "quoteSingle":
31682 newNode.type = "quote";
31688 var printerYaml = {
31689 preprocess: preprocess$3,
31690 print: genericPrint$6,
31691 massageAstNode: clean$7,
31692 insertPragma: insertPragma$9
31696 bracketSpacing: commonOptions.bracketSpacing,
31697 singleQuote: commonOptions.singleQuote,
31698 proseWrap: commonOptions.proseWrap
31701 var name$h = "YAML";
31702 var type$g = "data";
31703 var tmScope$g = "source.yaml";
31707 var extensions$g = [
31715 ".yaml-tmlanguage",
31718 var filenames$4 = [
31724 var aceMode$g = "yaml";
31725 var codemirrorMode$c = "yaml";
31726 var codemirrorMimeType$c = "text/x-yaml";
31727 var languageId$g = 407;
31731 tmScope: tmScope$g,
31732 aliases: aliases$6,
31733 extensions: extensions$g,
31734 filenames: filenames$4,
31735 aceMode: aceMode$g,
31736 codemirrorMode: codemirrorMode$c,
31737 codemirrorMimeType: codemirrorMimeType$c,
31738 languageId: languageId$g
31741 var YAML$1 = /*#__PURE__*/Object.freeze({
31745 tmScope: tmScope$g,
31746 aliases: aliases$6,
31747 extensions: extensions$g,
31748 filenames: filenames$4,
31749 aceMode: aceMode$g,
31750 codemirrorMode: codemirrorMode$c,
31751 codemirrorMimeType: codemirrorMimeType$c,
31752 languageId: languageId$g,
31756 var require$$0$8 = getCjsExportFromNamespace(YAML$1);
31758 var languages$6 = [createLanguage(require$$0$8, function (data) {
31759 return Object.assign(data, {
31762 vscodeLanguageIds: ["yaml"]
31765 var languageYaml = {
31766 languages: languages$6,
31773 var version$2 = require$$0.version;
31774 var getSupportInfo$2 = support.getSupportInfo;
31775 var internalPlugins = [languageCss, languageGraphql, languageHandlebars, languageHtml, languageJs, languageMarkdown, languageYaml];
31777 var isArray$1 = Array.isArray || function (arr) {
31778 return Object.prototype.toString.call(arr) === "[object Array]";
31779 }; // Luckily `opts` is always the 2nd argument
31782 function withPlugins(fn) {
31783 return function () {
31784 var args = Array.from(arguments);
31785 var plugins = args[1] && args[1].plugins || [];
31787 if (!isArray$1(plugins)) {
31788 plugins = Object.values(plugins);
31791 args[1] = Object.assign({}, args[1], {
31792 plugins: internalPlugins.concat(plugins)
31794 return fn.apply(null, args);
31798 var formatWithCursor = withPlugins(core.formatWithCursor);
31800 formatWithCursor: formatWithCursor,
31801 format: function format(text, opts) {
31802 return formatWithCursor(text, opts).formatted;
31804 check: function check(text, opts) {
31805 var formatted = formatWithCursor(text, opts).formatted;
31806 return formatted === text;
31809 getSupportInfo: withPlugins(getSupportInfo$2),
31810 version: version$2,
31813 parse: withPlugins(core.parse),
31814 formatAST: withPlugins(core.formatAST),
31815 formatDoc: withPlugins(core.formatDoc),
31816 printToDoc: withPlugins(core.printToDoc),
31817 printDocToString: withPlugins(core.printDocToString)
31821 var standalone$1 = standalone;
31823 return standalone$1;