#!/usr/bin/env node
'use strict';
-var path = require('path');
-var fs$2 = require('fs');
-var readline = require('readline');
-var os = require('os');
-var tty = require('tty');
-var util$2 = require('util');
-var stream_1 = require('stream');
-var events_1 = require('events');
+var require$$0$2 = require('path');
+var require$$0$5 = require('fs');
+var require$$0$1 = require('os');
+var require$$1 = require('tty');
+var require$$0$3 = require('util');
+var require$$0$4 = require('stream');
+var require$$0$6 = require('events');
+var require$$0$7 = require('readline');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
-var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$2);
-var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
-var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
-var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
-var util__default = /*#__PURE__*/_interopDefaultLegacy(util$2);
-var stream_1__default = /*#__PURE__*/_interopDefaultLegacy(stream_1);
-var events_1__default = /*#__PURE__*/_interopDefaultLegacy(events_1);
+var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
+var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$5);
+var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
+var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
+var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3);
+var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4);
+var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6);
+var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7);
-var semverCompare = function cmp(a, b) {
+var require$$0 = require("./package.json");
+
+var semverCompare$1 = function cmp(a, b) {
var pa = a.split('.');
var pb = b.split('.');
return 0;
};
+var semverCompare = semverCompare$1;
+
var pleaseUpgradeNode = function pleaseUpgradeNode(pkg, opts) {
var opts = opts || {};
var requiredVersion = pkg.engines.node.replace('>=', '');
}
};
-var name = "prettier";
-var version = "2.2.1";
-var description = "Prettier is an opinionated code formatter";
-var bin = "./bin/prettier.js";
-var repository = "prettier/prettier";
-var homepage = "https://prettier.io";
-var author = "James Long";
-var license = "MIT";
-var main = "./index.js";
-var browser = "./standalone.js";
-var unpkg = "./standalone.js";
-var engines = {
- node: ">=10.13.0"
-};
-var files = [
- "index.js",
- "standalone.js",
- "src",
- "bin"
-];
-var dependencies = {
- "@angular/compiler": "10.2.3",
- "@babel/code-frame": "7.10.4",
- "@babel/parser": "7.12.5",
- "@glimmer/syntax": "0.66.0",
- "@iarna/toml": "2.2.5",
- "@typescript-eslint/typescript-estree": "4.8.1",
- "angular-estree-parser": "2.2.1",
- "angular-html-parser": "1.7.1",
- camelcase: "6.2.0",
- chalk: "4.1.0",
- "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
- "cjk-regex": "2.0.0",
- cosmiconfig: "7.0.0",
- dashify: "2.0.0",
- diff: "5.0.0",
- editorconfig: "0.15.3",
- "editorconfig-to-prettier": "0.2.0",
- "escape-string-regexp": "4.0.0",
- espree: "7.3.0",
- esutils: "2.0.3",
- "fast-glob": "3.2.4",
- "fast-json-stable-stringify": "2.1.0",
- "find-parent-dir": "0.3.0",
- "flow-parser": "0.138.0",
- "get-stdin": "8.0.0",
- globby: "11.0.1",
- graphql: "15.4.0",
- "html-element-attributes": "2.3.0",
- "html-styles": "1.0.0",
- "html-tag-names": "1.1.5",
- "html-void-elements": "1.0.5",
- ignore: "4.0.6",
- "jest-docblock": "26.0.0",
- json5: "2.1.3",
- leven: "3.1.0",
- "lines-and-columns": "1.1.6",
- "linguist-languages": "7.12.1",
- lodash: "4.17.20",
- mem: "8.0.0",
- meriyah: "3.1.6",
- minimatch: "3.0.4",
- minimist: "1.2.5",
- "n-readlines": "1.0.1",
- outdent: "0.7.1",
- "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
- "please-upgrade-node": "3.2.0",
- "postcss-less": "3.1.4",
- "postcss-media-query-parser": "0.2.3",
- "postcss-scss": "2.1.1",
- "postcss-selector-parser": "2.2.3",
- "postcss-values-parser": "2.0.1",
- "regexp-util": "1.2.2",
- "remark-footnotes": "2.0.0",
- "remark-math": "3.0.1",
- "remark-parse": "8.0.3",
- resolve: "1.19.0",
- semver: "7.3.2",
- "string-width": "4.2.0",
- typescript: "4.1.2",
- "unicode-regex": "3.0.0",
- unified: "9.2.0",
- vnopts: "1.0.2",
- "yaml-unist-parser": "1.3.1"
+var check = function (it) {
+ return it && it.Math == Math && it;
};
-var devDependencies = {
- "@babel/core": "7.12.3",
- "@babel/preset-env": "7.12.1",
- "@babel/types": "7.12.6",
- "@glimmer/reference": "0.66.0",
- "@rollup/plugin-alias": "3.1.1",
- "@rollup/plugin-babel": "5.2.1",
- "@rollup/plugin-commonjs": "16.0.0",
- "@rollup/plugin-json": "4.1.0",
- "@rollup/plugin-node-resolve": "10.0.0",
- "@rollup/plugin-replace": "2.3.4",
- "@types/estree": "0.0.45",
- "@types/node": "14.14.0",
- "@typescript-eslint/types": "4.8.1",
- "babel-jest": "26.6.3",
- "babel-loader": "8.2.1",
- benchmark: "2.1.4",
- "builtin-modules": "3.1.0",
- "cross-env": "7.0.2",
- cspell: "4.2.2",
- eslint: "7.13.0",
- "eslint-config-prettier": "6.15.0",
- "eslint-formatter-friendly": "7.0.0",
- "eslint-plugin-import": "2.22.1",
- "eslint-plugin-jest": "24.1.3",
- "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules",
- "eslint-plugin-react": "7.21.5",
- "eslint-plugin-unicorn": "23.0.0",
- execa: "4.1.0",
- jest: "26.6.3",
- "jest-snapshot-serializer-ansi": "1.0.0",
- "jest-snapshot-serializer-raw": "1.1.0",
- "jest-watch-typeahead": "0.6.1",
- "npm-run-all": "4.1.5",
- "path-browserify": "1.0.1",
- prettier: "2.2.0",
- rimraf: "3.0.2",
- rollup: "2.33.3",
- "rollup-plugin-node-globals": "1.4.0",
- "rollup-plugin-terser": "7.0.2",
- shelljs: "0.8.4",
- "snapshot-diff": "0.8.1",
- "strip-ansi": "6.0.0",
- "synchronous-promise": "2.0.15",
- tempy: "1.0.0",
- "terser-webpack-plugin": "5.0.3",
- webpack: "5.5.1"
-};
-var scripts = {
- prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
- "prepare-release": "yarn && yarn build && yarn test:dist",
- test: "jest",
- "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest",
- "test:dist": "cross-env NODE_ENV=production jest",
- "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest",
- "test:integration": "jest tests_integration",
- "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",
- "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",
- "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",
- lint: "run-p lint:*",
- "lint:typecheck": "tsc",
- "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
- "lint:changelog": "node ./scripts/lint-changelog.js",
- "lint:prettier": "prettier . \"!test*\" --check",
- "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2018 \"dist/!(bin-prettier|index|third-party).js\"",
- "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"",
- "lint:deps": "node ./scripts/check-deps.js",
- fix: "run-s fix:eslint fix:prettier",
- "fix:eslint": "yarn lint:eslint --fix",
- "fix:prettier": "yarn lint:prettier --write",
- build: "node --max-old-space-size=3072 ./scripts/build/build.js",
- "build-docs": "node ./scripts/build-docs.js"
+
+// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
+var global$r =
+ // eslint-disable-next-line es/no-global-this -- safe
+ check(typeof globalThis == 'object' && globalThis) ||
+ check(typeof window == 'object' && window) ||
+ // eslint-disable-next-line no-restricted-globals -- safe
+ check(typeof self == 'object' && self) ||
+ check(typeof global$r == 'object' && global$r) ||
+ // eslint-disable-next-line no-new-func -- fallback
+ (function () { return this; })() || Function('return this')();
+
+var objectGetOwnPropertyDescriptor = {};
+
+var fails$8 = function (exec) {
+ try {
+ return !!exec();
+ } catch (error) {
+ return true;
+ }
};
-var require$$1 = {
- name: name,
- version: version,
- description: description,
- bin: bin,
- repository: repository,
- homepage: homepage,
- author: author,
- license: license,
- main: main,
- browser: browser,
- unpkg: unpkg,
- engines: engines,
- files: files,
- dependencies: dependencies,
- devDependencies: devDependencies,
- scripts: scripts
+
+var fails$7 = fails$8;
+
+// Detect IE8's incomplete defineProperty implementation
+var descriptors = !fails$7(function () {
+ // eslint-disable-next-line es/no-object-defineproperty -- required for testing
+ return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
+});
+
+var call$7 = Function.prototype.call;
+
+var functionCall = call$7.bind ? call$7.bind(call$7) : function () {
+ return call$7.apply(call$7, arguments);
};
-var fastJsonStableStringify = function (data, opts) {
- if (!opts) opts = {};
- if (typeof opts === 'function') opts = {
- cmp: opts
+var objectPropertyIsEnumerable = {};
+
+var $propertyIsEnumerable = {}.propertyIsEnumerable;
+// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
+var getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
+
+// Nashorn ~ JDK8 bug
+var NASHORN_BUG = getOwnPropertyDescriptor$1 && !$propertyIsEnumerable.call({ 1: 2 }, 1);
+
+// `Object.prototype.propertyIsEnumerable` method implementation
+// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
+objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
+ var descriptor = getOwnPropertyDescriptor$1(this, V);
+ return !!descriptor && descriptor.enumerable;
+} : $propertyIsEnumerable;
+
+var createPropertyDescriptor$3 = function (bitmap, value) {
+ return {
+ enumerable: !(bitmap & 1),
+ configurable: !(bitmap & 2),
+ writable: !(bitmap & 4),
+ value: value
};
- var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
+};
- var cmp = opts.cmp && function (f) {
- return function (node) {
- return function (a, b) {
- var aobj = {
- key: a,
- value: node[a]
- };
- var bobj = {
- key: b,
- value: node[b]
- };
- return f(aobj, bobj);
- };
- };
- }(opts.cmp);
+var FunctionPrototype$1 = Function.prototype;
+var bind$3 = FunctionPrototype$1.bind;
+var call$6 = FunctionPrototype$1.call;
+var callBind = bind$3 && bind$3.bind(call$6);
- var seen = [];
- return function stringify(node) {
- if (node && node.toJSON && typeof node.toJSON === 'function') {
- node = node.toJSON();
- }
+var functionUncurryThis = bind$3 ? function (fn) {
+ return fn && callBind(call$6, fn);
+} : function (fn) {
+ return fn && function () {
+ return call$6.apply(fn, arguments);
+ };
+};
- if (node === undefined) return;
- if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
- if (typeof node !== 'object') return JSON.stringify(node);
- var i, out;
+var uncurryThis$c = functionUncurryThis;
- if (Array.isArray(node)) {
- out = '[';
+var toString$5 = uncurryThis$c({}.toString);
+var stringSlice = uncurryThis$c(''.slice);
- for (i = 0; i < node.length; i++) {
- if (i) out += ',';
- out += stringify(node[i]) || 'null';
- }
+var classofRaw$1 = function (it) {
+ return stringSlice(toString$5(it), 8, -1);
+};
- return out + ']';
- }
+var global$q = global$r;
+var uncurryThis$b = functionUncurryThis;
+var fails$6 = fails$8;
+var classof$5 = classofRaw$1;
- if (node === null) return 'null';
+var Object$4 = global$q.Object;
+var split = uncurryThis$b(''.split);
- if (seen.indexOf(node) !== -1) {
- if (cycles) return JSON.stringify('__cycle__');
- throw new TypeError('Converting circular structure to JSON');
- }
+// fallback for non-array-like ES3 and non-enumerable old V8 strings
+var indexedObject = fails$6(function () {
+ // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
+ // eslint-disable-next-line no-prototype-builtins -- safe
+ return !Object$4('z').propertyIsEnumerable(0);
+}) ? function (it) {
+ return classof$5(it) == 'String' ? split(it, '') : Object$4(it);
+} : Object$4;
- var seenIndex = seen.push(node) - 1;
- var keys = Object.keys(node).sort(cmp && cmp(node));
- out = '';
+var global$p = global$r;
- for (i = 0; i < keys.length; i++) {
- var key = keys[i];
- var value = stringify(node[key]);
- if (!value) continue;
- if (out) out += ',';
- out += JSON.stringify(key) + ':' + value;
- }
+var TypeError$a = global$p.TypeError;
- seen.splice(seenIndex, 1);
- return '{' + out + '}';
- }(data);
+// `RequireObjectCoercible` abstract operation
+// https://tc39.es/ecma262/#sec-requireobjectcoercible
+var requireObjectCoercible$2 = function (it) {
+ if (it == undefined) throw TypeError$a("Can't call method on " + it);
+ return it;
};
-var src = require("./index");
+// toObject with fallback for non-array-like ES3 strings
+var IndexedObject = indexedObject;
+var requireObjectCoercible$1 = requireObjectCoercible$2;
-const preserveCamelCase = (string, locale) => {
- let isLastCharLower = false;
- let isLastCharUpper = false;
- let isLastLastCharUpper = false;
+var toIndexedObject$4 = function (it) {
+ return IndexedObject(requireObjectCoercible$1(it));
+};
- for (let i = 0; i < string.length; i++) {
- const character = string[i];
+// `IsCallable` abstract operation
+// https://tc39.es/ecma262/#sec-iscallable
+var isCallable$b = function (argument) {
+ return typeof argument == 'function';
+};
- if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
- string = string.slice(0, i) + '-' + string.slice(i);
- isLastCharLower = false;
- isLastLastCharUpper = isLastCharUpper;
- isLastCharUpper = true;
- i++;
- } else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
- string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
- isLastLastCharUpper = isLastCharUpper;
- isLastCharUpper = false;
- isLastCharLower = true;
- } else {
- isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
- isLastLastCharUpper = isLastCharUpper;
- isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
- }
- }
+var isCallable$a = isCallable$b;
- return string;
+var isObject$d = function (it) {
+ return typeof it == 'object' ? it !== null : isCallable$a(it);
};
-const preserveConsecutiveUppercase = input => {
- return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, m1 => m1.toLowerCase());
+var global$o = global$r;
+var isCallable$9 = isCallable$b;
+
+var aFunction = function (argument) {
+ return isCallable$9(argument) ? argument : undefined;
};
-const postProcess = (input, options) => {
- return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale)).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase(options.locale));
+var getBuiltIn$5 = function (namespace, method) {
+ return arguments.length < 2 ? aFunction(global$o[namespace]) : global$o[namespace] && global$o[namespace][method];
};
-const camelCase = (input, options) => {
- if (!(typeof input === 'string' || Array.isArray(input))) {
- throw new TypeError('Expected the input to be `string | string[]`');
- }
+var uncurryThis$a = functionUncurryThis;
- options = Object.assign({
- pascalCase: false,
- preserveConsecutiveUppercase: false
- }, options);
+var objectIsPrototypeOf = uncurryThis$a({}.isPrototypeOf);
- if (Array.isArray(input)) {
- input = input.map(x => x.trim()).filter(x => x.length).join('-');
- } else {
- input = input.trim();
- }
+var getBuiltIn$4 = getBuiltIn$5;
- if (input.length === 0) {
- return '';
- }
+var engineUserAgent = getBuiltIn$4('navigator', 'userAgent') || '';
- if (input.length === 1) {
- return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
- }
+var global$n = global$r;
+var userAgent$2 = engineUserAgent;
- const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
+var process$1 = global$n.process;
+var Deno = global$n.Deno;
+var versions = process$1 && process$1.versions || Deno && Deno.version;
+var v8 = versions && versions.v8;
+var match, version;
- if (hasUpperCase) {
- input = preserveCamelCase(input, options.locale);
+if (v8) {
+ match = v8.split('.');
+ // in old Chrome, versions of V8 isn't V8 = Chrome / 10
+ // but their correct versions are not interesting for us
+ version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
+}
+
+// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
+// so check `userAgent` even if `.v8` exists, but 0
+if (!version && userAgent$2) {
+ match = userAgent$2.match(/Edge\/(\d+)/);
+ if (!match || match[1] >= 74) {
+ match = userAgent$2.match(/Chrome\/(\d+)/);
+ if (match) version = +match[1];
}
+}
- input = input.replace(/^[_.\- ]+/, '');
+var engineV8Version = version;
- if (options.preserveConsecutiveUppercase) {
- input = preserveConsecutiveUppercase(input);
- } else {
- input = input.toLocaleLowerCase();
- }
+/* eslint-disable es/no-symbol -- required for testing */
- if (options.pascalCase) {
- input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
+var V8_VERSION = engineV8Version;
+var fails$5 = fails$8;
+
+// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
+var nativeSymbol = !!Object.getOwnPropertySymbols && !fails$5(function () {
+ var symbol = Symbol();
+ // Chrome 38 Symbol has incorrect toString conversion
+ // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
+ return !String(symbol) || !(Object(symbol) instanceof Symbol) ||
+ // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
+ !Symbol.sham && V8_VERSION && V8_VERSION < 41;
+});
+
+/* eslint-disable es/no-symbol -- required for testing */
+
+var NATIVE_SYMBOL$1 = nativeSymbol;
+
+var useSymbolAsUid = NATIVE_SYMBOL$1
+ && !Symbol.sham
+ && typeof Symbol.iterator == 'symbol';
+
+var global$m = global$r;
+var getBuiltIn$3 = getBuiltIn$5;
+var isCallable$8 = isCallable$b;
+var isPrototypeOf$1 = objectIsPrototypeOf;
+var USE_SYMBOL_AS_UID$1 = useSymbolAsUid;
+
+var Object$3 = global$m.Object;
+
+var isSymbol$6 = USE_SYMBOL_AS_UID$1 ? function (it) {
+ return typeof it == 'symbol';
+} : function (it) {
+ var $Symbol = getBuiltIn$3('Symbol');
+ return isCallable$8($Symbol) && isPrototypeOf$1($Symbol.prototype, Object$3(it));
+};
+
+var global$l = global$r;
+
+var String$3 = global$l.String;
+
+var tryToString$3 = function (argument) {
+ try {
+ return String$3(argument);
+ } catch (error) {
+ return 'Object';
}
+};
- return postProcess(input, options);
+var global$k = global$r;
+var isCallable$7 = isCallable$b;
+var tryToString$2 = tryToString$3;
+
+var TypeError$9 = global$k.TypeError;
+
+// `Assert: IsCallable(argument) is true`
+var aCallable$5 = function (argument) {
+ if (isCallable$7(argument)) return argument;
+ throw TypeError$9(tryToString$2(argument) + ' is not a function');
};
-var camelcase = camelCase; // TODO: Remove this for the next major release
+var aCallable$4 = aCallable$5;
-var _default = camelCase;
-camelcase.default = _default;
+// `GetMethod` abstract operation
+// https://tc39.es/ecma262/#sec-getmethod
+var getMethod$3 = function (V, P) {
+ var func = V[P];
+ return func == null ? undefined : aCallable$4(func);
+};
-/*!
- * dashify <https://github.com/jonschlinkert/dashify>
- *
- * Copyright (c) 2015-2017, Jon Schlinkert.
- * Released under the MIT License.
- */
+var global$j = global$r;
+var call$5 = functionCall;
+var isCallable$6 = isCallable$b;
+var isObject$c = isObject$d;
+
+var TypeError$8 = global$j.TypeError;
+
+// `OrdinaryToPrimitive` abstract operation
+// https://tc39.es/ecma262/#sec-ordinarytoprimitive
+var ordinaryToPrimitive$1 = function (input, pref) {
+ var fn, val;
+ if (pref === 'string' && isCallable$6(fn = input.toString) && !isObject$c(val = call$5(fn, input))) return val;
+ if (isCallable$6(fn = input.valueOf) && !isObject$c(val = call$5(fn, input))) return val;
+ if (pref !== 'string' && isCallable$6(fn = input.toString) && !isObject$c(val = call$5(fn, input))) return val;
+ throw TypeError$8("Can't convert object to primitive value");
+};
-var dashify = (str, options) => {
- if (typeof str !== 'string') throw new TypeError('expected a string');
- return str.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\W/g, m => /[À-ž]/.test(m) ? m : '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, m => options && options.condense ? '-' : m).toLowerCase();
+var shared$3 = {exports: {}};
+
+var global$i = global$r;
+
+// eslint-disable-next-line es/no-object-defineproperty -- safe
+var defineProperty$3 = Object.defineProperty;
+
+var setGlobal$3 = function (key, value) {
+ try {
+ defineProperty$3(global$i, key, { value: value, configurable: true, writable: true });
+ } catch (error) {
+ global$i[key] = value;
+ } return value;
+};
+
+var global$h = global$r;
+var setGlobal$2 = setGlobal$3;
+
+var SHARED = '__core-js_shared__';
+var store$3 = global$h[SHARED] || setGlobal$2(SHARED, {});
+
+var sharedStore = store$3;
+
+var store$2 = sharedStore;
+
+(shared$3.exports = function (key, value) {
+ return store$2[key] || (store$2[key] = value !== undefined ? value : {});
+})('versions', []).push({
+ version: '3.19.1',
+ mode: 'global',
+ copyright: '© 2021 Denis Pushkarev (zloirock.ru)'
+});
+
+var global$g = global$r;
+var requireObjectCoercible = requireObjectCoercible$2;
+
+var Object$2 = global$g.Object;
+
+// `ToObject` abstract operation
+// https://tc39.es/ecma262/#sec-toobject
+var toObject$4 = function (argument) {
+ return Object$2(requireObjectCoercible(argument));
+};
+
+var uncurryThis$9 = functionUncurryThis;
+var toObject$3 = toObject$4;
+
+var hasOwnProperty$b = uncurryThis$9({}.hasOwnProperty);
+
+// `HasOwnProperty` abstract operation
+// https://tc39.es/ecma262/#sec-hasownproperty
+var hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
+ return hasOwnProperty$b(toObject$3(it), key);
+};
+
+var uncurryThis$8 = functionUncurryThis;
+
+var id = 0;
+var postfix = Math.random();
+var toString$4 = uncurryThis$8(1.0.toString);
+
+var uid$2 = function (key) {
+ return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString$4(++id + postfix, 36);
+};
+
+var global$f = global$r;
+var shared$2 = shared$3.exports;
+var hasOwn$6 = hasOwnProperty_1;
+var uid$1 = uid$2;
+var NATIVE_SYMBOL = nativeSymbol;
+var USE_SYMBOL_AS_UID = useSymbolAsUid;
+
+var WellKnownSymbolsStore = shared$2('wks');
+var Symbol$7 = global$f.Symbol;
+var symbolFor = Symbol$7 && Symbol$7['for'];
+var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol$7 : Symbol$7 && Symbol$7.withoutSetter || uid$1;
+
+var wellKnownSymbol$7 = function (name) {
+ if (!hasOwn$6(WellKnownSymbolsStore, name) || !(NATIVE_SYMBOL || typeof WellKnownSymbolsStore[name] == 'string')) {
+ var description = 'Symbol.' + name;
+ if (NATIVE_SYMBOL && hasOwn$6(Symbol$7, name)) {
+ WellKnownSymbolsStore[name] = Symbol$7[name];
+ } else if (USE_SYMBOL_AS_UID && symbolFor) {
+ WellKnownSymbolsStore[name] = symbolFor(description);
+ } else {
+ WellKnownSymbolsStore[name] = createWellKnownSymbol(description);
+ }
+ } return WellKnownSymbolsStore[name];
+};
+
+var global$e = global$r;
+var call$4 = functionCall;
+var isObject$b = isObject$d;
+var isSymbol$5 = isSymbol$6;
+var getMethod$2 = getMethod$3;
+var ordinaryToPrimitive = ordinaryToPrimitive$1;
+var wellKnownSymbol$6 = wellKnownSymbol$7;
+
+var TypeError$7 = global$e.TypeError;
+var TO_PRIMITIVE = wellKnownSymbol$6('toPrimitive');
+
+// `ToPrimitive` abstract operation
+// https://tc39.es/ecma262/#sec-toprimitive
+var toPrimitive$1 = function (input, pref) {
+ if (!isObject$b(input) || isSymbol$5(input)) return input;
+ var exoticToPrim = getMethod$2(input, TO_PRIMITIVE);
+ var result;
+ if (exoticToPrim) {
+ if (pref === undefined) pref = 'default';
+ result = call$4(exoticToPrim, input, pref);
+ if (!isObject$b(result) || isSymbol$5(result)) return result;
+ throw TypeError$7("Can't convert object to primitive value");
+ }
+ if (pref === undefined) pref = 'number';
+ return ordinaryToPrimitive(input, pref);
+};
+
+var toPrimitive = toPrimitive$1;
+var isSymbol$4 = isSymbol$6;
+
+// `ToPropertyKey` abstract operation
+// https://tc39.es/ecma262/#sec-topropertykey
+var toPropertyKey$3 = function (argument) {
+ var key = toPrimitive(argument, 'string');
+ return isSymbol$4(key) ? key : key + '';
+};
+
+var global$d = global$r;
+var isObject$a = isObject$d;
+
+var document$1 = global$d.document;
+// typeof document.createElement is 'object' in old IE
+var EXISTS$1 = isObject$a(document$1) && isObject$a(document$1.createElement);
+
+var documentCreateElement$1 = function (it) {
+ return EXISTS$1 ? document$1.createElement(it) : {};
+};
+
+var DESCRIPTORS$5 = descriptors;
+var fails$4 = fails$8;
+var createElement = documentCreateElement$1;
+
+// Thank's IE8 for his funny defineProperty
+var ie8DomDefine = !DESCRIPTORS$5 && !fails$4(function () {
+ // eslint-disable-next-line es/no-object-defineproperty -- requied for testing
+ return Object.defineProperty(createElement('div'), 'a', {
+ get: function () { return 7; }
+ }).a != 7;
+});
+
+var DESCRIPTORS$4 = descriptors;
+var call$3 = functionCall;
+var propertyIsEnumerableModule = objectPropertyIsEnumerable;
+var createPropertyDescriptor$2 = createPropertyDescriptor$3;
+var toIndexedObject$3 = toIndexedObject$4;
+var toPropertyKey$2 = toPropertyKey$3;
+var hasOwn$5 = hasOwnProperty_1;
+var IE8_DOM_DEFINE$1 = ie8DomDefine;
+
+// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
+var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
+
+// `Object.getOwnPropertyDescriptor` method
+// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
+objectGetOwnPropertyDescriptor.f = DESCRIPTORS$4 ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
+ O = toIndexedObject$3(O);
+ P = toPropertyKey$2(P);
+ if (IE8_DOM_DEFINE$1) try {
+ return $getOwnPropertyDescriptor(O, P);
+ } catch (error) { /* empty */ }
+ if (hasOwn$5(O, P)) return createPropertyDescriptor$2(!call$3(propertyIsEnumerableModule.f, O, P), O[P]);
};
-function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
+var objectDefineProperty = {};
+
+var global$c = global$r;
+var isObject$9 = isObject$d;
+
+var String$2 = global$c.String;
+var TypeError$6 = global$c.TypeError;
+
+// `Assert: Type(argument) is Object`
+var anObject$7 = function (argument) {
+ if (isObject$9(argument)) return argument;
+ throw TypeError$6(String$2(argument) + ' is not an object');
+};
+
+var global$b = global$r;
+var DESCRIPTORS$3 = descriptors;
+var IE8_DOM_DEFINE = ie8DomDefine;
+var anObject$6 = anObject$7;
+var toPropertyKey$1 = toPropertyKey$3;
+
+var TypeError$5 = global$b.TypeError;
+// eslint-disable-next-line es/no-object-defineproperty -- safe
+var $defineProperty = Object.defineProperty;
+
+// `Object.defineProperty` method
+// https://tc39.es/ecma262/#sec-object.defineproperty
+objectDefineProperty.f = DESCRIPTORS$3 ? $defineProperty : function defineProperty(O, P, Attributes) {
+ anObject$6(O);
+ P = toPropertyKey$1(P);
+ anObject$6(Attributes);
+ if (IE8_DOM_DEFINE) try {
+ return $defineProperty(O, P, Attributes);
+ } catch (error) { /* empty */ }
+ if ('get' in Attributes || 'set' in Attributes) throw TypeError$5('Accessors not supported');
+ if ('value' in Attributes) O[P] = Attributes.value;
+ return O;
+};
+
+var DESCRIPTORS$2 = descriptors;
+var definePropertyModule$4 = objectDefineProperty;
+var createPropertyDescriptor$1 = createPropertyDescriptor$3;
+
+var createNonEnumerableProperty$3 = DESCRIPTORS$2 ? function (object, key, value) {
+ return definePropertyModule$4.f(object, key, createPropertyDescriptor$1(1, value));
+} : function (object, key, value) {
+ object[key] = value;
+ return object;
+};
+
+var redefine$1 = {exports: {}};
+
+var uncurryThis$7 = functionUncurryThis;
+var isCallable$5 = isCallable$b;
+var store$1 = sharedStore;
+
+var functionToString = uncurryThis$7(Function.toString);
+
+// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
+if (!isCallable$5(store$1.inspectSource)) {
+ store$1.inspectSource = function (it) {
+ return functionToString(it);
+ };
}
-function commonjsRequire () {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
+var inspectSource$3 = store$1.inspectSource;
+
+var global$a = global$r;
+var isCallable$4 = isCallable$b;
+var inspectSource$2 = inspectSource$3;
+
+var WeakMap$4 = global$a.WeakMap;
+
+var nativeWeakMap = isCallable$4(WeakMap$4) && /native code/.test(inspectSource$2(WeakMap$4));
+
+var shared$1 = shared$3.exports;
+var uid = uid$2;
+
+var keys$4 = shared$1('keys');
+
+var sharedKey$2 = function (key) {
+ return keys$4[key] || (keys$4[key] = uid(key));
+};
+
+var hiddenKeys$4 = {};
+
+var NATIVE_WEAK_MAP = nativeWeakMap;
+var global$9 = global$r;
+var uncurryThis$6 = functionUncurryThis;
+var isObject$8 = isObject$d;
+var createNonEnumerableProperty$2 = createNonEnumerableProperty$3;
+var hasOwn$4 = hasOwnProperty_1;
+var shared = sharedStore;
+var sharedKey$1 = sharedKey$2;
+var hiddenKeys$3 = hiddenKeys$4;
+
+var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
+var TypeError$4 = global$9.TypeError;
+var WeakMap$3 = global$9.WeakMap;
+var set, get$2, has;
+
+var enforce = function (it) {
+ return has(it) ? get$2(it) : set(it, {});
+};
+
+var getterFor = function (TYPE) {
+ return function (it) {
+ var state;
+ if (!isObject$8(it) || (state = get$2(it)).type !== TYPE) {
+ throw TypeError$4('Incompatible receiver, ' + TYPE + ' required');
+ } return state;
+ };
+};
+
+if (NATIVE_WEAK_MAP || shared.state) {
+ var store = shared.state || (shared.state = new WeakMap$3());
+ var wmget = uncurryThis$6(store.get);
+ var wmhas = uncurryThis$6(store.has);
+ var wmset = uncurryThis$6(store.set);
+ set = function (it, metadata) {
+ if (wmhas(store, it)) throw new TypeError$4(OBJECT_ALREADY_INITIALIZED);
+ metadata.facade = it;
+ wmset(store, it, metadata);
+ return metadata;
+ };
+ get$2 = function (it) {
+ return wmget(store, it) || {};
+ };
+ has = function (it) {
+ return wmhas(store, it);
+ };
+} else {
+ var STATE = sharedKey$1('state');
+ hiddenKeys$3[STATE] = true;
+ set = function (it, metadata) {
+ if (hasOwn$4(it, STATE)) throw new TypeError$4(OBJECT_ALREADY_INITIALIZED);
+ metadata.facade = it;
+ createNonEnumerableProperty$2(it, STATE, metadata);
+ return metadata;
+ };
+ get$2 = function (it) {
+ return hasOwn$4(it, STATE) ? it[STATE] : {};
+ };
+ has = function (it) {
+ return hasOwn$4(it, STATE);
+ };
}
-var colorName = {
- "aliceblue": [240, 248, 255],
- "antiquewhite": [250, 235, 215],
- "aqua": [0, 255, 255],
- "aquamarine": [127, 255, 212],
- "azure": [240, 255, 255],
- "beige": [245, 245, 220],
- "bisque": [255, 228, 196],
- "black": [0, 0, 0],
- "blanchedalmond": [255, 235, 205],
- "blue": [0, 0, 255],
- "blueviolet": [138, 43, 226],
- "brown": [165, 42, 42],
- "burlywood": [222, 184, 135],
+var internalState = {
+ set: set,
+ get: get$2,
+ has: has,
+ enforce: enforce,
+ getterFor: getterFor
+};
+
+var DESCRIPTORS$1 = descriptors;
+var hasOwn$3 = hasOwnProperty_1;
+
+var FunctionPrototype = Function.prototype;
+// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
+var getDescriptor = DESCRIPTORS$1 && Object.getOwnPropertyDescriptor;
+
+var EXISTS = hasOwn$3(FunctionPrototype, 'name');
+// additional protection from minified / mangled / dropped function names
+var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
+var CONFIGURABLE = EXISTS && (!DESCRIPTORS$1 || (DESCRIPTORS$1 && getDescriptor(FunctionPrototype, 'name').configurable));
+
+var functionName = {
+ EXISTS: EXISTS,
+ PROPER: PROPER,
+ CONFIGURABLE: CONFIGURABLE
+};
+
+var global$8 = global$r;
+var isCallable$3 = isCallable$b;
+var hasOwn$2 = hasOwnProperty_1;
+var createNonEnumerableProperty$1 = createNonEnumerableProperty$3;
+var setGlobal$1 = setGlobal$3;
+var inspectSource$1 = inspectSource$3;
+var InternalStateModule = internalState;
+var CONFIGURABLE_FUNCTION_NAME = functionName.CONFIGURABLE;
+
+var getInternalState = InternalStateModule.get;
+var enforceInternalState = InternalStateModule.enforce;
+var TEMPLATE = String(String).split('String');
+
+(redefine$1.exports = function (O, key, value, options) {
+ var unsafe = options ? !!options.unsafe : false;
+ var simple = options ? !!options.enumerable : false;
+ var noTargetGet = options ? !!options.noTargetGet : false;
+ var name = options && options.name !== undefined ? options.name : key;
+ var state;
+ if (isCallable$3(value)) {
+ if (String(name).slice(0, 7) === 'Symbol(') {
+ name = '[' + String(name).replace(/^Symbol\(([^)]*)\)/, '$1') + ']';
+ }
+ if (!hasOwn$2(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
+ createNonEnumerableProperty$1(value, 'name', name);
+ }
+ state = enforceInternalState(value);
+ if (!state.source) {
+ state.source = TEMPLATE.join(typeof name == 'string' ? name : '');
+ }
+ }
+ if (O === global$8) {
+ if (simple) O[key] = value;
+ else setGlobal$1(key, value);
+ return;
+ } else if (!unsafe) {
+ delete O[key];
+ } else if (!noTargetGet && O[key]) {
+ simple = true;
+ }
+ if (simple) O[key] = value;
+ else createNonEnumerableProperty$1(O, key, value);
+// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
+})(Function.prototype, 'toString', function toString() {
+ return isCallable$3(this) && getInternalState(this).source || inspectSource$1(this);
+});
+
+var objectGetOwnPropertyNames = {};
+
+var ceil = Math.ceil;
+var floor$1 = Math.floor;
+
+// `ToIntegerOrInfinity` abstract operation
+// https://tc39.es/ecma262/#sec-tointegerorinfinity
+var toIntegerOrInfinity$3 = function (argument) {
+ var number = +argument;
+ // eslint-disable-next-line no-self-compare -- safe
+ return number !== number || number === 0 ? 0 : (number > 0 ? floor$1 : ceil)(number);
+};
+
+var toIntegerOrInfinity$2 = toIntegerOrInfinity$3;
+
+var max = Math.max;
+var min$1 = Math.min;
+
+// Helper for a popular repeating case of the spec:
+// Let integer be ? ToInteger(index).
+// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
+var toAbsoluteIndex$1 = function (index, length) {
+ var integer = toIntegerOrInfinity$2(index);
+ return integer < 0 ? max(integer + length, 0) : min$1(integer, length);
+};
+
+var toIntegerOrInfinity$1 = toIntegerOrInfinity$3;
+
+var min = Math.min;
+
+// `ToLength` abstract operation
+// https://tc39.es/ecma262/#sec-tolength
+var toLength$1 = function (argument) {
+ return argument > 0 ? min(toIntegerOrInfinity$1(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
+};
+
+var toLength = toLength$1;
+
+// `LengthOfArrayLike` abstract operation
+// https://tc39.es/ecma262/#sec-lengthofarraylike
+var lengthOfArrayLike$6 = function (obj) {
+ return toLength(obj.length);
+};
+
+var toIndexedObject$2 = toIndexedObject$4;
+var toAbsoluteIndex = toAbsoluteIndex$1;
+var lengthOfArrayLike$5 = lengthOfArrayLike$6;
+
+// `Array.prototype.{ indexOf, includes }` methods implementation
+var createMethod = function (IS_INCLUDES) {
+ return function ($this, el, fromIndex) {
+ var O = toIndexedObject$2($this);
+ var length = lengthOfArrayLike$5(O);
+ var index = toAbsoluteIndex(fromIndex, length);
+ var value;
+ // Array#includes uses SameValueZero equality algorithm
+ // eslint-disable-next-line no-self-compare -- NaN check
+ if (IS_INCLUDES && el != el) while (length > index) {
+ value = O[index++];
+ // eslint-disable-next-line no-self-compare -- NaN check
+ if (value != value) return true;
+ // Array#indexOf ignores holes, Array#includes - not
+ } else for (;length > index; index++) {
+ if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
+ } return !IS_INCLUDES && -1;
+ };
+};
+
+var arrayIncludes = {
+ // `Array.prototype.includes` method
+ // https://tc39.es/ecma262/#sec-array.prototype.includes
+ includes: createMethod(true),
+ // `Array.prototype.indexOf` method
+ // https://tc39.es/ecma262/#sec-array.prototype.indexof
+ indexOf: createMethod(false)
+};
+
+var uncurryThis$5 = functionUncurryThis;
+var hasOwn$1 = hasOwnProperty_1;
+var toIndexedObject$1 = toIndexedObject$4;
+var indexOf = arrayIncludes.indexOf;
+var hiddenKeys$2 = hiddenKeys$4;
+
+var push$1 = uncurryThis$5([].push);
+
+var objectKeysInternal = function (object, names) {
+ var O = toIndexedObject$1(object);
+ var i = 0;
+ var result = [];
+ var key;
+ for (key in O) !hasOwn$1(hiddenKeys$2, key) && hasOwn$1(O, key) && push$1(result, key);
+ // Don't enum bug & hidden keys
+ while (names.length > i) if (hasOwn$1(O, key = names[i++])) {
+ ~indexOf(result, key) || push$1(result, key);
+ }
+ return result;
+};
+
+// IE8- don't enum bug keys
+var enumBugKeys$3 = [
+ 'constructor',
+ 'hasOwnProperty',
+ 'isPrototypeOf',
+ 'propertyIsEnumerable',
+ 'toLocaleString',
+ 'toString',
+ 'valueOf'
+];
+
+var internalObjectKeys$1 = objectKeysInternal;
+var enumBugKeys$2 = enumBugKeys$3;
+
+var hiddenKeys$1 = enumBugKeys$2.concat('length', 'prototype');
+
+// `Object.getOwnPropertyNames` method
+// https://tc39.es/ecma262/#sec-object.getownpropertynames
+// eslint-disable-next-line es/no-object-getownpropertynames -- safe
+objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
+ return internalObjectKeys$1(O, hiddenKeys$1);
+};
+
+var objectGetOwnPropertySymbols = {};
+
+// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
+objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
+
+var getBuiltIn$2 = getBuiltIn$5;
+var uncurryThis$4 = functionUncurryThis;
+var getOwnPropertyNamesModule = objectGetOwnPropertyNames;
+var getOwnPropertySymbolsModule = objectGetOwnPropertySymbols;
+var anObject$5 = anObject$7;
+
+var concat = uncurryThis$4([].concat);
+
+// all object keys, includes non-enumerable and symbols
+var ownKeys$1 = getBuiltIn$2('Reflect', 'ownKeys') || function ownKeys(it) {
+ var keys = getOwnPropertyNamesModule.f(anObject$5(it));
+ var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
+ return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
+};
+
+var hasOwn = hasOwnProperty_1;
+var ownKeys = ownKeys$1;
+var getOwnPropertyDescriptorModule = objectGetOwnPropertyDescriptor;
+var definePropertyModule$3 = objectDefineProperty;
+
+var copyConstructorProperties$1 = function (target, source) {
+ var keys = ownKeys(source);
+ var defineProperty = definePropertyModule$3.f;
+ var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ if (!hasOwn(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
+ }
+};
+
+var fails$3 = fails$8;
+var isCallable$2 = isCallable$b;
+
+var replacement = /#|\.prototype\./;
+
+var isForced$1 = function (feature, detection) {
+ var value = data[normalize(feature)];
+ return value == POLYFILL ? true
+ : value == NATIVE ? false
+ : isCallable$2(detection) ? fails$3(detection)
+ : !!detection;
+};
+
+var normalize = isForced$1.normalize = function (string) {
+ return String(string).replace(replacement, '.').toLowerCase();
+};
+
+var data = isForced$1.data = {};
+var NATIVE = isForced$1.NATIVE = 'N';
+var POLYFILL = isForced$1.POLYFILL = 'P';
+
+var isForced_1 = isForced$1;
+
+var global$7 = global$r;
+var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
+var createNonEnumerableProperty = createNonEnumerableProperty$3;
+var redefine = redefine$1.exports;
+var setGlobal = setGlobal$3;
+var copyConstructorProperties = copyConstructorProperties$1;
+var isForced = isForced_1;
+
+/*
+ options.target - name of the target object
+ options.global - target is the global object
+ options.stat - export as static methods of target
+ options.proto - export as prototype methods of target
+ options.real - real prototype method for the `pure` version
+ options.forced - export even if the native feature is available
+ options.bind - bind methods to the target, required for the `pure` version
+ options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
+ options.unsafe - use the simple assignment of property instead of delete + defineProperty
+ options.sham - add a flag to not completely full polyfills
+ options.enumerable - export as enumerable property
+ options.noTargetGet - prevent calling a getter on target
+ options.name - the .name of the function if it does not match the key
+*/
+var _export = function (options, source) {
+ var TARGET = options.target;
+ var GLOBAL = options.global;
+ var STATIC = options.stat;
+ var FORCED, target, key, targetProperty, sourceProperty, descriptor;
+ if (GLOBAL) {
+ target = global$7;
+ } else if (STATIC) {
+ target = global$7[TARGET] || setGlobal(TARGET, {});
+ } else {
+ target = (global$7[TARGET] || {}).prototype;
+ }
+ if (target) for (key in source) {
+ sourceProperty = source[key];
+ if (options.noTargetGet) {
+ descriptor = getOwnPropertyDescriptor(target, key);
+ targetProperty = descriptor && descriptor.value;
+ } else targetProperty = target[key];
+ FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
+ // contained in target
+ if (!FORCED && targetProperty !== undefined) {
+ if (typeof sourceProperty == typeof targetProperty) continue;
+ copyConstructorProperties(sourceProperty, targetProperty);
+ }
+ // add a flag to not completely full polyfills
+ if (options.sham || (targetProperty && targetProperty.sham)) {
+ createNonEnumerableProperty(sourceProperty, 'sham', true);
+ }
+ // extend global
+ redefine(target, key, sourceProperty, options);
+ }
+};
+
+var wellKnownSymbol$5 = wellKnownSymbol$7;
+
+var TO_STRING_TAG$1 = wellKnownSymbol$5('toStringTag');
+var test$1 = {};
+
+test$1[TO_STRING_TAG$1] = 'z';
+
+var toStringTagSupport = String(test$1) === '[object z]';
+
+var global$6 = global$r;
+var TO_STRING_TAG_SUPPORT = toStringTagSupport;
+var isCallable$1 = isCallable$b;
+var classofRaw = classofRaw$1;
+var wellKnownSymbol$4 = wellKnownSymbol$7;
+
+var TO_STRING_TAG = wellKnownSymbol$4('toStringTag');
+var Object$1 = global$6.Object;
+
+// ES3 wrong here
+var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
+
+// fallback for IE11 Script Access Denied error
+var tryGet = function (it, key) {
+ try {
+ return it[key];
+ } catch (error) { /* empty */ }
+};
+
+// getting tag from ES6+ `Object.prototype.toString`
+var classof$4 = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
+ var O, tag, result;
+ return it === undefined ? 'Undefined' : it === null ? 'Null'
+ // @@toStringTag case
+ : typeof (tag = tryGet(O = Object$1(it), TO_STRING_TAG)) == 'string' ? tag
+ // builtinTag case
+ : CORRECT_ARGUMENTS ? classofRaw(O)
+ // ES3 arguments fallback
+ : (result = classofRaw(O)) == 'Object' && isCallable$1(O.callee) ? 'Arguments' : result;
+};
+
+var global$5 = global$r;
+var classof$3 = classof$4;
+
+var String$1 = global$5.String;
+
+var toString$3 = function (argument) {
+ if (classof$3(argument) === 'Symbol') throw TypeError('Cannot convert a Symbol value to a string');
+ return String$1(argument);
+};
+
+var uncurryThis$3 = functionUncurryThis;
+
+var arraySlice$1 = uncurryThis$3([].slice);
+
+var arraySlice = arraySlice$1;
+
+var floor = Math.floor;
+
+var mergeSort = function (array, comparefn) {
+ var length = array.length;
+ var middle = floor(length / 2);
+ return length < 8 ? insertionSort(array, comparefn) : merge$3(
+ array,
+ mergeSort(arraySlice(array, 0, middle), comparefn),
+ mergeSort(arraySlice(array, middle), comparefn),
+ comparefn
+ );
+};
+
+var insertionSort = function (array, comparefn) {
+ var length = array.length;
+ var i = 1;
+ var element, j;
+
+ while (i < length) {
+ j = i;
+ element = array[i];
+ while (j && comparefn(array[j - 1], element) > 0) {
+ array[j] = array[--j];
+ }
+ if (j !== i++) array[j] = element;
+ } return array;
+};
+
+var merge$3 = function (array, left, right, comparefn) {
+ var llength = left.length;
+ var rlength = right.length;
+ var lindex = 0;
+ var rindex = 0;
+
+ while (lindex < llength || rindex < rlength) {
+ array[lindex + rindex] = (lindex < llength && rindex < rlength)
+ ? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++]
+ : lindex < llength ? left[lindex++] : right[rindex++];
+ } return array;
+};
+
+var arraySort = mergeSort;
+
+var fails$2 = fails$8;
+
+var arrayMethodIsStrict$1 = function (METHOD_NAME, argument) {
+ var method = [][METHOD_NAME];
+ return !!method && fails$2(function () {
+ // eslint-disable-next-line no-useless-call,no-throw-literal -- required for testing
+ method.call(null, argument || function () { throw 1; }, 1);
+ });
+};
+
+var userAgent$1 = engineUserAgent;
+
+var firefox = userAgent$1.match(/firefox\/(\d+)/i);
+
+var engineFfVersion = !!firefox && +firefox[1];
+
+var UA = engineUserAgent;
+
+var engineIsIeOrEdge = /MSIE|Trident/.test(UA);
+
+var userAgent = engineUserAgent;
+
+var webkit = userAgent.match(/AppleWebKit\/(\d+)\./);
+
+var engineWebkitVersion = !!webkit && +webkit[1];
+
+var $$3 = _export;
+var uncurryThis$2 = functionUncurryThis;
+var aCallable$3 = aCallable$5;
+var toObject$2 = toObject$4;
+var lengthOfArrayLike$4 = lengthOfArrayLike$6;
+var toString$2 = toString$3;
+var fails$1 = fails$8;
+var internalSort = arraySort;
+var arrayMethodIsStrict = arrayMethodIsStrict$1;
+var FF = engineFfVersion;
+var IE_OR_EDGE = engineIsIeOrEdge;
+var V8 = engineV8Version;
+var WEBKIT = engineWebkitVersion;
+
+var test = [];
+var un$Sort = uncurryThis$2(test.sort);
+var push = uncurryThis$2(test.push);
+
+// IE8-
+var FAILS_ON_UNDEFINED = fails$1(function () {
+ test.sort(undefined);
+});
+// V8 bug
+var FAILS_ON_NULL = fails$1(function () {
+ test.sort(null);
+});
+// Old WebKit
+var STRICT_METHOD = arrayMethodIsStrict('sort');
+
+var STABLE_SORT = !fails$1(function () {
+ // feature detection can be too slow, so check engines versions
+ if (V8) return V8 < 70;
+ if (FF && FF > 3) return;
+ if (IE_OR_EDGE) return true;
+ if (WEBKIT) return WEBKIT < 603;
+
+ var result = '';
+ var code, chr, value, index;
+
+ // generate an array with more 512 elements (Chakra and old V8 fails only in this case)
+ for (code = 65; code < 76; code++) {
+ chr = String.fromCharCode(code);
+
+ switch (code) {
+ case 66: case 69: case 70: case 72: value = 3; break;
+ case 68: case 71: value = 4; break;
+ default: value = 2;
+ }
+
+ for (index = 0; index < 47; index++) {
+ test.push({ k: chr + index, v: value });
+ }
+ }
+
+ test.sort(function (a, b) { return b.v - a.v; });
+
+ for (index = 0; index < test.length; index++) {
+ chr = test[index].k.charAt(0);
+ if (result.charAt(result.length - 1) !== chr) result += chr;
+ }
+
+ return result !== 'DGBEFHACIJK';
+});
+
+var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD || !STABLE_SORT;
+
+var getSortCompare = function (comparefn) {
+ return function (x, y) {
+ if (y === undefined) return -1;
+ if (x === undefined) return 1;
+ if (comparefn !== undefined) return +comparefn(x, y) || 0;
+ return toString$2(x) > toString$2(y) ? 1 : -1;
+ };
+};
+
+// `Array.prototype.sort` method
+// https://tc39.es/ecma262/#sec-array.prototype.sort
+$$3({ target: 'Array', proto: true, forced: FORCED }, {
+ sort: function sort(comparefn) {
+ if (comparefn !== undefined) aCallable$3(comparefn);
+
+ var array = toObject$2(this);
+
+ if (STABLE_SORT) return comparefn === undefined ? un$Sort(array) : un$Sort(array, comparefn);
+
+ var items = [];
+ var arrayLength = lengthOfArrayLike$4(array);
+ var itemsLength, index;
+
+ for (index = 0; index < arrayLength; index++) {
+ if (index in array) push(items, array[index]);
+ }
+
+ internalSort(items, getSortCompare(comparefn));
+
+ itemsLength = items.length;
+ index = 0;
+
+ while (index < itemsLength) array[index] = items[index++];
+ while (index < arrayLength) delete array[index++];
+
+ return array;
+ }
+});
+
+var fastJsonStableStringify = function (data, opts) {
+ if (!opts) opts = {};
+ if (typeof opts === 'function') opts = {
+ cmp: opts
+ };
+ var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
+
+ var cmp = opts.cmp && function (f) {
+ return function (node) {
+ return function (a, b) {
+ var aobj = {
+ key: a,
+ value: node[a]
+ };
+ var bobj = {
+ key: b,
+ value: node[b]
+ };
+ return f(aobj, bobj);
+ };
+ };
+ }(opts.cmp);
+
+ var seen = [];
+ return function stringify(node) {
+ if (node && node.toJSON && typeof node.toJSON === 'function') {
+ node = node.toJSON();
+ }
+
+ if (node === undefined) return;
+ if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
+ if (typeof node !== 'object') return JSON.stringify(node);
+ var i, out;
+
+ if (Array.isArray(node)) {
+ out = '[';
+
+ for (i = 0; i < node.length; i++) {
+ if (i) out += ',';
+ out += stringify(node[i]) || 'null';
+ }
+
+ return out + ']';
+ }
+
+ if (node === null) return 'null';
+
+ if (seen.indexOf(node) !== -1) {
+ if (cycles) return JSON.stringify('__cycle__');
+ throw new TypeError('Converting circular structure to JSON');
+ }
+
+ var seenIndex = seen.push(node) - 1;
+ var keys = Object.keys(node).sort(cmp && cmp(node));
+ out = '';
+
+ for (i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ var value = stringify(node[key]);
+ if (!value) continue;
+ if (out) out += ',';
+ out += JSON.stringify(key) + ':' + value;
+ }
+
+ seen.splice(seenIndex, 1);
+ return '{' + out + '}';
+ }(data);
+};
+
+var require$$3 = require("./index.js");
+
+var ansiStyles$1 = {exports: {}};
+
+var colorName = {
+ "aliceblue": [240, 248, 255],
+ "antiquewhite": [250, 235, 215],
+ "aqua": [0, 255, 255],
+ "aquamarine": [127, 255, 212],
+ "azure": [240, 255, 255],
+ "beige": [245, 245, 220],
+ "bisque": [255, 228, 196],
+ "black": [0, 0, 0],
+ "blanchedalmond": [255, 235, 205],
+ "blue": [0, 0, 255],
+ "blueviolet": [138, 43, 226],
+ "brown": [165, 42, 42],
+ "burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
};
/* MIT license */
-
/* eslint-disable no-mixed-operators */
-// NOTE: conversions should only return primitive values (i.e. arrays, or
+
+const cssKeywords = colorName; // NOTE: conversions should only return primitive values (i.e. arrays, or
// values that give correct `typeof` results).
// do not use box values types (i.e. Number(), String(), etc.)
const reverseKeywords = {};
-for (const key of Object.keys(colorName)) {
- reverseKeywords[colorName[key]] = key;
+for (const key of Object.keys(cssKeywords)) {
+ reverseKeywords[cssKeywords[key]] = key;
}
-const convert = {
+const convert$1 = {
rgb: {
channels: 3,
labels: 'rgb'
labels: ['gray']
}
};
-var conversions = convert; // Hide .channels and .labels properties
+var conversions$2 = convert$1; // Hide .channels and .labels properties
-for (const model of Object.keys(convert)) {
- if (!('channels' in convert[model])) {
+for (const model of Object.keys(convert$1)) {
+ if (!('channels' in convert$1[model])) {
throw new Error('missing channels property: ' + model);
}
- if (!('labels' in convert[model])) {
+ if (!('labels' in convert$1[model])) {
throw new Error('missing channel labels property: ' + model);
}
- if (convert[model].labels.length !== convert[model].channels) {
+ if (convert$1[model].labels.length !== convert$1[model].channels) {
throw new Error('channel and label counts mismatch: ' + model);
}
const {
channels,
labels
- } = convert[model];
- delete convert[model].channels;
- delete convert[model].labels;
- Object.defineProperty(convert[model], 'channels', {
+ } = convert$1[model];
+ delete convert$1[model].channels;
+ delete convert$1[model].labels;
+ Object.defineProperty(convert$1[model], 'channels', {
value: channels
});
- Object.defineProperty(convert[model], 'labels', {
+ Object.defineProperty(convert$1[model], 'labels', {
value: labels
});
}
-convert.rgb.hsl = function (rgb) {
+convert$1.rgb.hsl = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
return [h, s * 100, l * 100];
};
-convert.rgb.hsv = function (rgb) {
+convert$1.rgb.hsv = function (rgb) {
let rdif;
let gdif;
let bdif;
return [h * 360, s * 100, v * 100];
};
-convert.rgb.hwb = function (rgb) {
+convert$1.rgb.hwb = function (rgb) {
const r = rgb[0];
const g = rgb[1];
let b = rgb[2];
- const h = convert.rgb.hsl(rgb)[0];
+ const h = convert$1.rgb.hsl(rgb)[0];
const w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
-convert.rgb.cmyk = function (rgb) {
+convert$1.rgb.cmyk = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
}
-convert.rgb.keyword = function (rgb) {
+convert$1.rgb.keyword = function (rgb) {
const reversed = reverseKeywords[rgb];
if (reversed) {
let currentClosestDistance = Infinity;
let currentClosestKeyword;
- for (const keyword of Object.keys(colorName)) {
- const value = colorName[keyword]; // Compute comparative distance
+ for (const keyword of Object.keys(cssKeywords)) {
+ const value = cssKeywords[keyword]; // Compute comparative distance
const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
return currentClosestKeyword;
};
-convert.keyword.rgb = function (keyword) {
- return colorName[keyword];
+convert$1.keyword.rgb = function (keyword) {
+ return cssKeywords[keyword];
};
-convert.rgb.xyz = function (rgb) {
+convert$1.rgb.xyz = function (rgb) {
let r = rgb[0] / 255;
let g = rgb[1] / 255;
let b = rgb[2] / 255; // Assume sRGB
return [x * 100, y * 100, z * 100];
};
-convert.rgb.lab = function (rgb) {
- const xyz = convert.rgb.xyz(rgb);
+convert$1.rgb.lab = function (rgb) {
+ const xyz = convert$1.rgb.xyz(rgb);
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
return [l, a, b];
};
-convert.hsl.rgb = function (hsl) {
+convert$1.hsl.rgb = function (hsl) {
const h = hsl[0] / 360;
const s = hsl[1] / 100;
const l = hsl[2] / 100;
return rgb;
};
-convert.hsl.hsv = function (hsl) {
+convert$1.hsl.hsv = function (hsl) {
const h = hsl[0];
let s = hsl[1] / 100;
let l = hsl[2] / 100;
return [h, sv * 100, v * 100];
};
-convert.hsv.rgb = function (hsv) {
+convert$1.hsv.rgb = function (hsv) {
const h = hsv[0] / 60;
const s = hsv[1] / 100;
let v = hsv[2] / 100;
}
};
-convert.hsv.hsl = function (hsv) {
+convert$1.hsv.hsl = function (hsv) {
const h = hsv[0];
const s = hsv[1] / 100;
const v = hsv[2] / 100;
}; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
-convert.hwb.rgb = function (hwb) {
+convert$1.hwb.rgb = function (hwb) {
const h = hwb[0] / 360;
let wh = hwb[1] / 100;
let bl = hwb[2] / 100;
return [r * 255, g * 255, b * 255];
};
-convert.cmyk.rgb = function (cmyk) {
+convert$1.cmyk.rgb = function (cmyk) {
const c = cmyk[0] / 100;
const m = cmyk[1] / 100;
const y = cmyk[2] / 100;
return [r * 255, g * 255, b * 255];
};
-convert.xyz.rgb = function (xyz) {
+convert$1.xyz.rgb = function (xyz) {
const x = xyz[0] / 100;
const y = xyz[1] / 100;
const z = xyz[2] / 100;
return [r * 255, g * 255, b * 255];
};
-convert.xyz.lab = function (xyz) {
+convert$1.xyz.lab = function (xyz) {
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
return [l, a, b];
};
-convert.lab.xyz = function (lab) {
+convert$1.lab.xyz = function (lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
return [x, y, z];
};
-convert.lab.lch = function (lab) {
+convert$1.lab.lch = function (lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
return [l, c, h];
};
-convert.lch.lab = function (lch) {
+convert$1.lch.lab = function (lch) {
const l = lch[0];
const c = lch[1];
const h = lch[2];
return [l, a, b];
};
-convert.rgb.ansi16 = function (args, saturation = null) {
+convert$1.rgb.ansi16 = function (args, saturation = null) {
const [r, g, b] = args;
- let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
+ let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
value = Math.round(value / 50);
return ansi;
};
-convert.hsv.ansi16 = function (args) {
+convert$1.hsv.ansi16 = function (args) {
// Optimization here; we already know the value and don't need to get
// it converted for us.
- return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
+ return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
};
-convert.rgb.ansi256 = function (args) {
+convert$1.rgb.ansi256 = function (args) {
const r = args[0];
const g = args[1];
const b = args[2]; // We use the extended greyscale palette here, with the exception of
return ansi;
};
-convert.ansi16.rgb = function (args) {
+convert$1.ansi16.rgb = function (args) {
let color = args % 10; // Handle greyscale
if (color === 0 || color === 7) {
return [r, g, b];
};
-convert.ansi256.rgb = function (args) {
+convert$1.ansi256.rgb = function (args) {
// Handle greyscale
if (args >= 232) {
const c = (args - 232) * 10 + 8;
return [r, g, b];
};
-convert.rgb.hex = function (args) {
+convert$1.rgb.hex = function (args) {
const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
const string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
-convert.hex.rgb = function (args) {
+convert$1.hex.rgb = function (args) {
const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [r, g, b];
};
-convert.rgb.hcg = function (rgb) {
+convert$1.rgb.hcg = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
return [hue * 360, chroma * 100, grayscale * 100];
};
-convert.hsl.hcg = function (hsl) {
+convert$1.hsl.hcg = function (hsl) {
const s = hsl[1] / 100;
const l = hsl[2] / 100;
const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
return [hsl[0], c * 100, f * 100];
};
-convert.hsv.hcg = function (hsv) {
+convert$1.hsv.hcg = function (hsv) {
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const c = s * v;
return [hsv[0], c * 100, f * 100];
};
-convert.hcg.rgb = function (hcg) {
+convert$1.hcg.rgb = function (hcg) {
const h = hcg[0] / 360;
const c = hcg[1] / 100;
const g = hcg[2] / 100;
return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
};
-convert.hcg.hsv = function (hcg) {
+convert$1.hcg.hsv = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1.0 - c);
return [hcg[0], f * 100, v * 100];
};
-convert.hcg.hsl = function (hcg) {
+convert$1.hcg.hsl = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const l = g * (1.0 - c) + 0.5 * c;
return [hcg[0], s * 100, l * 100];
};
-convert.hcg.hwb = function (hcg) {
+convert$1.hcg.hwb = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1.0 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
-convert.hwb.hcg = function (hwb) {
+convert$1.hwb.hcg = function (hwb) {
const w = hwb[1] / 100;
const b = hwb[2] / 100;
const v = 1 - b;
return [hwb[0], c * 100, g * 100];
};
-convert.apple.rgb = function (apple) {
+convert$1.apple.rgb = function (apple) {
return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
};
-convert.rgb.apple = function (rgb) {
+convert$1.rgb.apple = function (rgb) {
return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
};
-convert.gray.rgb = function (args) {
+convert$1.gray.rgb = function (args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
-convert.gray.hsl = function (args) {
+convert$1.gray.hsl = function (args) {
return [0, 0, args[0]];
};
-convert.gray.hsv = convert.gray.hsl;
+convert$1.gray.hsv = convert$1.gray.hsl;
-convert.gray.hwb = function (gray) {
+convert$1.gray.hwb = function (gray) {
return [0, 100, gray[0]];
};
-convert.gray.cmyk = function (gray) {
+convert$1.gray.cmyk = function (gray) {
return [0, 0, 0, gray[0]];
};
-convert.gray.lab = function (gray) {
+convert$1.gray.lab = function (gray) {
return [gray[0], 0, 0];
};
-convert.gray.hex = function (gray) {
+convert$1.gray.hex = function (gray) {
const val = Math.round(gray[0] / 100 * 255) & 0xFF;
const integer = (val << 16) + (val << 8) + val;
const string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
-convert.rgb.gray = function (rgb) {
+convert$1.rgb.gray = function (rgb) {
const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};
+const conversions$1 = conversions$2;
/*
This function routes a model to all other models.
function buildGraph() {
const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
- const models = Object.keys(conversions);
+ const models = Object.keys(conversions$1);
for (let len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
while (queue.length) {
const current = queue.pop();
- const adjacents = Object.keys(conversions[current]);
+ const adjacents = Object.keys(conversions$1[current]);
for (let len = adjacents.length, i = 0; i < len; i++) {
const adjacent = adjacents[i];
function wrapConversion(toModel, graph) {
const path = [graph[toModel].parent, toModel];
- let fn = conversions[graph[toModel].parent][toModel];
+ let fn = conversions$1[graph[toModel].parent][toModel];
let cur = graph[toModel].parent;
while (graph[cur].parent) {
path.unshift(graph[cur].parent);
- fn = link(conversions[graph[cur].parent][cur], fn);
+ fn = link(conversions$1[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
return fn;
}
-var route = function (fromModel) {
+var route$1 = function (fromModel) {
const graph = deriveBFS(fromModel);
const conversion = {};
const models = Object.keys(graph);
return conversion;
};
-const convert$1 = {};
+const conversions = conversions$2;
+const route = route$1;
+const convert = {};
const models = Object.keys(conversions);
function wrapRaw(fn) {
}
models.forEach(fromModel => {
- convert$1[fromModel] = {};
- Object.defineProperty(convert$1[fromModel], 'channels', {
+ convert[fromModel] = {};
+ Object.defineProperty(convert[fromModel], 'channels', {
value: conversions[fromModel].channels
});
- Object.defineProperty(convert$1[fromModel], 'labels', {
+ Object.defineProperty(convert[fromModel], 'labels', {
value: conversions[fromModel].labels
});
const routes = route(fromModel);
const routeModels = Object.keys(routes);
routeModels.forEach(toModel => {
const fn = routes[toModel];
- convert$1[fromModel][toModel] = wrapRounded(fn);
- convert$1[fromModel][toModel].raw = wrapRaw(fn);
+ convert[fromModel][toModel] = wrapRounded(fn);
+ convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
-var colorConvert = convert$1;
+var colorConvert = convert;
-var ansiStyles = createCommonjsModule(function (module) {
+(function (module) {
const wrapAnsi16 = (fn, offset) => (...args) => {
const code = fn(...args);
enumerable: true,
get: assembleStyles
});
-});
+})(ansiStyles$1);
-var hasFlag = (flag, argv = process.argv) => {
+var hasFlag$1 = (flag, argv = process.argv) => {
const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf('--');
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
};
+const os = require$$0__default["default"];
+const tty = require$$1__default["default"];
+const hasFlag = hasFlag$1;
const {
env
} = process;
if (process.platform === 'win32') {
// Windows 10 build 10586 is the first Windows release that supports 256 colors.
// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
- const osRelease = os__default['default'].release().split('.');
+ const osRelease = os.release().split('.');
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
if ('CI' in env) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
+ if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
return 1;
}
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
- if ('GITHUB_ACTIONS' in env) {
- return 1;
- }
-
if (env.COLORTERM === 'truecolor') {
return 3;
}
var supportsColor_1 = {
supportsColor: getSupportLevel,
- stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
- stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
+ stdout: translateLevel(supportsColor(true, tty.isatty(1))),
+ stderr: translateLevel(supportsColor(true, tty.isatty(2)))
};
-const stringReplaceAll = (string, substring, replacer) => {
+const stringReplaceAll$1 = (string, substring, replacer) => {
let index = string.indexOf(substring);
if (index === -1) {
return returnValue;
};
-const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
+const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
let endIndex = 0;
let returnValue = '';
return returnValue;
};
-var util = {
- stringReplaceAll,
- stringEncaseCRLFWithFirstIndex
+var util$2 = {
+ stringReplaceAll: stringReplaceAll$1,
+ stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
};
const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
return chunks.join('');
};
+const ansiStyles = ansiStyles$1.exports;
const {
stdout: stdoutColor,
stderr: stderrColor
} = supportsColor_1;
const {
- stringReplaceAll: stringReplaceAll$1,
- stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
-} = util;
+ stringReplaceAll,
+ stringEncaseCRLFWithFirstIndex
+} = util$2;
const {
- isArray
+ isArray: isArray$e
} = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
};
}
-const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
+const proto = Object.defineProperties(() => {}, Object.assign(Object.assign({}, styles), {}, {
level: {
enumerable: true,
const createBuilder = (self, _styler, _isEmpty) => {
const builder = (...arguments_) => {
- if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
+ if (isArray$e(arguments_[0]) && isArray$e(arguments_[0].raw)) {
// Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
return applyStyle(builder, chalkTag(builder, ...arguments_));
} // Single argument is hot path, implicit coercion is faster than anything
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
- string = stringReplaceAll$1(string, styler.close, styler.open);
+ string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
} // We can move both next actions out of loop, because remaining actions in loop won't have
const lfIndex = string.indexOf('\n');
if (lfIndex !== -1) {
- string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
const chalkTag = (chalk, ...strings) => {
const [firstString] = strings;
- if (!isArray(firstString) || !isArray(firstString.raw)) {
+ if (!isArray$e(firstString) || !isArray$e(firstString.raw)) {
// If chalk() was called by itself or with a string,
// return the string itself as a string.
return strings.join(' ');
};
Object.defineProperties(Chalk.prototype, styles);
-const chalk = Chalk(); // eslint-disable-line new-cap
+const chalk$2 = Chalk(); // eslint-disable-line new-cap
-chalk.supportsColor = stdoutColor;
-chalk.stderr = Chalk({
+chalk$2.supportsColor = stdoutColor;
+chalk$2.stderr = Chalk({
level: stderrColor ? stderrColor.level : 0
}); // eslint-disable-line new-cap
-chalk.stderr.supportsColor = stderrColor;
-var source = chalk;
+chalk$2.stderr.supportsColor = stderrColor;
+var source = chalk$2;
-/**
- * The inverse of `_.toPairs`; this method returns an object composed
- * from key-value `pairs`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Array
- * @param {Array} pairs The key-value pairs.
- * @returns {Object} Returns the new object.
- * @example
- *
- * _.fromPairs([['a', 1], ['b', 2]]);
- * // => { 'a': 1, 'b': 2 }
- */
-function fromPairs(pairs) {
- var index = -1,
- length = pairs == null ? 0 : pairs.length,
- result = {};
-
- while (++index < length) {
- var pair = pairs[index];
- result[pair[0]] = pair[1];
- }
+var require$$4 = require("./third-party.js");
- return result;
-}
+var prettierInternal = require$$3.__internal;
-var fromPairs_1 = fromPairs;
+var classof$2 = classofRaw$1;
-/**
- * Checks if `value` is classified as an `Array` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array, else `false`.
- * @example
- *
- * _.isArray([1, 2, 3]);
- * // => true
- *
- * _.isArray(document.body.children);
- * // => false
- *
- * _.isArray('abc');
- * // => false
- *
- * _.isArray(_.noop);
- * // => false
- */
-var isArray$1 = Array.isArray;
-var isArray_1 = isArray$1;
+// `IsArray` abstract operation
+// https://tc39.es/ecma262/#sec-isarray
+// eslint-disable-next-line es/no-array-isarray -- safe
+var isArray$d = Array.isArray || function isArray(argument) {
+ return classof$2(argument) == 'Array';
+};
-/** Detect free variable `global` from Node.js. */
-var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
-var _freeGlobal = freeGlobal;
+var uncurryThis$1 = functionUncurryThis;
+var aCallable$2 = aCallable$5;
-/** Detect free variable `self`. */
+var bind$2 = uncurryThis$1(uncurryThis$1.bind);
-var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
-/** Used as a reference to the global object. */
+// optional / simple context binding
+var functionBindContext = function (fn, that) {
+ aCallable$2(fn);
+ return that === undefined ? fn : bind$2 ? bind$2(fn, that) : function (/* ...args */) {
+ return fn.apply(that, arguments);
+ };
+};
-var root = _freeGlobal || freeSelf || Function('return this')();
-var _root = root;
+var global$4 = global$r;
+var isArray$c = isArray$d;
+var lengthOfArrayLike$3 = lengthOfArrayLike$6;
+var bind$1 = functionBindContext;
-/** Built-in value references. */
+var TypeError$3 = global$4.TypeError;
-var Symbol$1 = _root.Symbol;
-var _Symbol = Symbol$1;
+// `FlattenIntoArray` abstract operation
+// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
+var flattenIntoArray$2 = function (target, original, source, sourceLen, start, depth, mapper, thisArg) {
+ var targetIndex = start;
+ var sourceIndex = 0;
+ var mapFn = mapper ? bind$1(mapper, thisArg) : false;
+ var element, elementLen;
-/** Used for built-in method references. */
+ while (sourceIndex < sourceLen) {
+ if (sourceIndex in source) {
+ element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
-var objectProto = Object.prototype;
-/** Used to check objects for own properties. */
+ if (depth > 0 && isArray$c(element)) {
+ elementLen = lengthOfArrayLike$3(element);
+ targetIndex = flattenIntoArray$2(target, original, element, elementLen, targetIndex, depth - 1) - 1;
+ } else {
+ if (targetIndex >= 0x1FFFFFFFFFFFFF) throw TypeError$3('Exceed the acceptable array length');
+ target[targetIndex] = element;
+ }
-var hasOwnProperty = objectProto.hasOwnProperty;
-/**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
+ targetIndex++;
+ }
+ sourceIndex++;
+ }
+ return targetIndex;
+};
-var nativeObjectToString = objectProto.toString;
-/** Built-in value references. */
+var flattenIntoArray_1 = flattenIntoArray$2;
-var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
-/**
- * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the raw `toStringTag`.
- */
+var uncurryThis = functionUncurryThis;
+var fails = fails$8;
+var isCallable = isCallable$b;
+var classof$1 = classof$4;
+var getBuiltIn$1 = getBuiltIn$5;
+var inspectSource = inspectSource$3;
-function getRawTag(value) {
- var isOwn = hasOwnProperty.call(value, symToStringTag),
- tag = value[symToStringTag];
+var noop$1 = function () { /* empty */ };
+var empty = [];
+var construct = getBuiltIn$1('Reflect', 'construct');
+var constructorRegExp = /^\s*(?:class|function)\b/;
+var exec = uncurryThis(constructorRegExp.exec);
+var INCORRECT_TO_STRING = !constructorRegExp.exec(noop$1);
+var isConstructorModern = function (argument) {
+ if (!isCallable(argument)) return false;
try {
- value[symToStringTag] = undefined;
- var unmasked = true;
- } catch (e) {}
+ construct(noop$1, empty, argument);
+ return true;
+ } catch (error) {
+ return false;
+ }
+};
- var result = nativeObjectToString.call(value);
+var isConstructorLegacy = function (argument) {
+ if (!isCallable(argument)) return false;
+ switch (classof$1(argument)) {
+ case 'AsyncFunction':
+ case 'GeneratorFunction':
+ case 'AsyncGeneratorFunction': return false;
+ // we can't check .prototype since constructors produced by .bind haven't it
+ } return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument));
+};
- if (unmasked) {
- if (isOwn) {
- value[symToStringTag] = tag;
+// `IsConstructor` abstract operation
+// https://tc39.es/ecma262/#sec-isconstructor
+var isConstructor$1 = !construct || fails(function () {
+ var called;
+ return isConstructorModern(isConstructorModern.call)
+ || !isConstructorModern(Object)
+ || !isConstructorModern(function () { called = true; })
+ || called;
+}) ? isConstructorLegacy : isConstructorModern;
+
+var global$3 = global$r;
+var isArray$b = isArray$d;
+var isConstructor = isConstructor$1;
+var isObject$7 = isObject$d;
+var wellKnownSymbol$3 = wellKnownSymbol$7;
+
+var SPECIES = wellKnownSymbol$3('species');
+var Array$1 = global$3.Array;
+
+// a part of `ArraySpeciesCreate` abstract operation
+// https://tc39.es/ecma262/#sec-arrayspeciescreate
+var arraySpeciesConstructor$1 = function (originalArray) {
+ var C;
+ if (isArray$b(originalArray)) {
+ C = originalArray.constructor;
+ // cross-realm fallback
+ if (isConstructor(C) && (C === Array$1 || isArray$b(C.prototype))) C = undefined;
+ else if (isObject$7(C)) {
+ C = C[SPECIES];
+ if (C === null) C = undefined;
+ }
+ } return C === undefined ? Array$1 : C;
+};
+
+var arraySpeciesConstructor = arraySpeciesConstructor$1;
+
+// `ArraySpeciesCreate` abstract operation
+// https://tc39.es/ecma262/#sec-arrayspeciescreate
+var arraySpeciesCreate$2 = function (originalArray, length) {
+ return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length);
+};
+
+var $$2 = _export;
+var flattenIntoArray$1 = flattenIntoArray_1;
+var aCallable$1 = aCallable$5;
+var toObject$1 = toObject$4;
+var lengthOfArrayLike$2 = lengthOfArrayLike$6;
+var arraySpeciesCreate$1 = arraySpeciesCreate$2;
+
+// `Array.prototype.flatMap` method
+// https://tc39.es/ecma262/#sec-array.prototype.flatmap
+$$2({ target: 'Array', proto: true }, {
+ flatMap: function flatMap(callbackfn /* , thisArg */) {
+ var O = toObject$1(this);
+ var sourceLen = lengthOfArrayLike$2(O);
+ var A;
+ aCallable$1(callbackfn);
+ A = arraySpeciesCreate$1(O, 0);
+ A.length = flattenIntoArray$1(A, O, O, sourceLen, 0, 1, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
+ return A;
+ }
+});
+
+var tasks = {};
+
+var utils$k = {};
+
+var array$3 = {};
+
+Object.defineProperty(array$3, "__esModule", {
+ value: true
+});
+array$3.splitWhen = array$3.flatten = void 0;
+
+function flatten$2(items) {
+ return items.reduce((collection, item) => [].concat(collection, item), []);
+}
+
+array$3.flatten = flatten$2;
+
+function splitWhen(items, predicate) {
+ const result = [[]];
+ let groupIndex = 0;
+
+ for (const item of items) {
+ if (predicate(item)) {
+ groupIndex++;
+ result[groupIndex] = [];
} else {
- delete value[symToStringTag];
+ result[groupIndex].push(item);
}
}
return result;
}
-var _getRawTag = getRawTag;
+array$3.splitWhen = splitWhen;
-/** Used for built-in method references. */
-var objectProto$1 = Object.prototype;
-/**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
+var errno$1 = {};
-var nativeObjectToString$1 = objectProto$1.toString;
-/**
- * Converts `value` to a string using `Object.prototype.toString`.
- *
- * @private
- * @param {*} value The value to convert.
- * @returns {string} Returns the converted string.
- */
+Object.defineProperty(errno$1, "__esModule", {
+ value: true
+});
+errno$1.isEnoentCodeError = void 0;
-function objectToString(value) {
- return nativeObjectToString$1.call(value);
+function isEnoentCodeError(error) {
+ return error.code === 'ENOENT';
}
-var _objectToString = objectToString;
-
-/** `Object#toString` result references. */
+errno$1.isEnoentCodeError = isEnoentCodeError;
-var nullTag = '[object Null]',
- undefinedTag = '[object Undefined]';
-/** Built-in value references. */
+var fs$9 = {};
-var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
-/**
- * The base implementation of `getTag` without fallbacks for buggy environments.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
+Object.defineProperty(fs$9, "__esModule", {
+ value: true
+});
+fs$9.createDirentFromStats = void 0;
-function baseGetTag(value) {
- if (value == null) {
- return value === undefined ? undefinedTag : nullTag;
+class DirentFromStats$1 {
+ constructor(name, stats) {
+ this.name = name;
+ this.isBlockDevice = stats.isBlockDevice.bind(stats);
+ this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
+ this.isDirectory = stats.isDirectory.bind(stats);
+ this.isFIFO = stats.isFIFO.bind(stats);
+ this.isFile = stats.isFile.bind(stats);
+ this.isSocket = stats.isSocket.bind(stats);
+ this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
}
- return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
}
-var _baseGetTag = baseGetTag;
-
-/**
- * Checks if `value` is object-like. A value is object-like if it's not `null`
- * and has a `typeof` result of "object".
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
- * @example
- *
- * _.isObjectLike({});
- * // => true
- *
- * _.isObjectLike([1, 2, 3]);
- * // => true
- *
- * _.isObjectLike(_.noop);
- * // => false
- *
- * _.isObjectLike(null);
- * // => false
- */
-function isObjectLike(value) {
- return value != null && typeof value == 'object';
+function createDirentFromStats$1(name, stats) {
+ return new DirentFromStats$1(name, stats);
}
-var isObjectLike_1 = isObjectLike;
+fs$9.createDirentFromStats = createDirentFromStats$1;
-/** `Object#toString` result references. */
+var path$c = {};
-var symbolTag = '[object Symbol]';
+Object.defineProperty(path$c, "__esModule", {
+ value: true
+});
+path$c.removeLeadingDotSegment = path$c.escape = path$c.makeAbsolute = path$c.unixify = void 0;
+const path$b = require$$0__default$1["default"];
+const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
+
+const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
/**
- * Checks if `value` is classified as a `Symbol` primitive or object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
- * @example
- *
- * _.isSymbol(Symbol.iterator);
- * // => true
- *
- * _.isSymbol('abc');
- * // => false
+ * Designed to work only with simple paths: `dir\\file`.
*/
-function isSymbol(value) {
- return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag;
+function unixify(filepath) {
+ return filepath.replace(/\\/g, '/');
}
-var isSymbol_1 = isSymbol;
-
-/** Used to match property names within property paths. */
+path$c.unixify = unixify;
-var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
- reIsPlainProp = /^\w*$/;
-/**
- * Checks if `value` is a property name and not a property path.
- *
- * @private
- * @param {*} value The value to check.
- * @param {Object} [object] The object to query keys on.
- * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
- */
+function makeAbsolute(cwd, filepath) {
+ return path$b.resolve(cwd, filepath);
+}
-function isKey(value, object) {
- if (isArray_1(value)) {
- return false;
- }
+path$c.makeAbsolute = makeAbsolute;
- var type = typeof value;
+function escape(pattern) {
+ return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
+}
- if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) {
- return true;
- }
+path$c.escape = escape;
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
-}
+function removeLeadingDotSegment(entry) {
+ // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
+ // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
+ if (entry.charAt(0) === '.') {
+ const secondCharactery = entry.charAt(1);
-var _isKey = isKey;
+ if (secondCharactery === '/' || secondCharactery === '\\') {
+ return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
+ }
+ }
-/**
- * Checks if `value` is the
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
- * @example
- *
- * _.isObject({});
- * // => true
- *
- * _.isObject([1, 2, 3]);
- * // => true
- *
- * _.isObject(_.noop);
- * // => true
- *
- * _.isObject(null);
- * // => false
- */
-function isObject(value) {
- var type = typeof value;
- return value != null && (type == 'object' || type == 'function');
+ return entry;
}
-var isObject_1 = isObject;
+path$c.removeLeadingDotSegment = removeLeadingDotSegment;
-/** `Object#toString` result references. */
+var pattern$1 = {};
-var asyncTag = '[object AsyncFunction]',
- funcTag = '[object Function]',
- genTag = '[object GeneratorFunction]',
- proxyTag = '[object Proxy]';
-/**
- * Checks if `value` is classified as a `Function` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a function, else `false`.
- * @example
- *
- * _.isFunction(_);
- * // => true
+/*!
+ * is-extglob <https://github.com/jonschlinkert/is-extglob>
*
- * _.isFunction(/abc/);
- * // => false
+ * Copyright (c) 2014-2016, Jon Schlinkert.
+ * Licensed under the MIT License.
*/
-function isFunction(value) {
- if (!isObject_1(value)) {
+var isExtglob$1 = function isExtglob(str) {
+ if (typeof str !== 'string' || str === '') {
return false;
- } // The use of `Object#toString` avoids issues with the `typeof` operator
- // in Safari 9 which returns 'object' for typed arrays and other constructors.
-
-
- var tag = _baseGetTag(value);
- return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
-}
-
-var isFunction_1 = isFunction;
+ }
-/** Used to detect overreaching core-js shims. */
+ var match;
-var coreJsData = _root['__core-js_shared__'];
-var _coreJsData = coreJsData;
+ while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
+ if (match[2]) return true;
+ str = str.slice(match.index + match[0].length);
+ }
-/** Used to detect methods masquerading as native. */
+ return false;
+};
-var maskSrcKey = function () {
- var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
- return uid ? 'Symbol(src)_1.' + uid : '';
-}();
-/**
- * Checks if `func` has its source masked.
+/*!
+ * is-glob <https://github.com/jonschlinkert/is-glob>
*
- * @private
- * @param {Function} func The function to check.
- * @returns {boolean} Returns `true` if `func` is masked, else `false`.
+ * Copyright (c) 2014-2017, Jon Schlinkert.
+ * Released under the MIT License.
*/
+var isExtglob = isExtglob$1;
+var chars = {
+ '{': '}',
+ '(': ')',
+ '[': ']'
+};
+var strictCheck = function (str) {
+ if (str[0] === '!') {
+ return true;
+ }
-function isMasked(func) {
- return !!maskSrcKey && maskSrcKey in func;
-}
+ var index = 0;
+ var pipeIndex = -2;
+ var closeSquareIndex = -2;
+ var closeCurlyIndex = -2;
+ var closeParenIndex = -2;
+ var backSlashIndex = -2;
-var _isMasked = isMasked;
+ while (index < str.length) {
+ if (str[index] === '*') {
+ return true;
+ }
-/** Used for built-in method references. */
-var funcProto = Function.prototype;
-/** Used to resolve the decompiled source of functions. */
+ if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
+ return true;
+ }
-var funcToString = funcProto.toString;
-/**
- * Converts `func` to its source code.
- *
- * @private
- * @param {Function} func The function to convert.
- * @returns {string} Returns the source code.
- */
+ if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
+ if (closeSquareIndex < index) {
+ closeSquareIndex = str.indexOf(']', index);
+ }
-function toSource(func) {
- if (func != null) {
- try {
- return funcToString.call(func);
- } catch (e) {}
+ if (closeSquareIndex > index) {
+ if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
+ return true;
+ }
- try {
- return func + '';
- } catch (e) {}
- }
+ backSlashIndex = str.indexOf('\\', index);
- return '';
-}
+ if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
+ return true;
+ }
+ }
+ }
-var _toSource = toSource;
+ if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
+ closeCurlyIndex = str.indexOf('}', index);
-/**
- * Used to match `RegExp`
- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
- */
+ if (closeCurlyIndex > index) {
+ backSlashIndex = str.indexOf('\\', index);
-var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
-/** Used to detect host constructors (Safari). */
+ if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
+ return true;
+ }
+ }
+ }
-var reIsHostCtor = /^\[object .+?Constructor\]$/;
-/** Used for built-in method references. */
+ if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
+ closeParenIndex = str.indexOf(')', index);
-var funcProto$1 = Function.prototype,
- objectProto$2 = Object.prototype;
-/** Used to resolve the decompiled source of functions. */
+ if (closeParenIndex > index) {
+ backSlashIndex = str.indexOf('\\', index);
-var funcToString$1 = funcProto$1.toString;
-/** Used to check objects for own properties. */
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
+ return true;
+ }
+ }
+ }
-var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
-/** Used to detect if a method is native. */
+ if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
+ if (pipeIndex < index) {
+ pipeIndex = str.indexOf('|', index);
+ }
-var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
-/**
- * The base implementation of `_.isNative` without bad shim checks.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a native function,
- * else `false`.
- */
+ if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
+ closeParenIndex = str.indexOf(')', pipeIndex);
-function baseIsNative(value) {
- if (!isObject_1(value) || _isMasked(value)) {
- return false;
- }
+ if (closeParenIndex > pipeIndex) {
+ backSlashIndex = str.indexOf('\\', pipeIndex);
- var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
- return pattern.test(_toSource(value));
-}
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
+ return true;
+ }
+ }
+ }
+ }
-var _baseIsNative = baseIsNative;
+ if (str[index] === '\\') {
+ var open = str[index + 1];
+ index += 2;
+ var close = chars[open];
-/**
- * Gets the value at `key` of `object`.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {string} key The key of the property to get.
- * @returns {*} Returns the property value.
- */
-function getValue(object, key) {
- return object == null ? undefined : object[key];
-}
+ if (close) {
+ var n = str.indexOf(close, index);
+
+ if (n !== -1) {
+ index = n + 1;
+ }
+ }
-var _getValue = getValue;
+ if (str[index] === '!') {
+ return true;
+ }
+ } else {
+ index++;
+ }
+ }
-/**
- * Gets the native function at `key` of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {string} key The key of the method to get.
- * @returns {*} Returns the function if it's native, else `undefined`.
- */
+ return false;
+};
-function getNative(object, key) {
- var value = _getValue(object, key);
- return _baseIsNative(value) ? value : undefined;
-}
+var relaxedCheck = function (str) {
+ if (str[0] === '!') {
+ return true;
+ }
-var _getNative = getNative;
+ var index = 0;
-/* Built-in method references that are verified to be native. */
+ while (index < str.length) {
+ if (/[*?{}()[\]]/.test(str[index])) {
+ return true;
+ }
-var nativeCreate = _getNative(Object, 'create');
-var _nativeCreate = nativeCreate;
+ if (str[index] === '\\') {
+ var open = str[index + 1];
+ index += 2;
+ var close = chars[open];
-/**
- * Removes all key-value entries from the hash.
- *
- * @private
- * @name clear
- * @memberOf Hash
- */
+ if (close) {
+ var n = str.indexOf(close, index);
-function hashClear() {
- this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
- this.size = 0;
-}
+ if (n !== -1) {
+ index = n + 1;
+ }
+ }
-var _hashClear = hashClear;
+ if (str[index] === '!') {
+ return true;
+ }
+ } else {
+ index++;
+ }
+ }
-/**
- * Removes `key` and its value from the hash.
- *
- * @private
- * @name delete
- * @memberOf Hash
- * @param {Object} hash The hash to modify.
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
-function hashDelete(key) {
- var result = this.has(key) && delete this.__data__[key];
- this.size -= result ? 1 : 0;
- return result;
-}
+ return false;
+};
-var _hashDelete = hashDelete;
+var isGlob$1 = function isGlob(str, options) {
+ if (typeof str !== 'string' || str === '') {
+ return false;
+ }
-/** Used to stand-in for `undefined` hash values. */
+ if (isExtglob(str)) {
+ return true;
+ }
-var HASH_UNDEFINED = '__lodash_hash_undefined__';
-/** Used for built-in method references. */
+ var check = strictCheck; // optionally relax check
-var objectProto$3 = Object.prototype;
-/** Used to check objects for own properties. */
+ if (options && options.strict === false) {
+ check = relaxedCheck;
+ }
-var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
+ return check(str);
+};
+
+var isGlob = isGlob$1;
+var pathPosixDirname = require$$0__default$1["default"].posix.dirname;
+var isWin32 = require$$0__default["default"].platform() === 'win32';
+var slash = '/';
+var backslash = /\\/g;
+var enclosure = /[\{\[].*[\}\]]$/;
+var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
+var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
/**
- * Gets the hash value for `key`.
- *
- * @private
- * @name get
- * @memberOf Hash
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
+ * @param {string} str
+ * @param {Object} opts
+ * @param {boolean} [opts.flipBackslashes=true]
+ * @returns {string}
*/
-function hashGet(key) {
- var data = this.__data__;
+var globParent$1 = function globParent(str, opts) {
+ var options = Object.assign({
+ flipBackslashes: true
+ }, opts); // flip windows path separators
- if (_nativeCreate) {
- var result = data[key];
- return result === HASH_UNDEFINED ? undefined : result;
- }
+ if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
+ str = str.replace(backslash, slash);
+ } // special case for strings ending in enclosure containing path separator
- return hasOwnProperty$2.call(data, key) ? data[key] : undefined;
-}
-var _hashGet = hashGet;
+ if (enclosure.test(str)) {
+ str += slash;
+ } // preserves full path in case of trailing path separator
-/** Used for built-in method references. */
-var objectProto$4 = Object.prototype;
-/** Used to check objects for own properties. */
+ str += 'a'; // remove path parts that are globby
-var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
-/**
- * Checks if a hash value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Hash
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
+ do {
+ str = pathPosixDirname(str);
+ } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
-function hashHas(key) {
- var data = this.__data__;
- return _nativeCreate ? data[key] !== undefined : hasOwnProperty$3.call(data, key);
-}
-var _hashHas = hashHas;
+ return str.replace(escaped, '$1');
+};
-/** Used to stand-in for `undefined` hash values. */
+var utils$j = {};
-var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
-/**
- * Sets the hash `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Hash
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the hash instance.
- */
+(function (exports) {
-function hashSet(key, value) {
- var data = this.__data__;
- this.size += this.has(key) ? 0 : 1;
- data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
- return this;
-}
+ exports.isInteger = num => {
+ if (typeof num === 'number') {
+ return Number.isInteger(num);
+ }
-var _hashSet = hashSet;
+ if (typeof num === 'string' && num.trim() !== '') {
+ return Number.isInteger(Number(num));
+ }
-/**
- * Creates a hash object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
+ return false;
+ };
+ /**
+ * Find a node of the given type
+ */
-function Hash(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
- this.clear();
-
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
-} // Add methods to `Hash`.
+ exports.find = (node, type) => node.nodes.find(node => node.type === type);
+ /**
+ * Find a node of the given type
+ */
-Hash.prototype.clear = _hashClear;
-Hash.prototype['delete'] = _hashDelete;
-Hash.prototype.get = _hashGet;
-Hash.prototype.has = _hashHas;
-Hash.prototype.set = _hashSet;
-var _Hash = Hash;
-/**
- * Removes all key-value entries from the list cache.
- *
- * @private
- * @name clear
- * @memberOf ListCache
- */
-function listCacheClear() {
- this.__data__ = [];
- this.size = 0;
-}
+ exports.exceedsLimit = (min, max, step = 1, limit) => {
+ if (limit === false) return false;
+ if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
+ return (Number(max) - Number(min)) / Number(step) >= limit;
+ };
+ /**
+ * Escape the given node with '\\' before node.value
+ */
-var _listCacheClear = listCacheClear;
-/**
- * Performs a
- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
- * comparison between two values to determine if they are equivalent.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * var object = { 'a': 1 };
- * var other = { 'a': 1 };
- *
- * _.eq(object, object);
- * // => true
- *
- * _.eq(object, other);
- * // => false
- *
- * _.eq('a', 'a');
- * // => true
- *
- * _.eq('a', Object('a'));
- * // => false
- *
- * _.eq(NaN, NaN);
- * // => true
- */
-function eq(value, other) {
- return value === other || value !== value && other !== other;
-}
+ exports.escapeNode = (block, n = 0, type) => {
+ let node = block.nodes[n];
+ if (!node) return;
-var eq_1 = eq;
+ if (type && node.type === type || node.type === 'open' || node.type === 'close') {
+ if (node.escaped !== true) {
+ node.value = '\\' + node.value;
+ node.escaped = true;
+ }
+ }
+ };
+ /**
+ * Returns true if the given brace node should be enclosed in literal braces
+ */
-/**
- * Gets the index at which the `key` is found in `array` of key-value pairs.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} key The key to search for.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
-function assocIndexOf(array, key) {
- var length = array.length;
+ exports.encloseBrace = node => {
+ if (node.type !== 'brace') return false;
- while (length--) {
- if (eq_1(array[length][0], key)) {
- return length;
+ if (node.commas >> 0 + node.ranges >> 0 === 0) {
+ node.invalid = true;
+ return true;
}
- }
-
- return -1;
-}
-var _assocIndexOf = assocIndexOf;
+ return false;
+ };
+ /**
+ * Returns true if a brace node is invalid.
+ */
-/** Used for built-in method references. */
-var arrayProto = Array.prototype;
-/** Built-in value references. */
+ exports.isInvalidBrace = block => {
+ if (block.type !== 'brace') return false;
+ if (block.invalid === true || block.dollar) return true;
-var splice = arrayProto.splice;
-/**
- * Removes `key` and its value from the list cache.
- *
- * @private
- * @name delete
- * @memberOf ListCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
+ if (block.commas >> 0 + block.ranges >> 0 === 0) {
+ block.invalid = true;
+ return true;
+ }
-function listCacheDelete(key) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
+ if (block.open !== true || block.close !== true) {
+ block.invalid = true;
+ return true;
+ }
- if (index < 0) {
return false;
- }
+ };
+ /**
+ * Returns true if a node is an open or close node
+ */
- var lastIndex = data.length - 1;
- if (index == lastIndex) {
- data.pop();
- } else {
- splice.call(data, index, 1);
- }
+ exports.isOpenOrClose = node => {
+ if (node.type === 'open' || node.type === 'close') {
+ return true;
+ }
- --this.size;
- return true;
-}
+ return node.open === true || node.close === true;
+ };
+ /**
+ * Reduce an array of text nodes.
+ */
-var _listCacheDelete = listCacheDelete;
-/**
- * Gets the list cache value for `key`.
- *
- * @private
- * @name get
- * @memberOf ListCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
+ exports.reduce = nodes => nodes.reduce((acc, node) => {
+ if (node.type === 'text') acc.push(node.value);
+ if (node.type === 'range') node.type = 'text';
+ return acc;
+ }, []);
+ /**
+ * Flatten an array
+ */
-function listCacheGet(key) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
- return index < 0 ? undefined : data[index][1];
-}
-var _listCacheGet = listCacheGet;
+ exports.flatten = (...args) => {
+ const result = [];
-/**
- * Checks if a list cache value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf ListCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
+ const flat = arr => {
+ for (let i = 0; i < arr.length; i++) {
+ let ele = arr[i];
+ Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
+ }
-function listCacheHas(key) {
- return _assocIndexOf(this.__data__, key) > -1;
-}
+ return result;
+ };
-var _listCacheHas = listCacheHas;
+ flat(args);
+ return result;
+ };
+})(utils$j);
-/**
- * Sets the list cache `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf ListCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the list cache instance.
- */
+const utils$i = utils$j;
-function listCacheSet(key, value) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
+var stringify$6 = (ast, options = {}) => {
+ let stringify = (node, parent = {}) => {
+ let invalidBlock = options.escapeInvalid && utils$i.isInvalidBrace(parent);
+ let invalidNode = node.invalid === true && options.escapeInvalid === true;
+ let output = '';
- if (index < 0) {
- ++this.size;
- data.push([key, value]);
- } else {
- data[index][1] = value;
- }
+ if (node.value) {
+ if ((invalidBlock || invalidNode) && utils$i.isOpenOrClose(node)) {
+ return '\\' + node.value;
+ }
- return this;
-}
+ return node.value;
+ }
+
+ if (node.value) {
+ return node.value;
+ }
-var _listCacheSet = listCacheSet;
+ if (node.nodes) {
+ for (let child of node.nodes) {
+ output += stringify(child);
+ }
+ }
-/**
- * Creates an list cache object.
+ return output;
+ };
+
+ return stringify(ast);
+};
+
+/*!
+ * is-number <https://github.com/jonschlinkert/is-number>
*
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
+ * Copyright (c) 2014-present, Jon Schlinkert.
+ * Released under the MIT License.
*/
-function ListCache(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
- this.clear();
-
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
+var isNumber$3 = function (num) {
+ if (typeof num === 'number') {
+ return num - num === 0;
}
-} // Add methods to `ListCache`.
+ if (typeof num === 'string' && num.trim() !== '') {
+ return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
+ }
-ListCache.prototype.clear = _listCacheClear;
-ListCache.prototype['delete'] = _listCacheDelete;
-ListCache.prototype.get = _listCacheGet;
-ListCache.prototype.has = _listCacheHas;
-ListCache.prototype.set = _listCacheSet;
-var _ListCache = ListCache;
+ return false;
+};
-/* Built-in method references that are verified to be native. */
+const isNumber$2 = isNumber$3;
-var Map$1 = _getNative(_root, 'Map');
-var _Map = Map$1;
+const toRegexRange$1 = (min, max, options) => {
+ if (isNumber$2(min) === false) {
+ throw new TypeError('toRegexRange: expected the first argument to be a number');
+ }
-/**
- * Removes all key-value entries from the map.
- *
- * @private
- * @name clear
- * @memberOf MapCache
- */
+ if (max === void 0 || min === max) {
+ return String(min);
+ }
-function mapCacheClear() {
- this.size = 0;
- this.__data__ = {
- 'hash': new _Hash(),
- 'map': new (_Map || _ListCache)(),
- 'string': new _Hash()
- };
-}
+ if (isNumber$2(max) === false) {
+ throw new TypeError('toRegexRange: expected the second argument to be a number.');
+ }
-var _mapCacheClear = mapCacheClear;
+ let opts = Object.assign({
+ relaxZeros: true
+ }, options);
-/**
- * Checks if `value` is suitable for use as unique object key.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
- */
-function isKeyable(value) {
- var type = typeof value;
- return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
-}
+ if (typeof opts.strictZeros === 'boolean') {
+ opts.relaxZeros = opts.strictZeros === false;
+ }
-var _isKeyable = isKeyable;
+ let relax = String(opts.relaxZeros);
+ let shorthand = String(opts.shorthand);
+ let capture = String(opts.capture);
+ let wrap = String(opts.wrap);
+ let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
-/**
- * Gets the data for `map`.
- *
- * @private
- * @param {Object} map The map to query.
- * @param {string} key The reference key.
- * @returns {*} Returns the map data.
- */
+ if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
+ return toRegexRange$1.cache[cacheKey].result;
+ }
-function getMapData(map, key) {
- var data = map.__data__;
- return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
-}
+ let a = Math.min(min, max);
+ let b = Math.max(min, max);
-var _getMapData = getMapData;
+ if (Math.abs(a - b) === 1) {
+ let result = min + '|' + max;
-/**
- * Removes `key` and its value from the map.
- *
- * @private
- * @name delete
- * @memberOf MapCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
+ if (opts.capture) {
+ return `(${result})`;
+ }
-function mapCacheDelete(key) {
- var result = _getMapData(this, key)['delete'](key);
- this.size -= result ? 1 : 0;
- return result;
-}
+ if (opts.wrap === false) {
+ return result;
+ }
-var _mapCacheDelete = mapCacheDelete;
+ return `(?:${result})`;
+ }
-/**
- * Gets the map value for `key`.
- *
- * @private
- * @name get
- * @memberOf MapCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
+ let isPadded = hasPadding(min) || hasPadding(max);
+ let state = {
+ min,
+ max,
+ a,
+ b
+ };
+ let positives = [];
+ let negatives = [];
-function mapCacheGet(key) {
- return _getMapData(this, key).get(key);
-}
+ if (isPadded) {
+ state.isPadded = isPadded;
+ state.maxLen = String(state.max).length;
+ }
-var _mapCacheGet = mapCacheGet;
+ if (a < 0) {
+ let newMin = b < 0 ? Math.abs(b) : 1;
+ negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
+ a = state.a = 0;
+ }
-/**
- * Checks if a map value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf MapCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
+ if (b >= 0) {
+ positives = splitToPatterns(a, b, state, opts);
+ }
-function mapCacheHas(key) {
- return _getMapData(this, key).has(key);
-}
+ state.negatives = negatives;
+ state.positives = positives;
+ state.result = collatePatterns(negatives, positives);
-var _mapCacheHas = mapCacheHas;
+ if (opts.capture === true) {
+ state.result = `(${state.result})`;
+ } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
+ state.result = `(?:${state.result})`;
+ }
-/**
- * Sets the map `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf MapCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the map cache instance.
- */
+ toRegexRange$1.cache[cacheKey] = state;
+ return state.result;
+};
-function mapCacheSet(key, value) {
- var data = _getMapData(this, key),
- size = data.size;
- data.set(key, value);
- this.size += data.size == size ? 0 : 1;
- return this;
+function collatePatterns(neg, pos, options) {
+ let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
+ let onlyPositive = filterPatterns(pos, neg, '', false) || [];
+ let intersected = filterPatterns(neg, pos, '-?', true) || [];
+ let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
+ return subpatterns.join('|');
}
-var _mapCacheSet = mapCacheSet;
-
-/**
- * Creates a map cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
-
-function MapCache(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
- this.clear();
+function splitToRanges(min, max) {
+ let nines = 1;
+ let zeros = 1;
+ let stop = countNines(min, nines);
+ let stops = new Set([max]);
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
+ while (min <= stop && stop <= max) {
+ stops.add(stop);
+ nines += 1;
+ stop = countNines(min, nines);
}
-} // Add methods to `MapCache`.
-
-MapCache.prototype.clear = _mapCacheClear;
-MapCache.prototype['delete'] = _mapCacheDelete;
-MapCache.prototype.get = _mapCacheGet;
-MapCache.prototype.has = _mapCacheHas;
-MapCache.prototype.set = _mapCacheSet;
-var _MapCache = MapCache;
+ stop = countZeros(max + 1, zeros) - 1;
-/** Error message constants. */
+ while (min < stop && stop <= max) {
+ stops.add(stop);
+ zeros += 1;
+ stop = countZeros(max + 1, zeros) - 1;
+ }
-var FUNC_ERROR_TEXT = 'Expected a function';
+ stops = [...stops];
+ stops.sort(compare);
+ return stops;
+}
/**
- * Creates a function that memoizes the result of `func`. If `resolver` is
- * provided, it determines the cache key for storing the result based on the
- * arguments provided to the memoized function. By default, the first argument
- * provided to the memoized function is used as the map cache key. The `func`
- * is invoked with the `this` binding of the memoized function.
- *
- * **Note:** The cache is exposed as the `cache` property on the memoized
- * function. Its creation may be customized by replacing the `_.memoize.Cache`
- * constructor with one whose instances implement the
- * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
- * method interface of `clear`, `delete`, `get`, `has`, and `set`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Function
- * @param {Function} func The function to have its output memoized.
- * @param {Function} [resolver] The function to resolve the cache key.
- * @returns {Function} Returns the new memoized function.
- * @example
- *
- * var object = { 'a': 1, 'b': 2 };
- * var other = { 'c': 3, 'd': 4 };
- *
- * var values = _.memoize(_.values);
- * values(object);
- * // => [1, 2]
- *
- * values(other);
- * // => [3, 4]
- *
- * object.a = 2;
- * values(object);
- * // => [1, 2]
- *
- * // Modify the result cache.
- * values.cache.set(object, ['a', 'b']);
- * values(object);
- * // => ['a', 'b']
- *
- * // Replace `_.memoize.Cache`.
- * _.memoize.Cache = WeakMap;
+ * Convert a range to a regex pattern
+ * @param {Number} `start`
+ * @param {Number} `stop`
+ * @return {String}
*/
-function memoize(func, resolver) {
- if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
- throw new TypeError(FUNC_ERROR_TEXT);
+
+function rangeToPattern(start, stop, options) {
+ if (start === stop) {
+ return {
+ pattern: start,
+ count: [],
+ digits: 0
+ };
}
- var memoized = function () {
- var args = arguments,
- key = resolver ? resolver.apply(this, args) : args[0],
- cache = memoized.cache;
+ let zipped = zip(start, stop);
+ let digits = zipped.length;
+ let pattern = '';
+ let count = 0;
- if (cache.has(key)) {
- return cache.get(key);
+ for (let i = 0; i < digits; i++) {
+ let [startDigit, stopDigit] = zipped[i];
+
+ if (startDigit === stopDigit) {
+ pattern += startDigit;
+ } else if (startDigit !== '0' || stopDigit !== '9') {
+ pattern += toCharacterClass(startDigit, stopDigit);
+ } else {
+ count++;
}
+ }
- var result = func.apply(this, args);
- memoized.cache = cache.set(key, result) || cache;
- return result;
- };
+ if (count) {
+ pattern += options.shorthand === true ? '\\d' : '[0-9]';
+ }
- memoized.cache = new (memoize.Cache || _MapCache)();
- return memoized;
-} // Expose `MapCache`.
+ return {
+ pattern,
+ count: [count],
+ digits
+ };
+}
+function splitToPatterns(min, max, tok, options) {
+ let ranges = splitToRanges(min, max);
+ let tokens = [];
+ let start = min;
+ let prev;
-memoize.Cache = _MapCache;
-var memoize_1 = memoize;
+ for (let i = 0; i < ranges.length; i++) {
+ let max = ranges[i];
+ let obj = rangeToPattern(String(start), String(max), options);
+ let zeros = '';
-/** Used as the maximum memoize cache size. */
+ if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
+ if (prev.count.length > 1) {
+ prev.count.pop();
+ }
-var MAX_MEMOIZE_SIZE = 500;
-/**
- * A specialized version of `_.memoize` which clears the memoized function's
- * cache when it exceeds `MAX_MEMOIZE_SIZE`.
- *
- * @private
- * @param {Function} func The function to have its output memoized.
- * @returns {Function} Returns the new memoized function.
- */
+ prev.count.push(obj.count[0]);
+ prev.string = prev.pattern + toQuantifier(prev.count);
+ start = max + 1;
+ continue;
+ }
-function memoizeCapped(func) {
- var result = memoize_1(func, function (key) {
- if (cache.size === MAX_MEMOIZE_SIZE) {
- cache.clear();
+ if (tok.isPadded) {
+ zeros = padZeros(max, tok, options);
}
- return key;
- });
- var cache = result.cache;
- return result;
-}
+ obj.string = zeros + obj.pattern + toQuantifier(obj.count);
+ tokens.push(obj);
+ start = max + 1;
+ prev = obj;
+ }
-var _memoizeCapped = memoizeCapped;
+ return tokens;
+}
-/** Used to match property names within property paths. */
+function filterPatterns(arr, comparison, prefix, intersection, options) {
+ let result = [];
-var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
-/** Used to match backslashes in property paths. */
+ for (let ele of arr) {
+ let {
+ string
+ } = ele; // only push if _both_ are negative...
-var reEscapeChar = /\\(\\)?/g;
-/**
- * Converts `string` to a property path array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the property path array.
- */
+ if (!intersection && !contains(comparison, 'string', string)) {
+ result.push(prefix + string);
+ } // or _both_ are positive
-var stringToPath = _memoizeCapped(function (string) {
- var result = [];
- if (string.charCodeAt(0) === 46
- /* . */
- ) {
- result.push('');
+ if (intersection && contains(comparison, 'string', string)) {
+ result.push(prefix + string);
}
-
- string.replace(rePropName, function (match, number, quote, subString) {
- result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
- });
- return result;
-});
-var _stringToPath = stringToPath;
-
-/**
- * A specialized version of `_.map` for arrays without support for iteratee
- * shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the new mapped array.
- */
-function arrayMap(array, iteratee) {
- var index = -1,
- length = array == null ? 0 : array.length,
- result = Array(length);
-
- while (++index < length) {
- result[index] = iteratee(array[index], index, array);
}
return result;
}
-
-var _arrayMap = arrayMap;
-
-/** Used as references for various `Number` constants. */
-
-var INFINITY = 1 / 0;
-/** Used to convert symbols to primitives and strings. */
-
-var symbolProto = _Symbol ? _Symbol.prototype : undefined,
- symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
- * The base implementation of `_.toString` which doesn't convert nullish
- * values to empty strings.
- *
- * @private
- * @param {*} value The value to process.
- * @returns {string} Returns the string.
+ * Zip strings
*/
-function baseToString(value) {
- // Exit early for strings to avoid a performance hit in some environments.
- if (typeof value == 'string') {
- return value;
- }
- if (isArray_1(value)) {
- // Recursively convert values (susceptible to call stack limits).
- return _arrayMap(value, baseToString) + '';
- }
+function zip(a, b) {
+ let arr = [];
- if (isSymbol_1(value)) {
- return symbolToString ? symbolToString.call(value) : '';
- }
+ for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
- var result = value + '';
- return result == '0' && 1 / value == -INFINITY ? '-0' : result;
+ return arr;
}
-var _baseToString = baseToString;
+function compare(a, b) {
+ return a > b ? 1 : b > a ? -1 : 0;
+}
-/**
- * Converts `value` to a string. An empty string is returned for `null`
- * and `undefined` values. The sign of `-0` is preserved.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {string} Returns the converted string.
- * @example
- *
- * _.toString(null);
- * // => ''
- *
- * _.toString(-0);
- * // => '-0'
- *
- * _.toString([1, 2, 3]);
- * // => '1,2,3'
- */
+function contains(arr, key, val) {
+ return arr.some(ele => ele[key] === val);
+}
-function toString(value) {
- return value == null ? '' : _baseToString(value);
+function countNines(min, len) {
+ return Number(String(min).slice(0, -len) + '9'.repeat(len));
}
-var toString_1 = toString;
+function countZeros(integer, zeros) {
+ return integer - integer % Math.pow(10, zeros);
+}
-/**
- * Casts `value` to a path array if it's not one.
- *
- * @private
- * @param {*} value The value to inspect.
- * @param {Object} [object] The object to query keys on.
- * @returns {Array} Returns the cast property path array.
- */
+function toQuantifier(digits) {
+ let [start = 0, stop = ''] = digits;
-function castPath(value, object) {
- if (isArray_1(value)) {
- return value;
+ if (stop || start > 1) {
+ return `{${start + (stop ? ',' + stop : '')}}`;
}
- return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
+ return '';
}
-var _castPath = castPath;
-
-/** Used as references for various `Number` constants. */
+function toCharacterClass(a, b, options) {
+ return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
+}
-var INFINITY$1 = 1 / 0;
-/**
- * Converts `value` to a string key if it's not a string or symbol.
- *
- * @private
- * @param {*} value The value to inspect.
- * @returns {string|symbol} Returns the key.
- */
+function hasPadding(str) {
+ return /^-?(0+)\d/.test(str);
+}
-function toKey(value) {
- if (typeof value == 'string' || isSymbol_1(value)) {
+function padZeros(value, tok, options) {
+ if (!tok.isPadded) {
return value;
}
- var result = value + '';
- return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
-}
+ let diff = Math.abs(tok.maxLen - String(value).length);
+ let relax = options.relaxZeros !== false;
-var _toKey = toKey;
+ switch (diff) {
+ case 0:
+ return '';
-/**
- * The base implementation of `_.get` without support for default values.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @returns {*} Returns the resolved value.
- */
+ case 1:
+ return relax ? '0?' : '0';
-function baseGet(object, path) {
- path = _castPath(path, object);
- var index = 0,
- length = path.length;
+ case 2:
+ return relax ? '0{0,2}' : '00';
- while (object != null && index < length) {
- object = object[_toKey(path[index++])];
+ default:
+ {
+ return relax ? `0{0,${diff}}` : `0{${diff}}`;
+ }
}
-
- return index && index == length ? object : undefined;
}
+/**
+ * Cache
+ */
-var _baseGet = baseGet;
-
-var defineProperty = function () {
- try {
- var func = _getNative(Object, 'defineProperty');
- func({}, '', {});
- return func;
- } catch (e) {}
-}();
-var _defineProperty = defineProperty;
+toRegexRange$1.cache = {};
+toRegexRange$1.clearCache = () => toRegexRange$1.cache = {};
/**
- * The base implementation of `assignValue` and `assignMergeValue` without
- * value checks.
- *
- * @private
- * @param {Object} object The object to modify.
- * @param {string} key The key of the property to assign.
- * @param {*} value The value to assign.
+ * Expose `toRegexRange`
*/
-function baseAssignValue(object, key, value) {
- if (key == '__proto__' && _defineProperty) {
- _defineProperty(object, key, {
- 'configurable': true,
- 'enumerable': true,
- 'value': value,
- 'writable': true
- });
- } else {
- object[key] = value;
- }
-}
-var _baseAssignValue = baseAssignValue;
+var toRegexRange_1 = toRegexRange$1;
-/** Used for built-in method references. */
+const util$1 = require$$0__default$2["default"];
+const toRegexRange = toRegexRange_1;
-var objectProto$5 = Object.prototype;
-/** Used to check objects for own properties. */
+const isObject$6 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
-var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
-/**
- * Assigns `value` to `key` of `object` if the existing value is not equivalent
- * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
- * for equality comparisons.
- *
- * @private
- * @param {Object} object The object to modify.
- * @param {string} key The key of the property to assign.
- * @param {*} value The value to assign.
- */
+const transform = toNumber => {
+ return value => toNumber === true ? Number(value) : String(value);
+};
-function assignValue(object, key, value) {
- var objValue = object[key];
+const isValidValue = value => {
+ return typeof value === 'number' || typeof value === 'string' && value !== '';
+};
- if (!(hasOwnProperty$4.call(object, key) && eq_1(objValue, value)) || value === undefined && !(key in object)) {
- _baseAssignValue(object, key, value);
- }
-}
+const isNumber$1 = num => Number.isInteger(+num);
-var _assignValue = assignValue;
+const zeros = input => {
+ let value = `${input}`;
+ let index = -1;
+ if (value[0] === '-') value = value.slice(1);
+ if (value === '0') return false;
-/** Used as references for various `Number` constants. */
-var MAX_SAFE_INTEGER = 9007199254740991;
-/** Used to detect unsigned integer values. */
+ while (value[++index] === '0');
-var reIsUint = /^(?:0|[1-9]\d*)$/;
-/**
- * Checks if `value` is a valid array-like index.
- *
- * @private
- * @param {*} value The value to check.
- * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
- * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
- */
+ return index > 0;
+};
-function isIndex(value, length) {
- var type = typeof value;
- length = length == null ? MAX_SAFE_INTEGER : length;
- return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
-}
+const stringify$5 = (start, end, options) => {
+ if (typeof start === 'string' || typeof end === 'string') {
+ return true;
+ }
-var _isIndex = isIndex;
+ return options.stringify === true;
+};
-/**
- * The base implementation of `_.set`.
- *
- * @private
- * @param {Object} object The object to modify.
- * @param {Array|string} path The path of the property to set.
- * @param {*} value The value to set.
- * @param {Function} [customizer] The function to customize path creation.
- * @returns {Object} Returns `object`.
- */
+const pad = (input, maxLength, toNumber) => {
+ if (maxLength > 0) {
+ let dash = input[0] === '-' ? '-' : '';
+ if (dash) input = input.slice(1);
+ input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
+ }
-function baseSet(object, path, value, customizer) {
- if (!isObject_1(object)) {
- return object;
+ if (toNumber === false) {
+ return String(input);
}
- path = _castPath(path, object);
- var index = -1,
- length = path.length,
- lastIndex = length - 1,
- nested = object;
+ return input;
+};
- while (nested != null && ++index < length) {
- var key = _toKey(path[index]),
- newValue = value;
+const toMaxLen = (input, maxLength) => {
+ let negative = input[0] === '-' ? '-' : '';
- if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
- return object;
- }
+ if (negative) {
+ input = input.slice(1);
+ maxLength--;
+ }
- if (index != lastIndex) {
- var objValue = nested[key];
- newValue = customizer ? customizer(objValue, key, nested) : undefined;
+ while (input.length < maxLength) input = '0' + input;
- if (newValue === undefined) {
- newValue = isObject_1(objValue) ? objValue : _isIndex(path[index + 1]) ? [] : {};
- }
- }
+ return negative ? '-' + input : input;
+};
- _assignValue(nested, key, newValue);
- nested = nested[key];
+const toSequence = (parts, options) => {
+ parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
+ parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
+ let prefix = options.capture ? '' : '?:';
+ let positives = '';
+ let negatives = '';
+ let result;
+
+ if (parts.positives.length) {
+ positives = parts.positives.join('|');
}
- return object;
-}
+ if (parts.negatives.length) {
+ negatives = `-(${prefix}${parts.negatives.join('|')})`;
+ }
-var _baseSet = baseSet;
+ if (positives && negatives) {
+ result = `${positives}|${negatives}`;
+ } else {
+ result = positives || negatives;
+ }
-/**
- * The base implementation of `_.pickBy` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The source object.
- * @param {string[]} paths The property paths to pick.
- * @param {Function} predicate The function invoked per property.
- * @returns {Object} Returns the new object.
- */
+ if (options.wrap) {
+ return `(${prefix}${result})`;
+ }
-function basePickBy(object, paths, predicate) {
- var index = -1,
- length = paths.length,
- result = {};
+ return result;
+};
- while (++index < length) {
- var path = paths[index],
- value = _baseGet(object, path);
+const toRange = (a, b, isNumbers, options) => {
+ if (isNumbers) {
+ return toRegexRange(a, b, Object.assign({
+ wrap: false
+ }, options));
+ }
- if (predicate(value, path)) {
- _baseSet(result, _castPath(path, object), value);
- }
+ let start = String.fromCharCode(a);
+ if (a === b) return start;
+ let stop = String.fromCharCode(b);
+ return `[${start}-${stop}]`;
+};
+
+const toRegex = (start, end, options) => {
+ if (Array.isArray(start)) {
+ let wrap = options.wrap === true;
+ let prefix = options.capture ? '' : '?:';
+ return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
}
- return result;
-}
+ return toRegexRange(start, end, options);
+};
-var _basePickBy = basePickBy;
+const rangeError = (...args) => {
+ return new RangeError('Invalid range arguments: ' + util$1.inspect(...args));
+};
-/**
- * The base implementation of `_.hasIn` without support for deep paths.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {Array|string} key The key to check.
- * @returns {boolean} Returns `true` if `key` exists, else `false`.
- */
-function baseHasIn(object, key) {
- return object != null && key in Object(object);
-}
+const invalidRange = (start, end, options) => {
+ if (options.strictRanges === true) throw rangeError([start, end]);
+ return [];
+};
-var _baseHasIn = baseHasIn;
+const invalidStep = (step, options) => {
+ if (options.strictRanges === true) {
+ throw new TypeError(`Expected step "${step}" to be a number`);
+ }
-/** `Object#toString` result references. */
+ return [];
+};
-var argsTag = '[object Arguments]';
-/**
- * The base implementation of `_.isArguments`.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- */
+const fillNumbers = (start, end, step = 1, options = {}) => {
+ let a = Number(start);
+ let b = Number(end);
-function baseIsArguments(value) {
- return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
-}
+ if (!Number.isInteger(a) || !Number.isInteger(b)) {
+ if (options.strictRanges === true) throw rangeError([start, end]);
+ return [];
+ } // fix negative zero
-var _baseIsArguments = baseIsArguments;
-/** Used for built-in method references. */
+ if (a === 0) a = 0;
+ if (b === 0) b = 0;
+ let descending = a > b;
+ let startString = String(start);
+ let endString = String(end);
+ let stepString = String(step);
+ step = Math.max(Math.abs(step), 1);
+ let padded = zeros(startString) || zeros(endString) || zeros(stepString);
+ let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
+ let toNumber = padded === false && stringify$5(start, end, options) === false;
+ let format = options.transform || transform(toNumber);
-var objectProto$6 = Object.prototype;
-/** Used to check objects for own properties. */
+ if (options.toRegex && step === 1) {
+ return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
+ }
-var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
-/** Built-in value references. */
+ let parts = {
+ negatives: [],
+ positives: []
+ };
-var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
-/**
- * Checks if `value` is likely an `arguments` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- * else `false`.
- * @example
- *
- * _.isArguments(function() { return arguments; }());
- * // => true
- *
- * _.isArguments([1, 2, 3]);
- * // => false
- */
+ let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
-var isArguments = _baseIsArguments(function () {
- return arguments;
-}()) ? _baseIsArguments : function (value) {
- return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
-};
-var isArguments_1 = isArguments;
+ let range = [];
+ let index = 0;
-/** Used as references for various `Number` constants. */
-var MAX_SAFE_INTEGER$1 = 9007199254740991;
-/**
- * Checks if `value` is a valid array-like length.
- *
- * **Note:** This method is loosely based on
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
- * @example
- *
- * _.isLength(3);
- * // => true
- *
- * _.isLength(Number.MIN_VALUE);
- * // => false
- *
- * _.isLength(Infinity);
- * // => false
- *
- * _.isLength('3');
- * // => false
- */
-
-function isLength(value) {
- return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
-}
+ while (descending ? a >= b : a <= b) {
+ if (options.toRegex === true && step > 1) {
+ push(a);
+ } else {
+ range.push(pad(format(a, index), maxLen, toNumber));
+ }
-var isLength_1 = isLength;
+ a = descending ? a - step : a + step;
+ index++;
+ }
-/**
- * Checks if `path` exists on `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @param {Function} hasFunc The function to check properties.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- */
+ if (options.toRegex === true) {
+ return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
+ wrap: false
+ }, options));
+ }
-function hasPath(object, path, hasFunc) {
- path = _castPath(path, object);
- var index = -1,
- length = path.length,
- result = false;
+ return range;
+};
- while (++index < length) {
- var key = _toKey(path[index]);
+const fillLetters = (start, end, step = 1, options = {}) => {
+ if (!isNumber$1(start) && start.length > 1 || !isNumber$1(end) && end.length > 1) {
+ return invalidRange(start, end, options);
+ }
- if (!(result = object != null && hasFunc(object, key))) {
- break;
- }
+ let format = options.transform || (val => String.fromCharCode(val));
- object = object[key];
- }
+ let a = `${start}`.charCodeAt(0);
+ let b = `${end}`.charCodeAt(0);
+ let descending = a > b;
+ let min = Math.min(a, b);
+ let max = Math.max(a, b);
- if (result || ++index != length) {
- return result;
+ if (options.toRegex && step === 1) {
+ return toRange(min, max, false, options);
}
- length = object == null ? 0 : object.length;
- return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
-}
+ let range = [];
+ let index = 0;
-var _hasPath = hasPath;
+ while (descending ? a >= b : a <= b) {
+ range.push(format(a, index));
+ a = descending ? a - step : a + step;
+ index++;
+ }
-/**
- * Checks if `path` is a direct or inherited property of `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- * @example
- *
- * var object = _.create({ 'a': _.create({ 'b': 2 }) });
- *
- * _.hasIn(object, 'a');
- * // => true
- *
- * _.hasIn(object, 'a.b');
- * // => true
- *
- * _.hasIn(object, ['a', 'b']);
- * // => true
- *
- * _.hasIn(object, 'b');
- * // => false
- */
+ if (options.toRegex === true) {
+ return toRegex(range, null, {
+ wrap: false,
+ options
+ });
+ }
-function hasIn(object, path) {
- return object != null && _hasPath(object, path, _baseHasIn);
-}
+ return range;
+};
-var hasIn_1 = hasIn;
+const fill$2 = (start, end, step, options = {}) => {
+ if (end == null && isValidValue(start)) {
+ return [start];
+ }
-/**
- * The base implementation of `_.pick` without support for individual
- * property identifiers.
- *
- * @private
- * @param {Object} object The source object.
- * @param {string[]} paths The property paths to pick.
- * @returns {Object} Returns the new object.
- */
+ if (!isValidValue(start) || !isValidValue(end)) {
+ return invalidRange(start, end, options);
+ }
-function basePick(object, paths) {
- return _basePickBy(object, paths, function (value, path) {
- return hasIn_1(object, path);
- });
-}
+ if (typeof step === 'function') {
+ return fill$2(start, end, 1, {
+ transform: step
+ });
+ }
-var _basePick = basePick;
+ if (isObject$6(step)) {
+ return fill$2(start, end, 0, step);
+ }
-/**
- * Appends the elements of `values` to `array`.
- *
- * @private
- * @param {Array} array The array to modify.
- * @param {Array} values The values to append.
- * @returns {Array} Returns `array`.
- */
-function arrayPush(array, values) {
- var index = -1,
- length = values.length,
- offset = array.length;
+ let opts = Object.assign({}, options);
+ if (opts.capture === true) opts.wrap = true;
+ step = step || opts.step || 1;
- while (++index < length) {
- array[offset + index] = values[index];
+ if (!isNumber$1(step)) {
+ if (step != null && !isObject$6(step)) return invalidStep(step, opts);
+ return fill$2(start, end, 1, step);
}
- return array;
-}
+ if (isNumber$1(start) && isNumber$1(end)) {
+ return fillNumbers(start, end, step, opts);
+ }
-var _arrayPush = arrayPush;
+ return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
+};
-/** Built-in value references. */
+var fillRange = fill$2;
-var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
-/**
- * Checks if `value` is a flattenable `arguments` object or array.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
- */
+const fill$1 = fillRange;
+const utils$h = utils$j;
-function isFlattenable(value) {
- return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
-}
+const compile$1 = (ast, options = {}) => {
+ let walk = (node, parent = {}) => {
+ let invalidBlock = utils$h.isInvalidBrace(parent);
+ let invalidNode = node.invalid === true && options.escapeInvalid === true;
+ let invalid = invalidBlock === true || invalidNode === true;
+ let prefix = options.escapeInvalid === true ? '\\' : '';
+ let output = '';
-var _isFlattenable = isFlattenable;
+ if (node.isOpen === true) {
+ return prefix + node.value;
+ }
-/**
- * The base implementation of `_.flatten` with support for restricting flattening.
- *
- * @private
- * @param {Array} array The array to flatten.
- * @param {number} depth The maximum recursion depth.
- * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
- * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
- * @param {Array} [result=[]] The initial result value.
- * @returns {Array} Returns the new flattened array.
- */
+ if (node.isClose === true) {
+ return prefix + node.value;
+ }
-function baseFlatten(array, depth, predicate, isStrict, result) {
- var index = -1,
- length = array.length;
- predicate || (predicate = _isFlattenable);
- result || (result = []);
+ if (node.type === 'open') {
+ return invalid ? prefix + node.value : '(';
+ }
- while (++index < length) {
- var value = array[index];
+ if (node.type === 'close') {
+ return invalid ? prefix + node.value : ')';
+ }
- if (depth > 0 && predicate(value)) {
- if (depth > 1) {
- // Recursively flatten arrays (susceptible to call stack limits).
- baseFlatten(value, depth - 1, predicate, isStrict, result);
- } else {
- _arrayPush(result, value);
- }
- } else if (!isStrict) {
- result[result.length] = value;
+ if (node.type === 'comma') {
+ return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
}
- }
- return result;
-}
+ if (node.value) {
+ return node.value;
+ }
-var _baseFlatten = baseFlatten;
+ if (node.nodes && node.ranges > 0) {
+ let args = utils$h.reduce(node.nodes);
+ let range = fill$1(...args, Object.assign(Object.assign({}, options), {}, {
+ wrap: false,
+ toRegex: true
+ }));
-/**
- * Flattens `array` a single level deep.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Array
- * @param {Array} array The array to flatten.
- * @returns {Array} Returns the new flattened array.
- * @example
- *
- * _.flatten([1, [2, [3, [4]], 5]]);
- * // => [1, 2, [3, [4]], 5]
- */
+ if (range.length !== 0) {
+ return args.length > 1 && range.length > 1 ? `(${range})` : range;
+ }
+ }
-function flatten(array) {
- var length = array == null ? 0 : array.length;
- return length ? _baseFlatten(array, 1) : [];
-}
+ if (node.nodes) {
+ for (let child of node.nodes) {
+ output += walk(child, node);
+ }
+ }
-var flatten_1 = flatten;
+ return output;
+ };
-/**
- * A faster alternative to `Function#apply`, this function invokes `func`
- * with the `this` binding of `thisArg` and the arguments of `args`.
- *
- * @private
- * @param {Function} func The function to invoke.
- * @param {*} thisArg The `this` binding of `func`.
- * @param {Array} args The arguments to invoke `func` with.
- * @returns {*} Returns the result of `func`.
- */
-function apply(func, thisArg, args) {
- switch (args.length) {
- case 0:
- return func.call(thisArg);
+ return walk(ast);
+};
- case 1:
- return func.call(thisArg, args[0]);
+var compile_1 = compile$1;
- case 2:
- return func.call(thisArg, args[0], args[1]);
+const fill = fillRange;
+const stringify$4 = stringify$6;
+const utils$g = utils$j;
- case 3:
- return func.call(thisArg, args[0], args[1], args[2]);
- }
+const append = (queue = '', stash = '', enclose = false) => {
+ let result = [];
+ queue = [].concat(queue);
+ stash = [].concat(stash);
+ if (!stash.length) return queue;
- return func.apply(thisArg, args);
-}
+ if (!queue.length) {
+ return enclose ? utils$g.flatten(stash).map(ele => `{${ele}}`) : stash;
+ }
-var _apply = apply;
+ for (let item of queue) {
+ if (Array.isArray(item)) {
+ for (let value of item) {
+ result.push(append(value, stash, enclose));
+ }
+ } else {
+ for (let ele of stash) {
+ if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
+ result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
+ }
+ }
+ }
-/* Built-in method references for those with the same name as other `lodash` methods. */
+ return utils$g.flatten(result);
+};
-var nativeMax = Math.max;
-/**
- * A specialized version of `baseRest` which transforms the rest array.
- *
- * @private
- * @param {Function} func The function to apply a rest parameter to.
- * @param {number} [start=func.length-1] The start position of the rest parameter.
- * @param {Function} transform The rest array transform.
- * @returns {Function} Returns the new function.
- */
+const expand$1 = (ast, options = {}) => {
+ let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
-function overRest(func, start, transform) {
- start = nativeMax(start === undefined ? func.length - 1 : start, 0);
- return function () {
- var args = arguments,
- index = -1,
- length = nativeMax(args.length - start, 0),
- array = Array(length);
+ let walk = (node, parent = {}) => {
+ node.queue = [];
+ let p = parent;
+ let q = parent.queue;
- while (++index < length) {
- array[index] = args[start + index];
+ while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
+ p = p.parent;
+ q = p.queue;
}
- index = -1;
- var otherArgs = Array(start + 1);
+ if (node.invalid || node.dollar) {
+ q.push(append(q.pop(), stringify$4(node, options)));
+ return;
+ }
- while (++index < start) {
- otherArgs[index] = args[index];
+ if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
+ q.push(append(q.pop(), ['{}']));
+ return;
}
- otherArgs[start] = transform(array);
- return _apply(func, this, otherArgs);
- };
-}
+ if (node.nodes && node.ranges > 0) {
+ let args = utils$g.reduce(node.nodes);
-var _overRest = overRest;
+ if (utils$g.exceedsLimit(...args, options.step, rangeLimit)) {
+ throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
+ }
-/**
- * Creates a function that returns `value`.
- *
- * @static
- * @memberOf _
- * @since 2.4.0
- * @category Util
- * @param {*} value The value to return from the new function.
- * @returns {Function} Returns the new constant function.
- * @example
- *
- * var objects = _.times(2, _.constant({ 'a': 1 }));
- *
- * console.log(objects);
- * // => [{ 'a': 1 }, { 'a': 1 }]
- *
- * console.log(objects[0] === objects[1]);
- * // => true
- */
-function constant(value) {
- return function () {
- return value;
- };
-}
+ let range = fill(...args, options);
-var constant_1 = constant;
+ if (range.length === 0) {
+ range = stringify$4(node, options);
+ }
-/**
- * This method returns the first argument it receives.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Util
- * @param {*} value Any value.
- * @returns {*} Returns `value`.
- * @example
- *
- * var object = { 'a': 1 };
- *
- * console.log(_.identity(object) === object);
- * // => true
- */
-function identity(value) {
- return value;
-}
+ q.push(append(q.pop(), range));
+ node.nodes = [];
+ return;
+ }
-var identity_1 = identity;
+ let enclose = utils$g.encloseBrace(node);
+ let queue = node.queue;
+ let block = node;
-/**
- * The base implementation of `setToString` without support for hot loop shorting.
- *
- * @private
- * @param {Function} func The function to modify.
- * @param {Function} string The `toString` result.
- * @returns {Function} Returns `func`.
- */
+ while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
+ block = block.parent;
+ queue = block.queue;
+ }
-var baseSetToString = !_defineProperty ? identity_1 : function (func, string) {
- return _defineProperty(func, 'toString', {
- 'configurable': true,
- 'enumerable': false,
- 'value': constant_1(string),
- 'writable': true
- });
-};
-var _baseSetToString = baseSetToString;
+ for (let i = 0; i < node.nodes.length; i++) {
+ let child = node.nodes[i];
-/** Used to detect hot functions by number of calls within a span of milliseconds. */
-var HOT_COUNT = 800,
- HOT_SPAN = 16;
-/* Built-in method references for those with the same name as other `lodash` methods. */
+ if (child.type === 'comma' && node.type === 'brace') {
+ if (i === 1) queue.push('');
+ queue.push('');
+ continue;
+ }
-var nativeNow = Date.now;
-/**
- * Creates a function that'll short out and invoke `identity` instead
- * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
- * milliseconds.
- *
- * @private
- * @param {Function} func The function to restrict.
- * @returns {Function} Returns the new shortable function.
- */
+ if (child.type === 'close') {
+ q.push(append(q.pop(), queue, enclose));
+ continue;
+ }
-function shortOut(func) {
- var count = 0,
- lastCalled = 0;
- return function () {
- var stamp = nativeNow(),
- remaining = HOT_SPAN - (stamp - lastCalled);
- lastCalled = stamp;
+ if (child.value && child.type !== 'open') {
+ queue.push(append(queue.pop(), child.value));
+ continue;
+ }
- if (remaining > 0) {
- if (++count >= HOT_COUNT) {
- return arguments[0];
+ if (child.nodes) {
+ walk(child, node);
}
- } else {
- count = 0;
}
- return func.apply(undefined, arguments);
+ return queue;
};
-}
-var _shortOut = shortOut;
+ return utils$g.flatten(walk(ast));
+};
-/**
- * Sets the `toString` method of `func` to return `string`.
- *
- * @private
- * @param {Function} func The function to modify.
- * @param {Function} string The `toString` result.
- * @returns {Function} Returns `func`.
- */
+var expand_1 = expand$1;
-var setToString = _shortOut(_baseSetToString);
-var _setToString = setToString;
+var constants$4 = {
+ MAX_LENGTH: 1024 * 64,
+ // Digits
+ CHAR_0: '0',
-/**
- * A specialized version of `baseRest` which flattens the rest array.
- *
- * @private
- * @param {Function} func The function to apply a rest parameter to.
- * @returns {Function} Returns the new function.
- */
+ /* 0 */
+ CHAR_9: '9',
-function flatRest(func) {
- return _setToString(_overRest(func, undefined, flatten_1), func + '');
-}
+ /* 9 */
+ // Alphabet chars.
+ CHAR_UPPERCASE_A: 'A',
-var _flatRest = flatRest;
+ /* A */
+ CHAR_LOWERCASE_A: 'a',
-/**
- * Creates an object composed of the picked `object` properties.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The source object.
- * @param {...(string|string[])} [paths] The property paths to pick.
- * @returns {Object} Returns the new object.
- * @example
- *
- * var object = { 'a': 1, 'b': '2', 'c': 3 };
- *
- * _.pick(object, ['a', 'c']);
- * // => { 'a': 1, 'c': 3 }
- */
+ /* a */
+ CHAR_UPPERCASE_Z: 'Z',
-var pick = _flatRest(function (object, paths) {
- return object == null ? {} : _basePick(object, paths);
-});
-var pick_1 = pick;
+ /* Z */
+ CHAR_LOWERCASE_Z: 'z',
-/**
- * A specialized version of `baseAggregator` for arrays.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} setter The function to set `accumulator` values.
- * @param {Function} iteratee The iteratee to transform keys.
- * @param {Object} accumulator The initial aggregated object.
- * @returns {Function} Returns `accumulator`.
- */
-function arrayAggregator(array, setter, iteratee, accumulator) {
- var index = -1,
- length = array == null ? 0 : array.length;
+ /* z */
+ CHAR_LEFT_PARENTHESES: '(',
- while (++index < length) {
- var value = array[index];
- setter(accumulator, value, iteratee(value), array);
- }
+ /* ( */
+ CHAR_RIGHT_PARENTHESES: ')',
- return accumulator;
-}
+ /* ) */
+ CHAR_ASTERISK: '*',
-var _arrayAggregator = arrayAggregator;
+ /* * */
+ // Non-alphabetic chars.
+ CHAR_AMPERSAND: '&',
-/**
- * Creates a base function for methods like `_.forIn` and `_.forOwn`.
- *
- * @private
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
-function createBaseFor(fromRight) {
- return function (object, iteratee, keysFunc) {
- var index = -1,
- iterable = Object(object),
- props = keysFunc(object),
- length = props.length;
-
- while (length--) {
- var key = props[fromRight ? length : ++index];
+ /* & */
+ CHAR_AT: '@',
- if (iteratee(iterable[key], key, iterable) === false) {
- break;
- }
- }
+ /* @ */
+ CHAR_BACKSLASH: '\\',
- return object;
- };
-}
+ /* \ */
+ CHAR_BACKTICK: '`',
-var _createBaseFor = createBaseFor;
+ /* ` */
+ CHAR_CARRIAGE_RETURN: '\r',
-/**
- * The base implementation of `baseForOwn` which iterates over `object`
- * properties returned by `keysFunc` and invokes `iteratee` for each property.
- * Iteratee functions may exit iteration early by explicitly returning `false`.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @returns {Object} Returns `object`.
- */
+ /* \r */
+ CHAR_CIRCUMFLEX_ACCENT: '^',
-var baseFor = _createBaseFor();
-var _baseFor = baseFor;
+ /* ^ */
+ CHAR_COLON: ':',
-/**
- * The base implementation of `_.times` without support for iteratee shorthands
- * or max array length checks.
- *
- * @private
- * @param {number} n The number of times to invoke `iteratee`.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the array of results.
- */
-function baseTimes(n, iteratee) {
- var index = -1,
- result = Array(n);
+ /* : */
+ CHAR_COMMA: ',',
- while (++index < n) {
- result[index] = iteratee(index);
- }
+ /* , */
+ CHAR_DOLLAR: '$',
- return result;
-}
+ /* . */
+ CHAR_DOT: '.',
-var _baseTimes = baseTimes;
+ /* . */
+ CHAR_DOUBLE_QUOTE: '"',
-/**
- * This method returns `false`.
- *
- * @static
- * @memberOf _
- * @since 4.13.0
- * @category Util
- * @returns {boolean} Returns `false`.
- * @example
- *
- * _.times(2, _.stubFalse);
- * // => [false, false]
- */
-function stubFalse() {
- return false;
-}
+ /* " */
+ CHAR_EQUAL: '=',
-var stubFalse_1 = stubFalse;
+ /* = */
+ CHAR_EXCLAMATION_MARK: '!',
-var isBuffer_1 = createCommonjsModule(function (module, exports) {
- /** Detect free variable `exports`. */
- var freeExports = exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
+ /* ! */
+ CHAR_FORM_FEED: '\f',
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
- /** Detect the popular CommonJS extension `module.exports`. */
+ /* \f */
+ CHAR_FORWARD_SLASH: '/',
- var moduleExports = freeModule && freeModule.exports === freeExports;
- /** Built-in value references. */
+ /* / */
+ CHAR_HASH: '#',
- var Buffer = moduleExports ? _root.Buffer : undefined;
- /* Built-in method references for those with the same name as other `lodash` methods. */
+ /* # */
+ CHAR_HYPHEN_MINUS: '-',
- var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
- /**
- * Checks if `value` is a buffer.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
- * @example
- *
- * _.isBuffer(new Buffer(2));
- * // => true
- *
- * _.isBuffer(new Uint8Array(2));
- * // => false
- */
+ /* - */
+ CHAR_LEFT_ANGLE_BRACKET: '<',
- var isBuffer = nativeIsBuffer || stubFalse_1;
- module.exports = isBuffer;
-});
+ /* < */
+ CHAR_LEFT_CURLY_BRACE: '{',
-/** `Object#toString` result references. */
+ /* { */
+ CHAR_LEFT_SQUARE_BRACKET: '[',
-var argsTag$1 = '[object Arguments]',
- arrayTag = '[object Array]',
- boolTag = '[object Boolean]',
- dateTag = '[object Date]',
- errorTag = '[object Error]',
- funcTag$1 = '[object Function]',
- mapTag = '[object Map]',
- numberTag = '[object Number]',
- objectTag = '[object Object]',
- regexpTag = '[object RegExp]',
- setTag = '[object Set]',
- stringTag = '[object String]',
- weakMapTag = '[object WeakMap]';
-var arrayBufferTag = '[object ArrayBuffer]',
- dataViewTag = '[object DataView]',
- float32Tag = '[object Float32Array]',
- float64Tag = '[object Float64Array]',
- int8Tag = '[object Int8Array]',
- int16Tag = '[object Int16Array]',
- int32Tag = '[object Int32Array]',
- uint8Tag = '[object Uint8Array]',
- uint8ClampedTag = '[object Uint8ClampedArray]',
- uint16Tag = '[object Uint16Array]',
- uint32Tag = '[object Uint32Array]';
-/** Used to identify `toStringTag` values of typed arrays. */
+ /* [ */
+ CHAR_LINE_FEED: '\n',
-var typedArrayTags = {};
-typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
-typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
-/**
- * The base implementation of `_.isTypedArray` without Node.js optimizations.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- */
+ /* \n */
+ CHAR_NO_BREAK_SPACE: '\u00A0',
-function baseIsTypedArray(value) {
- return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
-}
+ /* \u00A0 */
+ CHAR_PERCENT: '%',
-var _baseIsTypedArray = baseIsTypedArray;
+ /* % */
+ CHAR_PLUS: '+',
-/**
- * The base implementation of `_.unary` without support for storing metadata.
- *
- * @private
- * @param {Function} func The function to cap arguments for.
- * @returns {Function} Returns the new capped function.
- */
-function baseUnary(func) {
- return function (value) {
- return func(value);
- };
-}
+ /* + */
+ CHAR_QUESTION_MARK: '?',
-var _baseUnary = baseUnary;
+ /* ? */
+ CHAR_RIGHT_ANGLE_BRACKET: '>',
-var _nodeUtil = createCommonjsModule(function (module, exports) {
- /** Detect free variable `exports`. */
- var freeExports = exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
+ /* > */
+ CHAR_RIGHT_CURLY_BRACE: '}',
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
- /** Detect the popular CommonJS extension `module.exports`. */
+ /* } */
+ CHAR_RIGHT_SQUARE_BRACKET: ']',
- var moduleExports = freeModule && freeModule.exports === freeExports;
- /** Detect free variable `process` from Node.js. */
+ /* ] */
+ CHAR_SEMICOLON: ';',
- var freeProcess = moduleExports && _freeGlobal.process;
- /** Used to access faster Node.js helpers. */
+ /* ; */
+ CHAR_SINGLE_QUOTE: '\'',
- var nodeUtil = function () {
- try {
- // Use `util.types` for Node.js 10+.
- var types = freeModule && freeModule.require && freeModule.require('util').types;
+ /* ' */
+ CHAR_SPACE: ' ',
- if (types) {
- return types;
- } // Legacy `process.binding('util')` for Node.js < 10.
+ /* */
+ CHAR_TAB: '\t',
+ /* \t */
+ CHAR_UNDERSCORE: '_',
- return freeProcess && freeProcess.binding && freeProcess.binding('util');
- } catch (e) {}
- }();
+ /* _ */
+ CHAR_VERTICAL_LINE: '|',
- module.exports = nodeUtil;
-});
+ /* | */
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
+ /* \uFEFF */
-/* Node.js helper references. */
+};
-var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
+const stringify$3 = stringify$6;
/**
- * Checks if `value` is classified as a typed array.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- * @example
- *
- * _.isTypedArray(new Uint8Array);
- * // => true
- *
- * _.isTypedArray([]);
- * // => false
+ * Constants
*/
-var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
-var isTypedArray_1 = isTypedArray;
+const {
+ MAX_LENGTH: MAX_LENGTH$1,
+ CHAR_BACKSLASH,
-/** Used for built-in method references. */
+ /* \ */
+ CHAR_BACKTICK,
-var objectProto$7 = Object.prototype;
-/** Used to check objects for own properties. */
+ /* ` */
+ CHAR_COMMA: CHAR_COMMA$1,
-var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
-/**
- * Creates an array of the enumerable property names of the array-like `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @param {boolean} inherited Specify returning inherited property names.
- * @returns {Array} Returns the array of property names.
- */
+ /* , */
+ CHAR_DOT: CHAR_DOT$1,
-function arrayLikeKeys(value, inherited) {
- var isArr = isArray_1(value),
- isArg = !isArr && isArguments_1(value),
- isBuff = !isArr && !isArg && isBuffer_1(value),
- isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
- skipIndexes = isArr || isArg || isBuff || isType,
- result = skipIndexes ? _baseTimes(value.length, String) : [],
- length = result.length;
+ /* . */
+ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
- for (var key in value) {
- if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
- key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
- isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
- isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
- _isIndex(key, length)))) {
- result.push(key);
- }
- }
+ /* ( */
+ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
- return result;
-}
+ /* ) */
+ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
-var _arrayLikeKeys = arrayLikeKeys;
+ /* { */
+ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
-/** Used for built-in method references. */
-var objectProto$8 = Object.prototype;
-/**
- * Checks if `value` is likely a prototype object.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
- */
+ /* } */
+ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
-function isPrototype(value) {
- var Ctor = value && value.constructor,
- proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
- return value === proto;
-}
+ /* [ */
+ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1,
+
+ /* ] */
+ CHAR_DOUBLE_QUOTE,
-var _isPrototype = isPrototype;
+ /* " */
+ CHAR_SINGLE_QUOTE,
+ /* ' */
+ CHAR_NO_BREAK_SPACE,
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE
+} = constants$4;
/**
- * Creates a unary function that invokes `func` with its argument transformed.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {Function} transform The argument transform.
- * @returns {Function} Returns the new function.
+ * parse
*/
-function overArg(func, transform) {
- return function (arg) {
- return func(transform(arg));
- };
-}
-var _overArg = overArg;
+const parse$4 = (input, options = {}) => {
+ if (typeof input !== 'string') {
+ throw new TypeError('Expected a string');
+ }
-/* Built-in method references for those with the same name as other `lodash` methods. */
+ let opts = options || {};
+ let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
-var nativeKeys = _overArg(Object.keys, Object);
-var _nativeKeys = nativeKeys;
+ if (input.length > max) {
+ throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
+ }
-/** Used for built-in method references. */
+ let ast = {
+ type: 'root',
+ input,
+ nodes: []
+ };
+ let stack = [ast];
+ let block = ast;
+ let prev = ast;
+ let brackets = 0;
+ let length = input.length;
+ let index = 0;
+ let depth = 0;
+ let value;
+ /**
+ * Helpers
+ */
-var objectProto$9 = Object.prototype;
-/** Used to check objects for own properties. */
+ const advance = () => input[index++];
-var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
-/**
- * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- */
+ const push = node => {
+ if (node.type === 'text' && prev.type === 'dot') {
+ prev.type = 'text';
+ }
-function baseKeys(object) {
- if (!_isPrototype(object)) {
- return _nativeKeys(object);
- }
+ if (prev && prev.type === 'text' && node.type === 'text') {
+ prev.value += node.value;
+ return;
+ }
- var result = [];
+ block.nodes.push(node);
+ node.parent = block;
+ node.prev = prev;
+ prev = node;
+ return node;
+ };
- for (var key in Object(object)) {
- if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
- result.push(key);
- }
- }
+ push({
+ type: 'bos'
+ });
- return result;
-}
+ while (index < length) {
+ block = stack[stack.length - 1];
+ value = advance();
+ /**
+ * Invalid chars
+ */
-var _baseKeys = baseKeys;
+ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
+ continue;
+ }
+ /**
+ * Escaped chars
+ */
-/**
- * Checks if `value` is array-like. A value is considered array-like if it's
- * not a function and has a `value.length` that's an integer greater than or
- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
- * @example
- *
- * _.isArrayLike([1, 2, 3]);
- * // => true
- *
- * _.isArrayLike(document.body.children);
- * // => true
- *
- * _.isArrayLike('abc');
- * // => true
- *
- * _.isArrayLike(_.noop);
- * // => false
- */
-function isArrayLike(value) {
- return value != null && isLength_1(value.length) && !isFunction_1(value);
-}
+ if (value === CHAR_BACKSLASH) {
+ push({
+ type: 'text',
+ value: (options.keepEscaping ? value : '') + advance()
+ });
+ continue;
+ }
+ /**
+ * Right square bracket (literal): ']'
+ */
-var isArrayLike_1 = isArrayLike;
-/**
- * Creates an array of the own enumerable property names of `object`.
- *
- * **Note:** Non-object values are coerced to objects. See the
- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
- * for more details.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.keys(new Foo);
- * // => ['a', 'b'] (iteration order is not guaranteed)
- *
- * _.keys('hi');
- * // => ['0', '1']
- */
+ if (value === CHAR_RIGHT_SQUARE_BRACKET$1) {
+ push({
+ type: 'text',
+ value: '\\' + value
+ });
+ continue;
+ }
+ /**
+ * Left square bracket: '['
+ */
-function keys(object) {
- return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
-}
-var keys_1 = keys;
+ if (value === CHAR_LEFT_SQUARE_BRACKET$1) {
+ brackets++;
+ let next;
-/**
- * The base implementation of `_.forOwn` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Object} Returns `object`.
- */
+ while (index < length && (next = advance())) {
+ value += next;
-function baseForOwn(object, iteratee) {
- return object && _baseFor(object, iteratee, keys_1);
-}
+ if (next === CHAR_LEFT_SQUARE_BRACKET$1) {
+ brackets++;
+ continue;
+ }
-var _baseForOwn = baseForOwn;
+ if (next === CHAR_BACKSLASH) {
+ value += advance();
+ continue;
+ }
-/**
- * Creates a `baseEach` or `baseEachRight` function.
- *
- * @private
- * @param {Function} eachFunc The function to iterate over a collection.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
+ if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
+ brackets--;
-function createBaseEach(eachFunc, fromRight) {
- return function (collection, iteratee) {
- if (collection == null) {
- return collection;
- }
+ if (brackets === 0) {
+ break;
+ }
+ }
+ }
- if (!isArrayLike_1(collection)) {
- return eachFunc(collection, iteratee);
+ push({
+ type: 'text',
+ value
+ });
+ continue;
}
+ /**
+ * Parentheses
+ */
- var length = collection.length,
- index = fromRight ? length : -1,
- iterable = Object(collection);
- while (fromRight ? index-- : ++index < length) {
- if (iteratee(iterable[index], index, iterable) === false) {
- break;
+ if (value === CHAR_LEFT_PARENTHESES$1) {
+ block = push({
+ type: 'paren',
+ nodes: []
+ });
+ stack.push(block);
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ }
+
+ if (value === CHAR_RIGHT_PARENTHESES$1) {
+ if (block.type !== 'paren') {
+ push({
+ type: 'text',
+ value
+ });
+ continue;
}
+
+ block = stack.pop();
+ push({
+ type: 'text',
+ value
+ });
+ block = stack[stack.length - 1];
+ continue;
}
+ /**
+ * Quotes: '|"|`
+ */
- return collection;
- };
-}
-var _createBaseEach = createBaseEach;
+ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
+ let open = value;
+ let next;
-/**
- * The base implementation of `_.forEach` without support for iteratee shorthands.
- *
- * @private
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array|Object} Returns `collection`.
- */
+ if (options.keepQuotes !== true) {
+ value = '';
+ }
-var baseEach = _createBaseEach(_baseForOwn);
-var _baseEach = baseEach;
+ while (index < length && (next = advance())) {
+ if (next === CHAR_BACKSLASH) {
+ value += next + advance();
+ continue;
+ }
-/**
- * Aggregates elements of `collection` on `accumulator` with keys transformed
- * by `iteratee` and values set by `setter`.
- *
- * @private
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} setter The function to set `accumulator` values.
- * @param {Function} iteratee The iteratee to transform keys.
- * @param {Object} accumulator The initial aggregated object.
- * @returns {Function} Returns `accumulator`.
- */
+ if (next === open) {
+ if (options.keepQuotes === true) value += next;
+ break;
+ }
-function baseAggregator(collection, setter, iteratee, accumulator) {
- _baseEach(collection, function (value, key, collection) {
- setter(accumulator, value, iteratee(value), collection);
- });
- return accumulator;
-}
+ value += next;
+ }
-var _baseAggregator = baseAggregator;
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ }
+ /**
+ * Left curly brace: '{'
+ */
-/**
- * Removes all key-value entries from the stack.
- *
- * @private
- * @name clear
- * @memberOf Stack
- */
-function stackClear() {
- this.__data__ = new _ListCache();
- this.size = 0;
-}
+ if (value === CHAR_LEFT_CURLY_BRACE$1) {
+ depth++;
+ let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
+ let brace = {
+ type: 'brace',
+ open: true,
+ close: false,
+ dollar,
+ depth,
+ commas: 0,
+ ranges: 0,
+ nodes: []
+ };
+ block = push(brace);
+ stack.push(block);
+ push({
+ type: 'open',
+ value
+ });
+ continue;
+ }
+ /**
+ * Right curly brace: '}'
+ */
-var _stackClear = stackClear;
-/**
- * Removes `key` and its value from the stack.
- *
- * @private
- * @name delete
- * @memberOf Stack
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
-function stackDelete(key) {
- var data = this.__data__,
- result = data['delete'](key);
- this.size = data.size;
- return result;
-}
+ if (value === CHAR_RIGHT_CURLY_BRACE$1) {
+ if (block.type !== 'brace') {
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ }
-var _stackDelete = stackDelete;
+ let type = 'close';
+ block = stack.pop();
+ block.close = true;
+ push({
+ type,
+ value
+ });
+ depth--;
+ block = stack[stack.length - 1];
+ continue;
+ }
+ /**
+ * Comma: ','
+ */
-/**
- * Gets the stack value for `key`.
- *
- * @private
- * @name get
- * @memberOf Stack
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
-function stackGet(key) {
- return this.__data__.get(key);
-}
-var _stackGet = stackGet;
+ if (value === CHAR_COMMA$1 && depth > 0) {
+ if (block.ranges > 0) {
+ block.ranges = 0;
+ let open = block.nodes.shift();
+ block.nodes = [open, {
+ type: 'text',
+ value: stringify$3(block)
+ }];
+ }
-/**
- * Checks if a stack value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Stack
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
-function stackHas(key) {
- return this.__data__.has(key);
-}
+ push({
+ type: 'comma',
+ value
+ });
+ block.commas++;
+ continue;
+ }
+ /**
+ * Dot: '.'
+ */
-var _stackHas = stackHas;
-/** Used as the size to enable large array optimizations. */
+ if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) {
+ let siblings = block.nodes;
-var LARGE_ARRAY_SIZE = 200;
-/**
- * Sets the stack `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Stack
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the stack cache instance.
- */
+ if (depth === 0 || siblings.length === 0) {
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ }
-function stackSet(key, value) {
- var data = this.__data__;
+ if (prev.type === 'dot') {
+ block.range = [];
+ prev.value += value;
+ prev.type = 'range';
- if (data instanceof _ListCache) {
- var pairs = data.__data__;
+ if (block.nodes.length !== 3 && block.nodes.length !== 5) {
+ block.invalid = true;
+ block.ranges = 0;
+ prev.type = 'text';
+ continue;
+ }
- if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
- pairs.push([key, value]);
- this.size = ++data.size;
- return this;
+ block.ranges++;
+ block.args = [];
+ continue;
+ }
+
+ if (prev.type === 'range') {
+ siblings.pop();
+ let before = siblings[siblings.length - 1];
+ before.value += prev.value + value;
+ prev = before;
+ block.ranges--;
+ continue;
+ }
+
+ push({
+ type: 'dot',
+ value
+ });
+ continue;
}
+ /**
+ * Text
+ */
- data = this.__data__ = new _MapCache(pairs);
- }
- data.set(key, value);
- this.size = data.size;
- return this;
-}
+ push({
+ type: 'text',
+ value
+ });
+ } // Mark imbalanced braces and brackets as invalid
-var _stackSet = stackSet;
-/**
- * Creates a stack cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
+ do {
+ block = stack.pop();
-function Stack(entries) {
- var data = this.__data__ = new _ListCache(entries);
- this.size = data.size;
-} // Add methods to `Stack`.
+ if (block.type !== 'root') {
+ block.nodes.forEach(node => {
+ if (!node.nodes) {
+ if (node.type === 'open') node.isOpen = true;
+ if (node.type === 'close') node.isClose = true;
+ if (!node.nodes) node.type = 'text';
+ node.invalid = true;
+ }
+ }); // get the location of the block on parent.nodes (block's siblings)
+ let parent = stack[stack.length - 1];
+ let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
-Stack.prototype.clear = _stackClear;
-Stack.prototype['delete'] = _stackDelete;
-Stack.prototype.get = _stackGet;
-Stack.prototype.has = _stackHas;
-Stack.prototype.set = _stackSet;
-var _Stack = Stack;
+ parent.nodes.splice(index, 1, ...block.nodes);
+ }
+ } while (stack.length > 0);
-/** Used to stand-in for `undefined` hash values. */
-var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
+ push({
+ type: 'eos'
+ });
+ return ast;
+};
+
+var parse_1$1 = parse$4;
+
+const stringify$2 = stringify$6;
+const compile = compile_1;
+const expand = expand_1;
+const parse$3 = parse_1$1;
/**
- * Adds `value` to the array cache.
+ * Expand the given pattern or create a regex-compatible string.
*
- * @private
- * @name add
- * @memberOf SetCache
- * @alias push
- * @param {*} value The value to cache.
- * @returns {Object} Returns the cache instance.
+ * ```js
+ * const braces = require('braces');
+ * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
+ * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
+ * ```
+ * @param {String} `str`
+ * @param {Object} `options`
+ * @return {String}
+ * @api public
*/
-function setCacheAdd(value) {
- this.__data__.set(value, HASH_UNDEFINED$2);
+const braces$1 = (input, options = {}) => {
+ let output = [];
- return this;
-}
+ if (Array.isArray(input)) {
+ for (let pattern of input) {
+ let result = braces$1.create(pattern, options);
+
+ if (Array.isArray(result)) {
+ output.push(...result);
+ } else {
+ output.push(result);
+ }
+ }
+ } else {
+ output = [].concat(braces$1.create(input, options));
+ }
-var _setCacheAdd = setCacheAdd;
+ if (options && options.expand === true && options.nodupes === true) {
+ output = [...new Set(output)];
+ }
+ return output;
+};
/**
- * Checks if `value` is in the array cache.
+ * Parse the given `str` with the given `options`.
*
- * @private
- * @name has
- * @memberOf SetCache
- * @param {*} value The value to search for.
- * @returns {number} Returns `true` if `value` is found, else `false`.
+ * ```js
+ * // braces.parse(pattern, [, options]);
+ * const ast = braces.parse('a/{b,c}/d');
+ * console.log(ast);
+ * ```
+ * @param {String} pattern Brace pattern to parse
+ * @param {Object} options
+ * @return {Object} Returns an AST
+ * @api public
*/
-function setCacheHas(value) {
- return this.__data__.has(value);
-}
-var _setCacheHas = setCacheHas;
+braces$1.parse = (input, options = {}) => parse$3(input, options);
/**
+ * Creates a braces string from an AST, or an AST node.
*
- * Creates an array cache object to store unique values.
- *
- * @private
- * @constructor
- * @param {Array} [values] The values to cache.
+ * ```js
+ * const braces = require('braces');
+ * let ast = braces.parse('foo/{a,b}/bar');
+ * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
+ * ```
+ * @param {String} `input` Brace pattern or AST.
+ * @param {Object} `options`
+ * @return {Array} Returns an array of expanded values.
+ * @api public
*/
-function SetCache(values) {
- var index = -1,
- length = values == null ? 0 : values.length;
- this.__data__ = new _MapCache();
- while (++index < length) {
- this.add(values[index]);
+braces$1.stringify = (input, options = {}) => {
+ if (typeof input === 'string') {
+ return stringify$2(braces$1.parse(input, options), options);
}
-} // Add methods to `SetCache`.
-
-
-SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
-SetCache.prototype.has = _setCacheHas;
-var _SetCache = SetCache;
+ return stringify$2(input, options);
+};
/**
- * A specialized version of `_.some` for arrays without support for iteratee
- * shorthands.
+ * Compiles a brace pattern into a regex-compatible, optimized string.
+ * This method is called by the main [braces](#braces) function by default.
*
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if any element passes the predicate check,
- * else `false`.
+ * ```js
+ * const braces = require('braces');
+ * console.log(braces.compile('a/{b,c}/d'));
+ * //=> ['a/(b|c)/d']
+ * ```
+ * @param {String} `input` Brace pattern or AST.
+ * @param {Object} `options`
+ * @return {Array} Returns an array of expanded values.
+ * @api public
*/
-function arraySome(array, predicate) {
- var index = -1,
- length = array == null ? 0 : array.length;
-
- while (++index < length) {
- if (predicate(array[index], index, array)) {
- return true;
- }
- }
- return false;
-}
-var _arraySome = arraySome;
+braces$1.compile = (input, options = {}) => {
+ if (typeof input === 'string') {
+ input = braces$1.parse(input, options);
+ }
+ return compile(input, options);
+};
/**
- * Checks if a `cache` value for `key` exists.
+ * Expands a brace pattern into an array. This method is called by the
+ * main [braces](#braces) function when `options.expand` is true. Before
+ * using this method it's recommended that you read the [performance notes](#performance))
+ * and advantages of using [.compile](#compile) instead.
*
- * @private
- * @param {Object} cache The cache to query.
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ * ```js
+ * const braces = require('braces');
+ * console.log(braces.expand('a/{b,c}/d'));
+ * //=> ['a/b/d', 'a/c/d'];
+ * ```
+ * @param {String} `pattern` Brace pattern
+ * @param {Object} `options`
+ * @return {Array} Returns an array of expanded values.
+ * @api public
*/
-function cacheHas(cache, key) {
- return cache.has(key);
-}
-
-var _cacheHas = cacheHas;
-/** Used to compose bitmasks for value comparisons. */
-
-var COMPARE_PARTIAL_FLAG = 1,
- COMPARE_UNORDERED_FLAG = 2;
-/**
- * A specialized version of `baseIsEqualDeep` for arrays with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Array} array The array to compare.
- * @param {Array} other The other array to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `array` and `other` objects.
- * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
- */
-function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
- arrLength = array.length,
- othLength = other.length;
+braces$1.expand = (input, options = {}) => {
+ if (typeof input === 'string') {
+ input = braces$1.parse(input, options);
+ }
- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
- return false;
- } // Check that cyclic values are equal.
+ let result = expand(input, options); // filter out empty strings if specified
+ if (options.noempty === true) {
+ result = result.filter(Boolean);
+ } // filter out duplicates if specified
- var arrStacked = stack.get(array);
- var othStacked = stack.get(other);
- if (arrStacked && othStacked) {
- return arrStacked == other && othStacked == array;
+ if (options.nodupes === true) {
+ result = [...new Set(result)];
}
- var index = -1,
- result = true,
- seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
- stack.set(array, other);
- stack.set(other, array); // Ignore non-index properties.
-
- while (++index < arrLength) {
- var arrValue = array[index],
- othValue = other[index];
-
- if (customizer) {
- var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
- }
+ return result;
+};
+/**
+ * Processes a brace pattern and returns either an expanded array
+ * (if `options.expand` is true), a highly optimized regex-compatible string.
+ * This method is called by the main [braces](#braces) function.
+ *
+ * ```js
+ * const braces = require('braces');
+ * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
+ * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
+ * ```
+ * @param {String} `pattern` Brace pattern
+ * @param {Object} `options`
+ * @return {Array} Returns an array of expanded values.
+ * @api public
+ */
- if (compared !== undefined) {
- if (compared) {
- continue;
- }
- result = false;
- break;
- } // Recursively compare arrays (susceptible to call stack limits).
+braces$1.create = (input, options = {}) => {
+ if (input === '' || input.length < 3) {
+ return [input];
+ }
+ return options.expand !== true ? braces$1.compile(input, options) : braces$1.expand(input, options);
+};
+/**
+ * Expose "braces"
+ */
- if (seen) {
- if (!_arraySome(other, function (othValue, othIndex) {
- if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
- return seen.push(othIndex);
- }
- })) {
- result = false;
- break;
- }
- } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
- result = false;
- break;
- }
- }
- stack['delete'](array);
- stack['delete'](other);
- return result;
-}
+var braces_1 = braces$1;
-var _equalArrays = equalArrays;
-
-/** Built-in value references. */
-
-var Uint8Array = _root.Uint8Array;
-var _Uint8Array = Uint8Array;
+var utils$f = {};
+const path$a = require$$0__default$1["default"];
+const WIN_SLASH = '\\\\/';
+const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
/**
- * Converts `map` to its key-value pairs.
- *
- * @private
- * @param {Object} map The map to convert.
- * @returns {Array} Returns the key-value pairs.
+ * Posix glob regex
*/
-function mapToArray(map) {
- var index = -1,
- result = Array(map.size);
- map.forEach(function (value, key) {
- result[++index] = [key, value];
- });
- return result;
-}
-var _mapToArray = mapToArray;
+const DOT_LITERAL = '\\.';
+const PLUS_LITERAL = '\\+';
+const QMARK_LITERAL = '\\?';
+const SLASH_LITERAL = '\\/';
+const ONE_CHAR = '(?=.)';
+const QMARK = '[^/]';
+const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
+const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
+const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
+const NO_DOT = `(?!${DOT_LITERAL})`;
+const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
+const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
+const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
+const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
+const STAR = `${QMARK}*?`;
+const POSIX_CHARS = {
+ DOT_LITERAL,
+ PLUS_LITERAL,
+ QMARK_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ QMARK,
+ END_ANCHOR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOTS,
+ NO_DOT_SLASH,
+ NO_DOTS_SLASH,
+ QMARK_NO_DOT,
+ STAR,
+ START_ANCHOR
+};
+/**
+ * Windows glob regex
+ */
+const WINDOWS_CHARS = Object.assign(Object.assign({}, POSIX_CHARS), {}, {
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
+ QMARK: WIN_NO_SLASH,
+ STAR: `${WIN_NO_SLASH}*?`,
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
+ NO_DOT: `(?!${DOT_LITERAL})`,
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
+});
/**
- * Converts `set` to an array of its values.
- *
- * @private
- * @param {Object} set The set to convert.
- * @returns {Array} Returns the values.
+ * POSIX Bracket Regex
*/
-function setToArray(set) {
- var index = -1,
- result = Array(set.size);
- set.forEach(function (value) {
- result[++index] = value;
- });
- return result;
-}
-var _setToArray = setToArray;
+const POSIX_REGEX_SOURCE$1 = {
+ alnum: 'a-zA-Z0-9',
+ alpha: 'a-zA-Z',
+ ascii: '\\x00-\\x7F',
+ blank: ' \\t',
+ cntrl: '\\x00-\\x1F\\x7F',
+ digit: '0-9',
+ graph: '\\x21-\\x7E',
+ lower: 'a-z',
+ print: '\\x20-\\x7E ',
+ punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
+ space: ' \\t\\r\\n\\v\\f',
+ upper: 'A-Z',
+ word: 'A-Za-z0-9_',
+ xdigit: 'A-Fa-f0-9'
+};
+var constants$3 = {
+ MAX_LENGTH: 1024 * 64,
+ POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
+ // regular expressions
+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
+ // Replace globs with equivalent patterns to reduce parsing time.
+ REPLACEMENTS: {
+ '***': '*',
+ '**/**': '**',
+ '**/**/**': '**'
+ },
+ // Digits
+ CHAR_0: 48,
-/** Used to compose bitmasks for value comparisons. */
+ /* 0 */
+ CHAR_9: 57,
-var COMPARE_PARTIAL_FLAG$1 = 1,
- COMPARE_UNORDERED_FLAG$1 = 2;
-/** `Object#toString` result references. */
+ /* 9 */
+ // Alphabet chars.
+ CHAR_UPPERCASE_A: 65,
-var boolTag$1 = '[object Boolean]',
- dateTag$1 = '[object Date]',
- errorTag$1 = '[object Error]',
- mapTag$1 = '[object Map]',
- numberTag$1 = '[object Number]',
- regexpTag$1 = '[object RegExp]',
- setTag$1 = '[object Set]',
- stringTag$1 = '[object String]',
- symbolTag$1 = '[object Symbol]';
-var arrayBufferTag$1 = '[object ArrayBuffer]',
- dataViewTag$1 = '[object DataView]';
-/** Used to convert symbols to primitives and strings. */
+ /* A */
+ CHAR_LOWERCASE_A: 97,
-var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
- symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
-/**
- * A specialized version of `baseIsEqualDeep` for comparing objects of
- * the same `toStringTag`.
- *
- * **Note:** This function only supports comparing values with tags of
- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {string} tag The `toStringTag` of the objects to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
+ /* a */
+ CHAR_UPPERCASE_Z: 90,
-function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
- switch (tag) {
- case dataViewTag$1:
- if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
- return false;
- }
+ /* Z */
+ CHAR_LOWERCASE_Z: 122,
- object = object.buffer;
- other = other.buffer;
+ /* z */
+ CHAR_LEFT_PARENTHESES: 40,
- case arrayBufferTag$1:
- if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
- return false;
- }
+ /* ( */
+ CHAR_RIGHT_PARENTHESES: 41,
- return true;
+ /* ) */
+ CHAR_ASTERISK: 42,
- case boolTag$1:
- case dateTag$1:
- case numberTag$1:
- // Coerce booleans to `1` or `0` and dates to milliseconds.
- // Invalid dates are coerced to `NaN`.
- return eq_1(+object, +other);
+ /* * */
+ // Non-alphabetic chars.
+ CHAR_AMPERSAND: 38,
- case errorTag$1:
- return object.name == other.name && object.message == other.message;
+ /* & */
+ CHAR_AT: 64,
- case regexpTag$1:
- case stringTag$1:
- // Coerce regexes to strings and treat strings, primitives and objects,
- // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
- // for more details.
- return object == other + '';
+ /* @ */
+ CHAR_BACKWARD_SLASH: 92,
- case mapTag$1:
- var convert = _mapToArray;
+ /* \ */
+ CHAR_CARRIAGE_RETURN: 13,
- case setTag$1:
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
- convert || (convert = _setToArray);
+ /* \r */
+ CHAR_CIRCUMFLEX_ACCENT: 94,
- if (object.size != other.size && !isPartial) {
- return false;
- } // Assume cyclic values are equal.
+ /* ^ */
+ CHAR_COLON: 58,
+ /* : */
+ CHAR_COMMA: 44,
- var stacked = stack.get(object);
+ /* , */
+ CHAR_DOT: 46,
- if (stacked) {
- return stacked == other;
- }
+ /* . */
+ CHAR_DOUBLE_QUOTE: 34,
- bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits).
+ /* " */
+ CHAR_EQUAL: 61,
- stack.set(object, other);
- var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
- stack['delete'](object);
- return result;
+ /* = */
+ CHAR_EXCLAMATION_MARK: 33,
- case symbolTag$1:
- if (symbolValueOf) {
- return symbolValueOf.call(object) == symbolValueOf.call(other);
- }
+ /* ! */
+ CHAR_FORM_FEED: 12,
- }
+ /* \f */
+ CHAR_FORWARD_SLASH: 47,
- return false;
-}
+ /* / */
+ CHAR_GRAVE_ACCENT: 96,
-var _equalByTag = equalByTag;
+ /* ` */
+ CHAR_HASH: 35,
-/**
- * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
- * `keysFunc` and `symbolsFunc` to get the enumerable property names and
- * symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @param {Function} symbolsFunc The function to get the symbols of `object`.
- * @returns {Array} Returns the array of property names and symbols.
- */
+ /* # */
+ CHAR_HYPHEN_MINUS: 45,
-function baseGetAllKeys(object, keysFunc, symbolsFunc) {
- var result = keysFunc(object);
- return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
-}
+ /* - */
+ CHAR_LEFT_ANGLE_BRACKET: 60,
-var _baseGetAllKeys = baseGetAllKeys;
+ /* < */
+ CHAR_LEFT_CURLY_BRACE: 123,
-/**
- * A specialized version of `_.filter` for arrays without support for
- * iteratee shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {Array} Returns the new filtered array.
- */
-function arrayFilter(array, predicate) {
- var index = -1,
- length = array == null ? 0 : array.length,
- resIndex = 0,
- result = [];
-
- while (++index < length) {
- var value = array[index];
+ /* { */
+ CHAR_LEFT_SQUARE_BRACKET: 91,
- if (predicate(value, index, array)) {
- result[resIndex++] = value;
- }
- }
+ /* [ */
+ CHAR_LINE_FEED: 10,
- return result;
-}
+ /* \n */
+ CHAR_NO_BREAK_SPACE: 160,
-var _arrayFilter = arrayFilter;
+ /* \u00A0 */
+ CHAR_PERCENT: 37,
-/**
- * This method returns a new empty array.
- *
- * @static
- * @memberOf _
- * @since 4.13.0
- * @category Util
- * @returns {Array} Returns the new empty array.
- * @example
- *
- * var arrays = _.times(2, _.stubArray);
- *
- * console.log(arrays);
- * // => [[], []]
- *
- * console.log(arrays[0] === arrays[1]);
- * // => false
- */
-function stubArray() {
- return [];
-}
+ /* % */
+ CHAR_PLUS: 43,
-var stubArray_1 = stubArray;
+ /* + */
+ CHAR_QUESTION_MARK: 63,
-/** Used for built-in method references. */
+ /* ? */
+ CHAR_RIGHT_ANGLE_BRACKET: 62,
-var objectProto$a = Object.prototype;
-/** Built-in value references. */
+ /* > */
+ CHAR_RIGHT_CURLY_BRACE: 125,
-var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable;
-/* Built-in method references for those with the same name as other `lodash` methods. */
+ /* } */
+ CHAR_RIGHT_SQUARE_BRACKET: 93,
-var nativeGetSymbols = Object.getOwnPropertySymbols;
-/**
- * Creates an array of the own enumerable symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of symbols.
- */
+ /* ] */
+ CHAR_SEMICOLON: 59,
-var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) {
- if (object == null) {
- return [];
- }
+ /* ; */
+ CHAR_SINGLE_QUOTE: 39,
- object = Object(object);
- return _arrayFilter(nativeGetSymbols(object), function (symbol) {
- return propertyIsEnumerable$1.call(object, symbol);
- });
-};
-var _getSymbols = getSymbols;
+ /* ' */
+ CHAR_SPACE: 32,
-/**
- * Creates an array of own enumerable property names and symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names and symbols.
- */
+ /* */
+ CHAR_TAB: 9,
-function getAllKeys(object) {
- return _baseGetAllKeys(object, keys_1, _getSymbols);
-}
+ /* \t */
+ CHAR_UNDERSCORE: 95,
-var _getAllKeys = getAllKeys;
+ /* _ */
+ CHAR_VERTICAL_LINE: 124,
-/** Used to compose bitmasks for value comparisons. */
+ /* | */
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
-var COMPARE_PARTIAL_FLAG$2 = 1;
-/** Used for built-in method references. */
+ /* \uFEFF */
+ SEP: path$a.sep,
-var objectProto$b = Object.prototype;
-/** Used to check objects for own properties. */
+ /**
+ * Create EXTGLOB_CHARS
+ */
+ extglobChars(chars) {
+ return {
+ '!': {
+ type: 'negate',
+ open: '(?:(?!(?:',
+ close: `))${chars.STAR})`
+ },
+ '?': {
+ type: 'qmark',
+ open: '(?:',
+ close: ')?'
+ },
+ '+': {
+ type: 'plus',
+ open: '(?:',
+ close: ')+'
+ },
+ '*': {
+ type: 'star',
+ open: '(?:',
+ close: ')*'
+ },
+ '@': {
+ type: 'at',
+ open: '(?:',
+ close: ')'
+ }
+ };
+ },
-var hasOwnProperty$8 = objectProto$b.hasOwnProperty;
-/**
- * A specialized version of `baseIsEqualDeep` for objects with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
+ /**
+ * Create GLOB_CHARS
+ */
+ globChars(win32) {
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
+ }
-function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
- objProps = _getAllKeys(object),
- objLength = objProps.length,
- othProps = _getAllKeys(other),
- othLength = othProps.length;
+};
- if (objLength != othLength && !isPartial) {
- return false;
- }
+(function (exports) {
- var index = objLength;
+ const path = require$$0__default$1["default"];
+ const win32 = process.platform === 'win32';
+ const {
+ REGEX_BACKSLASH,
+ REGEX_REMOVE_BACKSLASH,
+ REGEX_SPECIAL_CHARS,
+ REGEX_SPECIAL_CHARS_GLOBAL
+ } = constants$3;
- while (index--) {
- var key = objProps[index];
+ exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
- if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) {
- return false;
- }
- } // Check that cyclic values are equal.
+ exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
+ exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
- var objStacked = stack.get(object);
- var othStacked = stack.get(other);
+ exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
- if (objStacked && othStacked) {
- return objStacked == other && othStacked == object;
- }
+ exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
- var result = true;
- stack.set(object, other);
- stack.set(other, object);
- var skipCtor = isPartial;
+ exports.removeBackslashes = str => {
+ return str.replace(REGEX_REMOVE_BACKSLASH, match => {
+ return match === '\\' ? '' : match;
+ });
+ };
- while (++index < objLength) {
- key = objProps[index];
- var objValue = object[key],
- othValue = other[key];
+ exports.supportsLookbehinds = () => {
+ const segs = process.version.slice(1).split('.').map(Number);
- if (customizer) {
- var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
- } // Recursively compare objects (susceptible to call stack limits).
+ if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
+ return true;
+ }
+ return false;
+ };
- if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
- result = false;
- break;
+ exports.isWindows = options => {
+ if (options && typeof options.windows === 'boolean') {
+ return options.windows;
}
- skipCtor || (skipCtor = key == 'constructor');
- }
+ return win32 === true || path.sep === '\\';
+ };
- if (result && !skipCtor) {
- var objCtor = object.constructor,
- othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
+ exports.escapeLast = (input, char, lastIdx) => {
+ const idx = input.lastIndexOf(char, lastIdx);
+ if (idx === -1) return input;
+ if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
+ };
- if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
- result = false;
+ exports.removePrefix = (input, state = {}) => {
+ let output = input;
+
+ if (output.startsWith('./')) {
+ output = output.slice(2);
+ state.prefix = './';
}
- }
- stack['delete'](object);
- stack['delete'](other);
- return result;
-}
+ return output;
+ };
-var _equalObjects = equalObjects;
+ exports.wrapOutput = (input, state = {}, options = {}) => {
+ const prepend = options.contains ? '' : '^';
+ const append = options.contains ? '' : '$';
+ let output = `${prepend}(?:${input})${append}`;
-/* Built-in method references that are verified to be native. */
+ if (state.negated === true) {
+ output = `(?:^(?!${output}).*$)`;
+ }
-var DataView = _getNative(_root, 'DataView');
-var _DataView = DataView;
+ return output;
+ };
+})(utils$f);
-/* Built-in method references that are verified to be native. */
+const utils$e = utils$f;
+const {
+ CHAR_ASTERISK,
-var Promise$1 = _getNative(_root, 'Promise');
-var _Promise = Promise$1;
+ /* * */
+ CHAR_AT,
-/* Built-in method references that are verified to be native. */
+ /* @ */
+ CHAR_BACKWARD_SLASH,
-var Set$1 = _getNative(_root, 'Set');
-var _Set = Set$1;
+ /* \ */
+ CHAR_COMMA,
-/* Built-in method references that are verified to be native. */
+ /* , */
+ CHAR_DOT,
-var WeakMap$1 = _getNative(_root, 'WeakMap');
-var _WeakMap = WeakMap$1;
+ /* . */
+ CHAR_EXCLAMATION_MARK,
-/** `Object#toString` result references. */
-
-var mapTag$2 = '[object Map]',
- objectTag$1 = '[object Object]',
- promiseTag = '[object Promise]',
- setTag$2 = '[object Set]',
- weakMapTag$1 = '[object WeakMap]';
-var dataViewTag$2 = '[object DataView]';
-/** Used to detect maps, sets, and weakmaps. */
-
-var dataViewCtorString = _toSource(_DataView),
- mapCtorString = _toSource(_Map),
- promiseCtorString = _toSource(_Promise),
- setCtorString = _toSource(_Set),
- weakMapCtorString = _toSource(_WeakMap);
-/**
- * Gets the `toStringTag` of `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
-
-var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
-
-if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) {
- getTag = function (value) {
- var result = _baseGetTag(value),
- Ctor = result == objectTag$1 ? value.constructor : undefined,
- ctorString = Ctor ? _toSource(Ctor) : '';
-
- if (ctorString) {
- switch (ctorString) {
- case dataViewCtorString:
- return dataViewTag$2;
+ /* ! */
+ CHAR_FORWARD_SLASH,
- case mapCtorString:
- return mapTag$2;
+ /* / */
+ CHAR_LEFT_CURLY_BRACE,
- case promiseCtorString:
- return promiseTag;
+ /* { */
+ CHAR_LEFT_PARENTHESES,
- case setCtorString:
- return setTag$2;
+ /* ( */
+ CHAR_LEFT_SQUARE_BRACKET,
- case weakMapCtorString:
- return weakMapTag$1;
- }
- }
+ /* [ */
+ CHAR_PLUS,
- return result;
- };
-}
+ /* + */
+ CHAR_QUESTION_MARK,
-var _getTag = getTag;
+ /* ? */
+ CHAR_RIGHT_CURLY_BRACE,
-/** Used to compose bitmasks for value comparisons. */
+ /* } */
+ CHAR_RIGHT_PARENTHESES,
-var COMPARE_PARTIAL_FLAG$3 = 1;
-/** `Object#toString` result references. */
+ /* ) */
+ CHAR_RIGHT_SQUARE_BRACKET
+ /* ] */
-var argsTag$2 = '[object Arguments]',
- arrayTag$1 = '[object Array]',
- objectTag$2 = '[object Object]';
-/** Used for built-in method references. */
+} = constants$3;
-var objectProto$c = Object.prototype;
-/** Used to check objects for own properties. */
+const isPathSeparator = code => {
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
+};
-var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
+const depth = token => {
+ if (token.isPrefix !== true) {
+ token.depth = token.isGlobstar ? Infinity : 1;
+ }
+};
/**
- * A specialized version of `baseIsEqual` for arrays and objects which performs
- * deep comparisons and tracks traversed objects enabling objects with circular
- * references to be compared.
+ * Quickly scans a glob pattern and returns an object with a handful of
+ * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
+ * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
+ * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
*
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} [stack] Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ * ```js
+ * const pm = require('picomatch');
+ * console.log(pm.scan('foo/bar/*.js'));
+ * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
+ * ```
+ * @param {String} `str`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with tokens and regex source string.
+ * @api public
*/
-function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
- var objIsArr = isArray_1(object),
- othIsArr = isArray_1(other),
- objTag = objIsArr ? arrayTag$1 : _getTag(object),
- othTag = othIsArr ? arrayTag$1 : _getTag(other);
- objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
- othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
- var objIsObj = objTag == objectTag$2,
- othIsObj = othTag == objectTag$2,
- isSameTag = objTag == othTag;
-
- if (isSameTag && isBuffer_1(object)) {
- if (!isBuffer_1(other)) {
- return false;
- }
-
- objIsArr = true;
- objIsObj = false;
- }
-
- if (isSameTag && !objIsObj) {
- stack || (stack = new _Stack());
- return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
- }
- if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
- var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'),
- othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__');
+const scan$1 = (input, options) => {
+ const opts = options || {};
+ const length = input.length - 1;
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
+ const slashes = [];
+ const tokens = [];
+ const parts = [];
+ let str = input;
+ let index = -1;
+ let start = 0;
+ let lastIndex = 0;
+ let isBrace = false;
+ let isBracket = false;
+ let isGlob = false;
+ let isExtglob = false;
+ let isGlobstar = false;
+ let braceEscaped = false;
+ let backslashes = false;
+ let negated = false;
+ let negatedExtglob = false;
+ let finished = false;
+ let braces = 0;
+ let prev;
+ let code;
+ let token = {
+ value: '',
+ depth: 0,
+ isGlob: false
+ };
- if (objIsWrapped || othIsWrapped) {
- var objUnwrapped = objIsWrapped ? object.value() : object,
- othUnwrapped = othIsWrapped ? other.value() : other;
- stack || (stack = new _Stack());
- return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
- }
- }
+ const eos = () => index >= length;
- if (!isSameTag) {
- return false;
- }
+ const peek = () => str.charCodeAt(index + 1);
- stack || (stack = new _Stack());
- return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
-}
+ const advance = () => {
+ prev = code;
+ return str.charCodeAt(++index);
+ };
-var _baseIsEqualDeep = baseIsEqualDeep;
+ while (index < length) {
+ code = advance();
+ let next;
-/**
- * The base implementation of `_.isEqual` which supports partial comparisons
- * and tracks traversed objects.
- *
- * @private
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @param {boolean} bitmask The bitmask flags.
- * 1 - Unordered comparison
- * 2 - Partial comparison
- * @param {Function} [customizer] The function to customize comparisons.
- * @param {Object} [stack] Tracks traversed `value` and `other` objects.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- */
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ code = advance();
-function baseIsEqual(value, other, bitmask, customizer, stack) {
- if (value === other) {
- return true;
- }
+ if (code === CHAR_LEFT_CURLY_BRACE) {
+ braceEscaped = true;
+ }
- if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
- return value !== value && other !== other;
- }
+ continue;
+ }
- return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
-}
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
+ braces++;
-var _baseIsEqual = baseIsEqual;
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ advance();
+ continue;
+ }
-/** Used to compose bitmasks for value comparisons. */
+ if (code === CHAR_LEFT_CURLY_BRACE) {
+ braces++;
+ continue;
+ }
-var COMPARE_PARTIAL_FLAG$4 = 1,
- COMPARE_UNORDERED_FLAG$2 = 2;
-/**
- * The base implementation of `_.isMatch` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to inspect.
- * @param {Object} source The object of property values to match.
- * @param {Array} matchData The property names, values, and compare flags to match.
- * @param {Function} [customizer] The function to customize comparisons.
- * @returns {boolean} Returns `true` if `object` is a match, else `false`.
- */
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
+ isBrace = token.isBrace = true;
+ isGlob = token.isGlob = true;
+ finished = true;
-function baseIsMatch(object, source, matchData, customizer) {
- var index = matchData.length,
- length = index,
- noCustomizer = !customizer;
+ if (scanToEnd === true) {
+ continue;
+ }
- if (object == null) {
- return !length;
- }
+ break;
+ }
- object = Object(object);
+ if (braceEscaped !== true && code === CHAR_COMMA) {
+ isBrace = token.isBrace = true;
+ isGlob = token.isGlob = true;
+ finished = true;
- while (index--) {
- var data = matchData[index];
+ if (scanToEnd === true) {
+ continue;
+ }
- if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
- return false;
- }
- }
+ break;
+ }
- while (++index < length) {
- data = matchData[index];
- var key = data[0],
- objValue = object[key],
- srcValue = data[1];
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
+ braces--;
- if (noCustomizer && data[2]) {
- if (objValue === undefined && !(key in object)) {
- return false;
+ if (braces === 0) {
+ braceEscaped = false;
+ isBrace = token.isBrace = true;
+ finished = true;
+ break;
+ }
+ }
}
- } else {
- var stack = new _Stack();
- if (customizer) {
- var result = customizer(objValue, srcValue, key, object, source, stack);
+ if (scanToEnd === true) {
+ continue;
}
- if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
- return false;
- }
+ break;
}
- }
- return true;
-}
-
-var _baseIsMatch = baseIsMatch;
-
-/**
- * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` if suitable for strict
- * equality comparisons, else `false`.
- */
-
-function isStrictComparable(value) {
- return value === value && !isObject_1(value);
-}
-
-var _isStrictComparable = isStrictComparable;
-
-/**
- * Gets the property names, values, and compare flags of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the match data of `object`.
- */
-
-function getMatchData(object) {
- var result = keys_1(object),
- length = result.length;
-
- while (length--) {
- var key = result[length],
- value = object[key];
- result[length] = [key, value, _isStrictComparable(value)];
- }
-
- return result;
-}
+ if (code === CHAR_FORWARD_SLASH) {
+ slashes.push(index);
+ tokens.push(token);
+ token = {
+ value: '',
+ depth: 0,
+ isGlob: false
+ };
+ if (finished === true) continue;
-var _getMatchData = getMatchData;
+ if (prev === CHAR_DOT && index === start + 1) {
+ start += 2;
+ continue;
+ }
-/**
- * A specialized version of `matchesProperty` for source values suitable
- * for strict equality comparisons, i.e. `===`.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @param {*} srcValue The value to match.
- * @returns {Function} Returns the new spec function.
- */
-function matchesStrictComparable(key, srcValue) {
- return function (object) {
- if (object == null) {
- return false;
+ lastIndex = index + 1;
+ continue;
}
- return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
- };
-}
+ if (opts.noext !== true) {
+ const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
-var _matchesStrictComparable = matchesStrictComparable;
+ if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
+ isGlob = token.isGlob = true;
+ isExtglob = token.isExtglob = true;
+ finished = true;
-/**
- * The base implementation of `_.matches` which doesn't clone `source`.
- *
- * @private
- * @param {Object} source The object of property values to match.
- * @returns {Function} Returns the new spec function.
- */
+ if (code === CHAR_EXCLAMATION_MARK && index === start) {
+ negatedExtglob = true;
+ }
-function baseMatches(source) {
- var matchData = _getMatchData(source);
+ if (scanToEnd === true) {
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ code = advance();
+ continue;
+ }
- if (matchData.length == 1 && matchData[0][2]) {
- return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
- }
+ if (code === CHAR_RIGHT_PARENTHESES) {
+ isGlob = token.isGlob = true;
+ finished = true;
+ break;
+ }
+ }
- return function (object) {
- return object === source || _baseIsMatch(object, source, matchData);
- };
-}
+ continue;
+ }
-var _baseMatches = baseMatches;
+ break;
+ }
+ }
-/**
- * Gets the value at `path` of `object`. If the resolved value is
- * `undefined`, the `defaultValue` is returned in its place.
- *
- * @static
- * @memberOf _
- * @since 3.7.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @param {*} [defaultValue] The value returned for `undefined` resolved values.
- * @returns {*} Returns the resolved value.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 3 } }] };
- *
- * _.get(object, 'a[0].b.c');
- * // => 3
- *
- * _.get(object, ['a', '0', 'b', 'c']);
- * // => 3
- *
- * _.get(object, 'a.b.c', 'default');
- * // => 'default'
- */
+ if (code === CHAR_ASTERISK) {
+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
+ isGlob = token.isGlob = true;
+ finished = true;
-function get(object, path, defaultValue) {
- var result = object == null ? undefined : _baseGet(object, path);
- return result === undefined ? defaultValue : result;
-}
+ if (scanToEnd === true) {
+ continue;
+ }
-var get_1 = get;
+ break;
+ }
-/** Used to compose bitmasks for value comparisons. */
+ if (code === CHAR_QUESTION_MARK) {
+ isGlob = token.isGlob = true;
+ finished = true;
-var COMPARE_PARTIAL_FLAG$5 = 1,
- COMPARE_UNORDERED_FLAG$3 = 2;
-/**
- * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
- *
- * @private
- * @param {string} path The path of the property to get.
- * @param {*} srcValue The value to match.
- * @returns {Function} Returns the new spec function.
- */
+ if (scanToEnd === true) {
+ continue;
+ }
-function baseMatchesProperty(path, srcValue) {
- if (_isKey(path) && _isStrictComparable(srcValue)) {
- return _matchesStrictComparable(_toKey(path), srcValue);
- }
+ break;
+ }
- return function (object) {
- var objValue = get_1(object, path);
- return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
- };
-}
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
+ while (eos() !== true && (next = advance())) {
+ if (next === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ advance();
+ continue;
+ }
-var _baseMatchesProperty = baseMatchesProperty;
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
+ isBracket = token.isBracket = true;
+ isGlob = token.isGlob = true;
+ finished = true;
+ break;
+ }
+ }
-/**
- * The base implementation of `_.property` without support for deep paths.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @returns {Function} Returns the new accessor function.
- */
-function baseProperty(key) {
- return function (object) {
- return object == null ? undefined : object[key];
- };
-}
+ if (scanToEnd === true) {
+ continue;
+ }
-var _baseProperty = baseProperty;
+ break;
+ }
-/**
- * A specialized version of `baseProperty` which supports deep paths.
- *
- * @private
- * @param {Array|string} path The path of the property to get.
- * @returns {Function} Returns the new accessor function.
- */
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
+ negated = token.negated = true;
+ start++;
+ continue;
+ }
-function basePropertyDeep(path) {
- return function (object) {
- return _baseGet(object, path);
- };
-}
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
+ isGlob = token.isGlob = true;
-var _basePropertyDeep = basePropertyDeep;
+ if (scanToEnd === true) {
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_LEFT_PARENTHESES) {
+ backslashes = token.backslashes = true;
+ code = advance();
+ continue;
+ }
-/**
- * Creates a function that returns the value at `path` of a given object.
- *
- * @static
- * @memberOf _
- * @since 2.4.0
- * @category Util
- * @param {Array|string} path The path of the property to get.
- * @returns {Function} Returns the new accessor function.
- * @example
- *
- * var objects = [
- * { 'a': { 'b': 2 } },
- * { 'a': { 'b': 1 } }
- * ];
- *
- * _.map(objects, _.property('a.b'));
- * // => [2, 1]
- *
- * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
- * // => [1, 2]
- */
+ if (code === CHAR_RIGHT_PARENTHESES) {
+ finished = true;
+ break;
+ }
+ }
-function property(path) {
- return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
-}
+ continue;
+ }
-var property_1 = property;
+ break;
+ }
-/**
- * The base implementation of `_.iteratee`.
- *
- * @private
- * @param {*} [value=_.identity] The value to convert to an iteratee.
- * @returns {Function} Returns the iteratee.
- */
+ if (isGlob === true) {
+ finished = true;
-function baseIteratee(value) {
- // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
- // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
- if (typeof value == 'function') {
- return value;
- }
+ if (scanToEnd === true) {
+ continue;
+ }
- if (value == null) {
- return identity_1;
+ break;
+ }
}
- if (typeof value == 'object') {
- return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
+ if (opts.noext === true) {
+ isExtglob = false;
+ isGlob = false;
}
- return property_1(value);
-}
-
-var _baseIteratee = baseIteratee;
-
-/**
- * Creates a function like `_.groupBy`.
- *
- * @private
- * @param {Function} setter The function to set accumulator values.
- * @param {Function} [initializer] The accumulator object initializer.
- * @returns {Function} Returns the new aggregator function.
- */
-
-function createAggregator(setter, initializer) {
- return function (collection, iteratee) {
- var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
- accumulator = initializer ? initializer() : {};
- return func(collection, setter, _baseIteratee(iteratee), accumulator);
- };
-}
-
-var _createAggregator = createAggregator;
-
-/** Used for built-in method references. */
-
-var objectProto$d = Object.prototype;
-/** Used to check objects for own properties. */
+ let base = str;
+ let prefix = '';
+ let glob = '';
-var hasOwnProperty$a = objectProto$d.hasOwnProperty;
-/**
- * Creates an object composed of keys generated from the results of running
- * each element of `collection` thru `iteratee`. The order of grouped values
- * is determined by the order they occur in `collection`. The corresponding
- * value of each key is an array of elements responsible for generating the
- * key. The iteratee is invoked with one argument: (value).
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Collection
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
- * @returns {Object} Returns the composed aggregate object.
- * @example
- *
- * _.groupBy([6.1, 4.2, 6.3], Math.floor);
- * // => { '4': [4.2], '6': [6.1, 6.3] }
- *
- * // The `_.property` iteratee shorthand.
- * _.groupBy(['one', 'two', 'three'], 'length');
- * // => { '3': ['one', 'two'], '5': ['three'] }
- */
+ if (start > 0) {
+ prefix = str.slice(0, start);
+ str = str.slice(start);
+ lastIndex -= start;
+ }
-var groupBy = _createAggregator(function (result, value, key) {
- if (hasOwnProperty$a.call(result, key)) {
- result[key].push(value);
+ if (base && isGlob === true && lastIndex > 0) {
+ base = str.slice(0, lastIndex);
+ glob = str.slice(lastIndex);
+ } else if (isGlob === true) {
+ base = '';
+ glob = str;
} else {
- _baseAssignValue(result, key, [value]);
+ base = str;
}
-});
-var groupBy_1 = groupBy;
-
-/**
- * Creates an array of elements split into two groups, the first of which
- * contains elements `predicate` returns truthy for, the second of which
- * contains elements `predicate` returns falsey for. The predicate is
- * invoked with one argument: (value).
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Collection
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} [predicate=_.identity] The function invoked per iteration.
- * @returns {Array} Returns the array of grouped elements.
- * @example
- *
- * var users = [
- * { 'user': 'barney', 'age': 36, 'active': false },
- * { 'user': 'fred', 'age': 40, 'active': true },
- * { 'user': 'pebbles', 'age': 1, 'active': false }
- * ];
- *
- * _.partition(users, function(o) { return o.active; });
- * // => objects for [['fred'], ['barney', 'pebbles']]
- *
- * // The `_.matches` iteratee shorthand.
- * _.partition(users, { 'age': 1, 'active': false });
- * // => objects for [['pebbles'], ['barney', 'fred']]
- *
- * // The `_.matchesProperty` iteratee shorthand.
- * _.partition(users, ['active', false]);
- * // => objects for [['barney', 'pebbles'], ['fred']]
- *
- * // The `_.property` iteratee shorthand.
- * _.partition(users, 'active');
- * // => objects for [['fred'], ['barney', 'pebbles']]
- */
-
-var partition = _createAggregator(function (result, value, key) {
- result[key ? 0 : 1].push(value);
-}, function () {
- return [[], []];
-});
-var partition_1 = partition;
-
-var thirdParty = require("./third-party");
-var prettierInternal = src.__internal;
+ if (base && base !== '' && base !== '/' && base !== str) {
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) {
+ base = base.slice(0, -1);
+ }
+ }
-var minimist = function (args, opts) {
- if (!opts) opts = {};
- var flags = {
- bools: {},
- strings: {},
- unknownFn: null
- };
+ if (opts.unescape === true) {
+ if (glob) glob = utils$e.removeBackslashes(glob);
- if (typeof opts['unknown'] === 'function') {
- flags.unknownFn = opts['unknown'];
+ if (base && backslashes === true) {
+ base = utils$e.removeBackslashes(base);
+ }
}
- if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
- flags.allBools = true;
- } else {
- [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
- flags.bools[key] = true;
- });
- }
+ const state = {
+ prefix,
+ input,
+ start,
+ base,
+ glob,
+ isBrace,
+ isBracket,
+ isGlob,
+ isExtglob,
+ isGlobstar,
+ negated,
+ negatedExtglob
+ };
- var aliases = {};
- Object.keys(opts.alias || {}).forEach(function (key) {
- aliases[key] = [].concat(opts.alias[key]);
- aliases[key].forEach(function (x) {
- aliases[x] = [key].concat(aliases[key].filter(function (y) {
- return x !== y;
- }));
- });
- });
- [].concat(opts.string).filter(Boolean).forEach(function (key) {
- flags.strings[key] = true;
+ if (opts.tokens === true) {
+ state.maxDepth = 0;
- if (aliases[key]) {
- flags.strings[aliases[key]] = true;
+ if (!isPathSeparator(code)) {
+ tokens.push(token);
}
- });
- var defaults = opts['default'] || {};
- var argv = {
- _: []
- };
- Object.keys(flags.bools).forEach(function (key) {
- setArg(key, defaults[key] === undefined ? false : defaults[key]);
- });
- var notFlags = [];
- if (args.indexOf('--') !== -1) {
- notFlags = args.slice(args.indexOf('--') + 1);
- args = args.slice(0, args.indexOf('--'));
+ state.tokens = tokens;
}
- function argDefined(key, arg) {
- return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key];
- }
+ if (opts.parts === true || opts.tokens === true) {
+ let prevIndex;
- function setArg(key, val, arg) {
- if (arg && flags.unknownFn && !argDefined(key, arg)) {
- if (flags.unknownFn(arg) === false) return;
- }
+ for (let idx = 0; idx < slashes.length; idx++) {
+ const n = prevIndex ? prevIndex + 1 : start;
+ const i = slashes[idx];
+ const value = input.slice(n, i);
- var value = !flags.strings[key] && isNumber(val) ? Number(val) : val;
- setKey(argv, key.split('.'), value);
- (aliases[key] || []).forEach(function (x) {
- setKey(argv, x.split('.'), value);
- });
- }
+ if (opts.tokens) {
+ if (idx === 0 && start !== 0) {
+ tokens[idx].isPrefix = true;
+ tokens[idx].value = prefix;
+ } else {
+ tokens[idx].value = value;
+ }
- function setKey(obj, keys, value) {
- var o = obj;
+ depth(tokens[idx]);
+ state.maxDepth += tokens[idx].depth;
+ }
- for (var i = 0; i < keys.length - 1; i++) {
- var key = keys[i];
- if (key === '__proto__') return;
- if (o[key] === undefined) o[key] = {};
- if (o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype) o[key] = {};
- if (o[key] === Array.prototype) o[key] = [];
- o = o[key];
+ if (idx !== 0 || value !== '') {
+ parts.push(value);
+ }
+
+ prevIndex = i;
}
- var key = keys[keys.length - 1];
- if (key === '__proto__') return;
- if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {};
- if (o === Array.prototype) o = [];
+ if (prevIndex && prevIndex + 1 < input.length) {
+ const value = input.slice(prevIndex + 1);
+ parts.push(value);
- if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
- o[key] = value;
- } else if (Array.isArray(o[key])) {
- o[key].push(value);
- } else {
- o[key] = [o[key], value];
+ if (opts.tokens) {
+ tokens[tokens.length - 1].value = value;
+ depth(tokens[tokens.length - 1]);
+ state.maxDepth += tokens[tokens.length - 1].depth;
+ }
}
- }
- function aliasIsBoolean(key) {
- return aliases[key].some(function (x) {
- return flags.bools[x];
- });
+ state.slashes = slashes;
+ state.parts = parts;
}
- for (var i = 0; i < args.length; i++) {
- var arg = args[i];
+ return state;
+};
- if (/^--.+=/.test(arg)) {
- // Using [\s\S] instead of . because js doesn't support the
- // 'dotall' regex modifier. See:
- // http://stackoverflow.com/a/1068308/13216
- var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
- var key = m[1];
- var value = m[2];
+var scan_1 = scan$1;
- if (flags.bools[key]) {
- value = value !== 'false';
- }
+const constants$2 = constants$3;
+const utils$d = utils$f;
+/**
+ * Constants
+ */
- setArg(key, value, arg);
- } else if (/^--no-.+/.test(arg)) {
- var key = arg.match(/^--no-(.+)/)[1];
- setArg(key, false, arg);
- } else if (/^--.+/.test(arg)) {
- var key = arg.match(/^--(.+)/)[1];
- var next = args[i + 1];
-
- if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
- setArg(key, next, arg);
- i++;
- } else if (/^(true|false)$/.test(next)) {
- setArg(key, next === 'true', arg);
- i++;
- } else {
- setArg(key, flags.strings[key] ? '' : true, arg);
- }
- } else if (/^-[^-]+/.test(arg)) {
- var letters = arg.slice(1, -1).split('');
- var broken = false;
-
- for (var j = 0; j < letters.length; j++) {
- var next = arg.slice(j + 2);
-
- if (next === '-') {
- setArg(letters[j], next, arg);
- continue;
- }
-
- if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
- setArg(letters[j], next.split('=')[1], arg);
- broken = true;
- break;
- }
-
- if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
- setArg(letters[j], next, arg);
- broken = true;
- break;
- }
-
- if (letters[j + 1] && letters[j + 1].match(/\W/)) {
- setArg(letters[j], arg.slice(j + 2), arg);
- broken = true;
- break;
- } else {
- setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
- }
- }
-
- var key = arg.slice(-1)[0];
-
- if (!broken && key !== '-') {
- if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
- setArg(key, args[i + 1], arg);
- i++;
- } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
- setArg(key, args[i + 1] === 'true', arg);
- i++;
- } else {
- setArg(key, flags.strings[key] ? '' : true, arg);
- }
- }
- } else {
- if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
- argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
- }
-
- if (opts.stopEarly) {
- argv._.push.apply(argv._, args.slice(i + 1));
+const {
+ MAX_LENGTH,
+ POSIX_REGEX_SOURCE,
+ REGEX_NON_SPECIAL_CHARS,
+ REGEX_SPECIAL_CHARS_BACKREF,
+ REPLACEMENTS
+} = constants$2;
+/**
+ * Helpers
+ */
- break;
- }
- }
+const expandRange = (args, options) => {
+ if (typeof options.expandRange === 'function') {
+ return options.expandRange(...args, options);
}
- Object.keys(defaults).forEach(function (key) {
- if (!hasKey(argv, key.split('.'))) {
- setKey(argv, key.split('.'), defaults[key]);
- (aliases[key] || []).forEach(function (x) {
- setKey(argv, x.split('.'), defaults[key]);
- });
- }
- });
+ args.sort();
+ const value = `[${args.join('-')}]`;
- if (opts['--']) {
- argv['--'] = new Array();
- notFlags.forEach(function (key) {
- argv['--'].push(key);
- });
- } else {
- notFlags.forEach(function (key) {
- argv._.push(key);
- });
+ try {
+ /* eslint-disable-next-line no-new */
+ new RegExp(value);
+ } catch (ex) {
+ return args.map(v => utils$d.escapeRegex(v)).join('..');
}
- return argv;
+ return value;
};
-
-function hasKey(obj, keys) {
- var o = obj;
- keys.slice(0, -1).forEach(function (key) {
- o = o[key] || {};
- });
- var key = keys[keys.length - 1];
- return key in o;
-}
-
-function isNumber(x) {
- if (typeof x === 'number') return true;
- if (/^0x[0-9a-f]+$/i.test(x)) return true;
- return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
-}
-
-const PLACEHOLDER = null;
/**
- * unspecified boolean flag without default value is parsed as `undefined` instead of `false`
+ * Create the message for a syntax error
*/
-var minimist_1 = function (args, options) {
- const boolean = options.boolean || [];
- const defaults = options.default || {};
- const booleanWithoutDefault = boolean.filter(key => !(key in defaults));
- const newDefaults = Object.assign({}, defaults, fromPairs_1(booleanWithoutDefault.map(key => [key, PLACEHOLDER])));
- const parsed = minimist(args, Object.assign({}, options, {
- default: newDefaults
- }));
- return fromPairs_1(Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER));
-};
-var array = createCommonjsModule(function (module, exports) {
+const syntaxError = (type, char) => {
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
+};
+/**
+ * Parse the given input string.
+ * @param {String} input
+ * @param {Object} options
+ * @return {Object}
+ */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.splitWhen = exports.flatten = void 0;
- function flatten(items) {
- return items.reduce((collection, item) => [].concat(collection, item), []);
+const parse$2 = (input, options) => {
+ if (typeof input !== 'string') {
+ throw new TypeError('Expected a string');
}
- exports.flatten = flatten;
-
- function splitWhen(items, predicate) {
- const result = [[]];
- let groupIndex = 0;
-
- for (const item of items) {
- if (predicate(item)) {
- groupIndex++;
- result[groupIndex] = [];
- } else {
- result[groupIndex].push(item);
- }
- }
+ input = REPLACEMENTS[input] || input;
+ const opts = Object.assign({}, options);
+ const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
+ let len = input.length;
- return result;
+ if (len > max) {
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
- exports.splitWhen = splitWhen;
-});
-
-var errno = createCommonjsModule(function (module, exports) {
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isEnoentCodeError = void 0;
-
- function isEnoentCodeError(error) {
- return error.code === 'ENOENT';
- }
+ const bos = {
+ type: 'bos',
+ value: '',
+ output: opts.prepend || ''
+ };
+ const tokens = [bos];
+ const capture = opts.capture ? '' : '?:';
+ const win32 = utils$d.isWindows(options); // create constants based on platform, for windows or posix
- exports.isEnoentCodeError = isEnoentCodeError;
-});
+ const PLATFORM_CHARS = constants$2.globChars(win32);
+ const EXTGLOB_CHARS = constants$2.extglobChars(PLATFORM_CHARS);
+ const {
+ DOT_LITERAL,
+ PLUS_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOT_SLASH,
+ NO_DOTS_SLASH,
+ QMARK,
+ QMARK_NO_DOT,
+ STAR,
+ START_ANCHOR
+ } = PLATFORM_CHARS;
-var fs = createCommonjsModule(function (module, exports) {
+ const globstar = opts => {
+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
+ };
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.createDirentFromStats = void 0;
+ const nodot = opts.dot ? '' : NO_DOT;
+ const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
+ let star = opts.bash === true ? globstar(opts) : STAR;
- class DirentFromStats {
- constructor(name, stats) {
- this.name = name;
- this.isBlockDevice = stats.isBlockDevice.bind(stats);
- this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
- this.isDirectory = stats.isDirectory.bind(stats);
- this.isFIFO = stats.isFIFO.bind(stats);
- this.isFile = stats.isFile.bind(stats);
- this.isSocket = stats.isSocket.bind(stats);
- this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
- }
+ if (opts.capture) {
+ star = `(${star})`;
+ } // minimatch options support
- }
- function createDirentFromStats(name, stats) {
- return new DirentFromStats(name, stats);
+ if (typeof opts.noext === 'boolean') {
+ opts.noextglob = opts.noext;
}
- exports.createDirentFromStats = createDirentFromStats;
-});
-
-var path_1 = createCommonjsModule(function (module, exports) {
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
- const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
-
- const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
- /**\r
- * Designed to work only with simple paths: `dir\\file`.\r
+ const state = {
+ input,
+ index: -1,
+ start: 0,
+ dot: opts.dot === true,
+ consumed: '',
+ output: '',
+ prefix: '',
+ backtrack: false,
+ negated: false,
+ brackets: 0,
+ braces: 0,
+ parens: 0,
+ quotes: 0,
+ globstar: false,
+ tokens
+ };
+ input = utils$d.removePrefix(input, state);
+ len = input.length;
+ const extglobs = [];
+ const braces = [];
+ const stack = [];
+ let prev = bos;
+ let value;
+ /**
+ * Tokenizing helpers
*/
- function unixify(filepath) {
- return filepath.replace(/\\/g, '/');
- }
-
- exports.unixify = unixify;
+ const eos = () => state.index === len - 1;
- function makeAbsolute(cwd, filepath) {
- return path__default['default'].resolve(cwd, filepath);
- }
+ const peek = state.peek = (n = 1) => input[state.index + n];
- exports.makeAbsolute = makeAbsolute;
+ const advance = state.advance = () => input[++state.index] || '';
- function escape(pattern) {
- return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
- }
+ const remaining = () => input.slice(state.index + 1);
- exports.escape = escape;
+ const consume = (value = '', num = 0) => {
+ state.consumed += value;
+ state.index += num;
+ };
- function removeLeadingDotSegment(entry) {
- // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
- // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
- if (entry.charAt(0) === '.') {
- const secondCharactery = entry.charAt(1);
+ const append = token => {
+ state.output += token.output != null ? token.output : token.value;
+ consume(token.value);
+ };
- if (secondCharactery === '/' || secondCharactery === '\\') {
- return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
- }
- }
+ const negate = () => {
+ let count = 1;
- return entry;
- }
+ while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
+ advance();
+ state.start++;
+ count++;
+ }
- exports.removeLeadingDotSegment = removeLeadingDotSegment;
-});
+ if (count % 2 === 0) {
+ return false;
+ }
-/*!
- * is-extglob <https://github.com/jonschlinkert/is-extglob>
- *
- * Copyright (c) 2014-2016, Jon Schlinkert.
- * Licensed under the MIT License.
- */
-var isExtglob = function isExtglob(str) {
- if (typeof str !== 'string' || str === '') {
- return false;
- }
+ state.negated = true;
+ state.start++;
+ return true;
+ };
- var match;
+ const increment = type => {
+ state[type]++;
+ stack.push(type);
+ };
- while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
- if (match[2]) return true;
- str = str.slice(match.index + match[0].length);
- }
+ const decrement = type => {
+ state[type]--;
+ stack.pop();
+ };
+ /**
+ * Push tokens onto the tokens array. This helper speeds up
+ * tokenizing by 1) helping us avoid backtracking as much as possible,
+ * and 2) helping us avoid creating extra tokens when consecutive
+ * characters are plain text. This improves performance and simplifies
+ * lookbehinds.
+ */
- return false;
-};
-/*!
- * is-glob <https://github.com/jonschlinkert/is-glob>
- *
- * Copyright (c) 2014-2017, Jon Schlinkert.
- * Released under the MIT License.
- */
+ const push = tok => {
+ if (prev.type === 'globstar') {
+ const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
+ const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
-var chars = {
- '{': '}',
- '(': ')',
- '[': ']'
-};
-var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
-var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
+ if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
+ state.output = state.output.slice(0, -prev.output.length);
+ prev.type = 'star';
+ prev.value = '*';
+ prev.output = star;
+ state.output += prev.output;
+ }
+ }
-var isGlob = function isGlob(str, options) {
- if (typeof str !== 'string' || str === '') {
- return false;
- }
+ if (extglobs.length && tok.type !== 'paren') {
+ extglobs[extglobs.length - 1].inner += tok.value;
+ }
- if (isExtglob(str)) {
- return true;
- }
+ if (tok.value || tok.output) append(tok);
- var regex = strictRegex;
- var match; // optionally relax regex
+ if (prev && prev.type === 'text' && tok.type === 'text') {
+ prev.value += tok.value;
+ prev.output = (prev.output || '') + tok.value;
+ return;
+ }
- if (options && options.strict === false) {
- regex = relaxedRegex;
- }
+ tok.prev = prev;
+ tokens.push(tok);
+ prev = tok;
+ };
- while (match = regex.exec(str)) {
- if (match[2]) return true;
- var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
- // set the index to the next closing character
+ const extglobOpen = (type, value) => {
+ const token = Object.assign(Object.assign({}, EXTGLOB_CHARS[value]), {}, {
+ conditions: 1,
+ inner: ''
+ });
+ token.prev = prev;
+ token.parens = state.parens;
+ token.output = state.output;
+ const output = (opts.capture ? '(' : '') + token.open;
+ increment('parens');
+ push({
+ type,
+ value,
+ output: state.output ? '' : ONE_CHAR
+ });
+ push({
+ type: 'paren',
+ extglob: true,
+ value: advance(),
+ output
+ });
+ extglobs.push(token);
+ };
- var open = match[1];
- var close = open ? chars[open] : null;
+ const extglobClose = token => {
+ let output = token.close + (opts.capture ? ')' : '');
+ let rest;
- if (open && close) {
- var n = str.indexOf(close, idx);
+ if (token.type === 'negate') {
+ let extglobStar = star;
- if (n !== -1) {
- idx = n + 1;
+ if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
+ extglobStar = globstar(opts);
}
- }
- str = str.slice(idx);
- }
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
+ output = token.close = `)$))${extglobStar}`;
+ }
- return false;
-};
+ if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
+ output = token.close = `)${rest})${extglobStar})`;
+ }
-var pathPosixDirname = path__default['default'].posix.dirname;
-var isWin32 = os__default['default'].platform() === 'win32';
-var slash = '/';
-var backslash = /\\/g;
-var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
-var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
-var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
-/**
- * @param {string} str
- * @param {Object} opts
- * @param {boolean} [opts.flipBackslashes=true]
- */
+ if (token.prev.type === 'bos') {
+ state.negatedExtglob = true;
+ }
+ }
-var globParent = function globParent(str, opts) {
- var options = Object.assign({
- flipBackslashes: true
- }, opts); // flip windows path separators
+ push({
+ type: 'paren',
+ extglob: true,
+ value,
+ output
+ });
+ decrement('parens');
+ };
+ /**
+ * Fast paths
+ */
- if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
- str = str.replace(backslash, slash);
- } // special case for strings ending in enclosure containing path separator
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
+ let backslashes = false;
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
+ if (first === '\\') {
+ backslashes = true;
+ return m;
+ }
- if (enclosure.test(str)) {
- str += slash;
- } // preserves full path in case of trailing path separator
+ if (first === '?') {
+ if (esc) {
+ return esc + first + (rest ? QMARK.repeat(rest.length) : '');
+ }
+ if (index === 0) {
+ return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
+ }
- str += 'a'; // remove path parts that are globby
+ return QMARK.repeat(chars.length);
+ }
- do {
- str = pathPosixDirname(str);
- } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
+ if (first === '.') {
+ return DOT_LITERAL.repeat(chars.length);
+ }
+ if (first === '*') {
+ if (esc) {
+ return esc + first + (rest ? star : '');
+ }
- return str.replace(escaped, '$1');
-};
+ return star;
+ }
-var utils = createCommonjsModule(function (module, exports) {
+ return esc ? m : `\\${m}`;
+ });
- exports.isInteger = num => {
- if (typeof num === 'number') {
- return Number.isInteger(num);
+ if (backslashes === true) {
+ if (opts.unescape === true) {
+ output = output.replace(/\\/g, '');
+ } else {
+ output = output.replace(/\\+/g, m => {
+ return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
+ });
+ }
}
- if (typeof num === 'string' && num.trim() !== '') {
- return Number.isInteger(Number(num));
+ if (output === input && opts.contains === true) {
+ state.output = input;
+ return state;
}
- return false;
- };
+ state.output = utils$d.wrapOutput(output, state, options);
+ return state;
+ }
/**
- * Find a node of the given type
+ * Tokenize input until we reach end-of-string
*/
- exports.find = (node, type) => node.nodes.find(node => node.type === type);
- /**
- * Find a node of the given type
- */
-
+ while (!eos()) {
+ value = advance();
- exports.exceedsLimit = (min, max, step = 1, limit) => {
- if (limit === false) return false;
- if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
- return (Number(max) - Number(min)) / Number(step) >= limit;
- };
- /**
- * Escape the given node with '\\' before node.value
- */
+ if (value === '\u0000') {
+ continue;
+ }
+ /**
+ * Escaped characters
+ */
- exports.escapeNode = (block, n = 0, type) => {
- let node = block.nodes[n];
- if (!node) return;
+ if (value === '\\') {
+ const next = peek();
- if (type && node.type === type || node.type === 'open' || node.type === 'close') {
- if (node.escaped !== true) {
- node.value = '\\' + node.value;
- node.escaped = true;
+ if (next === '/' && opts.bash !== true) {
+ continue;
}
- }
- };
- /**
- * Returns true if the given brace node should be enclosed in literal braces
- */
+ if (next === '.' || next === ';') {
+ continue;
+ }
- exports.encloseBrace = node => {
- if (node.type !== 'brace') return false;
-
- if (node.commas >> 0 + node.ranges >> 0 === 0) {
- node.invalid = true;
- return true;
- }
-
- return false;
- };
- /**
- * Returns true if a brace node is invalid.
- */
-
+ if (!next) {
+ value += '\\';
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ } // collapse slashes to reduce potential for exploits
- exports.isInvalidBrace = block => {
- if (block.type !== 'brace') return false;
- if (block.invalid === true || block.dollar) return true;
- if (block.commas >> 0 + block.ranges >> 0 === 0) {
- block.invalid = true;
- return true;
- }
+ const match = /^\\+/.exec(remaining());
+ let slashes = 0;
- if (block.open !== true || block.close !== true) {
- block.invalid = true;
- return true;
- }
+ if (match && match[0].length > 2) {
+ slashes = match[0].length;
+ state.index += slashes;
- return false;
- };
- /**
- * Returns true if a node is an open or close node
- */
+ if (slashes % 2 !== 0) {
+ value += '\\';
+ }
+ }
+ if (opts.unescape === true) {
+ value = advance();
+ } else {
+ value += advance();
+ }
- exports.isOpenOrClose = node => {
- if (node.type === 'open' || node.type === 'close') {
- return true;
+ if (state.brackets === 0) {
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ }
}
+ /**
+ * If we're inside a regex character class, continue
+ * until we reach the closing bracket.
+ */
- return node.open === true || node.close === true;
- };
- /**
- * Reduce an array of text nodes.
- */
+ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
+ if (opts.posix !== false && value === ':') {
+ const inner = prev.value.slice(1);
- exports.reduce = nodes => nodes.reduce((acc, node) => {
- if (node.type === 'text') acc.push(node.value);
- if (node.type === 'range') node.type = 'text';
- return acc;
- }, []);
- /**
- * Flatten an array
- */
+ if (inner.includes('[')) {
+ prev.posix = true;
+ if (inner.includes(':')) {
+ const idx = prev.value.lastIndexOf('[');
+ const pre = prev.value.slice(0, idx);
+ const rest = prev.value.slice(idx + 2);
+ const posix = POSIX_REGEX_SOURCE[rest];
- exports.flatten = (...args) => {
- const result = [];
+ if (posix) {
+ prev.value = pre + posix;
+ state.backtrack = true;
+ advance();
- const flat = arr => {
- for (let i = 0; i < arr.length; i++) {
- let ele = arr[i];
- Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
- }
+ if (!bos.output && tokens.indexOf(prev) === 1) {
+ bos.output = ONE_CHAR;
+ }
- return result;
- };
+ continue;
+ }
+ }
+ }
+ }
- flat(args);
- return result;
- };
-});
+ if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
+ value = `\\${value}`;
+ }
-var stringify = (ast, options = {}) => {
- let stringify = (node, parent = {}) => {
- let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
- let invalidNode = node.invalid === true && options.escapeInvalid === true;
- let output = '';
+ if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
+ value = `\\${value}`;
+ }
- if (node.value) {
- if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
- return '\\' + node.value;
+ if (opts.posix === true && value === '!' && prev.value === '[') {
+ value = '^';
}
- return node.value;
+ prev.value += value;
+ append({
+ value
+ });
+ continue;
}
+ /**
+ * If we're inside a quoted string, continue
+ * until we reach the closing double quote.
+ */
- if (node.value) {
- return node.value;
- }
- if (node.nodes) {
- for (let child of node.nodes) {
- output += stringify(child);
- }
+ if (state.quotes === 1 && value !== '"') {
+ value = utils$d.escapeRegex(value);
+ prev.value += value;
+ append({
+ value
+ });
+ continue;
}
+ /**
+ * Double quotes
+ */
- return output;
- };
-
- return stringify(ast);
-};
-
-/*!
- * is-number <https://github.com/jonschlinkert/is-number>
- *
- * Copyright (c) 2014-present, Jon Schlinkert.
- * Released under the MIT License.
- */
-
-var isNumber$1 = function (num) {
- if (typeof num === 'number') {
- return num - num === 0;
- }
- if (typeof num === 'string' && num.trim() !== '') {
- return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
- }
+ if (value === '"') {
+ state.quotes = state.quotes === 1 ? 0 : 1;
- return false;
-};
+ if (opts.keepQuotes === true) {
+ push({
+ type: 'text',
+ value
+ });
+ }
-const toRegexRange = (min, max, options) => {
- if (isNumber$1(min) === false) {
- throw new TypeError('toRegexRange: expected the first argument to be a number');
- }
+ continue;
+ }
+ /**
+ * Parentheses
+ */
- if (max === void 0 || min === max) {
- return String(min);
- }
- if (isNumber$1(max) === false) {
- throw new TypeError('toRegexRange: expected the second argument to be a number.');
- }
+ if (value === '(') {
+ increment('parens');
+ push({
+ type: 'paren',
+ value
+ });
+ continue;
+ }
- let opts = Object.assign({
- relaxZeros: true
- }, options);
+ if (value === ')') {
+ if (state.parens === 0 && opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('opening', '('));
+ }
- if (typeof opts.strictZeros === 'boolean') {
- opts.relaxZeros = opts.strictZeros === false;
- }
+ const extglob = extglobs[extglobs.length - 1];
- let relax = String(opts.relaxZeros);
- let shorthand = String(opts.shorthand);
- let capture = String(opts.capture);
- let wrap = String(opts.wrap);
- let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
+ if (extglob && state.parens === extglob.parens + 1) {
+ extglobClose(extglobs.pop());
+ continue;
+ }
- if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
- return toRegexRange.cache[cacheKey].result;
- }
+ push({
+ type: 'paren',
+ value,
+ output: state.parens ? ')' : '\\)'
+ });
+ decrement('parens');
+ continue;
+ }
+ /**
+ * Square brackets
+ */
- let a = Math.min(min, max);
- let b = Math.max(min, max);
- if (Math.abs(a - b) === 1) {
- let result = min + '|' + max;
+ if (value === '[') {
+ if (opts.nobracket === true || !remaining().includes(']')) {
+ if (opts.nobracket !== true && opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('closing', ']'));
+ }
- if (opts.capture) {
- return `(${result})`;
- }
+ value = `\\${value}`;
+ } else {
+ increment('brackets');
+ }
- if (opts.wrap === false) {
- return result;
+ push({
+ type: 'bracket',
+ value
+ });
+ continue;
}
- return `(?:${result})`;
- }
-
- let isPadded = hasPadding(min) || hasPadding(max);
- let state = {
- min,
- max,
- a,
- b
- };
- let positives = [];
- let negatives = [];
+ if (value === ']') {
+ if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
+ push({
+ type: 'text',
+ value,
+ output: `\\${value}`
+ });
+ continue;
+ }
- if (isPadded) {
- state.isPadded = isPadded;
- state.maxLen = String(state.max).length;
- }
+ if (state.brackets === 0) {
+ if (opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('opening', '['));
+ }
- if (a < 0) {
- let newMin = b < 0 ? Math.abs(b) : 1;
- negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
- a = state.a = 0;
- }
+ push({
+ type: 'text',
+ value,
+ output: `\\${value}`
+ });
+ continue;
+ }
- if (b >= 0) {
- positives = splitToPatterns(a, b, state, opts);
- }
+ decrement('brackets');
+ const prevValue = prev.value.slice(1);
- state.negatives = negatives;
- state.positives = positives;
- state.result = collatePatterns(negatives, positives);
+ if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
+ value = `/${value}`;
+ }
- if (opts.capture === true) {
- state.result = `(${state.result})`;
- } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
- state.result = `(?:${state.result})`;
- }
+ prev.value += value;
+ append({
+ value
+ }); // when literal brackets are explicitly disabled
+ // assume we should match with a regex character class
- toRegexRange.cache[cacheKey] = state;
- return state.result;
-};
+ if (opts.literalBrackets === false || utils$d.hasRegexChars(prevValue)) {
+ continue;
+ }
-function collatePatterns(neg, pos, options) {
- let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
- let onlyPositive = filterPatterns(pos, neg, '', false) || [];
- let intersected = filterPatterns(neg, pos, '-?', true) || [];
- let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
- return subpatterns.join('|');
-}
+ const escaped = utils$d.escapeRegex(prev.value);
+ state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
+ // assume we should escape the brackets to match literal characters
-function splitToRanges(min, max) {
- let nines = 1;
- let zeros = 1;
- let stop = countNines(min, nines);
- let stops = new Set([max]);
+ if (opts.literalBrackets === true) {
+ state.output += escaped;
+ prev.value = escaped;
+ continue;
+ } // when the user specifies nothing, try to match both
- while (min <= stop && stop <= max) {
- stops.add(stop);
- nines += 1;
- stop = countNines(min, nines);
- }
- stop = countZeros(max + 1, zeros) - 1;
+ prev.value = `(${capture}${escaped}|${prev.value})`;
+ state.output += prev.value;
+ continue;
+ }
+ /**
+ * Braces
+ */
- while (min < stop && stop <= max) {
- stops.add(stop);
- zeros += 1;
- stop = countZeros(max + 1, zeros) - 1;
- }
- stops = [...stops];
- stops.sort(compare);
- return stops;
-}
-/**
- * Convert a range to a regex pattern
- * @param {Number} `start`
- * @param {Number} `stop`
- * @return {String}
- */
+ if (value === '{' && opts.nobrace !== true) {
+ increment('braces');
+ const open = {
+ type: 'brace',
+ value,
+ output: '(',
+ outputIndex: state.output.length,
+ tokensIndex: state.tokens.length
+ };
+ braces.push(open);
+ push(open);
+ continue;
+ }
+ if (value === '}') {
+ const brace = braces[braces.length - 1];
-function rangeToPattern(start, stop, options) {
- if (start === stop) {
- return {
- pattern: start,
- count: [],
- digits: 0
- };
- }
+ if (opts.nobrace === true || !brace) {
+ push({
+ type: 'text',
+ value,
+ output: value
+ });
+ continue;
+ }
- let zipped = zip(start, stop);
- let digits = zipped.length;
- let pattern = '';
- let count = 0;
+ let output = ')';
- for (let i = 0; i < digits; i++) {
- let [startDigit, stopDigit] = zipped[i];
+ if (brace.dots === true) {
+ const arr = tokens.slice();
+ const range = [];
- if (startDigit === stopDigit) {
- pattern += startDigit;
- } else if (startDigit !== '0' || stopDigit !== '9') {
- pattern += toCharacterClass(startDigit, stopDigit);
- } else {
- count++;
- }
- }
+ for (let i = arr.length - 1; i >= 0; i--) {
+ tokens.pop();
- if (count) {
- pattern += options.shorthand === true ? '\\d' : '[0-9]';
- }
+ if (arr[i].type === 'brace') {
+ break;
+ }
- return {
- pattern,
- count: [count],
- digits
- };
-}
+ if (arr[i].type !== 'dots') {
+ range.unshift(arr[i].value);
+ }
+ }
-function splitToPatterns(min, max, tok, options) {
- let ranges = splitToRanges(min, max);
- let tokens = [];
- let start = min;
- let prev;
+ output = expandRange(range, opts);
+ state.backtrack = true;
+ }
- for (let i = 0; i < ranges.length; i++) {
- let max = ranges[i];
- let obj = rangeToPattern(String(start), String(max), options);
- let zeros = '';
+ if (brace.comma !== true && brace.dots !== true) {
+ const out = state.output.slice(0, brace.outputIndex);
+ const toks = state.tokens.slice(brace.tokensIndex);
+ brace.value = brace.output = '\\{';
+ value = output = '\\}';
+ state.output = out;
- if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
- if (prev.count.length > 1) {
- prev.count.pop();
+ for (const t of toks) {
+ state.output += t.output || t.value;
+ }
}
- prev.count.push(obj.count[0]);
- prev.string = prev.pattern + toQuantifier(prev.count);
- start = max + 1;
+ push({
+ type: 'brace',
+ value,
+ output
+ });
+ decrement('braces');
+ braces.pop();
continue;
}
+ /**
+ * Pipes
+ */
- if (tok.isPadded) {
- zeros = padZeros(max, tok, options);
- }
-
- obj.string = zeros + obj.pattern + toQuantifier(obj.count);
- tokens.push(obj);
- start = max + 1;
- prev = obj;
- }
- return tokens;
-}
+ if (value === '|') {
+ if (extglobs.length > 0) {
+ extglobs[extglobs.length - 1].conditions++;
+ }
-function filterPatterns(arr, comparison, prefix, intersection, options) {
- let result = [];
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ }
+ /**
+ * Commas
+ */
- for (let ele of arr) {
- let {
- string
- } = ele; // only push if _both_ are negative...
- if (!intersection && !contains(comparison, 'string', string)) {
- result.push(prefix + string);
- } // or _both_ are positive
+ if (value === ',') {
+ let output = value;
+ const brace = braces[braces.length - 1];
+ if (brace && stack[stack.length - 1] === 'braces') {
+ brace.comma = true;
+ output = '|';
+ }
- if (intersection && contains(comparison, 'string', string)) {
- result.push(prefix + string);
- }
- }
+ push({
+ type: 'comma',
+ value,
+ output
+ });
+ continue;
+ }
+ /**
+ * Slashes
+ */
- return result;
-}
-/**
- * Zip strings
- */
+ if (value === '/') {
+ // if the beginning of the glob is "./", advance the start
+ // to the current index, and don't add the "./" characters
+ // to the state. This greatly simplifies lookbehinds when
+ // checking for BOS characters like "!" and "." (not "./")
+ if (prev.type === 'dot' && state.index === state.start + 1) {
+ state.start = state.index + 1;
+ state.consumed = '';
+ state.output = '';
+ tokens.pop();
+ prev = bos; // reset "prev" to the first token
-function zip(a, b) {
- let arr = [];
+ continue;
+ }
- for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
+ push({
+ type: 'slash',
+ value,
+ output: SLASH_LITERAL
+ });
+ continue;
+ }
+ /**
+ * Dots
+ */
- return arr;
-}
-function compare(a, b) {
- return a > b ? 1 : b > a ? -1 : 0;
-}
+ if (value === '.') {
+ if (state.braces > 0 && prev.type === 'dot') {
+ if (prev.value === '.') prev.output = DOT_LITERAL;
+ const brace = braces[braces.length - 1];
+ prev.type = 'dots';
+ prev.output += value;
+ prev.value += value;
+ brace.dots = true;
+ continue;
+ }
-function contains(arr, key, val) {
- return arr.some(ele => ele[key] === val);
-}
+ if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
+ push({
+ type: 'text',
+ value,
+ output: DOT_LITERAL
+ });
+ continue;
+ }
-function countNines(min, len) {
- return Number(String(min).slice(0, -len) + '9'.repeat(len));
-}
+ push({
+ type: 'dot',
+ value,
+ output: DOT_LITERAL
+ });
+ continue;
+ }
+ /**
+ * Question marks
+ */
-function countZeros(integer, zeros) {
- return integer - integer % Math.pow(10, zeros);
-}
-function toQuantifier(digits) {
- let [start = 0, stop = ''] = digits;
+ if (value === '?') {
+ const isGroup = prev && prev.value === '(';
- if (stop || start > 1) {
- return `{${start + (stop ? ',' + stop : '')}}`;
- }
+ if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ extglobOpen('qmark', value);
+ continue;
+ }
- return '';
-}
+ if (prev && prev.type === 'paren') {
+ const next = peek();
+ let output = value;
-function toCharacterClass(a, b, options) {
- return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
-}
+ if (next === '<' && !utils$d.supportsLookbehinds()) {
+ throw new Error('Node.js v10 or higher is required for regex lookbehinds');
+ }
-function hasPadding(str) {
- return /^-?(0+)\d/.test(str);
-}
+ if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
+ output = `\\${value}`;
+ }
-function padZeros(value, tok, options) {
- if (!tok.isPadded) {
- return value;
- }
+ push({
+ type: 'text',
+ value,
+ output
+ });
+ continue;
+ }
- let diff = Math.abs(tok.maxLen - String(value).length);
- let relax = options.relaxZeros !== false;
+ if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
+ push({
+ type: 'qmark',
+ value,
+ output: QMARK_NO_DOT
+ });
+ continue;
+ }
- switch (diff) {
- case 0:
- return '';
+ push({
+ type: 'qmark',
+ value,
+ output: QMARK
+ });
+ continue;
+ }
+ /**
+ * Exclamation
+ */
- case 1:
- return relax ? '0?' : '0';
- case 2:
- return relax ? '0{0,2}' : '00';
+ if (value === '!') {
+ if (opts.noextglob !== true && peek() === '(') {
+ if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
+ extglobOpen('negate', value);
+ continue;
+ }
+ }
- default:
- {
- return relax ? `0{0,${diff}}` : `0{${diff}}`;
+ if (opts.nonegate !== true && state.index === 0) {
+ negate();
+ continue;
}
- }
-}
-/**
- * Cache
- */
+ }
+ /**
+ * Plus
+ */
-toRegexRange.cache = {};
+ if (value === '+') {
+ if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ extglobOpen('plus', value);
+ continue;
+ }
-toRegexRange.clearCache = () => toRegexRange.cache = {};
-/**
- * Expose `toRegexRange`
- */
+ if (prev && prev.value === '(' || opts.regex === false) {
+ push({
+ type: 'plus',
+ value,
+ output: PLUS_LITERAL
+ });
+ continue;
+ }
+ if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
+ push({
+ type: 'plus',
+ value
+ });
+ continue;
+ }
-var toRegexRange_1 = toRegexRange;
+ push({
+ type: 'plus',
+ value: PLUS_LITERAL
+ });
+ continue;
+ }
+ /**
+ * Plain text
+ */
-const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
-const transform = toNumber => {
- return value => toNumber === true ? Number(value) : String(value);
-};
+ if (value === '@') {
+ if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ push({
+ type: 'at',
+ extglob: true,
+ value,
+ output: ''
+ });
+ continue;
+ }
-const isValidValue = value => {
- return typeof value === 'number' || typeof value === 'string' && value !== '';
-};
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ }
+ /**
+ * Plain text
+ */
-const isNumber$2 = num => Number.isInteger(+num);
-const zeros = input => {
- let value = `${input}`;
- let index = -1;
- if (value[0] === '-') value = value.slice(1);
- if (value === '0') return false;
+ if (value !== '*') {
+ if (value === '$' || value === '^') {
+ value = `\\${value}`;
+ }
- while (value[++index] === '0');
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
- return index > 0;
-};
+ if (match) {
+ value += match[0];
+ state.index += match[0].length;
+ }
-const stringify$1 = (start, end, options) => {
- if (typeof start === 'string' || typeof end === 'string') {
- return true;
- }
+ push({
+ type: 'text',
+ value
+ });
+ continue;
+ }
+ /**
+ * Stars
+ */
- return options.stringify === true;
-};
-
-const pad = (input, maxLength, toNumber) => {
- if (maxLength > 0) {
- let dash = input[0] === '-' ? '-' : '';
- if (dash) input = input.slice(1);
- input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
- }
-
- if (toNumber === false) {
- return String(input);
- }
-
- return input;
-};
-const toMaxLen = (input, maxLength) => {
- let negative = input[0] === '-' ? '-' : '';
+ if (prev && (prev.type === 'globstar' || prev.star === true)) {
+ prev.type = 'star';
+ prev.star = true;
+ prev.value += value;
+ prev.output = star;
+ state.backtrack = true;
+ state.globstar = true;
+ consume(value);
+ continue;
+ }
- if (negative) {
- input = input.slice(1);
- maxLength--;
- }
+ let rest = remaining();
- while (input.length < maxLength) input = '0' + input;
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
+ extglobOpen('star', value);
+ continue;
+ }
- return negative ? '-' + input : input;
-};
+ if (prev.type === 'star') {
+ if (opts.noglobstar === true) {
+ consume(value);
+ continue;
+ }
-const toSequence = (parts, options) => {
- parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- let prefix = options.capture ? '' : '?:';
- let positives = '';
- let negatives = '';
- let result;
+ const prior = prev.prev;
+ const before = prior.prev;
+ const isStart = prior.type === 'slash' || prior.type === 'bos';
+ const afterStar = before && (before.type === 'star' || before.type === 'globstar');
- if (parts.positives.length) {
- positives = parts.positives.join('|');
- }
+ if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
+ push({
+ type: 'star',
+ value,
+ output: ''
+ });
+ continue;
+ }
- if (parts.negatives.length) {
- negatives = `-(${prefix}${parts.negatives.join('|')})`;
- }
+ const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
+ const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
- if (positives && negatives) {
- result = `${positives}|${negatives}`;
- } else {
- result = positives || negatives;
- }
+ if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
+ push({
+ type: 'star',
+ value,
+ output: ''
+ });
+ continue;
+ } // strip consecutive `/**/`
- if (options.wrap) {
- return `(${prefix}${result})`;
- }
- return result;
-};
+ while (rest.slice(0, 3) === '/**') {
+ const after = input[state.index + 4];
-const toRange = (a, b, isNumbers, options) => {
- if (isNumbers) {
- return toRegexRange_1(a, b, Object.assign({
- wrap: false
- }, options));
- }
+ if (after && after !== '/') {
+ break;
+ }
- let start = String.fromCharCode(a);
- if (a === b) return start;
- let stop = String.fromCharCode(b);
- return `[${start}-${stop}]`;
-};
+ rest = rest.slice(3);
+ consume('/**', 3);
+ }
-const toRegex = (start, end, options) => {
- if (Array.isArray(start)) {
- let wrap = options.wrap === true;
- let prefix = options.capture ? '' : '?:';
- return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
- }
+ if (prior.type === 'bos' && eos()) {
+ prev.type = 'globstar';
+ prev.value += value;
+ prev.output = globstar(opts);
+ state.output = prev.output;
+ state.globstar = true;
+ consume(value);
+ continue;
+ }
- return toRegexRange_1(start, end, options);
-};
+ if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
+ prior.output = `(?:${prior.output}`;
+ prev.type = 'globstar';
+ prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
+ prev.value += value;
+ state.globstar = true;
+ state.output += prior.output + prev.output;
+ consume(value);
+ continue;
+ }
-const rangeError = (...args) => {
- return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args));
-};
+ if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
+ const end = rest[1] !== void 0 ? '|$' : '';
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
+ prior.output = `(?:${prior.output}`;
+ prev.type = 'globstar';
+ prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
+ prev.value += value;
+ state.output += prior.output + prev.output;
+ state.globstar = true;
+ consume(value + advance());
+ push({
+ type: 'slash',
+ value: '/',
+ output: ''
+ });
+ continue;
+ }
-const invalidRange = (start, end, options) => {
- if (options.strictRanges === true) throw rangeError([start, end]);
- return [];
-};
+ if (prior.type === 'bos' && rest[0] === '/') {
+ prev.type = 'globstar';
+ prev.value += value;
+ prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
+ state.output = prev.output;
+ state.globstar = true;
+ consume(value + advance());
+ push({
+ type: 'slash',
+ value: '/',
+ output: ''
+ });
+ continue;
+ } // remove single star from output
-const invalidStep = (step, options) => {
- if (options.strictRanges === true) {
- throw new TypeError(`Expected step "${step}" to be a number`);
- }
- return [];
-};
+ state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
-const fillNumbers = (start, end, step = 1, options = {}) => {
- let a = Number(start);
- let b = Number(end);
+ prev.type = 'globstar';
+ prev.output = globstar(opts);
+ prev.value += value; // reset output with globstar
- if (!Number.isInteger(a) || !Number.isInteger(b)) {
- if (options.strictRanges === true) throw rangeError([start, end]);
- return [];
- } // fix negative zero
+ state.output += prev.output;
+ state.globstar = true;
+ consume(value);
+ continue;
+ }
+ const token = {
+ type: 'star',
+ value,
+ output: star
+ };
- if (a === 0) a = 0;
- if (b === 0) b = 0;
- let descending = a > b;
- let startString = String(start);
- let endString = String(end);
- let stepString = String(step);
- step = Math.max(Math.abs(step), 1);
- let padded = zeros(startString) || zeros(endString) || zeros(stepString);
- let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
- let toNumber = padded === false && stringify$1(start, end, options) === false;
- let format = options.transform || transform(toNumber);
+ if (opts.bash === true) {
+ token.output = '.*?';
- if (options.toRegex && step === 1) {
- return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
- }
+ if (prev.type === 'bos' || prev.type === 'slash') {
+ token.output = nodot + token.output;
+ }
- let parts = {
- negatives: [],
- positives: []
- };
+ push(token);
+ continue;
+ }
- let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
+ if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
+ token.output = value;
+ push(token);
+ continue;
+ }
- let range = [];
- let index = 0;
+ if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
+ if (prev.type === 'dot') {
+ state.output += NO_DOT_SLASH;
+ prev.output += NO_DOT_SLASH;
+ } else if (opts.dot === true) {
+ state.output += NO_DOTS_SLASH;
+ prev.output += NO_DOTS_SLASH;
+ } else {
+ state.output += nodot;
+ prev.output += nodot;
+ }
- while (descending ? a >= b : a <= b) {
- if (options.toRegex === true && step > 1) {
- push(a);
- } else {
- range.push(pad(format(a, index), maxLen, toNumber));
+ if (peek() !== '*') {
+ state.output += ONE_CHAR;
+ prev.output += ONE_CHAR;
+ }
}
- a = descending ? a - step : a + step;
- index++;
+ push(token);
}
- if (options.toRegex === true) {
- return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
- wrap: false
- }, options));
+ while (state.brackets > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
+ state.output = utils$d.escapeLast(state.output, '[');
+ decrement('brackets');
}
- return range;
-};
-
-const fillLetters = (start, end, step = 1, options = {}) => {
- if (!isNumber$2(start) && start.length > 1 || !isNumber$2(end) && end.length > 1) {
- return invalidRange(start, end, options);
+ while (state.parens > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
+ state.output = utils$d.escapeLast(state.output, '(');
+ decrement('parens');
}
- let format = options.transform || (val => String.fromCharCode(val));
+ while (state.braces > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
+ state.output = utils$d.escapeLast(state.output, '{');
+ decrement('braces');
+ }
- let a = `${start}`.charCodeAt(0);
- let b = `${end}`.charCodeAt(0);
- let descending = a > b;
- let min = Math.min(a, b);
- let max = Math.max(a, b);
+ if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
+ push({
+ type: 'maybe_slash',
+ value: '',
+ output: `${SLASH_LITERAL}?`
+ });
+ } // rebuild the output if we had to backtrack at any point
- if (options.toRegex && step === 1) {
- return toRange(min, max, false, options);
- }
- let range = [];
- let index = 0;
+ if (state.backtrack === true) {
+ state.output = '';
- while (descending ? a >= b : a <= b) {
- range.push(format(a, index));
- a = descending ? a - step : a + step;
- index++;
- }
+ for (const token of state.tokens) {
+ state.output += token.output != null ? token.output : token.value;
- if (options.toRegex === true) {
- return toRegex(range, null, {
- wrap: false,
- options
- });
+ if (token.suffix) {
+ state.output += token.suffix;
+ }
+ }
}
- return range;
+ return state;
};
+/**
+ * Fast paths for creating regular expressions for common glob patterns.
+ * This can significantly speed up processing and has very little downside
+ * impact when none of the fast paths match.
+ */
-const fill = (start, end, step, options = {}) => {
- if (end == null && isValidValue(start)) {
- return [start];
- }
-
- if (!isValidValue(start) || !isValidValue(end)) {
- return invalidRange(start, end, options);
- }
- if (typeof step === 'function') {
- return fill(start, end, 1, {
- transform: step
- });
- }
+parse$2.fastpaths = (input, options) => {
+ const opts = Object.assign({}, options);
+ const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
+ const len = input.length;
- if (isObject$1(step)) {
- return fill(start, end, 0, step);
+ if (len > max) {
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
- let opts = Object.assign({}, options);
- if (opts.capture === true) opts.wrap = true;
- step = step || opts.step || 1;
+ input = REPLACEMENTS[input] || input;
+ const win32 = utils$d.isWindows(options); // create constants based on platform, for windows or posix
- if (!isNumber$2(step)) {
- if (step != null && !isObject$1(step)) return invalidStep(step, opts);
- return fill(start, end, 1, step);
- }
+ const {
+ DOT_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOTS,
+ NO_DOTS_SLASH,
+ STAR,
+ START_ANCHOR
+ } = constants$2.globChars(win32);
+ const nodot = opts.dot ? NO_DOTS : NO_DOT;
+ const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
+ const capture = opts.capture ? '' : '?:';
+ const state = {
+ negated: false,
+ prefix: ''
+ };
+ let star = opts.bash === true ? '.*?' : STAR;
- if (isNumber$2(start) && isNumber$2(end)) {
- return fillNumbers(start, end, step, opts);
+ if (opts.capture) {
+ star = `(${star})`;
}
- return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
-};
-
-var fillRange = fill;
-
-const compile = (ast, options = {}) => {
- let walk = (node, parent = {}) => {
- let invalidBlock = utils.isInvalidBrace(parent);
- let invalidNode = node.invalid === true && options.escapeInvalid === true;
- let invalid = invalidBlock === true || invalidNode === true;
- let prefix = options.escapeInvalid === true ? '\\' : '';
- let output = '';
+ const globstar = opts => {
+ if (opts.noglobstar === true) return star;
+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
+ };
- if (node.isOpen === true) {
- return prefix + node.value;
- }
+ const create = str => {
+ switch (str) {
+ case '*':
+ return `${nodot}${ONE_CHAR}${star}`;
- if (node.isClose === true) {
- return prefix + node.value;
- }
+ case '.*':
+ return `${DOT_LITERAL}${ONE_CHAR}${star}`;
- if (node.type === 'open') {
- return invalid ? prefix + node.value : '(';
- }
+ case '*.*':
+ return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
- if (node.type === 'close') {
- return invalid ? prefix + node.value : ')';
- }
+ case '*/*':
+ return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
- if (node.type === 'comma') {
- return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
- }
+ case '**':
+ return nodot + globstar(opts);
- if (node.value) {
- return node.value;
- }
+ case '**/*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
- if (node.nodes && node.ranges > 0) {
- let args = utils.reduce(node.nodes);
- let range = fillRange(...args, Object.assign({}, options, {
- wrap: false,
- toRegex: true
- }));
+ case '**/*.*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
- if (range.length !== 0) {
- return args.length > 1 && range.length > 1 ? `(${range})` : range;
- }
- }
+ case '**/.*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
- if (node.nodes) {
- for (let child of node.nodes) {
- output += walk(child, node);
- }
+ default:
+ {
+ const match = /^(.*?)\.(\w+)$/.exec(str);
+ if (!match) return;
+ const source = create(match[1]);
+ if (!source) return;
+ return source + DOT_LITERAL + match[2];
+ }
}
-
- return output;
};
- return walk(ast);
-};
-
-var compile_1 = compile;
-
-const append = (queue = '', stash = '', enclose = false) => {
- let result = [];
- queue = [].concat(queue);
- stash = [].concat(stash);
- if (!stash.length) return queue;
-
- if (!queue.length) {
- return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
- }
+ const output = utils$d.removePrefix(input, state);
+ let source = create(output);
- for (let item of queue) {
- if (Array.isArray(item)) {
- for (let value of item) {
- result.push(append(value, stash, enclose));
- }
- } else {
- for (let ele of stash) {
- if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
- result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
- }
- }
+ if (source && opts.strictSlashes !== true) {
+ source += `${SLASH_LITERAL}?`;
}
- return utils.flatten(result);
+ return source;
};
-const expand = (ast, options = {}) => {
- let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
-
- let walk = (node, parent = {}) => {
- node.queue = [];
- let p = parent;
- let q = parent.queue;
+var parse_1 = parse$2;
- while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
- p = p.parent;
- q = p.queue;
- }
+const path$9 = require$$0__default$1["default"];
+const scan = scan_1;
+const parse$1 = parse_1;
+const utils$c = utils$f;
+const constants$1 = constants$3;
- if (node.invalid || node.dollar) {
- q.push(append(q.pop(), stringify(node, options)));
- return;
- }
+const isObject$5 = val => val && typeof val === 'object' && !Array.isArray(val);
+/**
+ * Creates a matcher function from one or more glob patterns. The
+ * returned function takes a string to match as its first argument,
+ * and returns true if the string is a match. The returned matcher
+ * function also takes a boolean as the second argument that, when true,
+ * returns an object with additional information.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch(glob[, options]);
+ *
+ * const isMatch = picomatch('*.!(*a)');
+ * console.log(isMatch('a.a')); //=> false
+ * console.log(isMatch('a.b')); //=> true
+ * ```
+ * @name picomatch
+ * @param {String|Array} `globs` One or more glob patterns.
+ * @param {Object=} `options`
+ * @return {Function=} Returns a matcher function.
+ * @api public
+ */
- if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
- q.push(append(q.pop(), ['{}']));
- return;
- }
- if (node.nodes && node.ranges > 0) {
- let args = utils.reduce(node.nodes);
+const picomatch$2 = (glob, options, returnState = false) => {
+ if (Array.isArray(glob)) {
+ const fns = glob.map(input => picomatch$2(input, options, returnState));
- if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
- throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
+ const arrayMatcher = str => {
+ for (const isMatch of fns) {
+ const state = isMatch(str);
+ if (state) return state;
}
- let range = fillRange(...args, options);
+ return false;
+ };
- if (range.length === 0) {
- range = stringify(node, options);
- }
+ return arrayMatcher;
+ }
- q.push(append(q.pop(), range));
- node.nodes = [];
- return;
- }
+ const isState = isObject$5(glob) && glob.tokens && glob.input;
- let enclose = utils.encloseBrace(node);
- let queue = node.queue;
- let block = node;
+ if (glob === '' || typeof glob !== 'string' && !isState) {
+ throw new TypeError('Expected pattern to be a non-empty string');
+ }
- while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
- block = block.parent;
- queue = block.queue;
- }
+ const opts = options || {};
+ const posix = utils$c.isWindows(options);
+ const regex = isState ? picomatch$2.compileRe(glob, options) : picomatch$2.makeRe(glob, options, false, true);
+ const state = regex.state;
+ delete regex.state;
- for (let i = 0; i < node.nodes.length; i++) {
- let child = node.nodes[i];
+ let isIgnored = () => false;
- if (child.type === 'comma' && node.type === 'brace') {
- if (i === 1) queue.push('');
- queue.push('');
- continue;
- }
+ if (opts.ignore) {
+ const ignoreOpts = Object.assign(Object.assign({}, options), {}, {
+ ignore: null,
+ onMatch: null,
+ onResult: null
+ });
+ isIgnored = picomatch$2(opts.ignore, ignoreOpts, returnState);
+ }
- if (child.type === 'close') {
- q.push(append(q.pop(), queue, enclose));
- continue;
- }
+ const matcher = (input, returnObject = false) => {
+ const {
+ isMatch,
+ match,
+ output
+ } = picomatch$2.test(input, regex, options, {
+ glob,
+ posix
+ });
+ const result = {
+ glob,
+ state,
+ regex,
+ posix,
+ input,
+ output,
+ match,
+ isMatch
+ };
- if (child.value && child.type !== 'open') {
- queue.push(append(queue.pop(), child.value));
- continue;
- }
+ if (typeof opts.onResult === 'function') {
+ opts.onResult(result);
+ }
- if (child.nodes) {
- walk(child, node);
+ if (isMatch === false) {
+ result.isMatch = false;
+ return returnObject ? result : false;
+ }
+
+ if (isIgnored(input)) {
+ if (typeof opts.onIgnore === 'function') {
+ opts.onIgnore(result);
}
+
+ result.isMatch = false;
+ return returnObject ? result : false;
}
- return queue;
+ if (typeof opts.onMatch === 'function') {
+ opts.onMatch(result);
+ }
+
+ return returnObject ? result : true;
};
- return utils.flatten(walk(ast));
+ if (returnState) {
+ matcher.state = state;
+ }
+
+ return matcher;
};
+/**
+ * Test `input` with the given `regex`. This is used by the main
+ * `picomatch()` function to test the input string.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.test(input, regex[, options]);
+ *
+ * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
+ * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
+ * ```
+ * @param {String} `input` String to test.
+ * @param {RegExp} `regex`
+ * @return {Object} Returns an object with matching info.
+ * @api public
+ */
-var expand_1 = expand;
-var constants = {
- MAX_LENGTH: 1024 * 64,
- // Digits
- CHAR_0: '0',
+picomatch$2.test = (input, regex, options, {
+ glob,
+ posix
+} = {}) => {
+ if (typeof input !== 'string') {
+ throw new TypeError('Expected input to be a string');
+ }
- /* 0 */
- CHAR_9: '9',
+ if (input === '') {
+ return {
+ isMatch: false,
+ output: ''
+ };
+ }
- /* 9 */
- // Alphabet chars.
- CHAR_UPPERCASE_A: 'A',
+ const opts = options || {};
+ const format = opts.format || (posix ? utils$c.toPosixSlashes : null);
+ let match = input === glob;
+ let output = match && format ? format(input) : input;
- /* A */
- CHAR_LOWERCASE_A: 'a',
+ if (match === false) {
+ output = format ? format(input) : input;
+ match = output === glob;
+ }
- /* a */
- CHAR_UPPERCASE_Z: 'Z',
+ if (match === false || opts.capture === true) {
+ if (opts.matchBase === true || opts.basename === true) {
+ match = picomatch$2.matchBase(input, regex, options, posix);
+ } else {
+ match = regex.exec(output);
+ }
+ }
- /* Z */
- CHAR_LOWERCASE_Z: 'z',
+ return {
+ isMatch: Boolean(match),
+ match,
+ output
+ };
+};
+/**
+ * Match the basename of a filepath.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.matchBase(input, glob[, options]);
+ * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
+ * ```
+ * @param {String} `input` String to test.
+ * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
+ * @return {Boolean}
+ * @api public
+ */
- /* z */
- CHAR_LEFT_PARENTHESES: '(',
- /* ( */
- CHAR_RIGHT_PARENTHESES: ')',
+picomatch$2.matchBase = (input, glob, options, posix = utils$c.isWindows(options)) => {
+ const regex = glob instanceof RegExp ? glob : picomatch$2.makeRe(glob, options);
+ return regex.test(path$9.basename(input));
+};
+/**
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.isMatch(string, patterns[, options]);
+ *
+ * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
+ * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
+ * ```
+ * @param {String|Array} str The string to test.
+ * @param {String|Array} patterns One or more glob patterns to use for matching.
+ * @param {Object} [options] See available [options](#options).
+ * @return {Boolean} Returns true if any patterns match `str`
+ * @api public
+ */
- /* ) */
- CHAR_ASTERISK: '*',
- /* * */
- // Non-alphabetic chars.
- CHAR_AMPERSAND: '&',
+picomatch$2.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
+/**
+ * Parse a glob pattern to create the source string for a regular
+ * expression.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * const result = picomatch.parse(pattern[, options]);
+ * ```
+ * @param {String} `pattern`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
+ * @api public
+ */
- /* & */
- CHAR_AT: '@',
- /* @ */
- CHAR_BACKSLASH: '\\',
+picomatch$2.parse = (pattern, options) => {
+ if (Array.isArray(pattern)) return pattern.map(p => picomatch$2.parse(p, options));
+ return parse$1(pattern, Object.assign(Object.assign({}, options), {}, {
+ fastpaths: false
+ }));
+};
+/**
+ * Scan a glob pattern to separate the pattern into segments.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.scan(input[, options]);
+ *
+ * const result = picomatch.scan('!./foo/*.js');
+ * console.log(result);
+ * { prefix: '!./',
+ * input: '!./foo/*.js',
+ * start: 3,
+ * base: 'foo',
+ * glob: '*.js',
+ * isBrace: false,
+ * isBracket: false,
+ * isGlob: true,
+ * isExtglob: false,
+ * isGlobstar: false,
+ * negated: true }
+ * ```
+ * @param {String} `input` Glob pattern to scan.
+ * @param {Object} `options`
+ * @return {Object} Returns an object with
+ * @api public
+ */
- /* \ */
- CHAR_BACKTICK: '`',
- /* ` */
- CHAR_CARRIAGE_RETURN: '\r',
+picomatch$2.scan = (input, options) => scan(input, options);
+/**
+ * Compile a regular expression from the `state` object returned by the
+ * [parse()](#parse) method.
+ *
+ * @param {Object} `state`
+ * @param {Object} `options`
+ * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
+ * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
+ * @return {RegExp}
+ * @api public
+ */
- /* \r */
- CHAR_CIRCUMFLEX_ACCENT: '^',
- /* ^ */
- CHAR_COLON: ':',
+picomatch$2.compileRe = (state, options, returnOutput = false, returnState = false) => {
+ if (returnOutput === true) {
+ return state.output;
+ }
- /* : */
- CHAR_COMMA: ',',
+ const opts = options || {};
+ const prepend = opts.contains ? '' : '^';
+ const append = opts.contains ? '' : '$';
+ let source = `${prepend}(?:${state.output})${append}`;
- /* , */
- CHAR_DOLLAR: '$',
+ if (state && state.negated === true) {
+ source = `^(?!${source}).*$`;
+ }
- /* . */
- CHAR_DOT: '.',
+ const regex = picomatch$2.toRegex(source, options);
- /* . */
- CHAR_DOUBLE_QUOTE: '"',
+ if (returnState === true) {
+ regex.state = state;
+ }
- /* " */
- CHAR_EQUAL: '=',
+ return regex;
+};
+/**
+ * Create a regular expression from a parsed glob pattern.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * const state = picomatch.parse('*.js');
+ * // picomatch.compileRe(state[, options]);
+ *
+ * console.log(picomatch.compileRe(state));
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
+ * ```
+ * @param {String} `state` The object returned from the `.parse` method.
+ * @param {Object} `options`
+ * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
+ * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
+ * @return {RegExp} Returns a regex created from the given pattern.
+ * @api public
+ */
- /* = */
- CHAR_EXCLAMATION_MARK: '!',
- /* ! */
- CHAR_FORM_FEED: '\f',
+picomatch$2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
+ if (!input || typeof input !== 'string') {
+ throw new TypeError('Expected a non-empty string');
+ }
- /* \f */
- CHAR_FORWARD_SLASH: '/',
+ let parsed = {
+ negated: false,
+ fastpaths: true
+ };
- /* / */
- CHAR_HASH: '#',
+ if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
+ parsed.output = parse$1.fastpaths(input, options);
+ }
- /* # */
- CHAR_HYPHEN_MINUS: '-',
+ if (!parsed.output) {
+ parsed = parse$1(input, options);
+ }
- /* - */
- CHAR_LEFT_ANGLE_BRACKET: '<',
+ return picomatch$2.compileRe(parsed, options, returnOutput, returnState);
+};
+/**
+ * Create a regular expression from the given regex source string.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.toRegex(source[, options]);
+ *
+ * const { output } = picomatch.parse('*.js');
+ * console.log(picomatch.toRegex(output));
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
+ * ```
+ * @param {String} `source` Regular expression source string.
+ * @param {Object} `options`
+ * @return {RegExp}
+ * @api public
+ */
- /* < */
- CHAR_LEFT_CURLY_BRACE: '{',
- /* { */
- CHAR_LEFT_SQUARE_BRACKET: '[',
+picomatch$2.toRegex = (source, options) => {
+ try {
+ const opts = options || {};
+ return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
+ } catch (err) {
+ if (options && options.debug === true) throw err;
+ return /$^/;
+ }
+};
+/**
+ * Picomatch constants.
+ * @return {Object}
+ */
- /* [ */
- CHAR_LINE_FEED: '\n',
- /* \n */
- CHAR_NO_BREAK_SPACE: '\u00A0',
+picomatch$2.constants = constants$1;
+/**
+ * Expose "picomatch"
+ */
- /* \u00A0 */
- CHAR_PERCENT: '%',
+var picomatch_1 = picomatch$2;
- /* % */
- CHAR_PLUS: '+',
+var picomatch$1 = picomatch_1;
- /* + */
- CHAR_QUESTION_MARK: '?',
+const util = require$$0__default$2["default"];
+const braces = braces_1;
+const picomatch = picomatch$1;
+const utils$b = utils$f;
- /* ? */
- CHAR_RIGHT_ANGLE_BRACKET: '>',
+const isEmptyString = val => val === '' || val === './';
+/**
+ * Returns an array of strings that match one or more glob patterns.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm(list, patterns[, options]);
+ *
+ * console.log(mm(['a.js', 'a.txt'], ['*.js']));
+ * //=> [ 'a.js' ]
+ * ```
+ * @param {String|Array<string>} `list` List of strings to match.
+ * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options)
+ * @return {Array} Returns an array of matches
+ * @summary false
+ * @api public
+ */
- /* > */
- CHAR_RIGHT_CURLY_BRACE: '}',
- /* } */
- CHAR_RIGHT_SQUARE_BRACKET: ']',
+const micromatch$1 = (list, patterns, options) => {
+ patterns = [].concat(patterns);
+ list = [].concat(list);
+ let omit = new Set();
+ let keep = new Set();
+ let items = new Set();
+ let negatives = 0;
- /* ] */
- CHAR_SEMICOLON: ';',
+ let onResult = state => {
+ items.add(state.output);
- /* ; */
- CHAR_SINGLE_QUOTE: '\'',
+ if (options && options.onResult) {
+ options.onResult(state);
+ }
+ };
- /* ' */
- CHAR_SPACE: ' ',
+ for (let i = 0; i < patterns.length; i++) {
+ let isMatch = picomatch(String(patterns[i]), Object.assign(Object.assign({}, options), {}, {
+ onResult
+ }), true);
+ let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
+ if (negated) negatives++;
- /* */
- CHAR_TAB: '\t',
+ for (let item of list) {
+ let matched = isMatch(item, true);
+ let match = negated ? !matched.isMatch : matched.isMatch;
+ if (!match) continue;
- /* \t */
- CHAR_UNDERSCORE: '_',
+ if (negated) {
+ omit.add(matched.output);
+ } else {
+ omit.delete(matched.output);
+ keep.add(matched.output);
+ }
+ }
+ }
- /* _ */
- CHAR_VERTICAL_LINE: '|',
+ let result = negatives === patterns.length ? [...items] : [...keep];
+ let matches = result.filter(item => !omit.has(item));
- /* | */
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
- /* \uFEFF */
+ if (options && matches.length === 0) {
+ if (options.failglob === true) {
+ throw new Error(`No matches found for "${patterns.join(', ')}"`);
+ }
-};
+ if (options.nonull === true || options.nullglob === true) {
+ return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
+ }
+ }
+ return matches;
+};
/**
- * Constants
+ * Backwards compatibility
*/
-const {
- MAX_LENGTH,
- CHAR_BACKSLASH,
-
- /* \ */
- CHAR_BACKTICK,
+micromatch$1.match = micromatch$1;
+/**
+ * Returns a matcher function from the given glob `pattern` and `options`.
+ * The returned function takes a string to match as its only argument and returns
+ * true if the string is a match.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.matcher(pattern[, options]);
+ *
+ * const isMatch = mm.matcher('*.!(*a)');
+ * console.log(isMatch('a.a')); //=> false
+ * console.log(isMatch('a.b')); //=> true
+ * ```
+ * @param {String} `pattern` Glob pattern
+ * @param {Object} `options`
+ * @return {Function} Returns a matcher function.
+ * @api public
+ */
- /* ` */
- CHAR_COMMA,
+micromatch$1.matcher = (pattern, options) => picomatch(pattern, options);
+/**
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.isMatch(string, patterns[, options]);
+ *
+ * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
+ * console.log(mm.isMatch('a.a', 'b.*')); //=> false
+ * ```
+ * @param {String} `str` The string to test.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `[options]` See available [options](#options).
+ * @return {Boolean} Returns true if any patterns match `str`
+ * @api public
+ */
- /* , */
- CHAR_DOT,
- /* . */
- CHAR_LEFT_PARENTHESES,
+micromatch$1.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
+/**
+ * Backwards compatibility
+ */
- /* ( */
- CHAR_RIGHT_PARENTHESES,
- /* ) */
- CHAR_LEFT_CURLY_BRACE,
+micromatch$1.any = micromatch$1.isMatch;
+/**
+ * Returns a list of strings that _**do not match any**_ of the given `patterns`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.not(list, patterns[, options]);
+ *
+ * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
+ * //=> ['b.b', 'c.c']
+ * ```
+ * @param {Array} `list` Array of strings to match.
+ * @param {String|Array} `patterns` One or more glob pattern to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Array} Returns an array of strings that **do not match** the given patterns.
+ * @api public
+ */
- /* { */
- CHAR_RIGHT_CURLY_BRACE,
+micromatch$1.not = (list, patterns, options = {}) => {
+ patterns = [].concat(patterns).map(String);
+ let result = new Set();
+ let items = [];
- /* } */
- CHAR_LEFT_SQUARE_BRACKET,
+ let onResult = state => {
+ if (options.onResult) options.onResult(state);
+ items.push(state.output);
+ };
- /* [ */
- CHAR_RIGHT_SQUARE_BRACKET,
+ let matches = micromatch$1(list, patterns, Object.assign(Object.assign({}, options), {}, {
+ onResult
+ }));
- /* ] */
- CHAR_DOUBLE_QUOTE,
+ for (let item of items) {
+ if (!matches.includes(item)) {
+ result.add(item);
+ }
+ }
- /* " */
- CHAR_SINGLE_QUOTE,
-
- /* ' */
- CHAR_NO_BREAK_SPACE,
- CHAR_ZERO_WIDTH_NOBREAK_SPACE
-} = constants;
+ return [...result];
+};
/**
- * parse
+ * Returns true if the given `string` contains the given pattern. Similar
+ * to [.isMatch](#isMatch) but the pattern can match any part of the string.
+ *
+ * ```js
+ * var mm = require('micromatch');
+ * // mm.contains(string, pattern[, options]);
+ *
+ * console.log(mm.contains('aa/bb/cc', '*b'));
+ * //=> true
+ * console.log(mm.contains('aa/bb/cc', '*d'));
+ * //=> false
+ * ```
+ * @param {String} `str` The string to match.
+ * @param {String|Array} `patterns` Glob pattern to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
+ * @api public
*/
-const parse = (input, options = {}) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected a string');
- }
-
- let opts = options || {};
- let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
- if (input.length > max) {
- throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
+micromatch$1.contains = (str, pattern, options) => {
+ if (typeof str !== 'string') {
+ throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
}
- let ast = {
- type: 'root',
- input,
- nodes: []
- };
- let stack = [ast];
- let block = ast;
- let prev = ast;
- let brackets = 0;
- let length = input.length;
- let index = 0;
- let depth = 0;
- let value;
- /**
- * Helpers
- */
-
- const advance = () => input[index++];
+ if (Array.isArray(pattern)) {
+ return pattern.some(p => micromatch$1.contains(str, p, options));
+ }
- const push = node => {
- if (node.type === 'text' && prev.type === 'dot') {
- prev.type = 'text';
+ if (typeof pattern === 'string') {
+ if (isEmptyString(str) || isEmptyString(pattern)) {
+ return false;
}
- if (prev && prev.type === 'text' && node.type === 'text') {
- prev.value += node.value;
- return;
+ if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
+ return true;
}
+ }
- block.nodes.push(node);
- node.parent = block;
- node.prev = prev;
- prev = node;
- return node;
- };
-
- push({
- type: 'bos'
- });
+ return micromatch$1.isMatch(str, pattern, Object.assign(Object.assign({}, options), {}, {
+ contains: true
+ }));
+};
+/**
+ * Filter the keys of the given object with the given `glob` pattern
+ * and `options`. Does not attempt to match nested keys. If you need this feature,
+ * use [glob-object][] instead.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.matchKeys(object, patterns[, options]);
+ *
+ * const obj = { aa: 'a', ab: 'b', ac: 'c' };
+ * console.log(mm.matchKeys(obj, '*b'));
+ * //=> { ab: 'b' }
+ * ```
+ * @param {Object} `object` The object with keys to filter.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Object} Returns an object with only keys that match the given patterns.
+ * @api public
+ */
- while (index < length) {
- block = stack[stack.length - 1];
- value = advance();
- /**
- * Invalid chars
- */
- if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
- continue;
- }
- /**
- * Escaped chars
- */
+micromatch$1.matchKeys = (obj, patterns, options) => {
+ if (!utils$b.isObject(obj)) {
+ throw new TypeError('Expected the first argument to be an object');
+ }
+ let keys = micromatch$1(Object.keys(obj), patterns, options);
+ let res = {};
- if (value === CHAR_BACKSLASH) {
- push({
- type: 'text',
- value: (options.keepEscaping ? value : '') + advance()
- });
- continue;
- }
- /**
- * Right square bracket (literal): ']'
- */
+ for (let key of keys) res[key] = obj[key];
+ return res;
+};
+/**
+ * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.some(list, patterns[, options]);
+ *
+ * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
+ * // true
+ * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
+ * // false
+ * ```
+ * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
+ * @api public
+ */
- if (value === CHAR_RIGHT_SQUARE_BRACKET) {
- push({
- type: 'text',
- value: '\\' + value
- });
- continue;
- }
- /**
- * Left square bracket: '['
- */
+micromatch$1.some = (list, patterns, options) => {
+ let items = [].concat(list);
- if (value === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- let next;
+ for (let pattern of [].concat(patterns)) {
+ let isMatch = picomatch(String(pattern), options);
- while (index < length && (next = advance())) {
- value += next;
+ if (items.some(item => isMatch(item))) {
+ return true;
+ }
+ }
- if (next === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- continue;
- }
+ return false;
+};
+/**
+ * Returns true if every string in the given `list` matches
+ * any of the given glob `patterns`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.every(list, patterns[, options]);
+ *
+ * console.log(mm.every('foo.js', ['foo.js']));
+ * // true
+ * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
+ * // true
+ * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
+ * // false
+ * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
+ * // false
+ * ```
+ * @param {String|Array} `list` The string or array of strings to test.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
+ * @api public
+ */
- if (next === CHAR_BACKSLASH) {
- value += advance();
- continue;
- }
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
- brackets--;
+micromatch$1.every = (list, patterns, options) => {
+ let items = [].concat(list);
- if (brackets === 0) {
- break;
- }
- }
- }
+ for (let pattern of [].concat(patterns)) {
+ let isMatch = picomatch(String(pattern), options);
- push({
- type: 'text',
- value
- });
- continue;
+ if (!items.every(item => isMatch(item))) {
+ return false;
}
- /**
- * Parentheses
- */
+ }
+ return true;
+};
+/**
+ * Returns true if **all** of the given `patterns` match
+ * the specified string.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.all(string, patterns[, options]);
+ *
+ * console.log(mm.all('foo.js', ['foo.js']));
+ * // true
+ *
+ * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
+ * // false
+ *
+ * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
+ * // true
+ *
+ * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
+ * // true
+ * ```
+ * @param {String|Array} `str` The string to test.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Boolean} Returns true if any patterns match `str`
+ * @api public
+ */
- if (value === CHAR_LEFT_PARENTHESES) {
- block = push({
- type: 'paren',
- nodes: []
- });
- stack.push(block);
- push({
- type: 'text',
- value
- });
- continue;
- }
-
- if (value === CHAR_RIGHT_PARENTHESES) {
- if (block.type !== 'paren') {
- push({
- type: 'text',
- value
- });
- continue;
- }
-
- block = stack.pop();
- push({
- type: 'text',
- value
- });
- block = stack[stack.length - 1];
- continue;
- }
- /**
- * Quotes: '|"|`
- */
+micromatch$1.all = (str, patterns, options) => {
+ if (typeof str !== 'string') {
+ throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
+ }
- if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
- let open = value;
- let next;
+ return [].concat(patterns).every(p => picomatch(p, options)(str));
+};
+/**
+ * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.capture(pattern, string[, options]);
+ *
+ * console.log(mm.capture('test/*.js', 'test/foo.js'));
+ * //=> ['foo']
+ * console.log(mm.capture('test/*.js', 'foo/bar.css'));
+ * //=> null
+ * ```
+ * @param {String} `glob` Glob pattern to use for matching.
+ * @param {String} `input` String to match
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
+ * @api public
+ */
- if (options.keepQuotes !== true) {
- value = '';
- }
- while (index < length && (next = advance())) {
- if (next === CHAR_BACKSLASH) {
- value += next + advance();
- continue;
- }
+micromatch$1.capture = (glob, input, options) => {
+ let posix = utils$b.isWindows(options);
+ let regex = picomatch.makeRe(String(glob), Object.assign(Object.assign({}, options), {}, {
+ capture: true
+ }));
+ let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input);
- if (next === open) {
- if (options.keepQuotes === true) value += next;
- break;
- }
+ if (match) {
+ return match.slice(1).map(v => v === void 0 ? '' : v);
+ }
+};
+/**
+ * Create a regular expression from the given glob `pattern`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.makeRe(pattern[, options]);
+ *
+ * console.log(mm.makeRe('*.js'));
+ * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
+ * ```
+ * @param {String} `pattern` A glob pattern to convert to regex.
+ * @param {Object} `options`
+ * @return {RegExp} Returns a regex created from the given pattern.
+ * @api public
+ */
- value += next;
- }
- push({
- type: 'text',
- value
- });
- continue;
- }
- /**
- * Left curly brace: '{'
- */
+micromatch$1.makeRe = (...args) => picomatch.makeRe(...args);
+/**
+ * Scan a glob pattern to separate the pattern into segments. Used
+ * by the [split](#split) method.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * const state = mm.scan(pattern[, options]);
+ * ```
+ * @param {String} `pattern`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with
+ * @api public
+ */
- if (value === CHAR_LEFT_CURLY_BRACE) {
- depth++;
- let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
- let brace = {
- type: 'brace',
- open: true,
- close: false,
- dollar,
- depth,
- commas: 0,
- ranges: 0,
- nodes: []
- };
- block = push(brace);
- stack.push(block);
- push({
- type: 'open',
- value
- });
- continue;
- }
- /**
- * Right curly brace: '}'
- */
+micromatch$1.scan = (...args) => picomatch.scan(...args);
+/**
+ * Parse a glob pattern to create the source string for a regular
+ * expression.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * const state = mm(pattern[, options]);
+ * ```
+ * @param {String} `glob`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with useful properties and output to be used as regex source string.
+ * @api public
+ */
- if (value === CHAR_RIGHT_CURLY_BRACE) {
- if (block.type !== 'brace') {
- push({
- type: 'text',
- value
- });
- continue;
- }
+micromatch$1.parse = (patterns, options) => {
+ let res = [];
- let type = 'close';
- block = stack.pop();
- block.close = true;
- push({
- type,
- value
- });
- depth--;
- block = stack[stack.length - 1];
- continue;
+ for (let pattern of [].concat(patterns || [])) {
+ for (let str of braces(String(pattern), options)) {
+ res.push(picomatch.parse(str, options));
}
- /**
- * Comma: ','
- */
+ }
+ return res;
+};
+/**
+ * Process the given brace `pattern`.
+ *
+ * ```js
+ * const { braces } = require('micromatch');
+ * console.log(braces('foo/{a,b,c}/bar'));
+ * //=> [ 'foo/(a|b|c)/bar' ]
+ *
+ * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
+ * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
+ * ```
+ * @param {String} `pattern` String with brace pattern to process.
+ * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
+ * @return {Array}
+ * @api public
+ */
- if (value === CHAR_COMMA && depth > 0) {
- if (block.ranges > 0) {
- block.ranges = 0;
- let open = block.nodes.shift();
- block.nodes = [open, {
- type: 'text',
- value: stringify(block)
- }];
- }
- push({
- type: 'comma',
- value
- });
- block.commas++;
- continue;
- }
- /**
- * Dot: '.'
- */
+micromatch$1.braces = (pattern, options) => {
+ if (typeof pattern !== 'string') throw new TypeError('Expected a string');
+ if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
+ return [pattern];
+ }
- if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
- let siblings = block.nodes;
+ return braces(pattern, options);
+};
+/**
+ * Expand braces
+ */
- if (depth === 0 || siblings.length === 0) {
- push({
- type: 'text',
- value
- });
- continue;
- }
- if (prev.type === 'dot') {
- block.range = [];
- prev.value += value;
- prev.type = 'range';
+micromatch$1.braceExpand = (pattern, options) => {
+ if (typeof pattern !== 'string') throw new TypeError('Expected a string');
+ return micromatch$1.braces(pattern, Object.assign(Object.assign({}, options), {}, {
+ expand: true
+ }));
+};
+/**
+ * Expose micromatch
+ */
- if (block.nodes.length !== 3 && block.nodes.length !== 5) {
- block.invalid = true;
- block.ranges = 0;
- prev.type = 'text';
- continue;
- }
- block.ranges++;
- block.args = [];
- continue;
- }
+var micromatch_1 = micromatch$1;
- if (prev.type === 'range') {
- siblings.pop();
- let before = siblings[siblings.length - 1];
- before.value += prev.value + value;
- prev = before;
- block.ranges--;
- continue;
- }
+Object.defineProperty(pattern$1, "__esModule", {
+ value: true
+});
+pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
+const path$8 = require$$0__default$1["default"];
+const globParent = globParent$1;
+const micromatch = micromatch_1;
+const GLOBSTAR = '**';
+const ESCAPE_SYMBOL = '\\';
+const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
+const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
+const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
+const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
+const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
+
+function isStaticPattern(pattern, options = {}) {
+ return !isDynamicPattern(pattern, options);
+}
- push({
- type: 'dot',
- value
- });
- continue;
- }
- /**
- * Text
- */
+pattern$1.isStaticPattern = isStaticPattern;
+function isDynamicPattern(pattern, options = {}) {
+ /**
+ * A special case with an empty string is necessary for matching patterns that start with a forward slash.
+ * An empty string cannot be a dynamic pattern.
+ * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
+ */
+ if (pattern === '') {
+ return false;
+ }
+ /**
+ * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
+ * filepath directly (without read directory).
+ */
- push({
- type: 'text',
- value
- });
- } // Mark imbalanced braces and brackets as invalid
+ if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
+ return true;
+ }
- do {
- block = stack.pop();
+ if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
+ return true;
+ }
- if (block.type !== 'root') {
- block.nodes.forEach(node => {
- if (!node.nodes) {
- if (node.type === 'open') node.isOpen = true;
- if (node.type === 'close') node.isClose = true;
- if (!node.nodes) node.type = 'text';
- node.invalid = true;
- }
- }); // get the location of the block on parent.nodes (block's siblings)
+ if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
+ return true;
+ }
- let parent = stack[stack.length - 1];
- let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
+ if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
+ return true;
+ }
- parent.nodes.splice(index, 1, ...block.nodes);
- }
- } while (stack.length > 0);
+ return false;
+}
- push({
- type: 'eos'
- });
- return ast;
-};
+pattern$1.isDynamicPattern = isDynamicPattern;
-var parse_1 = parse;
+function convertToPositivePattern(pattern) {
+ return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
+}
-/**
- * Expand the given pattern or create a regex-compatible string.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
- * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
- * ```
- * @param {String} `str`
- * @param {Object} `options`
- * @return {String}
- * @api public
- */
+pattern$1.convertToPositivePattern = convertToPositivePattern;
+function convertToNegativePattern(pattern) {
+ return '!' + pattern;
+}
-const braces = (input, options = {}) => {
- let output = [];
+pattern$1.convertToNegativePattern = convertToNegativePattern;
- if (Array.isArray(input)) {
- for (let pattern of input) {
- let result = braces.create(pattern, options);
+function isNegativePattern(pattern) {
+ return pattern.startsWith('!') && pattern[1] !== '(';
+}
- if (Array.isArray(result)) {
- output.push(...result);
- } else {
- output.push(result);
- }
- }
- } else {
- output = [].concat(braces.create(input, options));
- }
+pattern$1.isNegativePattern = isNegativePattern;
- if (options && options.expand === true && options.nodupes === true) {
- output = [...new Set(output)];
- }
+function isPositivePattern(pattern) {
+ return !isNegativePattern(pattern);
+}
- return output;
-};
+pattern$1.isPositivePattern = isPositivePattern;
+
+function getNegativePatterns(patterns) {
+ return patterns.filter(isNegativePattern);
+}
+
+pattern$1.getNegativePatterns = getNegativePatterns;
+
+function getPositivePatterns$1(patterns) {
+ return patterns.filter(isPositivePattern);
+}
+
+pattern$1.getPositivePatterns = getPositivePatterns$1;
/**
- * Parse the given `str` with the given `options`.
+ * Returns patterns that can be applied inside the current directory.
*
- * ```js
- * // braces.parse(pattern, [, options]);
- * const ast = braces.parse('a/{b,c}/d');
- * console.log(ast);
- * ```
- * @param {String} pattern Brace pattern to parse
- * @param {Object} options
- * @return {Object} Returns an AST
- * @api public
+ * @example
+ * // ['./*', '*', 'a/*']
+ * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
*/
+function getPatternsInsideCurrentDirectory(patterns) {
+ return patterns.filter(pattern => !isPatternRelatedToParentDirectory(pattern));
+}
-braces.parse = (input, options = {}) => parse_1(input, options);
+pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
/**
- * Creates a braces string from an AST, or an AST node.
+ * Returns patterns to be expanded relative to (outside) the current directory.
*
- * ```js
- * const braces = require('braces');
- * let ast = braces.parse('foo/{a,b}/bar');
- * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
- * ```
- * @param {String} `input` Brace pattern or AST.
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
+ * @example
+ * // ['../*', './../*']
+ * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
*/
+function getPatternsOutsideCurrentDirectory(patterns) {
+ return patterns.filter(isPatternRelatedToParentDirectory);
+}
-braces.stringify = (input, options = {}) => {
- if (typeof input === 'string') {
- return stringify(braces.parse(input, options), options);
- }
+pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
- return stringify(input, options);
-};
-/**
- * Compiles a brace pattern into a regex-compatible, optimized string.
- * This method is called by the main [braces](#braces) function by default.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.compile('a/{b,c}/d'));
- * //=> ['a/(b|c)/d']
- * ```
- * @param {String} `input` Brace pattern or AST.
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
+function isPatternRelatedToParentDirectory(pattern) {
+ return pattern.startsWith('..') || pattern.startsWith('./..');
+}
+pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
-braces.compile = (input, options = {}) => {
- if (typeof input === 'string') {
- input = braces.parse(input, options);
+function getBaseDirectory(pattern) {
+ return globParent(pattern, {
+ flipBackslashes: false
+ });
+}
+
+pattern$1.getBaseDirectory = getBaseDirectory;
+
+function hasGlobStar(pattern) {
+ return pattern.includes(GLOBSTAR);
+}
+
+pattern$1.hasGlobStar = hasGlobStar;
+
+function endsWithSlashGlobStar(pattern) {
+ return pattern.endsWith('/' + GLOBSTAR);
+}
+
+pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
+
+function isAffectDepthOfReadingPattern(pattern) {
+ const basename = path$8.basename(pattern);
+ return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
+}
+
+pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
+
+function expandPatternsWithBraceExpansion(patterns) {
+ return patterns.reduce((collection, pattern) => {
+ return collection.concat(expandBraceExpansion(pattern));
+ }, []);
+}
+
+pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
+
+function expandBraceExpansion(pattern) {
+ return micromatch.braces(pattern, {
+ expand: true,
+ nodupes: true
+ });
+}
+
+pattern$1.expandBraceExpansion = expandBraceExpansion;
+
+function getPatternParts(pattern, options) {
+ let {
+ parts
+ } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), {
+ parts: true
+ }));
+ /**
+ * The scan method returns an empty array in some cases.
+ * See micromatch/picomatch#58 for more details.
+ */
+
+ if (parts.length === 0) {
+ parts = [pattern];
}
+ /**
+ * The scan method does not return an empty part for the pattern with a forward slash.
+ * This is another part of micromatch/picomatch#58.
+ */
- return compile_1(input, options);
-};
-/**
- * Expands a brace pattern into an array. This method is called by the
- * main [braces](#braces) function when `options.expand` is true. Before
- * using this method it's recommended that you read the [performance notes](#performance))
- * and advantages of using [.compile](#compile) instead.
+
+ if (parts[0].startsWith('/')) {
+ parts[0] = parts[0].slice(1);
+ parts.unshift('');
+ }
+
+ return parts;
+}
+
+pattern$1.getPatternParts = getPatternParts;
+
+function makeRe(pattern, options) {
+ return micromatch.makeRe(pattern, options);
+}
+
+pattern$1.makeRe = makeRe;
+
+function convertPatternsToRe(patterns, options) {
+ return patterns.map(pattern => makeRe(pattern, options));
+}
+
+pattern$1.convertPatternsToRe = convertPatternsToRe;
+
+function matchAny(entry, patternsRe) {
+ return patternsRe.some(patternRe => patternRe.test(entry));
+}
+
+pattern$1.matchAny = matchAny;
+
+var stream$4 = {};
+
+/*
+ * merge2
+ * https://github.com/teambition/merge2
*
- * ```js
- * const braces = require('braces');
- * console.log(braces.expand('a/{b,c}/d'));
- * //=> ['a/b/d', 'a/c/d'];
- * ```
- * @param {String} `pattern` Brace pattern
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
+ * Copyright (c) 2014-2020 Teambition
+ * Licensed under the MIT license.
*/
-braces.expand = (input, options = {}) => {
- if (typeof input === 'string') {
- input = braces.parse(input, options);
- }
+const Stream = require$$0__default$3["default"];
+const PassThrough = Stream.PassThrough;
+const slice = Array.prototype.slice;
+var merge2_1 = merge2$1;
- let result = expand_1(input, options); // filter out empty strings if specified
+function merge2$1() {
+ const streamsQueue = [];
+ const args = slice.call(arguments);
+ let merging = false;
+ let options = args[args.length - 1];
- if (options.noempty === true) {
- result = result.filter(Boolean);
- } // filter out duplicates if specified
+ if (options && !Array.isArray(options) && options.pipe == null) {
+ args.pop();
+ } else {
+ options = {};
+ }
+ const doEnd = options.end !== false;
+ const doPipeError = options.pipeError === true;
- if (options.nodupes === true) {
- result = [...new Set(result)];
+ if (options.objectMode == null) {
+ options.objectMode = true;
}
- return result;
-};
-/**
- * Processes a brace pattern and returns either an expanded array
- * (if `options.expand` is true), a highly optimized regex-compatible string.
- * This method is called by the main [braces](#braces) function.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
- * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
- * ```
- * @param {String} `pattern` Brace pattern
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
+ if (options.highWaterMark == null) {
+ options.highWaterMark = 64 * 1024;
+ }
+
+ const mergedStream = PassThrough(options);
+ function addStream() {
+ for (let i = 0, len = arguments.length; i < len; i++) {
+ streamsQueue.push(pauseStreams(arguments[i], options));
+ }
-braces.create = (input, options = {}) => {
- if (input === '' || input.length < 3) {
- return [input];
+ mergeStream();
+ return this;
}
- return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
-};
-/**
- * Expose "braces"
- */
+ function mergeStream() {
+ if (merging) {
+ return;
+ }
+ merging = true;
+ let streams = streamsQueue.shift();
-var braces_1 = braces;
+ if (!streams) {
+ process.nextTick(endStream);
+ return;
+ }
-const WIN_SLASH = '\\\\/';
-const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
-/**
- * Posix glob regex
- */
+ if (!Array.isArray(streams)) {
+ streams = [streams];
+ }
-const DOT_LITERAL = '\\.';
-const PLUS_LITERAL = '\\+';
-const QMARK_LITERAL = '\\?';
-const SLASH_LITERAL = '\\/';
-const ONE_CHAR = '(?=.)';
-const QMARK = '[^/]';
-const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
-const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
-const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
-const NO_DOT = `(?!${DOT_LITERAL})`;
-const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
-const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
-const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
-const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
-const STAR = `${QMARK}*?`;
-const POSIX_CHARS = {
- DOT_LITERAL,
- PLUS_LITERAL,
- QMARK_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- QMARK,
- END_ANCHOR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR
-};
-/**
- * Windows glob regex
- */
+ let pipesCount = streams.length + 1;
-const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, {
- SLASH_LITERAL: `[${WIN_SLASH}]`,
- QMARK: WIN_NO_SLASH,
- STAR: `${WIN_NO_SLASH}*?`,
- DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
- NO_DOT: `(?!${DOT_LITERAL})`,
- NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
- NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
- START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
- END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
-});
-/**
- * POSIX Bracket Regex
- */
+ function next() {
+ if (--pipesCount > 0) {
+ return;
+ }
-const POSIX_REGEX_SOURCE = {
- alnum: 'a-zA-Z0-9',
- alpha: 'a-zA-Z',
- ascii: '\\x00-\\x7F',
- blank: ' \\t',
- cntrl: '\\x00-\\x1F\\x7F',
- digit: '0-9',
- graph: '\\x21-\\x7E',
- lower: 'a-z',
- print: '\\x20-\\x7E ',
- punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
- space: ' \\t\\r\\n\\v\\f',
- upper: 'A-Z',
- word: 'A-Za-z0-9_',
- xdigit: 'A-Fa-f0-9'
-};
-var constants$1 = {
- MAX_LENGTH: 1024 * 64,
- POSIX_REGEX_SOURCE,
- // regular expressions
- REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
- REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
- REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
- REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
- REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
- REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
- // Replace globs with equivalent patterns to reduce parsing time.
- REPLACEMENTS: {
- '***': '*',
- '**/**': '**',
- '**/**/**': '**'
- },
- // Digits
- CHAR_0: 48,
+ merging = false;
+ mergeStream();
+ }
- /* 0 */
- CHAR_9: 57,
+ function pipe(stream) {
+ function onend() {
+ stream.removeListener('merge2UnpipeEnd', onend);
+ stream.removeListener('end', onend);
- /* 9 */
- // Alphabet chars.
- CHAR_UPPERCASE_A: 65,
+ if (doPipeError) {
+ stream.removeListener('error', onerror);
+ }
- /* A */
- CHAR_LOWERCASE_A: 97,
+ next();
+ }
- /* a */
- CHAR_UPPERCASE_Z: 90,
+ function onerror(err) {
+ mergedStream.emit('error', err);
+ } // skip ended stream
- /* Z */
- CHAR_LOWERCASE_Z: 122,
- /* z */
- CHAR_LEFT_PARENTHESES: 40,
+ if (stream._readableState.endEmitted) {
+ return next();
+ }
- /* ( */
- CHAR_RIGHT_PARENTHESES: 41,
+ stream.on('merge2UnpipeEnd', onend);
+ stream.on('end', onend);
- /* ) */
- CHAR_ASTERISK: 42,
+ if (doPipeError) {
+ stream.on('error', onerror);
+ }
- /* * */
- // Non-alphabetic chars.
- CHAR_AMPERSAND: 38,
+ stream.pipe(mergedStream, {
+ end: false
+ }); // compatible for old stream
- /* & */
- CHAR_AT: 64,
+ stream.resume();
+ }
- /* @ */
- CHAR_BACKWARD_SLASH: 92,
+ for (let i = 0; i < streams.length; i++) {
+ pipe(streams[i]);
+ }
- /* \ */
- CHAR_CARRIAGE_RETURN: 13,
+ next();
+ }
- /* \r */
- CHAR_CIRCUMFLEX_ACCENT: 94,
+ function endStream() {
+ merging = false; // emit 'queueDrain' when all streams merged.
- /* ^ */
- CHAR_COLON: 58,
+ mergedStream.emit('queueDrain');
- /* : */
- CHAR_COMMA: 44,
+ if (doEnd) {
+ mergedStream.end();
+ }
+ }
- /* , */
- CHAR_DOT: 46,
+ mergedStream.setMaxListeners(0);
+ mergedStream.add = addStream;
+ mergedStream.on('unpipe', function (stream) {
+ stream.emit('merge2UnpipeEnd');
+ });
- /* . */
- CHAR_DOUBLE_QUOTE: 34,
+ if (args.length) {
+ addStream.apply(null, args);
+ }
- /* " */
- CHAR_EQUAL: 61,
+ return mergedStream;
+} // check and pause streams for pipe.
- /* = */
- CHAR_EXCLAMATION_MARK: 33,
- /* ! */
- CHAR_FORM_FEED: 12,
+function pauseStreams(streams, options) {
+ if (!Array.isArray(streams)) {
+ // Backwards-compat with old-style streams
+ if (!streams._readableState && streams.pipe) {
+ streams = streams.pipe(PassThrough(options));
+ }
- /* \f */
- CHAR_FORWARD_SLASH: 47,
+ if (!streams._readableState || !streams.pause || !streams.pipe) {
+ throw new Error('Only readable stream can be merged.');
+ }
- /* / */
- CHAR_GRAVE_ACCENT: 96,
+ streams.pause();
+ } else {
+ for (let i = 0, len = streams.length; i < len; i++) {
+ streams[i] = pauseStreams(streams[i], options);
+ }
+ }
- /* ` */
- CHAR_HASH: 35,
+ return streams;
+}
- /* # */
- CHAR_HYPHEN_MINUS: 45,
+Object.defineProperty(stream$4, "__esModule", {
+ value: true
+});
+stream$4.merge = void 0;
+const merge2 = merge2_1;
- /* - */
- CHAR_LEFT_ANGLE_BRACKET: 60,
+function merge$2(streams) {
+ const mergedStream = merge2(streams);
+ streams.forEach(stream => {
+ stream.once('error', error => mergedStream.emit('error', error));
+ });
+ mergedStream.once('close', () => propagateCloseEventToSources(streams));
+ mergedStream.once('end', () => propagateCloseEventToSources(streams));
+ return mergedStream;
+}
- /* < */
- CHAR_LEFT_CURLY_BRACE: 123,
+stream$4.merge = merge$2;
- /* { */
- CHAR_LEFT_SQUARE_BRACKET: 91,
+function propagateCloseEventToSources(streams) {
+ streams.forEach(stream => stream.emit('close'));
+}
- /* [ */
- CHAR_LINE_FEED: 10,
+var string$1 = {};
- /* \n */
- CHAR_NO_BREAK_SPACE: 160,
+Object.defineProperty(string$1, "__esModule", {
+ value: true
+});
+string$1.isEmpty = string$1.isString = void 0;
- /* \u00A0 */
- CHAR_PERCENT: 37,
+function isString(input) {
+ return typeof input === 'string';
+}
- /* % */
- CHAR_PLUS: 43,
+string$1.isString = isString;
- /* + */
- CHAR_QUESTION_MARK: 63,
+function isEmpty(input) {
+ return input === '';
+}
- /* ? */
- CHAR_RIGHT_ANGLE_BRACKET: 62,
+string$1.isEmpty = isEmpty;
- /* > */
- CHAR_RIGHT_CURLY_BRACE: 125,
+Object.defineProperty(utils$k, "__esModule", {
+ value: true
+});
+utils$k.string = utils$k.stream = utils$k.pattern = utils$k.path = utils$k.fs = utils$k.errno = utils$k.array = void 0;
+const array$2 = array$3;
+utils$k.array = array$2;
+const errno = errno$1;
+utils$k.errno = errno;
+const fs$8 = fs$9;
+utils$k.fs = fs$8;
+const path$7 = path$c;
+utils$k.path = path$7;
+const pattern = pattern$1;
+utils$k.pattern = pattern;
+const stream$3 = stream$4;
+utils$k.stream = stream$3;
+const string = string$1;
+utils$k.string = string;
+
+Object.defineProperty(tasks, "__esModule", {
+ value: true
+});
+tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
+const utils$a = utils$k;
+
+function generate(patterns, settings) {
+ const positivePatterns = getPositivePatterns(patterns);
+ const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
+ const staticPatterns = positivePatterns.filter(pattern => utils$a.pattern.isStaticPattern(pattern, settings));
+ const dynamicPatterns = positivePatterns.filter(pattern => utils$a.pattern.isDynamicPattern(pattern, settings));
+ const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
+ /* dynamic */
+ false);
+ const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
+ /* dynamic */
+ true);
+ return staticTasks.concat(dynamicTasks);
+}
- /* } */
- CHAR_RIGHT_SQUARE_BRACKET: 93,
+tasks.generate = generate;
+/**
+ * Returns tasks grouped by basic pattern directories.
+ *
+ * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
+ * This is necessary because directory traversal starts at the base directory and goes deeper.
+ */
- /* ] */
- CHAR_SEMICOLON: 59,
+function convertPatternsToTasks(positive, negative, dynamic) {
+ const tasks = [];
+ const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive);
+ const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive);
+ const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
+ const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
+ tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
+ /*
+ * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
+ * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
+ */
- /* ; */
- CHAR_SINGLE_QUOTE: 39,
+ if ('.' in insideCurrentDirectoryGroup) {
+ tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
+ } else {
+ tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
+ }
- /* ' */
- CHAR_SPACE: 32,
+ return tasks;
+}
- /* */
- CHAR_TAB: 9,
+tasks.convertPatternsToTasks = convertPatternsToTasks;
- /* \t */
- CHAR_UNDERSCORE: 95,
+function getPositivePatterns(patterns) {
+ return utils$a.pattern.getPositivePatterns(patterns);
+}
- /* _ */
- CHAR_VERTICAL_LINE: 124,
+tasks.getPositivePatterns = getPositivePatterns;
- /* | */
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
+function getNegativePatternsAsPositive(patterns, ignore) {
+ const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore);
+ const positive = negative.map(utils$a.pattern.convertToPositivePattern);
+ return positive;
+}
- /* \uFEFF */
- SEP: path__default['default'].sep,
+tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
- /**
- * Create EXTGLOB_CHARS
- */
- extglobChars(chars) {
- return {
- '!': {
- type: 'negate',
- open: '(?:(?!(?:',
- close: `))${chars.STAR})`
- },
- '?': {
- type: 'qmark',
- open: '(?:',
- close: ')?'
- },
- '+': {
- type: 'plus',
- open: '(?:',
- close: ')+'
- },
- '*': {
- type: 'star',
- open: '(?:',
- close: ')*'
- },
- '@': {
- type: 'at',
- open: '(?:',
- close: ')'
- }
- };
- },
+function groupPatternsByBaseDirectory(patterns) {
+ const group = {};
+ return patterns.reduce((collection, pattern) => {
+ const base = utils$a.pattern.getBaseDirectory(pattern);
- /**
- * Create GLOB_CHARS
- */
- globChars(win32) {
- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
- }
+ if (base in collection) {
+ collection[base].push(pattern);
+ } else {
+ collection[base] = [pattern];
+ }
-};
+ return collection;
+ }, group);
+}
-var utils$1 = createCommonjsModule(function (module, exports) {
+tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
- const win32 = process.platform === 'win32';
- const {
- REGEX_BACKSLASH,
- REGEX_REMOVE_BACKSLASH,
- REGEX_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_GLOBAL
- } = constants$1;
+function convertPatternGroupsToTasks(positive, negative, dynamic) {
+ return Object.keys(positive).map(base => {
+ return convertPatternGroupToTask(base, positive[base], negative, dynamic);
+ });
+}
- exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
+tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
- exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
+function convertPatternGroupToTask(base, positive, negative, dynamic) {
+ return {
+ dynamic,
+ positive,
+ negative,
+ base,
+ patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern))
+ };
+}
- exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
+tasks.convertPatternGroupToTask = convertPatternGroupToTask;
- exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
+var async$6 = {};
- exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
+var stream$2 = {};
- exports.removeBackslashes = str => {
- return str.replace(REGEX_REMOVE_BACKSLASH, match => {
- return match === '\\' ? '' : match;
- });
- };
+var out$3 = {};
- exports.supportsLookbehinds = () => {
- const segs = process.version.slice(1).split('.').map(Number);
+var async$5 = {};
- if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
- return true;
- }
+Object.defineProperty(async$5, "__esModule", {
+ value: true
+});
+async$5.read = void 0;
- return false;
- };
+function read$3(path, settings, callback) {
+ settings.fs.lstat(path, (lstatError, lstat) => {
+ if (lstatError !== null) {
+ callFailureCallback$2(callback, lstatError);
+ return;
+ }
- exports.isWindows = options => {
- if (options && typeof options.windows === 'boolean') {
- return options.windows;
+ if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
+ callSuccessCallback$2(callback, lstat);
+ return;
}
- return win32 === true || path__default['default'].sep === '\\';
- };
+ settings.fs.stat(path, (statError, stat) => {
+ if (statError !== null) {
+ if (settings.throwErrorOnBrokenSymbolicLink) {
+ callFailureCallback$2(callback, statError);
+ return;
+ }
- exports.escapeLast = (input, char, lastIdx) => {
- const idx = input.lastIndexOf(char, lastIdx);
- if (idx === -1) return input;
- if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
- return `${input.slice(0, idx)}\\${input.slice(idx)}`;
- };
+ callSuccessCallback$2(callback, lstat);
+ return;
+ }
- exports.removePrefix = (input, state = {}) => {
- let output = input;
+ if (settings.markSymbolicLink) {
+ stat.isSymbolicLink = () => true;
+ }
- if (output.startsWith('./')) {
- output = output.slice(2);
- state.prefix = './';
- }
+ callSuccessCallback$2(callback, stat);
+ });
+ });
+}
- return output;
- };
+async$5.read = read$3;
- exports.wrapOutput = (input, state = {}, options = {}) => {
- const prepend = options.contains ? '' : '^';
- const append = options.contains ? '' : '$';
- let output = `${prepend}(?:${input})${append}`;
+function callFailureCallback$2(callback, error) {
+ callback(error);
+}
- if (state.negated === true) {
- output = `(?:^(?!${output}).*$)`;
- }
+function callSuccessCallback$2(callback, result) {
+ callback(null, result);
+}
- return output;
- };
-});
+var sync$7 = {};
-const {
- CHAR_ASTERISK,
+Object.defineProperty(sync$7, "__esModule", {
+ value: true
+});
+sync$7.read = void 0;
- /* * */
- CHAR_AT,
+function read$2(path, settings) {
+ const lstat = settings.fs.lstatSync(path);
- /* @ */
- CHAR_BACKWARD_SLASH,
+ if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
+ return lstat;
+ }
- /* \ */
- CHAR_COMMA: CHAR_COMMA$1,
+ try {
+ const stat = settings.fs.statSync(path);
- /* , */
- CHAR_DOT: CHAR_DOT$1,
+ if (settings.markSymbolicLink) {
+ stat.isSymbolicLink = () => true;
+ }
- /* . */
- CHAR_EXCLAMATION_MARK,
+ return stat;
+ } catch (error) {
+ if (!settings.throwErrorOnBrokenSymbolicLink) {
+ return lstat;
+ }
- /* ! */
- CHAR_FORWARD_SLASH,
+ throw error;
+ }
+}
- /* / */
- CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
+sync$7.read = read$2;
- /* { */
- CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
+var settings$3 = {};
- /* ( */
- CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
+var fs$7 = {};
- /* [ */
- CHAR_PLUS,
+(function (exports) {
- /* + */
- CHAR_QUESTION_MARK,
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
+ const fs = require$$0__default$4["default"];
+ exports.FILE_SYSTEM_ADAPTER = {
+ lstat: fs.lstat,
+ stat: fs.stat,
+ lstatSync: fs.lstatSync,
+ statSync: fs.statSync
+ };
- /* ? */
- CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
+ function createFileSystemAdapter(fsMethods) {
+ if (fsMethods === undefined) {
+ return exports.FILE_SYSTEM_ADAPTER;
+ }
- /* } */
- CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
+ return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
+ }
- /* ) */
- CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
- /* ] */
+ exports.createFileSystemAdapter = createFileSystemAdapter;
+})(fs$7);
-} = constants$1;
+Object.defineProperty(settings$3, "__esModule", {
+ value: true
+});
+const fs$6 = fs$7;
-const isPathSeparator = code => {
- return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
-};
+class Settings$2 {
+ constructor(_options = {}) {
+ this._options = _options;
+ this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
+ this.fs = fs$6.createFileSystemAdapter(this._options.fs);
+ this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
+ this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
+ }
-const depth = token => {
- if (token.isPrefix !== true) {
- token.depth = token.isGlobstar ? Infinity : 1;
+ _getValue(option, value) {
+ return option !== null && option !== void 0 ? option : value;
}
-};
-/**
- * Quickly scans a glob pattern and returns an object with a handful of
- * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
- * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
- *
- * ```js
- * const pm = require('picomatch');
- * console.log(pm.scan('foo/bar/*.js'));
- * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
- * ```
- * @param {String} `str`
- * @param {Object} `options`
- * @return {Object} Returns an object with tokens and regex source string.
- * @api public
- */
+}
-const scan = (input, options) => {
- const opts = options || {};
- const length = input.length - 1;
- const scanToEnd = opts.parts === true || opts.scanToEnd === true;
- const slashes = [];
- const tokens = [];
- const parts = [];
- let str = input;
- let index = -1;
- let start = 0;
- let lastIndex = 0;
- let isBrace = false;
- let isBracket = false;
- let isGlob = false;
- let isExtglob = false;
- let isGlobstar = false;
- let braceEscaped = false;
- let backslashes = false;
- let negated = false;
- let finished = false;
- let braces = 0;
- let prev;
- let code;
- let token = {
- value: '',
- depth: 0,
- isGlob: false
- };
+settings$3.default = Settings$2;
- const eos = () => index >= length;
+Object.defineProperty(out$3, "__esModule", {
+ value: true
+});
+out$3.statSync = out$3.stat = out$3.Settings = void 0;
+const async$4 = async$5;
+const sync$6 = sync$7;
+const settings_1$3 = settings$3;
+out$3.Settings = settings_1$3.default;
+
+function stat(path, optionsOrSettingsOrCallback, callback) {
+ if (typeof optionsOrSettingsOrCallback === 'function') {
+ async$4.read(path, getSettings$2(), optionsOrSettingsOrCallback);
+ return;
+ }
- const peek = () => str.charCodeAt(index + 1);
+ async$4.read(path, getSettings$2(optionsOrSettingsOrCallback), callback);
+}
- const advance = () => {
- prev = code;
- return str.charCodeAt(++index);
- };
+out$3.stat = stat;
- while (index < length) {
- code = advance();
- let next;
+function statSync(path, optionsOrSettings) {
+ const settings = getSettings$2(optionsOrSettings);
+ return sync$6.read(path, settings);
+}
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
+out$3.statSync = statSync;
- if (code === CHAR_LEFT_CURLY_BRACE$1) {
- braceEscaped = true;
- }
+function getSettings$2(settingsOrOptions = {}) {
+ if (settingsOrOptions instanceof settings_1$3.default) {
+ return settingsOrOptions;
+ }
- continue;
- }
+ return new settings_1$3.default(settingsOrOptions);
+}
- if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
- braces++;
+var out$2 = {};
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
+var async$3 = {};
- if (code === CHAR_LEFT_CURLY_BRACE$1) {
- braces++;
- continue;
- }
+var async$2 = {};
- if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
+var out$1 = {};
- if (scanToEnd === true) {
- continue;
- }
+var async$1 = {};
- break;
- }
+/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
+let promise;
+var queueMicrotask_1 = typeof queueMicrotask === 'function' ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global) // reuse resolved promise, and allocate it lazily
+: cb => (promise || (promise = Promise.resolve())).then(cb).catch(err => setTimeout(() => {
+ throw err;
+}, 0));
- if (braceEscaped !== true && code === CHAR_COMMA$1) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
+/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
+var runParallel_1 = runParallel;
+const queueMicrotask$1 = queueMicrotask_1;
- if (scanToEnd === true) {
- continue;
- }
+function runParallel(tasks, cb) {
+ let results, pending, keys;
+ let isSync = true;
- break;
- }
+ if (Array.isArray(tasks)) {
+ results = [];
+ pending = tasks.length;
+ } else {
+ keys = Object.keys(tasks);
+ results = {};
+ pending = keys.length;
+ }
- if (code === CHAR_RIGHT_CURLY_BRACE$1) {
- braces--;
+ function done(err) {
+ function end() {
+ if (cb) cb(err, results);
+ cb = null;
+ }
- if (braces === 0) {
- braceEscaped = false;
- isBrace = token.isBrace = true;
- finished = true;
- break;
- }
- }
- }
+ if (isSync) queueMicrotask$1(end);else end();
+ }
- if (scanToEnd === true) {
- continue;
- }
+ function each(i, err, result) {
+ results[i] = result;
- break;
+ if (--pending === 0 || err) {
+ done(err);
}
+ }
- if (code === CHAR_FORWARD_SLASH) {
- slashes.push(index);
- tokens.push(token);
- token = {
- value: '',
- depth: 0,
- isGlob: false
- };
- if (finished === true) continue;
+ if (!pending) {
+ // empty
+ done(null);
+ } else if (keys) {
+ // object
+ keys.forEach(function (key) {
+ tasks[key](function (err, result) {
+ each(key, err, result);
+ });
+ });
+ } else {
+ // array
+ tasks.forEach(function (task, i) {
+ task(function (err, result) {
+ each(i, err, result);
+ });
+ });
+ }
- if (prev === CHAR_DOT$1 && index === start + 1) {
- start += 2;
- continue;
- }
+ isSync = false;
+}
- lastIndex = index + 1;
- continue;
- }
+var constants = {};
- if (opts.noext !== true) {
- const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
+Object.defineProperty(constants, "__esModule", {
+ value: true
+});
+constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
+const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
- if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
- isGlob = token.isGlob = true;
- isExtglob = token.isExtglob = true;
- finished = true;
+if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
+ throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
+}
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
+const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
+const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
+const SUPPORTED_MAJOR_VERSION = 10;
+const SUPPORTED_MINOR_VERSION = 10;
+const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
+const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
+/**
+ * IS `true` for Node.js 10.10 and greater.
+ */
- if (code === CHAR_RIGHT_PARENTHESES$1) {
- isGlob = token.isGlob = true;
- finished = true;
- break;
- }
- }
+constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
- continue;
- }
+var utils$9 = {};
- break;
- }
- }
+var fs$5 = {};
- if (code === CHAR_ASTERISK) {
- if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
- isGlob = token.isGlob = true;
- finished = true;
+Object.defineProperty(fs$5, "__esModule", {
+ value: true
+});
+fs$5.createDirentFromStats = void 0;
- if (scanToEnd === true) {
- continue;
- }
+class DirentFromStats {
+ constructor(name, stats) {
+ this.name = name;
+ this.isBlockDevice = stats.isBlockDevice.bind(stats);
+ this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
+ this.isDirectory = stats.isDirectory.bind(stats);
+ this.isFIFO = stats.isFIFO.bind(stats);
+ this.isFile = stats.isFile.bind(stats);
+ this.isSocket = stats.isSocket.bind(stats);
+ this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
+ }
- break;
- }
+}
- if (code === CHAR_QUESTION_MARK) {
- isGlob = token.isGlob = true;
- finished = true;
+function createDirentFromStats(name, stats) {
+ return new DirentFromStats(name, stats);
+}
- if (scanToEnd === true) {
- continue;
- }
+fs$5.createDirentFromStats = createDirentFromStats;
- break;
- }
+Object.defineProperty(utils$9, "__esModule", {
+ value: true
+});
+utils$9.fs = void 0;
+const fs$4 = fs$5;
+utils$9.fs = fs$4;
- if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
- while (eos() !== true && (next = advance())) {
- if (next === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
+var common$6 = {};
- if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
- isBracket = token.isBracket = true;
- isGlob = token.isGlob = true;
- finished = true;
+Object.defineProperty(common$6, "__esModule", {
+ value: true
+});
+common$6.joinPathSegments = void 0;
- if (scanToEnd === true) {
- continue;
- }
+function joinPathSegments$1(a, b, separator) {
+ /**
+ * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
+ */
+ if (a.endsWith(separator)) {
+ return a + b;
+ }
- break;
- }
- }
+ return a + separator + b;
+}
+
+common$6.joinPathSegments = joinPathSegments$1;
+
+Object.defineProperty(async$1, "__esModule", {
+ value: true
+});
+async$1.readdir = async$1.readdirWithFileTypes = async$1.read = void 0;
+const fsStat$5 = out$3;
+const rpl = runParallel_1;
+const constants_1$1 = constants;
+const utils$8 = utils$9;
+const common$5 = common$6;
+
+function read$1(directory, settings, callback) {
+ if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
+ readdirWithFileTypes$1(directory, settings, callback);
+ return;
+ }
+
+ readdir$1(directory, settings, callback);
+}
+
+async$1.read = read$1;
+
+function readdirWithFileTypes$1(directory, settings, callback) {
+ settings.fs.readdir(directory, {
+ withFileTypes: true
+ }, (readdirError, dirents) => {
+ if (readdirError !== null) {
+ callFailureCallback$1(callback, readdirError);
+ return;
}
- if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
- negated = token.negated = true;
- start++;
- continue;
+ const entries = dirents.map(dirent => ({
+ dirent,
+ name: dirent.name,
+ path: common$5.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
+ }));
+
+ if (!settings.followSymbolicLinks) {
+ callSuccessCallback$1(callback, entries);
+ return;
}
- if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
- isGlob = token.isGlob = true;
+ const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
+ rpl(tasks, (rplError, rplEntries) => {
+ if (rplError !== null) {
+ callFailureCallback$1(callback, rplError);
+ return;
+ }
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_LEFT_PARENTHESES$1) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
+ callSuccessCallback$1(callback, rplEntries);
+ });
+ });
+}
- if (code === CHAR_RIGHT_PARENTHESES$1) {
- finished = true;
- break;
- }
+async$1.readdirWithFileTypes = readdirWithFileTypes$1;
+
+function makeRplTaskEntry(entry, settings) {
+ return done => {
+ if (!entry.dirent.isSymbolicLink()) {
+ done(null, entry);
+ return;
+ }
+
+ settings.fs.stat(entry.path, (statError, stats) => {
+ if (statError !== null) {
+ if (settings.throwErrorOnBrokenSymbolicLink) {
+ done(statError);
+ return;
}
- continue;
+ done(null, entry);
+ return;
}
- break;
+ entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats);
+ done(null, entry);
+ });
+ };
+}
+
+function readdir$1(directory, settings, callback) {
+ settings.fs.readdir(directory, (readdirError, names) => {
+ if (readdirError !== null) {
+ callFailureCallback$1(callback, readdirError);
+ return;
}
- if (isGlob === true) {
- finished = true;
+ const tasks = names.map(name => {
+ const path = common$5.joinPathSegments(directory, name, settings.pathSegmentSeparator);
+ return done => {
+ fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => {
+ if (error !== null) {
+ done(error);
+ return;
+ }
- if (scanToEnd === true) {
- continue;
+ const entry = {
+ name,
+ path,
+ dirent: utils$8.fs.createDirentFromStats(name, stats)
+ };
+
+ if (settings.stats) {
+ entry.stats = stats;
+ }
+
+ done(null, entry);
+ });
+ };
+ });
+ rpl(tasks, (rplError, entries) => {
+ if (rplError !== null) {
+ callFailureCallback$1(callback, rplError);
+ return;
}
- break;
- }
- }
+ callSuccessCallback$1(callback, entries);
+ });
+ });
+}
- if (opts.noext === true) {
- isExtglob = false;
- isGlob = false;
- }
+async$1.readdir = readdir$1;
- let base = str;
- let prefix = '';
- let glob = '';
+function callFailureCallback$1(callback, error) {
+ callback(error);
+}
- if (start > 0) {
- prefix = str.slice(0, start);
- str = str.slice(start);
- lastIndex -= start;
- }
+function callSuccessCallback$1(callback, result) {
+ callback(null, result);
+}
- if (base && isGlob === true && lastIndex > 0) {
- base = str.slice(0, lastIndex);
- glob = str.slice(lastIndex);
- } else if (isGlob === true) {
- base = '';
- glob = str;
- } else {
- base = str;
- }
+var sync$5 = {};
- if (base && base !== '' && base !== '/' && base !== str) {
- if (isPathSeparator(base.charCodeAt(base.length - 1))) {
- base = base.slice(0, -1);
- }
+Object.defineProperty(sync$5, "__esModule", {
+ value: true
+});
+sync$5.readdir = sync$5.readdirWithFileTypes = sync$5.read = void 0;
+const fsStat$4 = out$3;
+const constants_1 = constants;
+const utils$7 = utils$9;
+const common$4 = common$6;
+
+function read(directory, settings) {
+ if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
+ return readdirWithFileTypes(directory, settings);
}
- if (opts.unescape === true) {
- if (glob) glob = utils$1.removeBackslashes(glob);
+ return readdir(directory, settings);
+}
- if (base && backslashes === true) {
- base = utils$1.removeBackslashes(base);
+sync$5.read = read;
+
+function readdirWithFileTypes(directory, settings) {
+ const dirents = settings.fs.readdirSync(directory, {
+ withFileTypes: true
+ });
+ return dirents.map(dirent => {
+ const entry = {
+ dirent,
+ name: dirent.name,
+ path: common$4.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
+ };
+
+ if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
+ try {
+ const stats = settings.fs.statSync(entry.path);
+ entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats);
+ } catch (error) {
+ if (settings.throwErrorOnBrokenSymbolicLink) {
+ throw error;
+ }
+ }
}
- }
- const state = {
- prefix,
- input,
- start,
- base,
- glob,
- isBrace,
- isBracket,
- isGlob,
- isExtglob,
- isGlobstar,
- negated
- };
+ return entry;
+ });
+}
- if (opts.tokens === true) {
- state.maxDepth = 0;
+sync$5.readdirWithFileTypes = readdirWithFileTypes;
+
+function readdir(directory, settings) {
+ const names = settings.fs.readdirSync(directory);
+ return names.map(name => {
+ const entryPath = common$4.joinPathSegments(directory, name, settings.pathSegmentSeparator);
+ const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings);
+ const entry = {
+ name,
+ path: entryPath,
+ dirent: utils$7.fs.createDirentFromStats(name, stats)
+ };
- if (!isPathSeparator(code)) {
- tokens.push(token);
+ if (settings.stats) {
+ entry.stats = stats;
}
- state.tokens = tokens;
- }
+ return entry;
+ });
+}
- if (opts.parts === true || opts.tokens === true) {
- let prevIndex;
+sync$5.readdir = readdir;
- for (let idx = 0; idx < slashes.length; idx++) {
- const n = prevIndex ? prevIndex + 1 : start;
- const i = slashes[idx];
- const value = input.slice(n, i);
+var settings$2 = {};
- if (opts.tokens) {
- if (idx === 0 && start !== 0) {
- tokens[idx].isPrefix = true;
- tokens[idx].value = prefix;
- } else {
- tokens[idx].value = value;
- }
+var fs$3 = {};
- depth(tokens[idx]);
- state.maxDepth += tokens[idx].depth;
- }
+(function (exports) {
- if (idx !== 0 || value !== '') {
- parts.push(value);
- }
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
+ const fs = require$$0__default$4["default"];
+ exports.FILE_SYSTEM_ADAPTER = {
+ lstat: fs.lstat,
+ stat: fs.stat,
+ lstatSync: fs.lstatSync,
+ statSync: fs.statSync,
+ readdir: fs.readdir,
+ readdirSync: fs.readdirSync
+ };
- prevIndex = i;
+ function createFileSystemAdapter(fsMethods) {
+ if (fsMethods === undefined) {
+ return exports.FILE_SYSTEM_ADAPTER;
}
- if (prevIndex && prevIndex + 1 < input.length) {
- const value = input.slice(prevIndex + 1);
- parts.push(value);
+ return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
+ }
- if (opts.tokens) {
- tokens[tokens.length - 1].value = value;
- depth(tokens[tokens.length - 1]);
- state.maxDepth += tokens[tokens.length - 1].depth;
- }
- }
+ exports.createFileSystemAdapter = createFileSystemAdapter;
+})(fs$3);
- state.slashes = slashes;
- state.parts = parts;
+Object.defineProperty(settings$2, "__esModule", {
+ value: true
+});
+const path$6 = require$$0__default$1["default"];
+const fsStat$3 = out$3;
+const fs$2 = fs$3;
+
+class Settings$1 {
+ constructor(_options = {}) {
+ this._options = _options;
+ this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
+ this.fs = fs$2.createFileSystemAdapter(this._options.fs);
+ this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$6.sep);
+ this.stats = this._getValue(this._options.stats, false);
+ this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
+ this.fsStatSettings = new fsStat$3.Settings({
+ followSymbolicLink: this.followSymbolicLinks,
+ fs: this.fs,
+ throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
+ });
}
- return state;
-};
+ _getValue(option, value) {
+ return option !== null && option !== void 0 ? option : value;
+ }
-var scan_1 = scan;
+}
-/**
- * Constants
- */
+settings$2.default = Settings$1;
+Object.defineProperty(out$1, "__esModule", {
+ value: true
+});
+out$1.Settings = out$1.scandirSync = out$1.scandir = void 0;
+const async = async$1;
+const sync$4 = sync$5;
+const settings_1$2 = settings$2;
+out$1.Settings = settings_1$2.default;
+
+function scandir(path, optionsOrSettingsOrCallback, callback) {
+ if (typeof optionsOrSettingsOrCallback === 'function') {
+ async.read(path, getSettings$1(), optionsOrSettingsOrCallback);
+ return;
+ }
-const {
- MAX_LENGTH: MAX_LENGTH$1,
- POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
- REGEX_NON_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_BACKREF,
- REPLACEMENTS
-} = constants$1;
-/**
- * Helpers
- */
+ async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback);
+}
-const expandRange = (args, options) => {
- if (typeof options.expandRange === 'function') {
- return options.expandRange(...args, options);
- }
+out$1.scandir = scandir;
- args.sort();
- const value = `[${args.join('-')}]`;
+function scandirSync(path, optionsOrSettings) {
+ const settings = getSettings$1(optionsOrSettings);
+ return sync$4.read(path, settings);
+}
- try {
- /* eslint-disable-next-line no-new */
- new RegExp(value);
- } catch (ex) {
- return args.map(v => utils$1.escapeRegex(v)).join('..');
+out$1.scandirSync = scandirSync;
+
+function getSettings$1(settingsOrOptions = {}) {
+ if (settingsOrOptions instanceof settings_1$2.default) {
+ return settingsOrOptions;
}
- return value;
-};
-/**
- * Create the message for a syntax error
- */
+ return new settings_1$2.default(settingsOrOptions);
+}
+var queue = {exports: {}};
-const syntaxError = (type, char) => {
- return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
-};
-/**
- * Parse the given input string.
- * @param {String} input
- * @param {Object} options
- * @return {Object}
- */
+function reusify$1(Constructor) {
+ var head = new Constructor();
+ var tail = head;
+ function get() {
+ var current = head;
-const parse$1 = (input, options) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected a string');
- }
+ if (current.next) {
+ head = current.next;
+ } else {
+ head = new Constructor();
+ tail = head;
+ }
- input = REPLACEMENTS[input] || input;
- const opts = Object.assign({}, options);
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
- let len = input.length;
+ current.next = null;
+ return current;
+ }
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
+ function release(obj) {
+ tail.next = obj;
+ tail = obj;
}
- const bos = {
- type: 'bos',
- value: '',
- output: opts.prepend || ''
+ return {
+ get: get,
+ release: release
};
- const tokens = [bos];
- const capture = opts.capture ? '' : '?:';
- const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix
+}
- const PLATFORM_CHARS = constants$1.globChars(win32);
- const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
- const {
- DOT_LITERAL,
- PLUS_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR
- } = PLATFORM_CHARS;
+var reusify_1 = reusify$1;
- const globstar = opts => {
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
+/* eslint-disable no-var */
- const nodot = opts.dot ? '' : NO_DOT;
- const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
- let star = opts.bash === true ? globstar(opts) : STAR;
- if (opts.capture) {
- star = `(${star})`;
- } // minimatch options support
+var reusify = reusify_1;
+function fastqueue(context, worker, concurrency) {
+ if (typeof context === 'function') {
+ concurrency = worker;
+ worker = context;
+ context = null;
+ }
- if (typeof opts.noext === 'boolean') {
- opts.noextglob = opts.noext;
+ if (concurrency < 1) {
+ throw new Error('fastqueue concurrency must be greater than 1');
}
- const state = {
- input,
- index: -1,
- start: 0,
- dot: opts.dot === true,
- consumed: '',
- output: '',
- prefix: '',
- backtrack: false,
- negated: false,
- brackets: 0,
- braces: 0,
- parens: 0,
- quotes: 0,
- globstar: false,
- tokens
+ var cache = reusify(Task);
+ var queueHead = null;
+ var queueTail = null;
+ var _running = 0;
+ var errorHandler = null;
+ var self = {
+ push: push,
+ drain: noop,
+ saturated: noop,
+ pause: pause,
+ paused: false,
+ concurrency: concurrency,
+ running: running,
+ resume: resume,
+ idle: idle,
+ length: length,
+ getQueue: getQueue,
+ unshift: unshift,
+ empty: noop,
+ kill: kill,
+ killAndDrain: killAndDrain,
+ error: error
};
- input = utils$1.removePrefix(input, state);
- len = input.length;
- const extglobs = [];
- const braces = [];
- const stack = [];
- let prev = bos;
- let value;
- /**
- * Tokenizing helpers
- */
-
- const eos = () => state.index === len - 1;
+ return self;
- const peek = state.peek = (n = 1) => input[state.index + n];
+ function running() {
+ return _running;
+ }
- const advance = state.advance = () => input[++state.index];
+ function pause() {
+ self.paused = true;
+ }
- const remaining = () => input.slice(state.index + 1);
+ function length() {
+ var current = queueHead;
+ var counter = 0;
- const consume = (value = '', num = 0) => {
- state.consumed += value;
- state.index += num;
- };
+ while (current) {
+ current = current.next;
+ counter++;
+ }
- const append = token => {
- state.output += token.output != null ? token.output : token.value;
- consume(token.value);
- };
+ return counter;
+ }
- const negate = () => {
- let count = 1;
+ function getQueue() {
+ var current = queueHead;
+ var tasks = [];
- while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
- advance();
- state.start++;
- count++;
+ while (current) {
+ tasks.push(current.value);
+ current = current.next;
}
- if (count % 2 === 0) {
- return false;
- }
+ return tasks;
+ }
- state.negated = true;
- state.start++;
- return true;
- };
+ function resume() {
+ if (!self.paused) return;
+ self.paused = false;
- const increment = type => {
- state[type]++;
- stack.push(type);
- };
+ for (var i = 0; i < self.concurrency; i++) {
+ _running++;
+ release();
+ }
+ }
- const decrement = type => {
- state[type]--;
- stack.pop();
- };
- /**
- * Push tokens onto the tokens array. This helper speeds up
- * tokenizing by 1) helping us avoid backtracking as much as possible,
- * and 2) helping us avoid creating extra tokens when consecutive
- * characters are plain text. This improves performance and simplifies
- * lookbehinds.
- */
+ function idle() {
+ return _running === 0 && self.length() === 0;
+ }
+ function push(value, done) {
+ var current = cache.get();
+ current.context = context;
+ current.release = release;
+ current.value = value;
+ current.callback = done || noop;
+ current.errorHandler = errorHandler;
- const push = tok => {
- if (prev.type === 'globstar') {
- const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
- const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
+ if (_running === self.concurrency || self.paused) {
+ if (queueTail) {
+ queueTail.next = current;
+ queueTail = current;
+ } else {
+ queueHead = current;
+ queueTail = current;
+ self.saturated();
+ }
+ } else {
+ _running++;
+ worker.call(context, current.value, current.worked);
+ }
+ }
- if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
- state.output = state.output.slice(0, -prev.output.length);
- prev.type = 'star';
- prev.value = '*';
- prev.output = star;
- state.output += prev.output;
+ function unshift(value, done) {
+ var current = cache.get();
+ current.context = context;
+ current.release = release;
+ current.value = value;
+ current.callback = done || noop;
+
+ if (_running === self.concurrency || self.paused) {
+ if (queueHead) {
+ current.next = queueHead;
+ queueHead = current;
+ } else {
+ queueHead = current;
+ queueTail = current;
+ self.saturated();
}
+ } else {
+ _running++;
+ worker.call(context, current.value, current.worked);
}
+ }
- if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
- extglobs[extglobs.length - 1].inner += tok.value;
+ function release(holder) {
+ if (holder) {
+ cache.release(holder);
}
- if (tok.value || tok.output) append(tok);
+ var next = queueHead;
- if (prev && prev.type === 'text' && tok.type === 'text') {
- prev.value += tok.value;
- prev.output = (prev.output || '') + tok.value;
- return;
+ if (next) {
+ if (!self.paused) {
+ if (queueTail === queueHead) {
+ queueTail = null;
+ }
+
+ queueHead = next.next;
+ next.next = null;
+ worker.call(context, next.value, next.worked);
+
+ if (queueTail === null) {
+ self.empty();
+ }
+ } else {
+ _running--;
+ }
+ } else if (--_running === 0) {
+ self.drain();
}
+ }
- tok.prev = prev;
- tokens.push(tok);
- prev = tok;
- };
+ function kill() {
+ queueHead = null;
+ queueTail = null;
+ self.drain = noop;
+ }
- const extglobOpen = (type, value) => {
- const token = Object.assign({}, EXTGLOB_CHARS[value], {
- conditions: 1,
- inner: ''
- });
- token.prev = prev;
- token.parens = state.parens;
- token.output = state.output;
- const output = (opts.capture ? '(' : '') + token.open;
- increment('parens');
- push({
- type,
- value,
- output: state.output ? '' : ONE_CHAR
- });
- push({
- type: 'paren',
- extglob: true,
- value: advance(),
- output
- });
- extglobs.push(token);
- };
+ function killAndDrain() {
+ queueHead = null;
+ queueTail = null;
+ self.drain();
+ self.drain = noop;
+ }
- const extglobClose = token => {
- let output = token.close + (opts.capture ? ')' : '');
+ function error(handler) {
+ errorHandler = handler;
+ }
+}
- if (token.type === 'negate') {
- let extglobStar = star;
+function noop() {}
- if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
- extglobStar = globstar(opts);
- }
+function Task() {
+ this.value = null;
+ this.callback = noop;
+ this.next = null;
+ this.release = noop;
+ this.context = null;
+ this.errorHandler = null;
+ var self = this;
- if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
- output = token.close = `)$))${extglobStar}`;
- }
+ this.worked = function worked(err, result) {
+ var callback = self.callback;
+ var errorHandler = self.errorHandler;
+ var val = self.value;
+ self.value = null;
+ self.callback = noop;
- if (token.prev.type === 'bos' && eos()) {
- state.negatedExtglob = true;
- }
+ if (self.errorHandler) {
+ errorHandler(err, val);
}
- push({
- type: 'paren',
- extglob: true,
- value,
- output
- });
- decrement('parens');
+ callback.call(self.context, err, result);
+ self.release(self);
};
- /**
- * Fast paths
- */
+}
+function queueAsPromised(context, worker, concurrency) {
+ if (typeof context === 'function') {
+ concurrency = worker;
+ worker = context;
+ context = null;
+ }
- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
- let backslashes = false;
- let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
- if (first === '\\') {
- backslashes = true;
- return m;
- }
+ function asyncWrapper(arg, cb) {
+ worker.call(this, arg).then(function (res) {
+ cb(null, res);
+ }, cb);
+ }
- if (first === '?') {
- if (esc) {
- return esc + first + (rest ? QMARK.repeat(rest.length) : '');
- }
+ var queue = fastqueue(context, asyncWrapper, concurrency);
+ var pushCb = queue.push;
+ var unshiftCb = queue.unshift;
+ queue.push = push;
+ queue.unshift = unshift;
+ queue.drained = drained;
+ return queue;
- if (index === 0) {
- return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
+ function push(value) {
+ var p = new Promise(function (resolve, reject) {
+ pushCb(value, function (err, result) {
+ if (err) {
+ reject(err);
+ return;
}
- return QMARK.repeat(chars.length);
- }
+ resolve(result);
+ });
+ }); // Let's fork the promise chain to
+ // make the error bubble up to the user but
+ // not lead to a unhandledRejection
- if (first === '.') {
- return DOT_LITERAL.repeat(chars.length);
- }
+ p.catch(noop);
+ return p;
+ }
- if (first === '*') {
- if (esc) {
- return esc + first + (rest ? star : '');
+ function unshift(value) {
+ var p = new Promise(function (resolve, reject) {
+ unshiftCb(value, function (err, result) {
+ if (err) {
+ reject(err);
+ return;
}
- return star;
- }
+ resolve(result);
+ });
+ }); // Let's fork the promise chain to
+ // make the error bubble up to the user but
+ // not lead to a unhandledRejection
- return esc ? m : `\\${m}`;
+ p.catch(noop);
+ return p;
+ }
+
+ function drained() {
+ var previousDrain = queue.drain;
+ var p = new Promise(function (resolve) {
+ queue.drain = function () {
+ previousDrain();
+ resolve();
+ };
});
+ return p;
+ }
+}
- if (backslashes === true) {
- if (opts.unescape === true) {
- output = output.replace(/\\/g, '');
- } else {
- output = output.replace(/\\+/g, m => {
- return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
- });
- }
- }
+queue.exports = fastqueue;
+queue.exports.promise = queueAsPromised;
- if (output === input && opts.contains === true) {
- state.output = input;
- return state;
- }
+var common$3 = {};
- state.output = utils$1.wrapOutput(output, state, options);
- return state;
+Object.defineProperty(common$3, "__esModule", {
+ value: true
+});
+common$3.joinPathSegments = common$3.replacePathSegmentSeparator = common$3.isAppliedFilter = common$3.isFatalError = void 0;
+
+function isFatalError(settings, error) {
+ if (settings.errorFilter === null) {
+ return true;
}
- /**
- * Tokenize input until we reach end-of-string
- */
+ return !settings.errorFilter(error);
+}
- while (!eos()) {
- value = advance();
+common$3.isFatalError = isFatalError;
- if (value === '\u0000') {
- continue;
- }
- /**
- * Escaped characters
- */
+function isAppliedFilter(filter, value) {
+ return filter === null || filter(value);
+}
+common$3.isAppliedFilter = isAppliedFilter;
- if (value === '\\') {
- const next = peek();
+function replacePathSegmentSeparator(filepath, separator) {
+ return filepath.split(/[/\\]/).join(separator);
+}
- if (next === '/' && opts.bash !== true) {
- continue;
- }
+common$3.replacePathSegmentSeparator = replacePathSegmentSeparator;
- if (next === '.' || next === ';') {
- continue;
- }
+function joinPathSegments(a, b, separator) {
+ if (a === '') {
+ return b;
+ }
+ /**
+ * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
+ */
- if (!next) {
- value += '\\';
- push({
- type: 'text',
- value
- });
- continue;
- } // collapse slashes to reduce potential for exploits
+ if (a.endsWith(separator)) {
+ return a + b;
+ }
- const match = /^\\+/.exec(remaining());
- let slashes = 0;
+ return a + separator + b;
+}
- if (match && match[0].length > 2) {
- slashes = match[0].length;
- state.index += slashes;
+common$3.joinPathSegments = joinPathSegments;
- if (slashes % 2 !== 0) {
- value += '\\';
- }
- }
+var reader$1 = {};
- if (opts.unescape === true) {
- value = advance() || '';
- } else {
- value += advance() || '';
- }
+Object.defineProperty(reader$1, "__esModule", {
+ value: true
+});
+const common$2 = common$3;
- if (state.brackets === 0) {
- push({
- type: 'text',
- value
- });
- continue;
+class Reader$1 {
+ constructor(_root, _settings) {
+ this._root = _root;
+ this._settings = _settings;
+ this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
+ }
+
+}
+
+reader$1.default = Reader$1;
+
+Object.defineProperty(async$2, "__esModule", {
+ value: true
+});
+const events_1 = require$$0__default$5["default"];
+const fsScandir$2 = out$1;
+const fastq = queue.exports;
+const common$1 = common$3;
+const reader_1$3 = reader$1;
+
+class AsyncReader extends reader_1$3.default {
+ constructor(_root, _settings) {
+ super(_root, _settings);
+ this._settings = _settings;
+ this._scandir = fsScandir$2.scandir;
+ this._emitter = new events_1.EventEmitter();
+ this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
+ this._isFatalError = false;
+ this._isDestroyed = false;
+
+ this._queue.drain = () => {
+ if (!this._isFatalError) {
+ this._emitter.emit('end');
}
+ };
+ }
+
+ read() {
+ this._isFatalError = false;
+ this._isDestroyed = false;
+ setImmediate(() => {
+ this._pushToQueue(this._root, this._settings.basePath);
+ });
+ return this._emitter;
+ }
+
+ get isDestroyed() {
+ return this._isDestroyed;
+ }
+
+ destroy() {
+ if (this._isDestroyed) {
+ throw new Error('The reader is already destroyed');
}
- /**
- * If we're inside a regex character class, continue
- * until we reach the closing bracket.
- */
+ this._isDestroyed = true;
- if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
- if (opts.posix !== false && value === ':') {
- const inner = prev.value.slice(1);
+ this._queue.killAndDrain();
+ }
- if (inner.includes('[')) {
- prev.posix = true;
+ onEntry(callback) {
+ this._emitter.on('entry', callback);
+ }
- if (inner.includes(':')) {
- const idx = prev.value.lastIndexOf('[');
- const pre = prev.value.slice(0, idx);
- const rest = prev.value.slice(idx + 2);
- const posix = POSIX_REGEX_SOURCE$1[rest];
+ onError(callback) {
+ this._emitter.once('error', callback);
+ }
- if (posix) {
- prev.value = pre + posix;
- state.backtrack = true;
- advance();
+ onEnd(callback) {
+ this._emitter.once('end', callback);
+ }
- if (!bos.output && tokens.indexOf(prev) === 1) {
- bos.output = ONE_CHAR;
- }
+ _pushToQueue(directory, base) {
+ const queueItem = {
+ directory,
+ base
+ };
- continue;
- }
- }
- }
+ this._queue.push(queueItem, error => {
+ if (error !== null) {
+ this._handleError(error);
}
+ });
+ }
- if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
- value = `\\${value}`;
+ _worker(item, done) {
+ this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
+ if (error !== null) {
+ done(error, undefined);
+ return;
}
- if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
- value = `\\${value}`;
+ for (const entry of entries) {
+ this._handleEntry(entry, item.base);
}
- if (opts.posix === true && value === '!' && prev.value === '[') {
- value = '^';
- }
+ done(null, undefined);
+ });
+ }
- prev.value += value;
- append({
- value
- });
- continue;
+ _handleError(error) {
+ if (this._isDestroyed || !common$1.isFatalError(this._settings, error)) {
+ return;
}
- /**
- * If we're inside a quoted string, continue
- * until we reach the closing double quote.
- */
+ this._isFatalError = true;
+ this._isDestroyed = true;
- if (state.quotes === 1 && value !== '"') {
- value = utils$1.escapeRegex(value);
- prev.value += value;
- append({
- value
- });
- continue;
+ this._emitter.emit('error', error);
+ }
+
+ _handleEntry(entry, base) {
+ if (this._isDestroyed || this._isFatalError) {
+ return;
}
- /**
- * Double quotes
- */
+ const fullpath = entry.path;
- if (value === '"') {
- state.quotes = state.quotes === 1 ? 0 : 1;
+ if (base !== undefined) {
+ entry.path = common$1.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
+ }
- if (opts.keepQuotes === true) {
- push({
- type: 'text',
- value
- });
- }
+ if (common$1.isAppliedFilter(this._settings.entryFilter, entry)) {
+ this._emitEntry(entry);
+ }
- continue;
+ if (entry.dirent.isDirectory() && common$1.isAppliedFilter(this._settings.deepFilter, entry)) {
+ this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
}
- /**
- * Parentheses
- */
+ }
+ _emitEntry(entry) {
+ this._emitter.emit('entry', entry);
+ }
- if (value === '(') {
- increment('parens');
- push({
- type: 'paren',
- value
- });
- continue;
- }
+}
- if (value === ')') {
- if (state.parens === 0 && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('opening', '('));
- }
+async$2.default = AsyncReader;
- const extglob = extglobs[extglobs.length - 1];
+Object.defineProperty(async$3, "__esModule", {
+ value: true
+});
+const async_1$3 = async$2;
- if (extglob && state.parens === extglob.parens + 1) {
- extglobClose(extglobs.pop());
- continue;
- }
+class AsyncProvider {
+ constructor(_root, _settings) {
+ this._root = _root;
+ this._settings = _settings;
+ this._reader = new async_1$3.default(this._root, this._settings);
+ this._storage = [];
+ }
- push({
- type: 'paren',
- value,
- output: state.parens ? ')' : '\\)'
- });
- decrement('parens');
- continue;
- }
- /**
- * Square brackets
- */
+ read(callback) {
+ this._reader.onError(error => {
+ callFailureCallback(callback, error);
+ });
+ this._reader.onEntry(entry => {
+ this._storage.push(entry);
+ });
- if (value === '[') {
- if (opts.nobracket === true || !remaining().includes(']')) {
- if (opts.nobracket !== true && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('closing', ']'));
- }
+ this._reader.onEnd(() => {
+ callSuccessCallback(callback, this._storage);
+ });
- value = `\\${value}`;
- } else {
- increment('brackets');
- }
+ this._reader.read();
+ }
- push({
- type: 'bracket',
- value
- });
- continue;
- }
+}
- if (value === ']') {
- if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
- push({
- type: 'text',
- value,
- output: `\\${value}`
- });
- continue;
- }
+async$3.default = AsyncProvider;
- if (state.brackets === 0) {
- if (opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('opening', '['));
- }
+function callFailureCallback(callback, error) {
+ callback(error);
+}
- push({
- type: 'text',
- value,
- output: `\\${value}`
- });
- continue;
- }
+function callSuccessCallback(callback, entries) {
+ callback(null, entries);
+}
- decrement('brackets');
- const prevValue = prev.value.slice(1);
+var stream$1 = {};
- if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
- value = `/${value}`;
+Object.defineProperty(stream$1, "__esModule", {
+ value: true
+});
+const stream_1$5 = require$$0__default$3["default"];
+const async_1$2 = async$2;
+
+class StreamProvider {
+ constructor(_root, _settings) {
+ this._root = _root;
+ this._settings = _settings;
+ this._reader = new async_1$2.default(this._root, this._settings);
+ this._stream = new stream_1$5.Readable({
+ objectMode: true,
+ read: () => {},
+ destroy: () => {
+ if (!this._reader.isDestroyed) {
+ this._reader.destroy();
+ }
}
+ });
+ }
- prev.value += value;
- append({
- value
- }); // when literal brackets are explicitly disabled
- // assume we should match with a regex character class
+ read() {
+ this._reader.onError(error => {
+ this._stream.emit('error', error);
+ });
- if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
- continue;
- }
+ this._reader.onEntry(entry => {
+ this._stream.push(entry);
+ });
- const escaped = utils$1.escapeRegex(prev.value);
- state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
- // assume we should escape the brackets to match literal characters
+ this._reader.onEnd(() => {
+ this._stream.push(null);
+ });
- if (opts.literalBrackets === true) {
- state.output += escaped;
- prev.value = escaped;
- continue;
- } // when the user specifies nothing, try to match both
+ this._reader.read();
+ return this._stream;
+ }
- prev.value = `(${capture}${escaped}|${prev.value})`;
- state.output += prev.value;
- continue;
- }
- /**
- * Braces
- */
+}
+stream$1.default = StreamProvider;
- if (value === '{' && opts.nobrace !== true) {
- increment('braces');
- const open = {
- type: 'brace',
- value,
- output: '(',
- outputIndex: state.output.length,
- tokensIndex: state.tokens.length
- };
- braces.push(open);
- push(open);
- continue;
- }
+var sync$3 = {};
- if (value === '}') {
- const brace = braces[braces.length - 1];
+var sync$2 = {};
- if (opts.nobrace === true || !brace) {
- push({
- type: 'text',
- value,
- output: value
- });
- continue;
- }
+Object.defineProperty(sync$2, "__esModule", {
+ value: true
+});
+const fsScandir$1 = out$1;
+const common = common$3;
+const reader_1$2 = reader$1;
- let output = ')';
+class SyncReader extends reader_1$2.default {
+ constructor() {
+ super(...arguments);
+ this._scandir = fsScandir$1.scandirSync;
+ this._storage = [];
+ this._queue = new Set();
+ }
- if (brace.dots === true) {
- const arr = tokens.slice();
- const range = [];
+ read() {
+ this._pushToQueue(this._root, this._settings.basePath);
- for (let i = arr.length - 1; i >= 0; i--) {
- tokens.pop();
+ this._handleQueue();
- if (arr[i].type === 'brace') {
- break;
- }
+ return this._storage;
+ }
- if (arr[i].type !== 'dots') {
- range.unshift(arr[i].value);
- }
- }
+ _pushToQueue(directory, base) {
+ this._queue.add({
+ directory,
+ base
+ });
+ }
- output = expandRange(range, opts);
- state.backtrack = true;
- }
+ _handleQueue() {
+ for (const item of this._queue.values()) {
+ this._handleDirectory(item.directory, item.base);
+ }
+ }
- if (brace.comma !== true && brace.dots !== true) {
- const out = state.output.slice(0, brace.outputIndex);
- const toks = state.tokens.slice(brace.tokensIndex);
- brace.value = brace.output = '\\{';
- value = output = '\\}';
- state.output = out;
+ _handleDirectory(directory, base) {
+ try {
+ const entries = this._scandir(directory, this._settings.fsScandirSettings);
- for (const t of toks) {
- state.output += t.output || t.value;
- }
+ for (const entry of entries) {
+ this._handleEntry(entry, base);
}
+ } catch (error) {
+ this._handleError(error);
+ }
+ }
- push({
- type: 'brace',
- value,
- output
- });
- decrement('braces');
- braces.pop();
- continue;
+ _handleError(error) {
+ if (!common.isFatalError(this._settings, error)) {
+ return;
}
- /**
- * Pipes
- */
+ throw error;
+ }
- if (value === '|') {
- if (extglobs.length > 0) {
- extglobs[extglobs.length - 1].conditions++;
- }
+ _handleEntry(entry, base) {
+ const fullpath = entry.path;
- push({
- type: 'text',
- value
- });
- continue;
+ if (base !== undefined) {
+ entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
}
- /**
- * Commas
- */
+ if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
+ this._pushToStorage(entry);
+ }
- if (value === ',') {
- let output = value;
- const brace = braces[braces.length - 1];
+ if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
+ this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
+ }
+ }
- if (brace && stack[stack.length - 1] === 'braces') {
- brace.comma = true;
- output = '|';
- }
+ _pushToStorage(entry) {
+ this._storage.push(entry);
+ }
- push({
- type: 'comma',
- value,
- output
- });
- continue;
- }
- /**
- * Slashes
- */
+}
+sync$2.default = SyncReader;
- if (value === '/') {
- // if the beginning of the glob is "./", advance the start
- // to the current index, and don't add the "./" characters
- // to the state. This greatly simplifies lookbehinds when
- // checking for BOS characters like "!" and "." (not "./")
- if (prev.type === 'dot' && state.index === state.start + 1) {
- state.start = state.index + 1;
- state.consumed = '';
- state.output = '';
- tokens.pop();
- prev = bos; // reset "prev" to the first token
+Object.defineProperty(sync$3, "__esModule", {
+ value: true
+});
+const sync_1$3 = sync$2;
- continue;
- }
+class SyncProvider {
+ constructor(_root, _settings) {
+ this._root = _root;
+ this._settings = _settings;
+ this._reader = new sync_1$3.default(this._root, this._settings);
+ }
- push({
- type: 'slash',
- value,
- output: SLASH_LITERAL
- });
- continue;
- }
- /**
- * Dots
- */
+ read() {
+ return this._reader.read();
+ }
+}
- if (value === '.') {
- if (state.braces > 0 && prev.type === 'dot') {
- if (prev.value === '.') prev.output = DOT_LITERAL;
- const brace = braces[braces.length - 1];
- prev.type = 'dots';
- prev.output += value;
- prev.value += value;
- brace.dots = true;
- continue;
- }
+sync$3.default = SyncProvider;
- if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
- push({
- type: 'text',
- value,
- output: DOT_LITERAL
- });
- continue;
- }
+var settings$1 = {};
- push({
- type: 'dot',
- value,
- output: DOT_LITERAL
- });
- continue;
- }
- /**
- * Question marks
- */
+Object.defineProperty(settings$1, "__esModule", {
+ value: true
+});
+const path$5 = require$$0__default$1["default"];
+const fsScandir = out$1;
+
+class Settings {
+ constructor(_options = {}) {
+ this._options = _options;
+ this.basePath = this._getValue(this._options.basePath, undefined);
+ this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
+ this.deepFilter = this._getValue(this._options.deepFilter, null);
+ this.entryFilter = this._getValue(this._options.entryFilter, null);
+ this.errorFilter = this._getValue(this._options.errorFilter, null);
+ this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$5.sep);
+ this.fsScandirSettings = new fsScandir.Settings({
+ followSymbolicLinks: this._options.followSymbolicLinks,
+ fs: this._options.fs,
+ pathSegmentSeparator: this._options.pathSegmentSeparator,
+ stats: this._options.stats,
+ throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
+ });
+ }
+ _getValue(option, value) {
+ return option !== null && option !== void 0 ? option : value;
+ }
- if (value === '?') {
- const isGroup = prev && prev.value === '(';
+}
- if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- extglobOpen('qmark', value);
- continue;
- }
+settings$1.default = Settings;
- if (prev && prev.type === 'paren') {
- const next = peek();
- let output = value;
+Object.defineProperty(out$2, "__esModule", {
+ value: true
+});
+out$2.Settings = out$2.walkStream = out$2.walkSync = out$2.walk = void 0;
+const async_1$1 = async$3;
+const stream_1$4 = stream$1;
+const sync_1$2 = sync$3;
+const settings_1$1 = settings$1;
+out$2.Settings = settings_1$1.default;
+
+function walk(directory, optionsOrSettingsOrCallback, callback) {
+ if (typeof optionsOrSettingsOrCallback === 'function') {
+ new async_1$1.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
+ return;
+ }
- if (next === '<' && !utils$1.supportsLookbehinds()) {
- throw new Error('Node.js v10 or higher is required for regex lookbehinds');
- }
+ new async_1$1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
+}
- if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
- output = `\\${value}`;
- }
+out$2.walk = walk;
- push({
- type: 'text',
- value,
- output
- });
- continue;
- }
+function walkSync(directory, optionsOrSettings) {
+ const settings = getSettings(optionsOrSettings);
+ const provider = new sync_1$2.default(directory, settings);
+ return provider.read();
+}
- if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
- push({
- type: 'qmark',
- value,
- output: QMARK_NO_DOT
- });
- continue;
- }
+out$2.walkSync = walkSync;
- push({
- type: 'qmark',
- value,
- output: QMARK
- });
- continue;
- }
- /**
- * Exclamation
- */
+function walkStream(directory, optionsOrSettings) {
+ const settings = getSettings(optionsOrSettings);
+ const provider = new stream_1$4.default(directory, settings);
+ return provider.read();
+}
+out$2.walkStream = walkStream;
- if (value === '!') {
- if (opts.noextglob !== true && peek() === '(') {
- if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
- extglobOpen('negate', value);
- continue;
- }
- }
+function getSettings(settingsOrOptions = {}) {
+ if (settingsOrOptions instanceof settings_1$1.default) {
+ return settingsOrOptions;
+ }
- if (opts.nonegate !== true && state.index === 0) {
- negate();
- continue;
- }
- }
- /**
- * Plus
- */
+ return new settings_1$1.default(settingsOrOptions);
+}
+var reader = {};
- if (value === '+') {
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- extglobOpen('plus', value);
- continue;
- }
+Object.defineProperty(reader, "__esModule", {
+ value: true
+});
+const path$4 = require$$0__default$1["default"];
+const fsStat$2 = out$3;
+const utils$6 = utils$k;
+
+class Reader {
+ constructor(_settings) {
+ this._settings = _settings;
+ this._fsStatSettings = new fsStat$2.Settings({
+ followSymbolicLink: this._settings.followSymbolicLinks,
+ fs: this._settings.fs,
+ throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
+ });
+ }
- if (prev && prev.value === '(' || opts.regex === false) {
- push({
- type: 'plus',
- value,
- output: PLUS_LITERAL
- });
- continue;
- }
+ _getFullEntryPath(filepath) {
+ return path$4.resolve(this._settings.cwd, filepath);
+ }
- if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
- push({
- type: 'plus',
- value
- });
- continue;
- }
+ _makeEntry(stats, pattern) {
+ const entry = {
+ name: pattern,
+ path: pattern,
+ dirent: utils$6.fs.createDirentFromStats(pattern, stats)
+ };
- push({
- type: 'plus',
- value: PLUS_LITERAL
- });
- continue;
+ if (this._settings.stats) {
+ entry.stats = stats;
}
- /**
- * Plain text
- */
+ return entry;
+ }
- if (value === '@') {
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- push({
- type: 'at',
- extglob: true,
- value,
- output: ''
- });
- continue;
- }
+ _isFatalError(error) {
+ return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
+ }
- push({
- type: 'text',
- value
- });
- continue;
- }
- /**
- * Plain text
- */
+}
+reader.default = Reader;
- if (value !== '*') {
- if (value === '$' || value === '^') {
- value = `\\${value}`;
- }
+Object.defineProperty(stream$2, "__esModule", {
+ value: true
+});
+const stream_1$3 = require$$0__default$3["default"];
+const fsStat$1 = out$3;
+const fsWalk$1 = out$2;
+const reader_1$1 = reader;
- const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
+class ReaderStream extends reader_1$1.default {
+ constructor() {
+ super(...arguments);
+ this._walkStream = fsWalk$1.walkStream;
+ this._stat = fsStat$1.stat;
+ }
- if (match) {
- value += match[0];
- state.index += match[0].length;
- }
+ dynamic(root, options) {
+ return this._walkStream(root, options);
+ }
- push({
- type: 'text',
- value
- });
- continue;
- }
- /**
- * Stars
- */
+ static(patterns, options) {
+ const filepaths = patterns.map(this._getFullEntryPath, this);
+ const stream = new stream_1$3.PassThrough({
+ objectMode: true
+ });
+ stream._write = (index, _enc, done) => {
+ return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
+ if (entry !== null && options.entryFilter(entry)) {
+ stream.push(entry);
+ }
- if (prev && (prev.type === 'globstar' || prev.star === true)) {
- prev.type = 'star';
- prev.star = true;
- prev.value += value;
- prev.output = star;
- state.backtrack = true;
- state.globstar = true;
- consume(value);
- continue;
- }
+ if (index === filepaths.length - 1) {
+ stream.end();
+ }
- let rest = remaining();
+ done();
+ }).catch(done);
+ };
- if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
- extglobOpen('star', value);
- continue;
+ for (let i = 0; i < filepaths.length; i++) {
+ stream.write(i);
}
- if (prev.type === 'star') {
- if (opts.noglobstar === true) {
- consume(value);
- continue;
- }
-
- const prior = prev.prev;
- const before = prior.prev;
- const isStart = prior.type === 'slash' || prior.type === 'bos';
- const afterStar = before && (before.type === 'star' || before.type === 'globstar');
+ return stream;
+ }
- if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
- push({
- type: 'star',
- value,
- output: ''
- });
- continue;
+ _getEntry(filepath, pattern, options) {
+ return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
+ if (options.errorFilter(error)) {
+ return null;
}
- const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
- const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
+ throw error;
+ });
+ }
- if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
- push({
- type: 'star',
- value,
- output: ''
- });
- continue;
- } // strip consecutive `/**/`
+ _getStat(filepath) {
+ return new Promise((resolve, reject) => {
+ this._stat(filepath, this._fsStatSettings, (error, stats) => {
+ return error === null ? resolve(stats) : reject(error);
+ });
+ });
+ }
+}
- while (rest.slice(0, 3) === '/**') {
- const after = input[state.index + 4];
+stream$2.default = ReaderStream;
- if (after && after !== '/') {
- break;
- }
+var provider = {};
- rest = rest.slice(3);
- consume('/**', 3);
- }
+var deep = {};
- if (prior.type === 'bos' && eos()) {
- prev.type = 'globstar';
- prev.value += value;
- prev.output = globstar(opts);
- state.output = prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
+var partial = {};
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
- prev.type = 'globstar';
- prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
- prev.value += value;
- state.globstar = true;
- state.output += prior.output + prev.output;
- consume(value);
- continue;
- }
+var matcher = {};
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
- const end = rest[1] !== void 0 ? '|$' : '';
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
- prev.type = 'globstar';
- prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
- prev.value += value;
- state.output += prior.output + prev.output;
- state.globstar = true;
- consume(value + advance());
- push({
- type: 'slash',
- value: '/',
- output: ''
- });
- continue;
- }
+Object.defineProperty(matcher, "__esModule", {
+ value: true
+});
+const utils$5 = utils$k;
- if (prior.type === 'bos' && rest[0] === '/') {
- prev.type = 'globstar';
- prev.value += value;
- prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
- state.output = prev.output;
- state.globstar = true;
- consume(value + advance());
- push({
- type: 'slash',
- value: '/',
- output: ''
- });
- continue;
- } // remove single star from output
+class Matcher {
+ constructor(_patterns, _settings, _micromatchOptions) {
+ this._patterns = _patterns;
+ this._settings = _settings;
+ this._micromatchOptions = _micromatchOptions;
+ this._storage = [];
+ this._fillStorage();
+ }
- state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
+ _fillStorage() {
+ /**
+ * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
+ * So, before expand patterns with brace expansion into separated patterns.
+ */
+ const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns);
- prev.type = 'globstar';
- prev.output = globstar(opts);
- prev.value += value; // reset output with globstar
+ for (const pattern of patterns) {
+ const segments = this._getPatternSegments(pattern);
- state.output += prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
+ const sections = this._splitSegmentsIntoSections(segments);
- const token = {
- type: 'star',
- value,
- output: star
- };
+ this._storage.push({
+ complete: sections.length <= 1,
+ pattern,
+ segments,
+ sections
+ });
+ }
+ }
- if (opts.bash === true) {
- token.output = '.*?';
+ _getPatternSegments(pattern) {
+ const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions);
+ return parts.map(part => {
+ const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings);
- if (prev.type === 'bos' || prev.type === 'slash') {
- token.output = nodot + token.output;
+ if (!dynamic) {
+ return {
+ dynamic: false,
+ pattern: part
+ };
}
- push(token);
- continue;
- }
+ return {
+ dynamic: true,
+ pattern: part,
+ patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions)
+ };
+ });
+ }
- if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
- token.output = value;
- push(token);
- continue;
- }
+ _splitSegmentsIntoSections(segments) {
+ return utils$5.array.splitWhen(segments, segment => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern));
+ }
- if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
- if (prev.type === 'dot') {
- state.output += NO_DOT_SLASH;
- prev.output += NO_DOT_SLASH;
- } else if (opts.dot === true) {
- state.output += NO_DOTS_SLASH;
- prev.output += NO_DOTS_SLASH;
- } else {
- state.output += nodot;
- prev.output += nodot;
+}
+
+matcher.default = Matcher;
+
+Object.defineProperty(partial, "__esModule", {
+ value: true
+});
+const matcher_1 = matcher;
+
+class PartialMatcher extends matcher_1.default {
+ match(filepath) {
+ const parts = filepath.split('/');
+ const levels = parts.length;
+
+ const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
+
+ for (const pattern of patterns) {
+ const section = pattern.sections[0];
+ /**
+ * In this case, the pattern has a globstar and we must read all directories unconditionally,
+ * but only if the level has reached the end of the first group.
+ *
+ * fixtures/{a,b}/**
+ * ^ true/false ^ always true
+ */
+
+ if (!pattern.complete && levels > section.length) {
+ return true;
}
- if (peek() !== '*') {
- state.output += ONE_CHAR;
- prev.output += ONE_CHAR;
+ const match = parts.every((part, index) => {
+ const segment = pattern.segments[index];
+
+ if (segment.dynamic && segment.patternRe.test(part)) {
+ return true;
+ }
+
+ if (!segment.dynamic && segment.pattern === part) {
+ return true;
+ }
+
+ return false;
+ });
+
+ if (match) {
+ return true;
}
}
- push(token);
+ return false;
}
- while (state.brackets > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
- state.output = utils$1.escapeLast(state.output, '[');
- decrement('brackets');
- }
+}
- while (state.parens > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
- state.output = utils$1.escapeLast(state.output, '(');
- decrement('parens');
- }
+partial.default = PartialMatcher;
- while (state.braces > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
- state.output = utils$1.escapeLast(state.output, '{');
- decrement('braces');
+Object.defineProperty(deep, "__esModule", {
+ value: true
+});
+const utils$4 = utils$k;
+const partial_1 = partial;
+
+class DeepFilter {
+ constructor(_settings, _micromatchOptions) {
+ this._settings = _settings;
+ this._micromatchOptions = _micromatchOptions;
}
- if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
- push({
- type: 'maybe_slash',
- value: '',
- output: `${SLASH_LITERAL}?`
- });
- } // rebuild the output if we had to backtrack at any point
+ getFilter(basePath, positive, negative) {
+ const matcher = this._getMatcher(positive);
+ const negativeRe = this._getNegativePatternsRe(negative);
- if (state.backtrack === true) {
- state.output = '';
+ return entry => this._filter(basePath, entry, matcher, negativeRe);
+ }
- for (const token of state.tokens) {
- state.output += token.output != null ? token.output : token.value;
+ _getMatcher(patterns) {
+ return new partial_1.default(patterns, this._settings, this._micromatchOptions);
+ }
- if (token.suffix) {
- state.output += token.suffix;
- }
+ _getNegativePatternsRe(patterns) {
+ const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
+ return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
+ }
+
+ _filter(basePath, entry, matcher, negativeRe) {
+ if (this._isSkippedByDeep(basePath, entry.path)) {
+ return false;
+ }
+
+ if (this._isSkippedSymbolicLink(entry)) {
+ return false;
+ }
+
+ const filepath = utils$4.path.removeLeadingDotSegment(entry.path);
+
+ if (this._isSkippedByPositivePatterns(filepath, matcher)) {
+ return false;
}
+
+ return this._isSkippedByNegativePatterns(filepath, negativeRe);
}
- return state;
-};
-/**
- * Fast paths for creating regular expressions for common glob patterns.
- * This can significantly speed up processing and has very little downside
- * impact when none of the fast paths match.
- */
+ _isSkippedByDeep(basePath, entryPath) {
+ /**
+ * Avoid unnecessary depth calculations when it doesn't matter.
+ */
+ if (this._settings.deep === Infinity) {
+ return false;
+ }
+ return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
+ }
-parse$1.fastpaths = (input, options) => {
- const opts = Object.assign({}, options);
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
- const len = input.length;
+ _getEntryLevel(basePath, entryPath) {
+ const entryPathDepth = entryPath.split('/').length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
+ if (basePath === '') {
+ return entryPathDepth;
+ }
+
+ const basePathDepth = basePath.split('/').length;
+ return entryPathDepth - basePathDepth;
}
- input = REPLACEMENTS[input] || input;
- const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix
+ _isSkippedSymbolicLink(entry) {
+ return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
+ }
- const {
- DOT_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOTS_SLASH,
- STAR,
- START_ANCHOR
- } = constants$1.globChars(win32);
- const nodot = opts.dot ? NO_DOTS : NO_DOT;
- const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
- const capture = opts.capture ? '' : '?:';
- const state = {
- negated: false,
- prefix: ''
- };
- let star = opts.bash === true ? '.*?' : STAR;
+ _isSkippedByPositivePatterns(entryPath, matcher) {
+ return !this._settings.baseNameMatch && !matcher.match(entryPath);
+ }
- if (opts.capture) {
- star = `(${star})`;
+ _isSkippedByNegativePatterns(entryPath, patternsRe) {
+ return !utils$4.pattern.matchAny(entryPath, patternsRe);
}
- const globstar = opts => {
- if (opts.noglobstar === true) return star;
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
+}
- const create = str => {
- switch (str) {
- case '*':
- return `${nodot}${ONE_CHAR}${star}`;
+deep.default = DeepFilter;
- case '.*':
- return `${DOT_LITERAL}${ONE_CHAR}${star}`;
+var entry$1 = {};
- case '*.*':
- return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
+Object.defineProperty(entry$1, "__esModule", {
+ value: true
+});
+const utils$3 = utils$k;
- case '*/*':
- return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
+class EntryFilter {
+ constructor(_settings, _micromatchOptions) {
+ this._settings = _settings;
+ this._micromatchOptions = _micromatchOptions;
+ this.index = new Map();
+ }
- case '**':
- return nodot + globstar(opts);
+ getFilter(positive, negative) {
+ const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
+ const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions);
+ return entry => this._filter(entry, positiveRe, negativeRe);
+ }
- case '**/*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
+ _filter(entry, positiveRe, negativeRe) {
+ if (this._settings.unique && this._isDuplicateEntry(entry)) {
+ return false;
+ }
- case '**/*.*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
+ if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
+ return false;
+ }
- case '**/.*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
+ if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
+ return false;
+ }
- default:
- {
- const match = /^(.*?)\.(\w+)$/.exec(str);
- if (!match) return;
- const source = create(match[1]);
- if (!source) return;
- return source + DOT_LITERAL + match[2];
- }
+ const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
+ const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
+
+ if (this._settings.unique && isMatched) {
+ this._createIndexRecord(entry);
}
- };
- const output = utils$1.removePrefix(input, state);
- let source = create(output);
+ return isMatched;
+ }
- if (source && opts.strictSlashes !== true) {
- source += `${SLASH_LITERAL}?`;
+ _isDuplicateEntry(entry) {
+ return this.index.has(entry.path);
}
- return source;
-};
+ _createIndexRecord(entry) {
+ this.index.set(entry.path, undefined);
+ }
-var parse_1$1 = parse$1;
+ _onlyFileFilter(entry) {
+ return this._settings.onlyFiles && !entry.dirent.isFile();
+ }
-const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
-/**
- * Creates a matcher function from one or more glob patterns. The
- * returned function takes a string to match as its first argument,
- * and returns true if the string is a match. The returned matcher
- * function also takes a boolean as the second argument that, when true,
- * returns an object with additional information.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch(glob[, options]);
- *
- * const isMatch = picomatch('*.!(*a)');
- * console.log(isMatch('a.a')); //=> false
- * console.log(isMatch('a.b')); //=> true
- * ```
- * @name picomatch
- * @param {String|Array} `globs` One or more glob patterns.
- * @param {Object=} `options`
- * @return {Function=} Returns a matcher function.
- * @api public
- */
+ _onlyDirectoryFilter(entry) {
+ return this._settings.onlyDirectories && !entry.dirent.isDirectory();
+ }
+
+ _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
+ if (!this._settings.absolute) {
+ return false;
+ }
+ const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
+ return utils$3.pattern.matchAny(fullpath, patternsRe);
+ }
-const picomatch = (glob, options, returnState = false) => {
- if (Array.isArray(glob)) {
- const fns = glob.map(input => picomatch(input, options, returnState));
+ _isMatchToPatterns(entryPath, patternsRe) {
+ const filepath = utils$3.path.removeLeadingDotSegment(entryPath);
+ return utils$3.pattern.matchAny(filepath, patternsRe);
+ }
- const arrayMatcher = str => {
- for (const isMatch of fns) {
- const state = isMatch(str);
- if (state) return state;
- }
+}
- return false;
- };
+entry$1.default = EntryFilter;
- return arrayMatcher;
+var error = {};
+
+Object.defineProperty(error, "__esModule", {
+ value: true
+});
+const utils$2 = utils$k;
+
+class ErrorFilter {
+ constructor(_settings) {
+ this._settings = _settings;
}
- const isState = isObject$2(glob) && glob.tokens && glob.input;
+ getFilter() {
+ return error => this._isNonFatalError(error);
+ }
- if (glob === '' || typeof glob !== 'string' && !isState) {
- throw new TypeError('Expected pattern to be a non-empty string');
+ _isNonFatalError(error) {
+ return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
}
- const opts = options || {};
- const posix = utils$1.isWindows(options);
- const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
- const state = regex.state;
- delete regex.state;
+}
- let isIgnored = () => false;
+error.default = ErrorFilter;
- if (opts.ignore) {
- const ignoreOpts = Object.assign({}, options, {
- ignore: null,
- onMatch: null,
- onResult: null
- });
- isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
- }
+var entry = {};
- const matcher = (input, returnObject = false) => {
- const {
- isMatch,
- match,
- output
- } = picomatch.test(input, regex, options, {
- glob,
- posix
- });
- const result = {
- glob,
- state,
- regex,
- posix,
- input,
- output,
- match,
- isMatch
- };
+Object.defineProperty(entry, "__esModule", {
+ value: true
+});
+const utils$1 = utils$k;
- if (typeof opts.onResult === 'function') {
- opts.onResult(result);
- }
+class EntryTransformer {
+ constructor(_settings) {
+ this._settings = _settings;
+ }
- if (isMatch === false) {
- result.isMatch = false;
- return returnObject ? result : false;
- }
+ getTransformer() {
+ return entry => this._transform(entry);
+ }
- if (isIgnored(input)) {
- if (typeof opts.onIgnore === 'function') {
- opts.onIgnore(result);
- }
+ _transform(entry) {
+ let filepath = entry.path;
- result.isMatch = false;
- return returnObject ? result : false;
+ if (this._settings.absolute) {
+ filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath);
+ filepath = utils$1.path.unixify(filepath);
}
- if (typeof opts.onMatch === 'function') {
- opts.onMatch(result);
+ if (this._settings.markDirectories && entry.dirent.isDirectory()) {
+ filepath += '/';
}
- return returnObject ? result : true;
- };
+ if (!this._settings.objectMode) {
+ return filepath;
+ }
- if (returnState) {
- matcher.state = state;
+ return Object.assign(Object.assign({}, entry), {
+ path: filepath
+ });
}
- return matcher;
-};
-/**
- * Test `input` with the given `regex`. This is used by the main
- * `picomatch()` function to test the input string.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.test(input, regex[, options]);
- *
- * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
- * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
- * ```
- * @param {String} `input` String to test.
- * @param {RegExp} `regex`
- * @return {Object} Returns an object with matching info.
- * @api public
- */
+}
+entry.default = EntryTransformer;
-picomatch.test = (input, regex, options, {
- glob,
- posix
-} = {}) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected input to be a string');
+Object.defineProperty(provider, "__esModule", {
+ value: true
+});
+const path$3 = require$$0__default$1["default"];
+const deep_1 = deep;
+const entry_1 = entry$1;
+const error_1 = error;
+const entry_2 = entry;
+
+class Provider {
+ constructor(_settings) {
+ this._settings = _settings;
+ this.errorFilter = new error_1.default(this._settings);
+ this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
+ this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
+ this.entryTransformer = new entry_2.default(this._settings);
}
- if (input === '') {
+ _getRootDirectory(task) {
+ return path$3.resolve(this._settings.cwd, task.base);
+ }
+
+ _getReaderOptions(task) {
+ const basePath = task.base === '.' ? '' : task.base;
return {
- isMatch: false,
- output: ''
+ basePath,
+ pathSegmentSeparator: '/',
+ concurrency: this._settings.concurrency,
+ deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
+ entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
+ errorFilter: this.errorFilter.getFilter(),
+ followSymbolicLinks: this._settings.followSymbolicLinks,
+ fs: this._settings.fs,
+ stats: this._settings.stats,
+ throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
+ transform: this.entryTransformer.getTransformer()
};
}
- const opts = options || {};
- const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
- let match = input === glob;
- let output = match && format ? format(input) : input;
+ _getMicromatchOptions() {
+ return {
+ dot: this._settings.dot,
+ matchBase: this._settings.baseNameMatch,
+ nobrace: !this._settings.braceExpansion,
+ nocase: !this._settings.caseSensitiveMatch,
+ noext: !this._settings.extglob,
+ noglobstar: !this._settings.globstar,
+ posix: true,
+ strictSlashes: false
+ };
+ }
- if (match === false) {
- output = format ? format(input) : input;
- match = output === glob;
+}
+
+provider.default = Provider;
+
+Object.defineProperty(async$6, "__esModule", {
+ value: true
+});
+const stream_1$2 = stream$2;
+const provider_1$2 = provider;
+
+class ProviderAsync extends provider_1$2.default {
+ constructor() {
+ super(...arguments);
+ this._reader = new stream_1$2.default(this._settings);
}
- if (match === false || opts.capture === true) {
- if (opts.matchBase === true || opts.basename === true) {
- match = picomatch.matchBase(input, regex, options, posix);
- } else {
- match = regex.exec(output);
+ read(task) {
+ const root = this._getRootDirectory(task);
+
+ const options = this._getReaderOptions(task);
+
+ const entries = [];
+ return new Promise((resolve, reject) => {
+ const stream = this.api(root, task, options);
+ stream.once('error', reject);
+ stream.on('data', entry => entries.push(options.transform(entry)));
+ stream.once('end', () => resolve(entries));
+ });
+ }
+
+ api(root, task, options) {
+ if (task.dynamic) {
+ return this._reader.dynamic(root, options);
}
+
+ return this._reader.static(task.patterns, options);
}
- return {
- isMatch: Boolean(match),
- match,
- output
- };
-};
-/**
- * Match the basename of a filepath.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.matchBase(input, glob[, options]);
- * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
- * ```
- * @param {String} `input` String to test.
- * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
- * @return {Boolean}
- * @api public
- */
-
-
-picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => {
- const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
- return regex.test(path__default['default'].basename(input));
-};
-/**
- * Returns true if **any** of the given glob `patterns` match the specified `string`.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.isMatch(string, patterns[, options]);
- *
- * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
- * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
- * ```
- * @param {String|Array} str The string to test.
- * @param {String|Array} patterns One or more glob patterns to use for matching.
- * @param {Object} [options] See available [options](#options).
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
-
+}
-picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
-/**
- * Parse a glob pattern to create the source string for a regular
- * expression.
- *
- * ```js
- * const picomatch = require('picomatch');
- * const result = picomatch.parse(pattern[, options]);
- * ```
- * @param {String} `pattern`
- * @param {Object} `options`
- * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
- * @api public
- */
+async$6.default = ProviderAsync;
+var stream = {};
-picomatch.parse = (pattern, options) => {
- if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
- return parse_1$1(pattern, Object.assign({}, options, {
- fastpaths: false
- }));
-};
-/**
- * Scan a glob pattern to separate the pattern into segments.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.scan(input[, options]);
- *
- * const result = picomatch.scan('!./foo/*.js');
- * console.log(result);
- * { prefix: '!./',
- * input: '!./foo/*.js',
- * start: 3,
- * base: 'foo',
- * glob: '*.js',
- * isBrace: false,
- * isBracket: false,
- * isGlob: true,
- * isExtglob: false,
- * isGlobstar: false,
- * negated: true }
- * ```
- * @param {String} `input` Glob pattern to scan.
- * @param {Object} `options`
- * @return {Object} Returns an object with
- * @api public
- */
+Object.defineProperty(stream, "__esModule", {
+ value: true
+});
+const stream_1$1 = require$$0__default$3["default"];
+const stream_2 = stream$2;
+const provider_1$1 = provider;
+class ProviderStream extends provider_1$1.default {
+ constructor() {
+ super(...arguments);
+ this._reader = new stream_2.default(this._settings);
+ }
-picomatch.scan = (input, options) => scan_1(input, options);
-/**
- * Create a regular expression from a parsed glob pattern.
- *
- * ```js
- * const picomatch = require('picomatch');
- * const state = picomatch.parse('*.js');
- * // picomatch.compileRe(state[, options]);
- *
- * console.log(picomatch.compileRe(state));
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {String} `state` The object returned from the `.parse` method.
- * @param {Object} `options`
- * @return {RegExp} Returns a regex created from the given pattern.
- * @api public
- */
+ read(task) {
+ const root = this._getRootDirectory(task);
+ const options = this._getReaderOptions(task);
-picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
- if (returnOutput === true) {
- return parsed.output;
+ const source = this.api(root, task, options);
+ const destination = new stream_1$1.Readable({
+ objectMode: true,
+ read: () => {}
+ });
+ source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
+ destination.once('close', () => source.destroy());
+ return destination;
}
- const opts = options || {};
- const prepend = opts.contains ? '' : '^';
- const append = opts.contains ? '' : '$';
- let source = `${prepend}(?:${parsed.output})${append}`;
+ api(root, task, options) {
+ if (task.dynamic) {
+ return this._reader.dynamic(root, options);
+ }
- if (parsed && parsed.negated === true) {
- source = `^(?!${source}).*$`;
+ return this._reader.static(task.patterns, options);
}
- const regex = picomatch.toRegex(source, options);
+}
- if (returnState === true) {
- regex.state = parsed;
- }
+stream.default = ProviderStream;
- return regex;
-};
+var sync$1 = {};
-picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
- if (!input || typeof input !== 'string') {
- throw new TypeError('Expected a non-empty string');
- }
+var sync = {};
- const opts = options || {};
- let parsed = {
- negated: false,
- fastpaths: true
- };
- let prefix = '';
- let output;
+Object.defineProperty(sync, "__esModule", {
+ value: true
+});
+const fsStat = out$3;
+const fsWalk = out$2;
+const reader_1 = reader;
- if (input.startsWith('./')) {
- input = input.slice(2);
- prefix = parsed.prefix = './';
+class ReaderSync extends reader_1.default {
+ constructor() {
+ super(...arguments);
+ this._walkSync = fsWalk.walkSync;
+ this._statSync = fsStat.statSync;
}
- if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
- output = parse_1$1.fastpaths(input, options);
+ dynamic(root, options) {
+ return this._walkSync(root, options);
}
- if (output === undefined) {
- parsed = parse_1$1(input, options);
- parsed.prefix = prefix + (parsed.prefix || '');
- } else {
- parsed.output = output;
- }
+ static(patterns, options) {
+ const entries = [];
- return picomatch.compileRe(parsed, options, returnOutput, returnState);
-};
-/**
- * Create a regular expression from the given regex source string.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.toRegex(source[, options]);
- *
- * const { output } = picomatch.parse('*.js');
- * console.log(picomatch.toRegex(output));
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {String} `source` Regular expression source string.
- * @param {Object} `options`
- * @return {RegExp}
- * @api public
- */
+ for (const pattern of patterns) {
+ const filepath = this._getFullEntryPath(pattern);
+ const entry = this._getEntry(filepath, pattern, options);
-picomatch.toRegex = (source, options) => {
- try {
- const opts = options || {};
- return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
- } catch (err) {
- if (options && options.debug === true) throw err;
- return /$^/;
+ if (entry === null || !options.entryFilter(entry)) {
+ continue;
+ }
+
+ entries.push(entry);
+ }
+
+ return entries;
}
-};
-/**
- * Picomatch constants.
- * @return {Object}
- */
+ _getEntry(filepath, pattern, options) {
+ try {
+ const stats = this._getStat(filepath);
-picomatch.constants = constants$1;
-/**
- * Expose "picomatch"
- */
+ return this._makeEntry(stats, pattern);
+ } catch (error) {
+ if (options.errorFilter(error)) {
+ return null;
+ }
-var picomatch_1 = picomatch;
+ throw error;
+ }
+ }
-var picomatch$1 = picomatch_1;
+ _getStat(filepath) {
+ return this._statSync(filepath, this._fsStatSettings);
+ }
-const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
-/**
- * Returns an array of strings that match one or more glob patterns.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm(list, patterns[, options]);
- *
- * console.log(mm(['a.js', 'a.txt'], ['*.js']));
- * //=> [ 'a.js' ]
- * ```
- * @param {String|Array<string>} list List of strings to match.
- * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
- * @param {Object} options See available [options](#options)
- * @return {Array} Returns an array of matches
- * @summary false
- * @api public
- */
+}
+sync.default = ReaderSync;
-const micromatch = (list, patterns, options) => {
- patterns = [].concat(patterns);
- list = [].concat(list);
- let omit = new Set();
- let keep = new Set();
- let items = new Set();
- let negatives = 0;
+Object.defineProperty(sync$1, "__esModule", {
+ value: true
+});
+const sync_1$1 = sync;
+const provider_1 = provider;
- let onResult = state => {
- items.add(state.output);
+class ProviderSync extends provider_1.default {
+ constructor() {
+ super(...arguments);
+ this._reader = new sync_1$1.default(this._settings);
+ }
- if (options && options.onResult) {
- options.onResult(state);
- }
- };
+ read(task) {
+ const root = this._getRootDirectory(task);
- for (let i = 0; i < patterns.length; i++) {
- let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, {
- onResult
- }), true);
- let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
- if (negated) negatives++;
+ const options = this._getReaderOptions(task);
- for (let item of list) {
- let matched = isMatch(item, true);
- let match = negated ? !matched.isMatch : matched.isMatch;
- if (!match) continue;
+ const entries = this.api(root, task, options);
+ return entries.map(options.transform);
+ }
- if (negated) {
- omit.add(matched.output);
- } else {
- omit.delete(matched.output);
- keep.add(matched.output);
- }
+ api(root, task, options) {
+ if (task.dynamic) {
+ return this._reader.dynamic(root, options);
}
+
+ return this._reader.static(task.patterns, options);
}
- let result = negatives === patterns.length ? [...items] : [...keep];
- let matches = result.filter(item => !omit.has(item));
+}
- if (options && matches.length === 0) {
- if (options.failglob === true) {
- throw new Error(`No matches found for "${patterns.join(', ')}"`);
- }
+sync$1.default = ProviderSync;
- if (options.nonull === true || options.nullglob === true) {
- return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
- }
- }
+var settings = {};
- return matches;
-};
-/**
- * Backwards compatibility
- */
+(function (exports) {
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
+ const fs = require$$0__default$4["default"];
+ const os = require$$0__default["default"];
+ /**
+ * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
+ * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
+ */
-micromatch.match = micromatch;
-/**
- * Returns a matcher function from the given glob `pattern` and `options`.
- * The returned function takes a string to match as its only argument and returns
- * true if the string is a match.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.matcher(pattern[, options]);
- *
- * const isMatch = mm.matcher('*.!(*a)');
- * console.log(isMatch('a.a')); //=> false
- * console.log(isMatch('a.b')); //=> true
- * ```
- * @param {String} `pattern` Glob pattern
- * @param {Object} `options`
- * @return {Function} Returns a matcher function.
- * @api public
- */
+ const CPU_COUNT = Math.max(os.cpus().length, 1);
+ exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
+ lstat: fs.lstat,
+ lstatSync: fs.lstatSync,
+ stat: fs.stat,
+ statSync: fs.statSync,
+ readdir: fs.readdir,
+ readdirSync: fs.readdirSync
+ };
-micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
-/**
- * Returns true if **any** of the given glob `patterns` match the specified `string`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.isMatch(string, patterns[, options]);
- *
- * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
- * console.log(mm.isMatch('a.a', 'b.*')); //=> false
- * ```
- * @param {String} str The string to test.
- * @param {String|Array} patterns One or more glob patterns to use for matching.
- * @param {Object} [options] See available [options](#options).
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
+ class Settings {
+ constructor(_options = {}) {
+ this._options = _options;
+ this.absolute = this._getValue(this._options.absolute, false);
+ this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
+ this.braceExpansion = this._getValue(this._options.braceExpansion, true);
+ this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
+ this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
+ this.cwd = this._getValue(this._options.cwd, process.cwd());
+ this.deep = this._getValue(this._options.deep, Infinity);
+ this.dot = this._getValue(this._options.dot, false);
+ this.extglob = this._getValue(this._options.extglob, true);
+ this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
+ this.fs = this._getFileSystemMethods(this._options.fs);
+ this.globstar = this._getValue(this._options.globstar, true);
+ this.ignore = this._getValue(this._options.ignore, []);
+ this.markDirectories = this._getValue(this._options.markDirectories, false);
+ this.objectMode = this._getValue(this._options.objectMode, false);
+ this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
+ this.onlyFiles = this._getValue(this._options.onlyFiles, true);
+ this.stats = this._getValue(this._options.stats, false);
+ this.suppressErrors = this._getValue(this._options.suppressErrors, false);
+ this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
+ this.unique = this._getValue(this._options.unique, true);
+ if (this.onlyDirectories) {
+ this.onlyFiles = false;
+ }
-micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
-/**
- * Backwards compatibility
- */
+ if (this.stats) {
+ this.objectMode = true;
+ }
+ }
+ _getValue(option, value) {
+ return option === undefined ? value : option;
+ }
-micromatch.any = micromatch.isMatch;
-/**
- * Returns a list of strings that _**do not match any**_ of the given `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.not(list, patterns[, options]);
- *
- * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
- * //=> ['b.b', 'c.c']
- * ```
- * @param {Array} `list` Array of strings to match.
- * @param {String|Array} `patterns` One or more glob pattern to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Array} Returns an array of strings that **do not match** the given patterns.
- * @api public
- */
+ _getFileSystemMethods(methods = {}) {
+ return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
+ }
-micromatch.not = (list, patterns, options = {}) => {
- patterns = [].concat(patterns).map(String);
- let result = new Set();
- let items = [];
+ }
- let onResult = state => {
- if (options.onResult) options.onResult(state);
- items.push(state.output);
- };
+ exports.default = Settings;
+})(settings);
- let matches = micromatch(list, patterns, Object.assign({}, options, {
- onResult
- }));
+const taskManager = tasks;
+const async_1 = async$6;
+const stream_1 = stream;
+const sync_1 = sync$1;
+const settings_1 = settings;
+const utils = utils$k;
- for (let item of items) {
- if (!matches.includes(item)) {
- result.add(item);
- }
+async function FastGlob(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, async_1.default, options);
+ const result = await Promise.all(works);
+ return utils.array.flatten(result);
+} // https://github.com/typescript-eslint/typescript-eslint/issues/60
+// eslint-disable-next-line no-redeclare
+
+
+(function (FastGlob) {
+ function sync(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, sync_1.default, options);
+ return utils.array.flatten(works);
}
- return [...result];
-};
-/**
- * Returns true if the given `string` contains the given pattern. Similar
- * to [.isMatch](#isMatch) but the pattern can match any part of the string.
- *
- * ```js
- * var mm = require('micromatch');
- * // mm.contains(string, pattern[, options]);
- *
- * console.log(mm.contains('aa/bb/cc', '*b'));
- * //=> true
- * console.log(mm.contains('aa/bb/cc', '*d'));
- * //=> false
- * ```
- * @param {String} `str` The string to match.
- * @param {String|Array} `patterns` Glob pattern to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if the patter matches any part of `str`.
- * @api public
- */
+ FastGlob.sync = sync;
+ function stream(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, stream_1.default, options);
+ /**
+ * The stream returned by the provider cannot work with an asynchronous iterator.
+ * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
+ * This affects performance (+25%). I don't see best solution right now.
+ */
-micromatch.contains = (str, pattern, options) => {
- if (typeof str !== 'string') {
- throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
+ return utils.stream.merge(works);
}
- if (Array.isArray(pattern)) {
- return pattern.some(p => micromatch.contains(str, p, options));
+ FastGlob.stream = stream;
+
+ function generateTasks(source, options) {
+ assertPatternsInput(source);
+ const patterns = [].concat(source);
+ const settings = new settings_1.default(options);
+ return taskManager.generate(patterns, settings);
}
- if (typeof pattern === 'string') {
- if (isEmptyString(str) || isEmptyString(pattern)) {
- return false;
- }
+ FastGlob.generateTasks = generateTasks;
- if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
- return true;
- }
+ function isDynamicPattern(source, options) {
+ assertPatternsInput(source);
+ const settings = new settings_1.default(options);
+ return utils.pattern.isDynamicPattern(source, settings);
}
- return micromatch.isMatch(str, pattern, Object.assign({}, options, {
- contains: true
- }));
-};
-/**
- * Filter the keys of the given object with the given `glob` pattern
- * and `options`. Does not attempt to match nested keys. If you need this feature,
- * use [glob-object][] instead.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.matchKeys(object, patterns[, options]);
- *
- * const obj = { aa: 'a', ab: 'b', ac: 'c' };
- * console.log(mm.matchKeys(obj, '*b'));
- * //=> { ab: 'b' }
- * ```
- * @param {Object} `object` The object with keys to filter.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Object} Returns an object with only keys that match the given patterns.
- * @api public
- */
+ FastGlob.isDynamicPattern = isDynamicPattern;
+
+ function escapePath(source) {
+ assertPatternsInput(source);
+ return utils.path.escape(source);
+ }
+ FastGlob.escapePath = escapePath;
+})(FastGlob || (FastGlob = {}));
-micromatch.matchKeys = (obj, patterns, options) => {
- if (!utils$1.isObject(obj)) {
- throw new TypeError('Expected the first argument to be an object');
+function getWorks(source, _Provider, options) {
+ const patterns = [].concat(source);
+ const settings = new settings_1.default(options);
+ const tasks = taskManager.generate(patterns, settings);
+ const provider = new _Provider(settings);
+ return tasks.map(provider.read, provider);
+}
+
+function assertPatternsInput(input) {
+ const source = [].concat(input);
+ const isValidSource = source.every(item => utils.string.isString(item) && !utils.string.isEmpty(item));
+
+ if (!isValidSource) {
+ throw new TypeError('Patterns must be a string (non empty) or an array of strings');
}
+}
- let keys = micromatch(Object.keys(obj), patterns, options);
- let res = {};
+var out = FastGlob;
- for (let key of keys) res[key] = obj[key];
+const path$2 = require$$0__default$1["default"];
+const {
+ promises: fs$1
+} = require$$0__default$4["default"];
+const fastGlob = out;
+/** @typedef {import('./context').Context} Context */
- return res;
-};
/**
- * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.some(list, patterns[, options]);
- *
- * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
- * // true
- * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
- * // false
- * ```
- * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
+ * @param {Context} context
*/
+async function* expandPatterns$1(context) {
+ const cwd = process.cwd();
+ const seen = new Set();
+ let noResults = true;
-micromatch.some = (list, patterns, options) => {
- let items = [].concat(list);
+ for await (const pathOrError of expandPatternsInternal(context)) {
+ noResults = false;
- for (let pattern of [].concat(patterns)) {
- let isMatch = picomatch$1(String(pattern), options);
+ if (typeof pathOrError !== "string") {
+ yield pathOrError;
+ continue;
+ }
- if (items.some(item => isMatch(item))) {
- return true;
+ const relativePath = path$2.relative(cwd, pathOrError); // filter out duplicates
+
+ if (seen.has(relativePath)) {
+ continue;
}
+
+ seen.add(relativePath);
+ yield relativePath;
}
- return false;
-};
+ if (noResults && context.argv["error-on-unmatched-pattern"] !== false) {
+ // If there was no files and no other errors, let's yield a general error.
+ yield {
+ error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`
+ };
+ }
+}
/**
- * Returns true if every string in the given `list` matches
- * any of the given glob `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.every(list, patterns[, options]);
- *
- * console.log(mm.every('foo.js', ['foo.js']));
- * // true
- * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
- * // true
- * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
- * // false
- * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
- * // false
- * ```
- * @param {String|Array} `list` The string or array of strings to test.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
+ * @param {Context} context
*/
-micromatch.every = (list, patterns, options) => {
- let items = [].concat(list);
-
- for (let pattern of [].concat(patterns)) {
- let isMatch = picomatch$1(String(pattern), options);
+async function* expandPatternsInternal(context) {
+ // Ignores files in version control systems directories and `node_modules`
+ const silentlyIgnoredDirs = [".git", ".svn", ".hg"];
- if (!items.every(item => isMatch(item))) {
- return false;
- }
+ if (context.argv["with-node-modules"] !== true) {
+ silentlyIgnoredDirs.push("node_modules");
}
- return true;
-};
-/**
- * Returns true if **all** of the given `patterns` match
- * the specified string.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.all(string, patterns[, options]);
- *
- * console.log(mm.all('foo.js', ['foo.js']));
- * // true
- *
- * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
- * // false
- *
- * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
- * // true
- *
- * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
- * // true
- * ```
- * @param {String|Array} `str` The string to test.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
+ const globOptions = {
+ dot: true,
+ ignore: silentlyIgnoredDirs.map(dir => "**/" + dir)
+ };
+ let supportedFilesGlob;
+ const cwd = process.cwd();
+ /** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */
+ const entries = [];
-micromatch.all = (str, patterns, options) => {
- if (typeof str !== 'string') {
- throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
+ for (const pattern of context.filePatterns) {
+ const absolutePath = path$2.resolve(cwd, pattern);
+
+ if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) {
+ continue;
+ }
+
+ const stat = await statSafe(absolutePath);
+
+ if (stat) {
+ if (stat.isFile()) {
+ entries.push({
+ type: "file",
+ glob: escapePathForGlob(fixWindowsSlashes$1(pattern)),
+ input: pattern
+ });
+ } else if (stat.isDirectory()) {
+ /*
+ 1. Remove trailing `/`, `fast-glob` can't find files for `src//*.js` pattern
+ 2. Cleanup dirname, when glob `src/../*.js` pattern with `fast-glob`,
+ it returns files like 'src/../index.js'
+ */
+ const relativePath = path$2.relative(cwd, absolutePath) || ".";
+ entries.push({
+ type: "dir",
+ glob: escapePathForGlob(fixWindowsSlashes$1(relativePath)) + "/" + getSupportedFilesGlob(),
+ input: pattern
+ });
+ }
+ } else if (pattern[0] === "!") {
+ // convert negative patterns to `ignore` entries
+ globOptions.ignore.push(fixWindowsSlashes$1(pattern.slice(1)));
+ } else {
+ entries.push({
+ type: "glob",
+ glob: fixWindowsSlashes$1(pattern),
+ input: pattern
+ });
+ }
}
- return [].concat(patterns).every(p => picomatch$1(p, options)(str));
-};
-/**
- * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.capture(pattern, string[, options]);
- *
- * console.log(mm.capture('test/*.js', 'test/foo.js'));
- * //=> ['foo']
- * console.log(mm.capture('test/*.js', 'foo/bar.css'));
- * //=> null
- * ```
- * @param {String} `glob` Glob pattern to use for matching.
- * @param {String} `input` String to match
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
- * @api public
- */
+ for (const {
+ type,
+ glob,
+ input
+ } of entries) {
+ let result;
+
+ try {
+ result = await fastGlob(glob, globOptions);
+ } catch ({
+ message
+ }) {
+ /* istanbul ignore next */
+ yield {
+ error: `${errorMessages.globError[type]}: ${input}\n${message}`
+ };
+ /* istanbul ignore next */
+ continue;
+ }
-micromatch.capture = (glob, input, options) => {
- let posix = utils$1.isWindows(options);
- let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, {
- capture: true
- }));
- let match = regex.exec(posix ? utils$1.toPosixSlashes(input) : input);
+ if (result.length === 0) {
+ if (context.argv["error-on-unmatched-pattern"] !== false) {
+ yield {
+ error: `${errorMessages.emptyResults[type]}: "${input}".`
+ };
+ }
+ } else {
+ yield* sortPaths(result);
+ }
+ }
- if (match) {
- return match.slice(1).map(v => v === void 0 ? '' : v);
+ function getSupportedFilesGlob() {
+ if (!supportedFilesGlob) {
+ const extensions = context.languages.flatMap(lang => lang.extensions || []);
+ const filenames = context.languages.flatMap(lang => lang.filenames || []);
+ supportedFilesGlob = `**/{${[...extensions.map(ext => "*" + (ext[0] === "." ? ext : "." + ext)), ...filenames]}}`;
+ }
+
+ return supportedFilesGlob;
+ }
+}
+
+const errorMessages = {
+ globError: {
+ file: "Unable to resolve file",
+ dir: "Unable to expand directory",
+ glob: "Unable to expand glob pattern"
+ },
+ emptyResults: {
+ file: "Explicitly specified file was ignored due to negative glob patterns",
+ dir: "No supported files were found in the directory",
+ glob: "No files matching the pattern were found"
}
};
/**
- * Create a regular expression from the given glob `pattern`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.makeRe(pattern[, options]);
- *
- * console.log(mm.makeRe('*.js'));
- * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
- * ```
- * @param {String} `pattern` A glob pattern to convert to regex.
- * @param {Object} `options`
- * @return {RegExp} Returns a regex created from the given pattern.
- * @api public
+ * @param {string} absolutePath
+ * @param {string} cwd
+ * @param {string[]} ignoredDirectories
*/
-
-micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
+function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) {
+ return path$2.relative(cwd, absolutePath).split(path$2.sep).some(dir => ignoredDirectories.includes(dir));
+}
/**
- * Scan a glob pattern to separate the pattern into segments. Used
- * by the [split](#split) method.
- *
- * ```js
- * const mm = require('micromatch');
- * const state = mm.scan(pattern[, options]);
- * ```
- * @param {String} `pattern`
- * @param {Object} `options`
- * @return {Object} Returns an object with
- * @api public
+ * @param {string[]} paths
*/
-micromatch.scan = (...args) => picomatch$1.scan(...args);
+function sortPaths(paths) {
+ return paths.sort((a, b) => a.localeCompare(b));
+}
/**
- * Parse a glob pattern to create the source string for a regular
- * expression.
- *
- * ```js
- * const mm = require('micromatch');
- * const state = mm(pattern[, options]);
- * ```
- * @param {String} `glob`
- * @param {Object} `options`
- * @return {Object} Returns an object with useful properties and output to be used as regex source string.
- * @api public
+ * Get stats of a given path.
+ * @param {string} filePath The path to target file.
+ * @returns {Promise<import('fs').Stats | undefined>} The stats.
*/
-micromatch.parse = (patterns, options) => {
- let res = [];
-
- for (let pattern of [].concat(patterns || [])) {
- for (let str of braces_1(String(pattern), options)) {
- res.push(picomatch$1.parse(str, options));
+async function statSafe(filePath) {
+ try {
+ return await fs$1.stat(filePath);
+ } catch (error) {
+ /* istanbul ignore next */
+ if (error.code !== "ENOENT") {
+ throw error;
}
}
-
- return res;
-};
+}
/**
- * Process the given brace `pattern`.
- *
- * ```js
- * const { braces } = require('micromatch');
- * console.log(braces('foo/{a,b,c}/bar'));
- * //=> [ 'foo/(a|b|c)/bar' ]
- *
- * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
- * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
- * ```
- * @param {String} `pattern` String with brace pattern to process.
- * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
- * @return {Array}
- * @api public
+ * This function should be replaced with `fastGlob.escapePath` when these issues are fixed:
+ * - https://github.com/mrmlnc/fast-glob/issues/261
+ * - https://github.com/mrmlnc/fast-glob/issues/262
+ * @param {string} path
*/
-micromatch.braces = (pattern, options) => {
- if (typeof pattern !== 'string') throw new TypeError('Expected a string');
-
- if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
- return [pattern];
- }
+function escapePathForGlob(path) {
+ return fastGlob.escapePath(path.replace(/\\/g, "\0") // Workaround for fast-glob#262 (part 1)
+ ).replace(/\\!/g, "@(!)") // Workaround for fast-glob#261
+ .replace(/\0/g, "@(\\\\)"); // Workaround for fast-glob#262 (part 2)
+}
- return braces_1(pattern, options);
-};
+const isWindows = path$2.sep === "\\";
/**
- * Expand braces
+ * Using backslashes in globs is probably not okay, but not accepting
+ * backslashes as path separators on Windows is even more not okay.
+ * https://github.com/prettier/prettier/pull/6776#discussion_r380723717
+ * https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows
+ * @param {string} pattern
*/
+function fixWindowsSlashes$1(pattern) {
+ return isWindows ? pattern.replace(/\\/g, "/") : pattern;
+}
-micromatch.braceExpand = (pattern, options) => {
- if (typeof pattern !== 'string') throw new TypeError('Expected a string');
- return micromatch.braces(pattern, Object.assign({}, options, {
- expand: true
- }));
+var expandPatterns_1 = {
+ expandPatterns: expandPatterns$1,
+ fixWindowsSlashes: fixWindowsSlashes$1
};
-/**
- * Expose micromatch
- */
+var iterators = {};
-var micromatch_1 = micromatch;
+var wellKnownSymbol$2 = wellKnownSymbol$7;
+var Iterators$1 = iterators;
-var pattern = createCommonjsModule(function (module, exports) {
+var ITERATOR$1 = wellKnownSymbol$2('iterator');
+var ArrayPrototype$1 = Array.prototype;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
- const GLOBSTAR = '**';
- const ESCAPE_SYMBOL = '\\';
- const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
- const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
- const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
- const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
- const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
-
- function isStaticPattern(pattern, options = {}) {
- return !isDynamicPattern(pattern, options);
- }
-
- exports.isStaticPattern = isStaticPattern;
-
- function isDynamicPattern(pattern, options = {}) {
- /**\r
- * A special case with an empty string is necessary for matching patterns that start with a forward slash.\r
- * An empty string cannot be a dynamic pattern.\r
- * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.\r
- */
- if (pattern === '') {
- return false;
- }
- /**\r
- * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check\r
- * filepath directly (without read directory).\r
- */
+// check on default Array iterator
+var isArrayIteratorMethod$1 = function (it) {
+ return it !== undefined && (Iterators$1.Array === it || ArrayPrototype$1[ITERATOR$1] === it);
+};
+var classof = classof$4;
+var getMethod$1 = getMethod$3;
+var Iterators = iterators;
+var wellKnownSymbol$1 = wellKnownSymbol$7;
- if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
- return true;
- }
+var ITERATOR = wellKnownSymbol$1('iterator');
- if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
- return true;
- }
+var getIteratorMethod$2 = function (it) {
+ if (it != undefined) return getMethod$1(it, ITERATOR)
+ || getMethod$1(it, '@@iterator')
+ || Iterators[classof(it)];
+};
- if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
- return true;
- }
+var global$2 = global$r;
+var call$2 = functionCall;
+var aCallable = aCallable$5;
+var anObject$4 = anObject$7;
+var tryToString$1 = tryToString$3;
+var getIteratorMethod$1 = getIteratorMethod$2;
- if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
- return true;
- }
+var TypeError$2 = global$2.TypeError;
- return false;
- }
+var getIterator$1 = function (argument, usingIterator) {
+ var iteratorMethod = arguments.length < 2 ? getIteratorMethod$1(argument) : usingIterator;
+ if (aCallable(iteratorMethod)) return anObject$4(call$2(iteratorMethod, argument));
+ throw TypeError$2(tryToString$1(argument) + ' is not iterable');
+};
- exports.isDynamicPattern = isDynamicPattern;
+var call$1 = functionCall;
+var anObject$3 = anObject$7;
+var getMethod = getMethod$3;
- function convertToPositivePattern(pattern) {
- return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
+var iteratorClose$1 = function (iterator, kind, value) {
+ var innerResult, innerError;
+ anObject$3(iterator);
+ try {
+ innerResult = getMethod(iterator, 'return');
+ if (!innerResult) {
+ if (kind === 'throw') throw value;
+ return value;
+ }
+ innerResult = call$1(innerResult, iterator);
+ } catch (error) {
+ innerError = true;
+ innerResult = error;
}
+ if (kind === 'throw') throw value;
+ if (innerError) throw innerResult;
+ anObject$3(innerResult);
+ return value;
+};
- exports.convertToPositivePattern = convertToPositivePattern;
-
- function convertToNegativePattern(pattern) {
- return '!' + pattern;
- }
+var global$1 = global$r;
+var bind = functionBindContext;
+var call = functionCall;
+var anObject$2 = anObject$7;
+var tryToString = tryToString$3;
+var isArrayIteratorMethod = isArrayIteratorMethod$1;
+var lengthOfArrayLike$1 = lengthOfArrayLike$6;
+var isPrototypeOf = objectIsPrototypeOf;
+var getIterator = getIterator$1;
+var getIteratorMethod = getIteratorMethod$2;
+var iteratorClose = iteratorClose$1;
+
+var TypeError$1 = global$1.TypeError;
+
+var Result = function (stopped, result) {
+ this.stopped = stopped;
+ this.result = result;
+};
- exports.convertToNegativePattern = convertToNegativePattern;
+var ResultPrototype = Result.prototype;
- function isNegativePattern(pattern) {
- return pattern.startsWith('!') && pattern[1] !== '(';
- }
+var iterate$1 = function (iterable, unboundFunction, options) {
+ var that = options && options.that;
+ var AS_ENTRIES = !!(options && options.AS_ENTRIES);
+ var IS_ITERATOR = !!(options && options.IS_ITERATOR);
+ var INTERRUPTED = !!(options && options.INTERRUPTED);
+ var fn = bind(unboundFunction, that);
+ var iterator, iterFn, index, length, result, next, step;
+
+ var stop = function (condition) {
+ if (iterator) iteratorClose(iterator, 'normal', condition);
+ return new Result(true, condition);
+ };
- exports.isNegativePattern = isNegativePattern;
+ var callFn = function (value) {
+ if (AS_ENTRIES) {
+ anObject$2(value);
+ return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
+ } return INTERRUPTED ? fn(value, stop) : fn(value);
+ };
- function isPositivePattern(pattern) {
- return !isNegativePattern(pattern);
+ if (IS_ITERATOR) {
+ iterator = iterable;
+ } else {
+ iterFn = getIteratorMethod(iterable);
+ if (!iterFn) throw TypeError$1(tryToString(iterable) + ' is not iterable');
+ // optimisation for array iterators
+ if (isArrayIteratorMethod(iterFn)) {
+ for (index = 0, length = lengthOfArrayLike$1(iterable); length > index; index++) {
+ result = callFn(iterable[index]);
+ if (result && isPrototypeOf(ResultPrototype, result)) return result;
+ } return new Result(false);
+ }
+ iterator = getIterator(iterable, iterFn);
}
- exports.isPositivePattern = isPositivePattern;
+ next = iterator.next;
+ while (!(step = call(next, iterator)).done) {
+ try {
+ result = callFn(step.value);
+ } catch (error) {
+ iteratorClose(iterator, 'throw', error);
+ }
+ if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
+ } return new Result(false);
+};
+
+var toPropertyKey = toPropertyKey$3;
+var definePropertyModule$2 = objectDefineProperty;
+var createPropertyDescriptor = createPropertyDescriptor$3;
- function getNegativePatterns(patterns) {
- return patterns.filter(isNegativePattern);
- }
+var createProperty$1 = function (object, key, value) {
+ var propertyKey = toPropertyKey(key);
+ if (propertyKey in object) definePropertyModule$2.f(object, propertyKey, createPropertyDescriptor(0, value));
+ else object[propertyKey] = value;
+};
- exports.getNegativePatterns = getNegativePatterns;
+var $$1 = _export;
+var iterate = iterate$1;
+var createProperty = createProperty$1;
- function getPositivePatterns(patterns) {
- return patterns.filter(isPositivePattern);
+// `Object.fromEntries` method
+// https://github.com/tc39/proposal-object-from-entries
+$$1({ target: 'Object', stat: true }, {
+ fromEntries: function fromEntries(iterable) {
+ var obj = {};
+ iterate(iterable, function (k, v) {
+ createProperty(obj, k, v);
+ }, { AS_ENTRIES: true });
+ return obj;
}
+});
- exports.getPositivePatterns = getPositivePatterns;
+/*!
+ * dashify <https://github.com/jonschlinkert/dashify>
+ *
+ * Copyright (c) 2015-2017, Jon Schlinkert.
+ * Released under the MIT License.
+ */
- function getBaseDirectory(pattern) {
- return globParent(pattern, {
- flipBackslashes: false
- });
- }
+var dashify$2 = (str, options) => {
+ if (typeof str !== 'string') throw new TypeError('expected a string');
+ return str.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\W/g, m => /[À-ž]/.test(m) ? m : '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, m => options && options.condense ? '-' : m).toLowerCase();
+};
- exports.getBaseDirectory = getBaseDirectory;
+var minimist$3 = function (args, opts) {
+ if (!opts) opts = {};
+ var flags = {
+ bools: {},
+ strings: {},
+ unknownFn: null
+ };
- function hasGlobStar(pattern) {
- return pattern.includes(GLOBSTAR);
+ if (typeof opts['unknown'] === 'function') {
+ flags.unknownFn = opts['unknown'];
}
- exports.hasGlobStar = hasGlobStar;
-
- function endsWithSlashGlobStar(pattern) {
- return pattern.endsWith('/' + GLOBSTAR);
+ if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
+ flags.allBools = true;
+ } else {
+ [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
+ flags.bools[key] = true;
+ });
}
- exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
+ var aliases = {};
+ Object.keys(opts.alias || {}).forEach(function (key) {
+ aliases[key] = [].concat(opts.alias[key]);
+ aliases[key].forEach(function (x) {
+ aliases[x] = [key].concat(aliases[key].filter(function (y) {
+ return x !== y;
+ }));
+ });
+ });
+ [].concat(opts.string).filter(Boolean).forEach(function (key) {
+ flags.strings[key] = true;
- function isAffectDepthOfReadingPattern(pattern) {
- const basename = path__default['default'].basename(pattern);
- return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
- }
+ if (aliases[key]) {
+ flags.strings[aliases[key]] = true;
+ }
+ });
+ var defaults = opts['default'] || {};
+ var argv = {
+ _: []
+ };
+ Object.keys(flags.bools).forEach(function (key) {
+ setArg(key, defaults[key] === undefined ? false : defaults[key]);
+ });
+ var notFlags = [];
- exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
+ if (args.indexOf('--') !== -1) {
+ notFlags = args.slice(args.indexOf('--') + 1);
+ args = args.slice(0, args.indexOf('--'));
+ }
- function expandPatternsWithBraceExpansion(patterns) {
- return patterns.reduce((collection, pattern) => {
- return collection.concat(expandBraceExpansion(pattern));
- }, []);
+ function argDefined(key, arg) {
+ return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key];
}
- exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
+ function setArg(key, val, arg) {
+ if (arg && flags.unknownFn && !argDefined(key, arg)) {
+ if (flags.unknownFn(arg) === false) return;
+ }
- function expandBraceExpansion(pattern) {
- return micromatch_1.braces(pattern, {
- expand: true,
- nodupes: true
+ var value = !flags.strings[key] && isNumber(val) ? Number(val) : val;
+ setKey(argv, key.split('.'), value);
+ (aliases[key] || []).forEach(function (x) {
+ setKey(argv, x.split('.'), value);
});
}
- exports.expandBraceExpansion = expandBraceExpansion;
-
- function getPatternParts(pattern, options) {
- let {
- parts
- } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), {
- parts: true
- }));
- /**\r
- * The scan method returns an empty array in some cases.\r
- * See micromatch/picomatch#58 for more details.\r
- */
+ function setKey(obj, keys, value) {
+ var o = obj;
- if (parts.length === 0) {
- parts = [pattern];
+ for (var i = 0; i < keys.length - 1; i++) {
+ var key = keys[i];
+ if (key === '__proto__') return;
+ if (o[key] === undefined) o[key] = {};
+ if (o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype) o[key] = {};
+ if (o[key] === Array.prototype) o[key] = [];
+ o = o[key];
}
- /**\r
- * The scan method does not return an empty part for the pattern with a forward slash.\r
- * This is another part of micromatch/picomatch#58.\r
- */
+ var key = keys[keys.length - 1];
+ if (key === '__proto__') return;
+ if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {};
+ if (o === Array.prototype) o = [];
- if (parts[0].startsWith('/')) {
- parts[0] = parts[0].slice(1);
- parts.unshift('');
+ if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
+ o[key] = value;
+ } else if (Array.isArray(o[key])) {
+ o[key].push(value);
+ } else {
+ o[key] = [o[key], value];
}
-
- return parts;
}
- exports.getPatternParts = getPatternParts;
-
- function makeRe(pattern, options) {
- return micromatch_1.makeRe(pattern, options);
+ function aliasIsBoolean(key) {
+ return aliases[key].some(function (x) {
+ return flags.bools[x];
+ });
}
- exports.makeRe = makeRe;
-
- function convertPatternsToRe(patterns, options) {
- return patterns.map(pattern => makeRe(pattern, options));
- }
+ for (var i = 0; i < args.length; i++) {
+ var arg = args[i];
- exports.convertPatternsToRe = convertPatternsToRe;
+ if (/^--.+=/.test(arg)) {
+ // Using [\s\S] instead of . because js doesn't support the
+ // 'dotall' regex modifier. See:
+ // http://stackoverflow.com/a/1068308/13216
+ var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
+ var key = m[1];
+ var value = m[2];
- function matchAny(entry, patternsRe) {
- return patternsRe.some(patternRe => patternRe.test(entry));
- }
+ if (flags.bools[key]) {
+ value = value !== 'false';
+ }
- exports.matchAny = matchAny;
-});
+ setArg(key, value, arg);
+ } else if (/^--no-.+/.test(arg)) {
+ var key = arg.match(/^--no-(.+)/)[1];
+ setArg(key, false, arg);
+ } else if (/^--.+/.test(arg)) {
+ var key = arg.match(/^--(.+)/)[1];
+ var next = args[i + 1];
-/*
- * merge2
- * https://github.com/teambition/merge2
- *
- * Copyright (c) 2014-2020 Teambition
- * Licensed under the MIT license.
- */
+ if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
+ setArg(key, next, arg);
+ i++;
+ } else if (/^(true|false)$/.test(next)) {
+ setArg(key, next === 'true', arg);
+ i++;
+ } else {
+ setArg(key, flags.strings[key] ? '' : true, arg);
+ }
+ } else if (/^-[^-]+/.test(arg)) {
+ var letters = arg.slice(1, -1).split('');
+ var broken = false;
+ for (var j = 0; j < letters.length; j++) {
+ var next = arg.slice(j + 2);
-const PassThrough = stream_1__default['default'].PassThrough;
-const slice = Array.prototype.slice;
-var merge2_1 = merge2;
+ if (next === '-') {
+ setArg(letters[j], next, arg);
+ continue;
+ }
-function merge2() {
- const streamsQueue = [];
- const args = slice.call(arguments);
- let merging = false;
- let options = args[args.length - 1];
+ if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
+ setArg(letters[j], next.split('=')[1], arg);
+ broken = true;
+ break;
+ }
- if (options && !Array.isArray(options) && options.pipe == null) {
- args.pop();
- } else {
- options = {};
- }
+ if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
+ setArg(letters[j], next, arg);
+ broken = true;
+ break;
+ }
- const doEnd = options.end !== false;
- const doPipeError = options.pipeError === true;
+ if (letters[j + 1] && letters[j + 1].match(/\W/)) {
+ setArg(letters[j], arg.slice(j + 2), arg);
+ broken = true;
+ break;
+ } else {
+ setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
+ }
+ }
- if (options.objectMode == null) {
- options.objectMode = true;
- }
+ var key = arg.slice(-1)[0];
- if (options.highWaterMark == null) {
- options.highWaterMark = 64 * 1024;
- }
+ if (!broken && key !== '-') {
+ if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
+ setArg(key, args[i + 1], arg);
+ i++;
+ } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
+ setArg(key, args[i + 1] === 'true', arg);
+ i++;
+ } else {
+ setArg(key, flags.strings[key] ? '' : true, arg);
+ }
+ }
+ } else {
+ if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
+ argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
+ }
- const mergedStream = PassThrough(options);
+ if (opts.stopEarly) {
+ argv._.push.apply(argv._, args.slice(i + 1));
- function addStream() {
- for (let i = 0, len = arguments.length; i < len; i++) {
- streamsQueue.push(pauseStreams(arguments[i], options));
+ break;
+ }
}
-
- mergeStream();
- return this;
}
- function mergeStream() {
- if (merging) {
- return;
+ Object.keys(defaults).forEach(function (key) {
+ if (!hasKey(argv, key.split('.'))) {
+ setKey(argv, key.split('.'), defaults[key]);
+ (aliases[key] || []).forEach(function (x) {
+ setKey(argv, x.split('.'), defaults[key]);
+ });
}
+ });
- merging = true;
- let streams = streamsQueue.shift();
-
- if (!streams) {
- process.nextTick(endStream);
- return;
- }
+ if (opts['--']) {
+ argv['--'] = new Array();
+ notFlags.forEach(function (key) {
+ argv['--'].push(key);
+ });
+ } else {
+ notFlags.forEach(function (key) {
+ argv._.push(key);
+ });
+ }
- if (!Array.isArray(streams)) {
- streams = [streams];
- }
+ return argv;
+};
- let pipesCount = streams.length + 1;
-
- function next() {
- if (--pipesCount > 0) {
- return;
- }
-
- merging = false;
- mergeStream();
- }
-
- function pipe(stream) {
- function onend() {
- stream.removeListener('merge2UnpipeEnd', onend);
- stream.removeListener('end', onend);
-
- if (doPipeError) {
- stream.removeListener('error', onerror);
- }
-
- next();
- }
+function hasKey(obj, keys) {
+ var o = obj;
+ keys.slice(0, -1).forEach(function (key) {
+ o = o[key] || {};
+ });
+ var key = keys[keys.length - 1];
+ return key in o;
+}
- function onerror(err) {
- mergedStream.emit('error', err);
- } // skip ended stream
+function isNumber(x) {
+ if (typeof x === 'number') return true;
+ if (/^0x[0-9a-f]+$/i.test(x)) return true;
+ return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
+}
+const minimist$2 = minimist$3;
+const PLACEHOLDER = null;
+/**
+ * unspecified boolean flag without default value is parsed as `undefined` instead of `false`
+ */
- if (stream._readableState.endEmitted) {
- return next();
- }
+var minimist_1 = function (args, options) {
+ const boolean = options.boolean || [];
+ const defaults = options.default || {};
+ const booleanWithoutDefault = boolean.filter(key => !(key in defaults));
+ const newDefaults = Object.assign(Object.assign({}, defaults), Object.fromEntries(booleanWithoutDefault.map(key => [key, PLACEHOLDER])));
+ const parsed = minimist$2(args, Object.assign(Object.assign({}, options), {}, {
+ default: newDefaults
+ }));
+ return Object.fromEntries(Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER));
+};
- stream.on('merge2UnpipeEnd', onend);
- stream.on('end', onend);
+/**
+ * A specialized version of `baseAggregator` for arrays.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} setter The function to set `accumulator` values.
+ * @param {Function} iteratee The iteratee to transform keys.
+ * @param {Object} accumulator The initial aggregated object.
+ * @returns {Function} Returns `accumulator`.
+ */
- if (doPipeError) {
- stream.on('error', onerror);
- }
+function arrayAggregator$1(array, setter, iteratee, accumulator) {
+ var index = -1,
+ length = array == null ? 0 : array.length;
- stream.pipe(mergedStream, {
- end: false
- }); // compatible for old stream
+ while (++index < length) {
+ var value = array[index];
+ setter(accumulator, value, iteratee(value), array);
+ }
- stream.resume();
- }
+ return accumulator;
+}
- for (let i = 0; i < streams.length; i++) {
- pipe(streams[i]);
- }
+var _arrayAggregator = arrayAggregator$1;
- next();
- }
+/**
+ * Creates a base function for methods like `_.forIn` and `_.forOwn`.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
- function endStream() {
- merging = false; // emit 'queueDrain' when all streams merged.
+function createBaseFor$1(fromRight) {
+ return function (object, iteratee, keysFunc) {
+ var index = -1,
+ iterable = Object(object),
+ props = keysFunc(object),
+ length = props.length;
- mergedStream.emit('queueDrain');
+ while (length--) {
+ var key = props[fromRight ? length : ++index];
- if (doEnd) {
- mergedStream.end();
+ if (iteratee(iterable[key], key, iterable) === false) {
+ break;
+ }
}
- }
- mergedStream.setMaxListeners(0);
- mergedStream.add = addStream;
- mergedStream.on('unpipe', function (stream) {
- stream.emit('merge2UnpipeEnd');
- });
+ return object;
+ };
+}
- if (args.length) {
- addStream.apply(null, args);
- }
+var _createBaseFor = createBaseFor$1;
- return mergedStream;
-} // check and pause streams for pipe.
+var createBaseFor = _createBaseFor;
+/**
+ * The base implementation of `baseForOwn` which iterates over `object`
+ * properties returned by `keysFunc` and invokes `iteratee` for each property.
+ * Iteratee functions may exit iteration early by explicitly returning `false`.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @returns {Object} Returns `object`.
+ */
+var baseFor$1 = createBaseFor();
+var _baseFor = baseFor$1;
-function pauseStreams(streams, options) {
- if (!Array.isArray(streams)) {
- // Backwards-compat with old-style streams
- if (!streams._readableState && streams.pipe) {
- streams = streams.pipe(PassThrough(options));
- }
+/**
+ * The base implementation of `_.times` without support for iteratee shorthands
+ * or max array length checks.
+ *
+ * @private
+ * @param {number} n The number of times to invoke `iteratee`.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the array of results.
+ */
- if (!streams._readableState || !streams.pause || !streams.pipe) {
- throw new Error('Only readable stream can be merged.');
- }
+function baseTimes$1(n, iteratee) {
+ var index = -1,
+ result = Array(n);
- streams.pause();
- } else {
- for (let i = 0, len = streams.length; i < len; i++) {
- streams[i] = pauseStreams(streams[i], options);
- }
+ while (++index < n) {
+ result[index] = iteratee(index);
}
- return streams;
+ return result;
}
-var stream = createCommonjsModule(function (module, exports) {
+var _baseTimes = baseTimes$1;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.merge = void 0;
-
- function merge(streams) {
- const mergedStream = merge2_1(streams);
- streams.forEach(stream => {
- stream.once('error', error => mergedStream.emit('error', error));
- });
- mergedStream.once('close', () => propagateCloseEventToSources(streams));
- mergedStream.once('end', () => propagateCloseEventToSources(streams));
- return mergedStream;
- }
-
- exports.merge = merge;
-
- function propagateCloseEventToSources(streams) {
- streams.forEach(stream => stream.emit('close'));
- }
-});
+/** Detect free variable `global` from Node.js. */
+var freeGlobal$1 = typeof global == 'object' && global && global.Object === Object && global;
+var _freeGlobal = freeGlobal$1;
-var string = createCommonjsModule(function (module, exports) {
+var freeGlobal = _freeGlobal;
+/** Detect free variable `self`. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isEmpty = exports.isString = void 0;
+var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
+/** Used as a reference to the global object. */
- function isString(input) {
- return typeof input === 'string';
- }
+var root$8 = freeGlobal || freeSelf || Function('return this')();
+var _root = root$8;
- exports.isString = isString;
+var root$7 = _root;
+/** Built-in value references. */
- function isEmpty(input) {
- return input === '';
- }
+var Symbol$6 = root$7.Symbol;
+var _Symbol = Symbol$6;
- exports.isEmpty = isEmpty;
-});
+var Symbol$5 = _Symbol;
+/** Used for built-in method references. */
-var utils$2 = createCommonjsModule(function (module, exports) {
+var objectProto$d = Object.prototype;
+/** Used to check objects for own properties. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
- exports.array = array;
- exports.errno = errno;
- exports.fs = fs;
- exports.path = path_1;
- exports.pattern = pattern;
- exports.stream = stream;
- exports.string = string;
-});
+var hasOwnProperty$a = objectProto$d.hasOwnProperty;
+/**
+ * Used to resolve the
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
+ * of values.
+ */
-var tasks = createCommonjsModule(function (module, exports) {
+var nativeObjectToString$1 = objectProto$d.toString;
+/** Built-in value references. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
+var symToStringTag$1 = Symbol$5 ? Symbol$5.toStringTag : undefined;
+/**
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @returns {string} Returns the raw `toStringTag`.
+ */
- function generate(patterns, settings) {
- const positivePatterns = getPositivePatterns(patterns);
- const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
- const staticPatterns = positivePatterns.filter(pattern => utils$2.pattern.isStaticPattern(pattern, settings));
- const dynamicPatterns = positivePatterns.filter(pattern => utils$2.pattern.isDynamicPattern(pattern, settings));
- const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
- /* dynamic */
- false);
- const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
- /* dynamic */
- true);
- return staticTasks.concat(dynamicTasks);
- }
+function getRawTag$1(value) {
+ var isOwn = hasOwnProperty$a.call(value, symToStringTag$1),
+ tag = value[symToStringTag$1];
- exports.generate = generate;
+ try {
+ value[symToStringTag$1] = undefined;
+ var unmasked = true;
+ } catch (e) {}
- function convertPatternsToTasks(positive, negative, dynamic) {
- const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks.
- // In this case, the global task covers the rest.
+ var result = nativeObjectToString$1.call(value);
- if ('.' in positivePatternsGroup) {
- const task = convertPatternGroupToTask('.', positive, negative, dynamic);
- return [task];
+ if (unmasked) {
+ if (isOwn) {
+ value[symToStringTag$1] = tag;
+ } else {
+ delete value[symToStringTag$1];
}
-
- return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
}
- exports.convertPatternsToTasks = convertPatternsToTasks;
+ return result;
+}
- function getPositivePatterns(patterns) {
- return utils$2.pattern.getPositivePatterns(patterns);
- }
+var _getRawTag = getRawTag$1;
- exports.getPositivePatterns = getPositivePatterns;
+/** Used for built-in method references. */
+var objectProto$c = Object.prototype;
+/**
+ * Used to resolve the
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
+ * of values.
+ */
- function getNegativePatternsAsPositive(patterns, ignore) {
- const negative = utils$2.pattern.getNegativePatterns(patterns).concat(ignore);
- const positive = negative.map(utils$2.pattern.convertToPositivePattern);
- return positive;
- }
+var nativeObjectToString = objectProto$c.toString;
+/**
+ * Converts `value` to a string using `Object.prototype.toString`.
+ *
+ * @private
+ * @param {*} value The value to convert.
+ * @returns {string} Returns the converted string.
+ */
- exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
+function objectToString$1(value) {
+ return nativeObjectToString.call(value);
+}
- function groupPatternsByBaseDirectory(patterns) {
- const group = {};
- return patterns.reduce((collection, pattern) => {
- const base = utils$2.pattern.getBaseDirectory(pattern);
+var _objectToString = objectToString$1;
- if (base in collection) {
- collection[base].push(pattern);
- } else {
- collection[base] = [pattern];
- }
+var Symbol$4 = _Symbol,
+ getRawTag = _getRawTag,
+ objectToString = _objectToString;
+/** `Object#toString` result references. */
- return collection;
- }, group);
- }
+var nullTag = '[object Null]',
+ undefinedTag = '[object Undefined]';
+/** Built-in value references. */
- exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
+var symToStringTag = Symbol$4 ? Symbol$4.toStringTag : undefined;
+/**
+ * The base implementation of `getTag` without fallbacks for buggy environments.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @returns {string} Returns the `toStringTag`.
+ */
- function convertPatternGroupsToTasks(positive, negative, dynamic) {
- return Object.keys(positive).map(base => {
- return convertPatternGroupToTask(base, positive[base], negative, dynamic);
- });
+function baseGetTag$5(value) {
+ if (value == null) {
+ return value === undefined ? undefinedTag : nullTag;
}
- exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
-
- function convertPatternGroupToTask(base, positive, negative, dynamic) {
- return {
- dynamic,
- positive,
- negative,
- base,
- patterns: [].concat(positive, negative.map(utils$2.pattern.convertToNegativePattern))
- };
- }
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
+}
- exports.convertPatternGroupToTask = convertPatternGroupToTask;
-});
+var _baseGetTag = baseGetTag$5;
-var async = createCommonjsModule(function (module, exports) {
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
-
- function read(path, settings, callback) {
- settings.fs.lstat(path, (lstatError, lstat) => {
- if (lstatError !== null) {
- return callFailureCallback(callback, lstatError);
- }
-
- if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
- return callSuccessCallback(callback, lstat);
- }
+/**
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
+ * and has a `typeof` result of "object".
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
+ * @example
+ *
+ * _.isObjectLike({});
+ * // => true
+ *
+ * _.isObjectLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isObjectLike(_.noop);
+ * // => false
+ *
+ * _.isObjectLike(null);
+ * // => false
+ */
- settings.fs.stat(path, (statError, stat) => {
- if (statError !== null) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- return callFailureCallback(callback, statError);
- }
+function isObjectLike$5(value) {
+ return value != null && typeof value == 'object';
+}
- return callSuccessCallback(callback, lstat);
- }
+var isObjectLike_1 = isObjectLike$5;
- if (settings.markSymbolicLink) {
- stat.isSymbolicLink = () => true;
- }
+var baseGetTag$4 = _baseGetTag,
+ isObjectLike$4 = isObjectLike_1;
+/** `Object#toString` result references. */
- callSuccessCallback(callback, stat);
- });
- });
- }
+var argsTag$2 = '[object Arguments]';
+/**
+ * The base implementation of `_.isArguments`.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
+ */
- exports.read = read;
+function baseIsArguments$1(value) {
+ return isObjectLike$4(value) && baseGetTag$4(value) == argsTag$2;
+}
- function callFailureCallback(callback, error) {
- callback(error);
- }
+var _baseIsArguments = baseIsArguments$1;
- function callSuccessCallback(callback, result) {
- callback(null, result);
- }
-});
+var baseIsArguments = _baseIsArguments,
+ isObjectLike$3 = isObjectLike_1;
+/** Used for built-in method references. */
-var sync = createCommonjsModule(function (module, exports) {
+var objectProto$b = Object.prototype;
+/** Used to check objects for own properties. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
+/** Built-in value references. */
- function read(path, settings) {
- const lstat = settings.fs.lstatSync(path);
+var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
+/**
+ * Checks if `value` is likely an `arguments` object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
+ * else `false`.
+ * @example
+ *
+ * _.isArguments(function() { return arguments; }());
+ * // => true
+ *
+ * _.isArguments([1, 2, 3]);
+ * // => false
+ */
- if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
- return lstat;
- }
+var isArguments$3 = baseIsArguments(function () {
+ return arguments;
+}()) ? baseIsArguments : function (value) {
+ return isObjectLike$3(value) && hasOwnProperty$9.call(value, 'callee') && !propertyIsEnumerable$1.call(value, 'callee');
+};
+var isArguments_1 = isArguments$3;
- try {
- const stat = settings.fs.statSync(path);
+/**
+ * Checks if `value` is classified as an `Array` object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an array, else `false`.
+ * @example
+ *
+ * _.isArray([1, 2, 3]);
+ * // => true
+ *
+ * _.isArray(document.body.children);
+ * // => false
+ *
+ * _.isArray('abc');
+ * // => false
+ *
+ * _.isArray(_.noop);
+ * // => false
+ */
+var isArray$a = Array.isArray;
+var isArray_1 = isArray$a;
- if (settings.markSymbolicLink) {
- stat.isSymbolicLink = () => true;
- }
+var isBuffer$2 = {exports: {}};
- return stat;
- } catch (error) {
- if (!settings.throwErrorOnBrokenSymbolicLink) {
- return lstat;
- }
+/**
+ * This method returns `false`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.13.0
+ * @category Util
+ * @returns {boolean} Returns `false`.
+ * @example
+ *
+ * _.times(2, _.stubFalse);
+ * // => [false, false]
+ */
- throw error;
- }
- }
+function stubFalse() {
+ return false;
+}
- exports.read = read;
-});
+var stubFalse_1 = stubFalse;
-var fs_1 = createCommonjsModule(function (module, exports) {
+(function (module, exports) {
+ var root = _root,
+ stubFalse = stubFalse_1;
+ /** Detect free variable `exports`. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.FILE_SYSTEM_ADAPTER = {
- lstat: fs__default['default'].lstat,
- stat: fs__default['default'].stat,
- lstatSync: fs__default['default'].lstatSync,
- statSync: fs__default['default'].statSync
- };
+ var freeExports = exports && !exports.nodeType && exports;
+ /** Detect free variable `module`. */
- function createFileSystemAdapter(fsMethods) {
- if (fsMethods === undefined) {
- return exports.FILE_SYSTEM_ADAPTER;
- }
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
+ /** Detect the popular CommonJS extension `module.exports`. */
- return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
- }
+ var moduleExports = freeModule && freeModule.exports === freeExports;
+ /** Built-in value references. */
- exports.createFileSystemAdapter = createFileSystemAdapter;
-});
+ var Buffer = moduleExports ? root.Buffer : undefined;
+ /* Built-in method references for those with the same name as other `lodash` methods. */
-var settings = createCommonjsModule(function (module, exports) {
+ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
+ /**
+ * Checks if `value` is a buffer.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.3.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
+ * @example
+ *
+ * _.isBuffer(new Buffer(2));
+ * // => true
+ *
+ * _.isBuffer(new Uint8Array(2));
+ * // => false
+ */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+ var isBuffer = nativeIsBuffer || stubFalse;
+ module.exports = isBuffer;
+})(isBuffer$2, isBuffer$2.exports);
- class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
- this.fs = fs_1.createFileSystemAdapter(this._options.fs);
- this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
- }
+/** Used as references for various `Number` constants. */
+var MAX_SAFE_INTEGER$1 = 9007199254740991;
+/** Used to detect unsigned integer values. */
- _getValue(option, value) {
- return option === undefined ? value : option;
- }
+var reIsUint = /^(?:0|[1-9]\d*)$/;
+/**
+ * Checks if `value` is a valid array-like index.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
+ * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
+ */
- }
+function isIndex$3(value, length) {
+ var type = typeof value;
+ length = length == null ? MAX_SAFE_INTEGER$1 : length;
+ return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
+}
- exports.default = Settings;
-});
+var _isIndex = isIndex$3;
-var out = createCommonjsModule(function (module, exports) {
+/** Used as references for various `Number` constants. */
+var MAX_SAFE_INTEGER = 9007199254740991;
+/**
+ * Checks if `value` is a valid array-like length.
+ *
+ * **Note:** This method is loosely based on
+ * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
+ * @example
+ *
+ * _.isLength(3);
+ * // => true
+ *
+ * _.isLength(Number.MIN_VALUE);
+ * // => false
+ *
+ * _.isLength(Infinity);
+ * // => false
+ *
+ * _.isLength('3');
+ * // => false
+ */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Settings = settings.default;
+function isLength$3(value) {
+ return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
+}
- function stat(path, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- return async.read(path, getSettings(), optionsOrSettingsOrCallback);
- }
+var isLength_1 = isLength$3;
- async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
- }
+var baseGetTag$3 = _baseGetTag,
+ isLength$2 = isLength_1,
+ isObjectLike$2 = isObjectLike_1;
+/** `Object#toString` result references. */
- exports.stat = stat;
+var argsTag$1 = '[object Arguments]',
+ arrayTag$1 = '[object Array]',
+ boolTag$1 = '[object Boolean]',
+ dateTag$1 = '[object Date]',
+ errorTag$1 = '[object Error]',
+ funcTag$1 = '[object Function]',
+ mapTag$2 = '[object Map]',
+ numberTag$1 = '[object Number]',
+ objectTag$2 = '[object Object]',
+ regexpTag$1 = '[object RegExp]',
+ setTag$2 = '[object Set]',
+ stringTag$1 = '[object String]',
+ weakMapTag$1 = '[object WeakMap]';
+var arrayBufferTag$1 = '[object ArrayBuffer]',
+ dataViewTag$2 = '[object DataView]',
+ float32Tag = '[object Float32Array]',
+ float64Tag = '[object Float64Array]',
+ int8Tag = '[object Int8Array]',
+ int16Tag = '[object Int16Array]',
+ int32Tag = '[object Int32Array]',
+ uint8Tag = '[object Uint8Array]',
+ uint8ClampedTag = '[object Uint8ClampedArray]',
+ uint16Tag = '[object Uint16Array]',
+ uint32Tag = '[object Uint32Array]';
+/** Used to identify `toStringTag` values of typed arrays. */
- function statSync(path, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- return sync.read(path, settings);
- }
-
- exports.statSync = statSync;
-
- function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings.default) {
- return settingsOrOptions;
- }
+var typedArrayTags = {};
+typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
+typedArrayTags[argsTag$1] = typedArrayTags[arrayTag$1] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$2] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$2] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag$2] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$2] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag$1] = false;
+/**
+ * The base implementation of `_.isTypedArray` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
+ */
- return new settings.default(settingsOrOptions);
- }
-});
+function baseIsTypedArray$1(value) {
+ return isObjectLike$2(value) && isLength$2(value.length) && !!typedArrayTags[baseGetTag$3(value)];
+}
-var runParallel_1 = runParallel;
+var _baseIsTypedArray = baseIsTypedArray$1;
-function runParallel(tasks, cb) {
- var results, pending, keys;
- var isSync = true;
+/**
+ * The base implementation of `_.unary` without support for storing metadata.
+ *
+ * @private
+ * @param {Function} func The function to cap arguments for.
+ * @returns {Function} Returns the new capped function.
+ */
- if (Array.isArray(tasks)) {
- results = [];
- pending = tasks.length;
- } else {
- keys = Object.keys(tasks);
- results = {};
- pending = keys.length;
- }
+function baseUnary$1(func) {
+ return function (value) {
+ return func(value);
+ };
+}
- function done(err) {
- function end() {
- if (cb) cb(err, results);
- cb = null;
- }
+var _baseUnary = baseUnary$1;
- if (isSync) process.nextTick(end);else end();
- }
+var _nodeUtil = {exports: {}};
- function each(i, err, result) {
- results[i] = result;
+(function (module, exports) {
+ var freeGlobal = _freeGlobal;
+ /** Detect free variable `exports`. */
- if (--pending === 0 || err) {
- done(err);
- }
- }
+ var freeExports = exports && !exports.nodeType && exports;
+ /** Detect free variable `module`. */
- if (!pending) {
- // empty
- done(null);
- } else if (keys) {
- // object
- keys.forEach(function (key) {
- tasks[key](function (err, result) {
- each(key, err, result);
- });
- });
- } else {
- // array
- tasks.forEach(function (task, i) {
- task(function (err, result) {
- each(i, err, result);
- });
- });
- }
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
+ /** Detect the popular CommonJS extension `module.exports`. */
- isSync = false;
-}
+ var moduleExports = freeModule && freeModule.exports === freeExports;
+ /** Detect free variable `process` from Node.js. */
-var constants$2 = createCommonjsModule(function (module, exports) {
+ var freeProcess = moduleExports && freeGlobal.process;
+ /** Used to access faster Node.js helpers. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
- const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
- const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
- const SUPPORTED_MAJOR_VERSION = 10;
- const SUPPORTED_MINOR_VERSION = 10;
- const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
- const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
- /**\r
- * IS `true` for Node.js 10.10 and greater.\r
- */
+ var nodeUtil = function () {
+ try {
+ // Use `util.types` for Node.js 10+.
+ var types = freeModule && freeModule.require && freeModule.require('util').types;
- exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
-});
+ if (types) {
+ return types;
+ } // Legacy `process.binding('util')` for Node.js < 10.
-var fs$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+ return freeProcess && freeProcess.binding && freeProcess.binding('util');
+ } catch (e) {}
+ }();
- class DirentFromStats {
- constructor(name, stats) {
- this.name = name;
- this.isBlockDevice = stats.isBlockDevice.bind(stats);
- this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
- this.isDirectory = stats.isDirectory.bind(stats);
- this.isFIFO = stats.isFIFO.bind(stats);
- this.isFile = stats.isFile.bind(stats);
- this.isSocket = stats.isSocket.bind(stats);
- this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
- }
+ module.exports = nodeUtil;
+})(_nodeUtil, _nodeUtil.exports);
- }
+var baseIsTypedArray = _baseIsTypedArray,
+ baseUnary = _baseUnary,
+ nodeUtil = _nodeUtil.exports;
+/* Node.js helper references. */
- function createDirentFromStats(name, stats) {
- return new DirentFromStats(name, stats);
- }
+var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
+/**
+ * Checks if `value` is classified as a typed array.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
+ * @example
+ *
+ * _.isTypedArray(new Uint8Array);
+ * // => true
+ *
+ * _.isTypedArray([]);
+ * // => false
+ */
- exports.createDirentFromStats = createDirentFromStats;
-});
+var isTypedArray$2 = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
+var isTypedArray_1 = isTypedArray$2;
-var utils$3 = createCommonjsModule(function (module, exports) {
+var baseTimes = _baseTimes,
+ isArguments$2 = isArguments_1,
+ isArray$9 = isArray_1,
+ isBuffer$1 = isBuffer$2.exports,
+ isIndex$2 = _isIndex,
+ isTypedArray$1 = isTypedArray_1;
+/** Used for built-in method references. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.fs = fs$1;
-});
+var objectProto$a = Object.prototype;
+/** Used to check objects for own properties. */
-var async$1 = createCommonjsModule(function (module, exports) {
+var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
+/**
+ * Creates an array of the enumerable property names of the array-like `value`.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @param {boolean} inherited Specify returning inherited property names.
+ * @returns {Array} Returns the array of property names.
+ */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+function arrayLikeKeys$1(value, inherited) {
+ var isArr = isArray$9(value),
+ isArg = !isArr && isArguments$2(value),
+ isBuff = !isArr && !isArg && isBuffer$1(value),
+ isType = !isArr && !isArg && !isBuff && isTypedArray$1(value),
+ skipIndexes = isArr || isArg || isBuff || isType,
+ result = skipIndexes ? baseTimes(value.length, String) : [],
+ length = result.length;
- function read(directory, settings, callback) {
- if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
- return readdirWithFileTypes(directory, settings, callback);
+ for (var key in value) {
+ if ((inherited || hasOwnProperty$8.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
+ key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
+ isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
+ isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
+ isIndex$2(key, length)))) {
+ result.push(key);
}
-
- return readdir(directory, settings, callback);
}
- exports.read = read;
-
- function readdirWithFileTypes(directory, settings, callback) {
- settings.fs.readdir(directory, {
- withFileTypes: true
- }, (readdirError, dirents) => {
- if (readdirError !== null) {
- return callFailureCallback(callback, readdirError);
- }
-
- const entries = dirents.map(dirent => ({
- dirent,
- name: dirent.name,
- path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
- }));
+ return result;
+}
- if (!settings.followSymbolicLinks) {
- return callSuccessCallback(callback, entries);
- }
+var _arrayLikeKeys = arrayLikeKeys$1;
- const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
- runParallel_1(tasks, (rplError, rplEntries) => {
- if (rplError !== null) {
- return callFailureCallback(callback, rplError);
- }
+/** Used for built-in method references. */
+var objectProto$9 = Object.prototype;
+/**
+ * Checks if `value` is likely a prototype object.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
+ */
- callSuccessCallback(callback, rplEntries);
- });
- });
- }
+function isPrototype$1(value) {
+ var Ctor = value && value.constructor,
+ proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$9;
+ return value === proto;
+}
- exports.readdirWithFileTypes = readdirWithFileTypes;
+var _isPrototype = isPrototype$1;
- function makeRplTaskEntry(entry, settings) {
- return done => {
- if (!entry.dirent.isSymbolicLink()) {
- return done(null, entry);
- }
+/**
+ * Creates a unary function that invokes `func` with its argument transformed.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {Function} transform The argument transform.
+ * @returns {Function} Returns the new function.
+ */
- settings.fs.stat(entry.path, (statError, stats) => {
- if (statError !== null) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- return done(statError);
- }
+function overArg$1(func, transform) {
+ return function (arg) {
+ return func(transform(arg));
+ };
+}
- return done(null, entry);
- }
+var _overArg = overArg$1;
- entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats);
- return done(null, entry);
- });
- };
- }
+var overArg = _overArg;
+/* Built-in method references for those with the same name as other `lodash` methods. */
- function readdir(directory, settings, callback) {
- settings.fs.readdir(directory, (readdirError, names) => {
- if (readdirError !== null) {
- return callFailureCallback(callback, readdirError);
- }
+var nativeKeys$1 = overArg(Object.keys, Object);
+var _nativeKeys = nativeKeys$1;
- const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`);
- const tasks = filepaths.map(filepath => {
- return done => out.stat(filepath, settings.fsStatSettings, done);
- });
- runParallel_1(tasks, (rplError, results) => {
- if (rplError !== null) {
- return callFailureCallback(callback, rplError);
- }
+var isPrototype = _isPrototype,
+ nativeKeys = _nativeKeys;
+/** Used for built-in method references. */
- const entries = [];
- names.forEach((name, index) => {
- const stats = results[index];
- const entry = {
- name,
- path: filepaths[index],
- dirent: utils$3.fs.createDirentFromStats(name, stats)
- };
+var objectProto$8 = Object.prototype;
+/** Used to check objects for own properties. */
- if (settings.stats) {
- entry.stats = stats;
- }
+var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
+/**
+ * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
- entries.push(entry);
- });
- callSuccessCallback(callback, entries);
- });
- });
+function baseKeys$1(object) {
+ if (!isPrototype(object)) {
+ return nativeKeys(object);
}
- exports.readdir = readdir;
-
- function callFailureCallback(callback, error) {
- callback(error);
- }
+ var result = [];
- function callSuccessCallback(callback, result) {
- callback(null, result);
+ for (var key in Object(object)) {
+ if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
+ result.push(key);
+ }
}
-});
-var sync$1 = createCommonjsModule(function (module, exports) {
+ return result;
+}
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var _baseKeys = baseKeys$1;
- function read(directory, settings) {
- if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
- return readdirWithFileTypes(directory, settings);
- }
+/**
+ * Checks if `value` is the
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
+ * @example
+ *
+ * _.isObject({});
+ * // => true
+ *
+ * _.isObject([1, 2, 3]);
+ * // => true
+ *
+ * _.isObject(_.noop);
+ * // => true
+ *
+ * _.isObject(null);
+ * // => false
+ */
- return readdir(directory, settings);
- }
+function isObject$4(value) {
+ var type = typeof value;
+ return value != null && (type == 'object' || type == 'function');
+}
- exports.read = read;
+var isObject_1 = isObject$4;
- function readdirWithFileTypes(directory, settings) {
- const dirents = settings.fs.readdirSync(directory, {
- withFileTypes: true
- });
- return dirents.map(dirent => {
- const entry = {
- dirent,
- name: dirent.name,
- path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
- };
+var baseGetTag$2 = _baseGetTag,
+ isObject$3 = isObject_1;
+/** `Object#toString` result references. */
- if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
- try {
- const stats = settings.fs.statSync(entry.path);
- entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats);
- } catch (error) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- throw error;
- }
- }
- }
+var asyncTag = '[object AsyncFunction]',
+ funcTag = '[object Function]',
+ genTag = '[object GeneratorFunction]',
+ proxyTag = '[object Proxy]';
+/**
+ * Checks if `value` is classified as a `Function` object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.
+ * @example
+ *
+ * _.isFunction(_);
+ * // => true
+ *
+ * _.isFunction(/abc/);
+ * // => false
+ */
- return entry;
- });
- }
+function isFunction$2(value) {
+ if (!isObject$3(value)) {
+ return false;
+ } // The use of `Object#toString` avoids issues with the `typeof` operator
+ // in Safari 9 which returns 'object' for typed arrays and other constructors.
- exports.readdirWithFileTypes = readdirWithFileTypes;
- function readdir(directory, settings) {
- const names = settings.fs.readdirSync(directory);
- return names.map(name => {
- const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`;
- const stats = out.statSync(entryPath, settings.fsStatSettings);
- const entry = {
- name,
- path: entryPath,
- dirent: utils$3.fs.createDirentFromStats(name, stats)
- };
+ var tag = baseGetTag$2(value);
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
+}
- if (settings.stats) {
- entry.stats = stats;
- }
+var isFunction_1 = isFunction$2;
- return entry;
- });
- }
+var isFunction$1 = isFunction_1,
+ isLength$1 = isLength_1;
+/**
+ * Checks if `value` is array-like. A value is considered array-like if it's
+ * not a function and has a `value.length` that's an integer greater than or
+ * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
+ * @example
+ *
+ * _.isArrayLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isArrayLike(document.body.children);
+ * // => true
+ *
+ * _.isArrayLike('abc');
+ * // => true
+ *
+ * _.isArrayLike(_.noop);
+ * // => false
+ */
- exports.readdir = readdir;
-});
+function isArrayLike$2(value) {
+ return value != null && isLength$1(value.length) && !isFunction$1(value);
+}
-var fs_1$1 = createCommonjsModule(function (module, exports) {
+var isArrayLike_1 = isArrayLike$2;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.FILE_SYSTEM_ADAPTER = {
- lstat: fs__default['default'].lstat,
- stat: fs__default['default'].stat,
- lstatSync: fs__default['default'].lstatSync,
- statSync: fs__default['default'].statSync,
- readdir: fs__default['default'].readdir,
- readdirSync: fs__default['default'].readdirSync
- };
+var arrayLikeKeys = _arrayLikeKeys,
+ baseKeys = _baseKeys,
+ isArrayLike$1 = isArrayLike_1;
+/**
+ * Creates an array of the own enumerable property names of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects. See the
+ * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
+ * for more details.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.keys(new Foo);
+ * // => ['a', 'b'] (iteration order is not guaranteed)
+ *
+ * _.keys('hi');
+ * // => ['0', '1']
+ */
- function createFileSystemAdapter(fsMethods) {
- if (fsMethods === undefined) {
- return exports.FILE_SYSTEM_ADAPTER;
- }
+function keys$3(object) {
+ return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object);
+}
- return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
- }
+var keys_1 = keys$3;
- exports.createFileSystemAdapter = createFileSystemAdapter;
-});
+var baseFor = _baseFor,
+ keys$2 = keys_1;
+/**
+ * The base implementation of `_.forOwn` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ */
-var settings$1 = createCommonjsModule(function (module, exports) {
+function baseForOwn$1(object, iteratee) {
+ return object && baseFor(object, iteratee, keys$2);
+}
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var _baseForOwn = baseForOwn$1;
- class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
- this.fs = fs_1$1.createFileSystemAdapter(this._options.fs);
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
- this.stats = this._getValue(this._options.stats, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
- this.fsStatSettings = new out.Settings({
- followSymbolicLink: this.followSymbolicLinks,
- fs: this.fs,
- throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
- });
+var isArrayLike = isArrayLike_1;
+/**
+ * Creates a `baseEach` or `baseEachRight` function.
+ *
+ * @private
+ * @param {Function} eachFunc The function to iterate over a collection.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
+
+function createBaseEach$1(eachFunc, fromRight) {
+ return function (collection, iteratee) {
+ if (collection == null) {
+ return collection;
}
- _getValue(option, value) {
- return option === undefined ? value : option;
+ if (!isArrayLike(collection)) {
+ return eachFunc(collection, iteratee);
}
- }
+ var length = collection.length,
+ index = fromRight ? length : -1,
+ iterable = Object(collection);
- exports.default = Settings;
-});
+ while (fromRight ? index-- : ++index < length) {
+ if (iteratee(iterable[index], index, iterable) === false) {
+ break;
+ }
+ }
+
+ return collection;
+ };
+}
-var out$1 = createCommonjsModule(function (module, exports) {
+var _createBaseEach = createBaseEach$1;
- Object.defineProperty(exports, "__esModule", {
- value: true
+var baseForOwn = _baseForOwn,
+ createBaseEach = _createBaseEach;
+/**
+ * The base implementation of `_.forEach` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array|Object} Returns `collection`.
+ */
+
+var baseEach$1 = createBaseEach(baseForOwn);
+var _baseEach = baseEach$1;
+
+var baseEach = _baseEach;
+/**
+ * Aggregates elements of `collection` on `accumulator` with keys transformed
+ * by `iteratee` and values set by `setter`.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} setter The function to set `accumulator` values.
+ * @param {Function} iteratee The iteratee to transform keys.
+ * @param {Object} accumulator The initial aggregated object.
+ * @returns {Function} Returns `accumulator`.
+ */
+
+function baseAggregator$1(collection, setter, iteratee, accumulator) {
+ baseEach(collection, function (value, key, collection) {
+ setter(accumulator, value, iteratee(value), collection);
});
- exports.Settings = settings$1.default;
+ return accumulator;
+}
- function scandir(path, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- return async$1.read(path, getSettings(), optionsOrSettingsOrCallback);
- }
+var _baseAggregator = baseAggregator$1;
- async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback);
- }
+/**
+ * Removes all key-value entries from the list cache.
+ *
+ * @private
+ * @name clear
+ * @memberOf ListCache
+ */
- exports.scandir = scandir;
+function listCacheClear$1() {
+ this.__data__ = [];
+ this.size = 0;
+}
- function scandirSync(path, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- return sync$1.read(path, settings);
- }
+var _listCacheClear = listCacheClear$1;
- exports.scandirSync = scandirSync;
+/**
+ * Performs a
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
+ * comparison between two values to determine if they are equivalent.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ * @example
+ *
+ * var object = { 'a': 1 };
+ * var other = { 'a': 1 };
+ *
+ * _.eq(object, object);
+ * // => true
+ *
+ * _.eq(object, other);
+ * // => false
+ *
+ * _.eq('a', 'a');
+ * // => true
+ *
+ * _.eq('a', Object('a'));
+ * // => false
+ *
+ * _.eq(NaN, NaN);
+ * // => true
+ */
- function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings$1.default) {
- return settingsOrOptions;
- }
+function eq$3(value, other) {
+ return value === other || value !== value && other !== other;
+}
- return new settings$1.default(settingsOrOptions);
- }
-});
+var eq_1 = eq$3;
-function reusify(Constructor) {
- var head = new Constructor();
- var tail = head;
+var eq$2 = eq_1;
+/**
+ * Gets the index at which the `key` is found in `array` of key-value pairs.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {*} key The key to search for.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
- function get() {
- var current = head;
+function assocIndexOf$4(array, key) {
+ var length = array.length;
- if (current.next) {
- head = current.next;
- } else {
- head = new Constructor();
- tail = head;
+ while (length--) {
+ if (eq$2(array[length][0], key)) {
+ return length;
}
-
- current.next = null;
- return current;
}
- function release(obj) {
- tail.next = obj;
- tail = obj;
- }
+ return -1;
+}
- return {
- get: get,
- release: release
- };
-}
+var _assocIndexOf = assocIndexOf$4;
-var reusify_1 = reusify;
+var assocIndexOf$3 = _assocIndexOf;
+/** Used for built-in method references. */
-function fastqueue(context, worker, concurrency) {
- if (typeof context === 'function') {
- concurrency = worker;
- worker = context;
- context = null;
- }
+var arrayProto = Array.prototype;
+/** Built-in value references. */
- var cache = reusify_1(Task);
- var queueHead = null;
- var queueTail = null;
- var _running = 0;
- var self = {
- push: push,
- drain: noop,
- saturated: noop,
- pause: pause,
- paused: false,
- concurrency: concurrency,
- running: running,
- resume: resume,
- idle: idle,
- length: length,
- getQueue: getQueue,
- unshift: unshift,
- empty: noop,
- kill: kill,
- killAndDrain: killAndDrain
- };
- return self;
+var splice = arrayProto.splice;
+/**
+ * Removes `key` and its value from the list cache.
+ *
+ * @private
+ * @name delete
+ * @memberOf ListCache
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
- function running() {
- return _running;
- }
+function listCacheDelete$1(key) {
+ var data = this.__data__,
+ index = assocIndexOf$3(data, key);
- function pause() {
- self.paused = true;
+ if (index < 0) {
+ return false;
}
- function length() {
- var current = queueHead;
- var counter = 0;
-
- while (current) {
- current = current.next;
- counter++;
- }
+ var lastIndex = data.length - 1;
- return counter;
+ if (index == lastIndex) {
+ data.pop();
+ } else {
+ splice.call(data, index, 1);
}
- function getQueue() {
- var current = queueHead;
- var tasks = [];
+ --this.size;
+ return true;
+}
- while (current) {
- tasks.push(current.value);
- current = current.next;
- }
+var _listCacheDelete = listCacheDelete$1;
- return tasks;
- }
+var assocIndexOf$2 = _assocIndexOf;
+/**
+ * Gets the list cache value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf ListCache
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
+ */
- function resume() {
- if (!self.paused) return;
- self.paused = false;
+function listCacheGet$1(key) {
+ var data = this.__data__,
+ index = assocIndexOf$2(data, key);
+ return index < 0 ? undefined : data[index][1];
+}
- for (var i = 0; i < self.concurrency; i++) {
- _running++;
- release();
- }
- }
+var _listCacheGet = listCacheGet$1;
- function idle() {
- return _running === 0 && self.length() === 0;
- }
+var assocIndexOf$1 = _assocIndexOf;
+/**
+ * Checks if a list cache value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf ListCache
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
- function push(value, done) {
- var current = cache.get();
- current.context = context;
- current.release = release;
- current.value = value;
- current.callback = done || noop;
+function listCacheHas$1(key) {
+ return assocIndexOf$1(this.__data__, key) > -1;
+}
- if (_running === self.concurrency || self.paused) {
- if (queueTail) {
- queueTail.next = current;
- queueTail = current;
- } else {
- queueHead = current;
- queueTail = current;
- self.saturated();
- }
- } else {
- _running++;
- worker.call(context, current.value, current.worked);
- }
- }
+var _listCacheHas = listCacheHas$1;
- function unshift(value, done) {
- var current = cache.get();
- current.context = context;
- current.release = release;
- current.value = value;
- current.callback = done || noop;
+var assocIndexOf = _assocIndexOf;
+/**
+ * Sets the list cache `key` to `value`.
+ *
+ * @private
+ * @name set
+ * @memberOf ListCache
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the list cache instance.
+ */
- if (_running === self.concurrency || self.paused) {
- if (queueHead) {
- current.next = queueHead;
- queueHead = current;
- } else {
- queueHead = current;
- queueTail = current;
- self.saturated();
- }
- } else {
- _running++;
- worker.call(context, current.value, current.worked);
- }
+function listCacheSet$1(key, value) {
+ var data = this.__data__,
+ index = assocIndexOf(data, key);
+
+ if (index < 0) {
+ ++this.size;
+ data.push([key, value]);
+ } else {
+ data[index][1] = value;
}
- function release(holder) {
- if (holder) {
- cache.release(holder);
- }
+ return this;
+}
- var next = queueHead;
+var _listCacheSet = listCacheSet$1;
- if (next) {
- if (!self.paused) {
- if (queueTail === queueHead) {
- queueTail = null;
- }
+var listCacheClear = _listCacheClear,
+ listCacheDelete = _listCacheDelete,
+ listCacheGet = _listCacheGet,
+ listCacheHas = _listCacheHas,
+ listCacheSet = _listCacheSet;
+/**
+ * Creates an list cache object.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [entries] The key-value pairs to cache.
+ */
- queueHead = next.next;
- next.next = null;
- worker.call(context, next.value, next.worked);
+function ListCache$4(entries) {
+ var index = -1,
+ length = entries == null ? 0 : entries.length;
+ this.clear();
- if (queueTail === null) {
- self.empty();
- }
- } else {
- _running--;
- }
- } else if (--_running === 0) {
- self.drain();
- }
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
}
+} // Add methods to `ListCache`.
- function kill() {
- queueHead = null;
- queueTail = null;
- self.drain = noop;
- }
- function killAndDrain() {
- queueHead = null;
- queueTail = null;
- self.drain();
- self.drain = noop;
- }
+ListCache$4.prototype.clear = listCacheClear;
+ListCache$4.prototype['delete'] = listCacheDelete;
+ListCache$4.prototype.get = listCacheGet;
+ListCache$4.prototype.has = listCacheHas;
+ListCache$4.prototype.set = listCacheSet;
+var _ListCache = ListCache$4;
+
+var ListCache$3 = _ListCache;
+/**
+ * Removes all key-value entries from the stack.
+ *
+ * @private
+ * @name clear
+ * @memberOf Stack
+ */
+
+function stackClear$1() {
+ this.__data__ = new ListCache$3();
+ this.size = 0;
}
-function noop() {}
+var _stackClear = stackClear$1;
-function Task() {
- this.value = null;
- this.callback = noop;
- this.next = null;
- this.release = noop;
- this.context = null;
- var self = this;
+/**
+ * Removes `key` and its value from the stack.
+ *
+ * @private
+ * @name delete
+ * @memberOf Stack
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
- this.worked = function worked(err, result) {
- var callback = self.callback;
- self.value = null;
- self.callback = noop;
- callback.call(self.context, err, result);
- self.release(self);
- };
+function stackDelete$1(key) {
+ var data = this.__data__,
+ result = data['delete'](key);
+ this.size = data.size;
+ return result;
}
-var queue = fastqueue;
-
-var common = createCommonjsModule(function (module, exports) {
+var _stackDelete = stackDelete$1;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
-
- function isFatalError(settings, error) {
- if (settings.errorFilter === null) {
- return true;
- }
+/**
+ * Gets the stack value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf Stack
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
+ */
- return !settings.errorFilter(error);
- }
+function stackGet$1(key) {
+ return this.__data__.get(key);
+}
- exports.isFatalError = isFatalError;
+var _stackGet = stackGet$1;
- function isAppliedFilter(filter, value) {
- return filter === null || filter(value);
- }
+/**
+ * Checks if a stack value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf Stack
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
- exports.isAppliedFilter = isAppliedFilter;
+function stackHas$1(key) {
+ return this.__data__.has(key);
+}
- function replacePathSegmentSeparator(filepath, separator) {
- return filepath.split(/[\\/]/).join(separator);
- }
+var _stackHas = stackHas$1;
- exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
+var root$6 = _root;
+/** Used to detect overreaching core-js shims. */
- function joinPathSegments(a, b, separator) {
- if (a === '') {
- return b;
- }
+var coreJsData$1 = root$6['__core-js_shared__'];
+var _coreJsData = coreJsData$1;
- return a + separator + b;
- }
+var coreJsData = _coreJsData;
+/** Used to detect methods masquerading as native. */
- exports.joinPathSegments = joinPathSegments;
-});
+var maskSrcKey = function () {
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
+ return uid ? 'Symbol(src)_1.' + uid : '';
+}();
+/**
+ * Checks if `func` has its source masked.
+ *
+ * @private
+ * @param {Function} func The function to check.
+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.
+ */
-var reader = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+function isMasked$1(func) {
+ return !!maskSrcKey && maskSrcKey in func;
+}
- class Reader {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
- }
+var _isMasked = isMasked$1;
- }
+/** Used for built-in method references. */
+var funcProto$1 = Function.prototype;
+/** Used to resolve the decompiled source of functions. */
- exports.default = Reader;
-});
+var funcToString$1 = funcProto$1.toString;
+/**
+ * Converts `func` to its source code.
+ *
+ * @private
+ * @param {Function} func The function to convert.
+ * @returns {string} Returns the source code.
+ */
-var async$2 = createCommonjsModule(function (module, exports) {
+function toSource$2(func) {
+ if (func != null) {
+ try {
+ return funcToString$1.call(func);
+ } catch (e) {}
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+ try {
+ return func + '';
+ } catch (e) {}
+ }
- class AsyncReader extends reader.default {
- constructor(_root, _settings) {
- super(_root, _settings);
- this._settings = _settings;
- this._scandir = out$1.scandir;
- this._emitter = new events_1__default['default'].EventEmitter();
- this._queue = queue(this._worker.bind(this), this._settings.concurrency);
- this._isFatalError = false;
- this._isDestroyed = false;
-
- this._queue.drain = () => {
- if (!this._isFatalError) {
- this._emitter.emit('end');
- }
- };
- }
+ return '';
+}
- read() {
- this._isFatalError = false;
- this._isDestroyed = false;
- setImmediate(() => {
- this._pushToQueue(this._root, this._settings.basePath);
- });
- return this._emitter;
- }
+var _toSource = toSource$2;
- destroy() {
- if (this._isDestroyed) {
- throw new Error('The reader is already destroyed');
- }
+var isFunction = isFunction_1,
+ isMasked = _isMasked,
+ isObject$2 = isObject_1,
+ toSource$1 = _toSource;
+/**
+ * Used to match `RegExp`
+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
+ */
- this._isDestroyed = true;
+var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
+/** Used to detect host constructors (Safari). */
- this._queue.killAndDrain();
- }
+var reIsHostCtor = /^\[object .+?Constructor\]$/;
+/** Used for built-in method references. */
- onEntry(callback) {
- this._emitter.on('entry', callback);
- }
+var funcProto = Function.prototype,
+ objectProto$7 = Object.prototype;
+/** Used to resolve the decompiled source of functions. */
- onError(callback) {
- this._emitter.once('error', callback);
- }
+var funcToString = funcProto.toString;
+/** Used to check objects for own properties. */
- onEnd(callback) {
- this._emitter.once('end', callback);
- }
+var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
+/** Used to detect if a method is native. */
- _pushToQueue(directory, base) {
- const queueItem = {
- directory,
- base
- };
+var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty$6).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
+/**
+ * The base implementation of `_.isNative` without bad shim checks.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a native function,
+ * else `false`.
+ */
- this._queue.push(queueItem, error => {
- if (error !== null) {
- this._handleError(error);
- }
- });
- }
+function baseIsNative$1(value) {
+ if (!isObject$2(value) || isMasked(value)) {
+ return false;
+ }
- _worker(item, done) {
- this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
- if (error !== null) {
- return done(error, undefined);
- }
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
+ return pattern.test(toSource$1(value));
+}
- for (const entry of entries) {
- this._handleEntry(entry, item.base);
- }
+var _baseIsNative = baseIsNative$1;
- done(null, undefined);
- });
- }
+/**
+ * Gets the value at `key` of `object`.
+ *
+ * @private
+ * @param {Object} [object] The object to query.
+ * @param {string} key The key of the property to get.
+ * @returns {*} Returns the property value.
+ */
- _handleError(error) {
- if (!common.isFatalError(this._settings, error)) {
- return;
- }
+function getValue$1(object, key) {
+ return object == null ? undefined : object[key];
+}
- this._isFatalError = true;
- this._isDestroyed = true;
+var _getValue = getValue$1;
- this._emitter.emit('error', error);
- }
+var baseIsNative = _baseIsNative,
+ getValue = _getValue;
+/**
+ * Gets the native function at `key` of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {string} key The key of the method to get.
+ * @returns {*} Returns the function if it's native, else `undefined`.
+ */
- _handleEntry(entry, base) {
- if (this._isDestroyed || this._isFatalError) {
- return;
- }
+function getNative$7(object, key) {
+ var value = getValue(object, key);
+ return baseIsNative(value) ? value : undefined;
+}
- const fullpath = entry.path;
+var _getNative = getNative$7;
- if (base !== undefined) {
- entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
- }
+var getNative$6 = _getNative,
+ root$5 = _root;
+/* Built-in method references that are verified to be native. */
- if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
- this._emitEntry(entry);
- }
+var Map$4 = getNative$6(root$5, 'Map');
+var _Map = Map$4;
- if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
- this._pushToQueue(fullpath, entry.path);
- }
- }
+var getNative$5 = _getNative;
+/* Built-in method references that are verified to be native. */
- _emitEntry(entry) {
- this._emitter.emit('entry', entry);
- }
+var nativeCreate$4 = getNative$5(Object, 'create');
+var _nativeCreate = nativeCreate$4;
- }
+var nativeCreate$3 = _nativeCreate;
+/**
+ * Removes all key-value entries from the hash.
+ *
+ * @private
+ * @name clear
+ * @memberOf Hash
+ */
- exports.default = AsyncReader;
-});
+function hashClear$1() {
+ this.__data__ = nativeCreate$3 ? nativeCreate$3(null) : {};
+ this.size = 0;
+}
-var async$3 = createCommonjsModule(function (module, exports) {
+var _hashClear = hashClear$1;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+/**
+ * Removes `key` and its value from the hash.
+ *
+ * @private
+ * @name delete
+ * @memberOf Hash
+ * @param {Object} hash The hash to modify.
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
- class AsyncProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new async$2.default(this._root, this._settings);
- this._storage = new Set();
- }
+function hashDelete$1(key) {
+ var result = this.has(key) && delete this.__data__[key];
+ this.size -= result ? 1 : 0;
+ return result;
+}
- read(callback) {
- this._reader.onError(error => {
- callFailureCallback(callback, error);
- });
+var _hashDelete = hashDelete$1;
- this._reader.onEntry(entry => {
- this._storage.add(entry);
- });
+var nativeCreate$2 = _nativeCreate;
+/** Used to stand-in for `undefined` hash values. */
- this._reader.onEnd(() => {
- callSuccessCallback(callback, [...this._storage]);
- });
+var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
+/** Used for built-in method references. */
- this._reader.read();
- }
+var objectProto$6 = Object.prototype;
+/** Used to check objects for own properties. */
- }
+var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
+/**
+ * Gets the hash value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf Hash
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
+ */
- exports.default = AsyncProvider;
+function hashGet$1(key) {
+ var data = this.__data__;
- function callFailureCallback(callback, error) {
- callback(error);
+ if (nativeCreate$2) {
+ var result = data[key];
+ return result === HASH_UNDEFINED$2 ? undefined : result;
}
- function callSuccessCallback(callback, entries) {
- callback(null, entries);
- }
-});
+ return hasOwnProperty$5.call(data, key) ? data[key] : undefined;
+}
-var stream$1 = createCommonjsModule(function (module, exports) {
+var _hashGet = hashGet$1;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var nativeCreate$1 = _nativeCreate;
+/** Used for built-in method references. */
- class StreamProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new async$2.default(this._root, this._settings);
- this._stream = new stream_1__default['default'].Readable({
- objectMode: true,
- read: () => {},
- destroy: this._reader.destroy.bind(this._reader)
- });
- }
+var objectProto$5 = Object.prototype;
+/** Used to check objects for own properties. */
- read() {
- this._reader.onError(error => {
- this._stream.emit('error', error);
- });
+var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
+/**
+ * Checks if a hash value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf Hash
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
- this._reader.onEntry(entry => {
- this._stream.push(entry);
- });
+function hashHas$1(key) {
+ var data = this.__data__;
+ return nativeCreate$1 ? data[key] !== undefined : hasOwnProperty$4.call(data, key);
+}
- this._reader.onEnd(() => {
- this._stream.push(null);
- });
+var _hashHas = hashHas$1;
- this._reader.read();
+var nativeCreate = _nativeCreate;
+/** Used to stand-in for `undefined` hash values. */
- return this._stream;
- }
+var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
+/**
+ * Sets the hash `key` to `value`.
+ *
+ * @private
+ * @name set
+ * @memberOf Hash
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the hash instance.
+ */
- }
+function hashSet$1(key, value) {
+ var data = this.__data__;
+ this.size += this.has(key) ? 0 : 1;
+ data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
+ return this;
+}
- exports.default = StreamProvider;
-});
+var _hashSet = hashSet$1;
-var sync$2 = createCommonjsModule(function (module, exports) {
+var hashClear = _hashClear,
+ hashDelete = _hashDelete,
+ hashGet = _hashGet,
+ hashHas = _hashHas,
+ hashSet = _hashSet;
+/**
+ * Creates a hash object.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [entries] The key-value pairs to cache.
+ */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+function Hash$1(entries) {
+ var index = -1,
+ length = entries == null ? 0 : entries.length;
+ this.clear();
- class SyncReader extends reader.default {
- constructor() {
- super(...arguments);
- this._scandir = out$1.scandirSync;
- this._storage = new Set();
- this._queue = new Set();
- }
-
- read() {
- this._pushToQueue(this._root, this._settings.basePath);
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
+ }
+} // Add methods to `Hash`.
- this._handleQueue();
- return [...this._storage];
- }
+Hash$1.prototype.clear = hashClear;
+Hash$1.prototype['delete'] = hashDelete;
+Hash$1.prototype.get = hashGet;
+Hash$1.prototype.has = hashHas;
+Hash$1.prototype.set = hashSet;
+var _Hash = Hash$1;
- _pushToQueue(directory, base) {
- this._queue.add({
- directory,
- base
- });
- }
+var Hash = _Hash,
+ ListCache$2 = _ListCache,
+ Map$3 = _Map;
+/**
+ * Removes all key-value entries from the map.
+ *
+ * @private
+ * @name clear
+ * @memberOf MapCache
+ */
- _handleQueue() {
- for (const item of this._queue.values()) {
- this._handleDirectory(item.directory, item.base);
- }
- }
+function mapCacheClear$1() {
+ this.size = 0;
+ this.__data__ = {
+ 'hash': new Hash(),
+ 'map': new (Map$3 || ListCache$2)(),
+ 'string': new Hash()
+ };
+}
- _handleDirectory(directory, base) {
- try {
- const entries = this._scandir(directory, this._settings.fsScandirSettings);
+var _mapCacheClear = mapCacheClear$1;
- for (const entry of entries) {
- this._handleEntry(entry, base);
- }
- } catch (error) {
- this._handleError(error);
- }
- }
+/**
+ * Checks if `value` is suitable for use as unique object key.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
+ */
- _handleError(error) {
- if (!common.isFatalError(this._settings, error)) {
- return;
- }
+function isKeyable$1(value) {
+ var type = typeof value;
+ return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
+}
- throw error;
- }
+var _isKeyable = isKeyable$1;
- _handleEntry(entry, base) {
- const fullpath = entry.path;
+var isKeyable = _isKeyable;
+/**
+ * Gets the data for `map`.
+ *
+ * @private
+ * @param {Object} map The map to query.
+ * @param {string} key The reference key.
+ * @returns {*} Returns the map data.
+ */
- if (base !== undefined) {
- entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
- }
+function getMapData$4(map, key) {
+ var data = map.__data__;
+ return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
+}
- if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
- this._pushToStorage(entry);
- }
+var _getMapData = getMapData$4;
- if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
- this._pushToQueue(fullpath, entry.path);
- }
- }
+var getMapData$3 = _getMapData;
+/**
+ * Removes `key` and its value from the map.
+ *
+ * @private
+ * @name delete
+ * @memberOf MapCache
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
- _pushToStorage(entry) {
- this._storage.add(entry);
- }
+function mapCacheDelete$1(key) {
+ var result = getMapData$3(this, key)['delete'](key);
+ this.size -= result ? 1 : 0;
+ return result;
+}
- }
+var _mapCacheDelete = mapCacheDelete$1;
- exports.default = SyncReader;
-});
+var getMapData$2 = _getMapData;
+/**
+ * Gets the map value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf MapCache
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
+ */
-var sync$3 = createCommonjsModule(function (module, exports) {
+function mapCacheGet$1(key) {
+ return getMapData$2(this, key).get(key);
+}
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var _mapCacheGet = mapCacheGet$1;
- class SyncProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new sync$2.default(this._root, this._settings);
- }
+var getMapData$1 = _getMapData;
+/**
+ * Checks if a map value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf MapCache
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
- read() {
- return this._reader.read();
- }
+function mapCacheHas$1(key) {
+ return getMapData$1(this, key).has(key);
+}
- }
+var _mapCacheHas = mapCacheHas$1;
- exports.default = SyncProvider;
-});
+var getMapData = _getMapData;
+/**
+ * Sets the map `key` to `value`.
+ *
+ * @private
+ * @name set
+ * @memberOf MapCache
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the map cache instance.
+ */
-var settings$2 = createCommonjsModule(function (module, exports) {
+function mapCacheSet$1(key, value) {
+ var data = getMapData(this, key),
+ size = data.size;
+ data.set(key, value);
+ this.size += data.size == size ? 0 : 1;
+ return this;
+}
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var _mapCacheSet = mapCacheSet$1;
- class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.basePath = this._getValue(this._options.basePath, undefined);
- this.concurrency = this._getValue(this._options.concurrency, Infinity);
- this.deepFilter = this._getValue(this._options.deepFilter, null);
- this.entryFilter = this._getValue(this._options.entryFilter, null);
- this.errorFilter = this._getValue(this._options.errorFilter, null);
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
- this.fsScandirSettings = new out$1.Settings({
- followSymbolicLinks: this._options.followSymbolicLinks,
- fs: this._options.fs,
- pathSegmentSeparator: this._options.pathSegmentSeparator,
- stats: this._options.stats,
- throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
- });
- }
+var mapCacheClear = _mapCacheClear,
+ mapCacheDelete = _mapCacheDelete,
+ mapCacheGet = _mapCacheGet,
+ mapCacheHas = _mapCacheHas,
+ mapCacheSet = _mapCacheSet;
+/**
+ * Creates a map cache object to store key-value pairs.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [entries] The key-value pairs to cache.
+ */
- _getValue(option, value) {
- return option === undefined ? value : option;
- }
+function MapCache$3(entries) {
+ var index = -1,
+ length = entries == null ? 0 : entries.length;
+ this.clear();
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
}
+} // Add methods to `MapCache`.
- exports.default = Settings;
-});
-var out$2 = createCommonjsModule(function (module, exports) {
+MapCache$3.prototype.clear = mapCacheClear;
+MapCache$3.prototype['delete'] = mapCacheDelete;
+MapCache$3.prototype.get = mapCacheGet;
+MapCache$3.prototype.has = mapCacheHas;
+MapCache$3.prototype.set = mapCacheSet;
+var _MapCache = MapCache$3;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Settings = settings$2.default;
+var ListCache$1 = _ListCache,
+ Map$2 = _Map,
+ MapCache$2 = _MapCache;
+/** Used as the size to enable large array optimizations. */
+
+var LARGE_ARRAY_SIZE = 200;
+/**
+ * Sets the stack `key` to `value`.
+ *
+ * @private
+ * @name set
+ * @memberOf Stack
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the stack cache instance.
+ */
+
+function stackSet$1(key, value) {
+ var data = this.__data__;
- function walk(directory, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- return new async$3.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
+ if (data instanceof ListCache$1) {
+ var pairs = data.__data__;
+
+ if (!Map$2 || pairs.length < LARGE_ARRAY_SIZE - 1) {
+ pairs.push([key, value]);
+ this.size = ++data.size;
+ return this;
}
- new async$3.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
+ data = this.__data__ = new MapCache$2(pairs);
}
- exports.walk = walk;
+ data.set(key, value);
+ this.size = data.size;
+ return this;
+}
- function walkSync(directory, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- const provider = new sync$3.default(directory, settings);
- return provider.read();
- }
+var _stackSet = stackSet$1;
- exports.walkSync = walkSync;
+var ListCache = _ListCache,
+ stackClear = _stackClear,
+ stackDelete = _stackDelete,
+ stackGet = _stackGet,
+ stackHas = _stackHas,
+ stackSet = _stackSet;
+/**
+ * Creates a stack cache object to store key-value pairs.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [entries] The key-value pairs to cache.
+ */
- function walkStream(directory, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- const provider = new stream$1.default(directory, settings);
- return provider.read();
- }
+function Stack$2(entries) {
+ var data = this.__data__ = new ListCache(entries);
+ this.size = data.size;
+} // Add methods to `Stack`.
- exports.walkStream = walkStream;
- function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings$2.default) {
- return settingsOrOptions;
- }
+Stack$2.prototype.clear = stackClear;
+Stack$2.prototype['delete'] = stackDelete;
+Stack$2.prototype.get = stackGet;
+Stack$2.prototype.has = stackHas;
+Stack$2.prototype.set = stackSet;
+var _Stack = Stack$2;
- return new settings$2.default(settingsOrOptions);
- }
-});
+/** Used to stand-in for `undefined` hash values. */
+var HASH_UNDEFINED = '__lodash_hash_undefined__';
+/**
+ * Adds `value` to the array cache.
+ *
+ * @private
+ * @name add
+ * @memberOf SetCache
+ * @alias push
+ * @param {*} value The value to cache.
+ * @returns {Object} Returns the cache instance.
+ */
-var reader$1 = createCommonjsModule(function (module, exports) {
+function setCacheAdd$1(value) {
+ this.__data__.set(value, HASH_UNDEFINED);
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+ return this;
+}
- class Reader {
- constructor(_settings) {
- this._settings = _settings;
- this._fsStatSettings = new out.Settings({
- followSymbolicLink: this._settings.followSymbolicLinks,
- fs: this._settings.fs,
- throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
- });
- }
+var _setCacheAdd = setCacheAdd$1;
- _getFullEntryPath(filepath) {
- return path__default['default'].resolve(this._settings.cwd, filepath);
- }
+/**
+ * Checks if `value` is in the array cache.
+ *
+ * @private
+ * @name has
+ * @memberOf SetCache
+ * @param {*} value The value to search for.
+ * @returns {number} Returns `true` if `value` is found, else `false`.
+ */
- _makeEntry(stats, pattern) {
- const entry = {
- name: pattern,
- path: pattern,
- dirent: utils$2.fs.createDirentFromStats(pattern, stats)
- };
+function setCacheHas$1(value) {
+ return this.__data__.has(value);
+}
- if (this._settings.stats) {
- entry.stats = stats;
- }
+var _setCacheHas = setCacheHas$1;
- return entry;
- }
+var MapCache$1 = _MapCache,
+ setCacheAdd = _setCacheAdd,
+ setCacheHas = _setCacheHas;
+/**
+ *
+ * Creates an array cache object to store unique values.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [values] The values to cache.
+ */
- _isFatalError(error) {
- return !utils$2.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
- }
+function SetCache$1(values) {
+ var index = -1,
+ length = values == null ? 0 : values.length;
+ this.__data__ = new MapCache$1();
+ while (++index < length) {
+ this.add(values[index]);
}
+} // Add methods to `SetCache`.
- exports.default = Reader;
-});
-var stream$2 = createCommonjsModule(function (module, exports) {
+SetCache$1.prototype.add = SetCache$1.prototype.push = setCacheAdd;
+SetCache$1.prototype.has = setCacheHas;
+var _SetCache = SetCache$1;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+/**
+ * A specialized version of `_.some` for arrays without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
+ * else `false`.
+ */
- class ReaderStream extends reader$1.default {
- constructor() {
- super(...arguments);
- this._walkStream = out$2.walkStream;
- this._stat = out.stat;
- }
+function arraySome$1(array, predicate) {
+ var index = -1,
+ length = array == null ? 0 : array.length;
- dynamic(root, options) {
- return this._walkStream(root, options);
+ while (++index < length) {
+ if (predicate(array[index], index, array)) {
+ return true;
}
+ }
- static(patterns, options) {
- const filepaths = patterns.map(this._getFullEntryPath, this);
- const stream = new stream_1__default['default'].PassThrough({
- objectMode: true
- });
+ return false;
+}
- stream._write = (index, _enc, done) => {
- return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
- if (entry !== null && options.entryFilter(entry)) {
- stream.push(entry);
- }
+var _arraySome = arraySome$1;
- if (index === filepaths.length - 1) {
- stream.end();
- }
+/**
+ * Checks if a `cache` value for `key` exists.
+ *
+ * @private
+ * @param {Object} cache The cache to query.
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
- done();
- }).catch(done);
- };
+function cacheHas$1(cache, key) {
+ return cache.has(key);
+}
- for (let i = 0; i < filepaths.length; i++) {
- stream.write(i);
- }
+var _cacheHas = cacheHas$1;
- return stream;
- }
+var SetCache = _SetCache,
+ arraySome = _arraySome,
+ cacheHas = _cacheHas;
+/** Used to compose bitmasks for value comparisons. */
- _getEntry(filepath, pattern, options) {
- return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
- if (options.errorFilter(error)) {
- return null;
- }
+var COMPARE_PARTIAL_FLAG$5 = 1,
+ COMPARE_UNORDERED_FLAG$3 = 2;
+/**
+ * A specialized version of `baseIsEqualDeep` for arrays with support for
+ * partial deep comparisons.
+ *
+ * @private
+ * @param {Array} array The array to compare.
+ * @param {Array} other The other array to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `array` and `other` objects.
+ * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
+ */
- throw error;
- });
- }
+function equalArrays$2(array, other, bitmask, customizer, equalFunc, stack) {
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5,
+ arrLength = array.length,
+ othLength = other.length;
- _getStat(filepath) {
- return new Promise((resolve, reject) => {
- this._stat(filepath, this._fsStatSettings, (error, stats) => {
- return error === null ? resolve(stats) : reject(error);
- });
- });
- }
+ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
+ return false;
+ } // Check that cyclic values are equal.
- }
- exports.default = ReaderStream;
-});
+ var arrStacked = stack.get(array);
+ var othStacked = stack.get(other);
-var matcher = createCommonjsModule(function (module, exports) {
+ if (arrStacked && othStacked) {
+ return arrStacked == other && othStacked == array;
+ }
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+ var index = -1,
+ result = true,
+ seen = bitmask & COMPARE_UNORDERED_FLAG$3 ? new SetCache() : undefined;
+ stack.set(array, other);
+ stack.set(other, array); // Ignore non-index properties.
- class Matcher {
- constructor(_patterns, _settings, _micromatchOptions) {
- this._patterns = _patterns;
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- this._storage = [];
+ while (++index < arrLength) {
+ var arrValue = array[index],
+ othValue = other[index];
- this._fillStorage();
+ if (customizer) {
+ var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
}
- _fillStorage() {
- /**\r
- * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).\r
- * So, before expand patterns with brace expansion into separated patterns.\r
- */
- const patterns = utils$2.pattern.expandPatternsWithBraceExpansion(this._patterns);
+ if (compared !== undefined) {
+ if (compared) {
+ continue;
+ }
- for (const pattern of patterns) {
- const segments = this._getPatternSegments(pattern);
+ result = false;
+ break;
+ } // Recursively compare arrays (susceptible to call stack limits).
- const sections = this._splitSegmentsIntoSections(segments);
- this._storage.push({
- complete: sections.length <= 1,
- pattern,
- segments,
- sections
- });
+ if (seen) {
+ if (!arraySome(other, function (othValue, othIndex) {
+ if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
+ return seen.push(othIndex);
+ }
+ })) {
+ result = false;
+ break;
}
+ } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
+ result = false;
+ break;
}
+ }
- _getPatternSegments(pattern) {
- const parts = utils$2.pattern.getPatternParts(pattern, this._micromatchOptions);
- return parts.map(part => {
- const dynamic = utils$2.pattern.isDynamicPattern(part, this._settings);
+ stack['delete'](array);
+ stack['delete'](other);
+ return result;
+}
- if (!dynamic) {
- return {
- dynamic: false,
- pattern: part
- };
- }
+var _equalArrays = equalArrays$2;
- return {
- dynamic: true,
- pattern: part,
- patternRe: utils$2.pattern.makeRe(part, this._micromatchOptions)
- };
- });
- }
+var root$4 = _root;
+/** Built-in value references. */
- _splitSegmentsIntoSections(segments) {
- return utils$2.array.splitWhen(segments, segment => segment.dynamic && utils$2.pattern.hasGlobStar(segment.pattern));
- }
+var Uint8Array$1 = root$4.Uint8Array;
+var _Uint8Array = Uint8Array$1;
- }
+/**
+ * Converts `map` to its key-value pairs.
+ *
+ * @private
+ * @param {Object} map The map to convert.
+ * @returns {Array} Returns the key-value pairs.
+ */
- exports.default = Matcher;
-});
+function mapToArray$1(map) {
+ var index = -1,
+ result = Array(map.size);
+ map.forEach(function (value, key) {
+ result[++index] = [key, value];
+ });
+ return result;
+}
-var partial = createCommonjsModule(function (module, exports) {
+var _mapToArray = mapToArray$1;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+/**
+ * Converts `set` to an array of its values.
+ *
+ * @private
+ * @param {Object} set The set to convert.
+ * @returns {Array} Returns the values.
+ */
- class PartialMatcher extends matcher.default {
- match(filepath) {
- const parts = filepath.split('/');
- const levels = parts.length;
-
- const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
-
- for (const pattern of patterns) {
- const section = pattern.sections[0];
- /**\r
- * In this case, the pattern has a globstar and we must read all directories unconditionally,\r
- * but only if the level has reached the end of the first group.\r
- *\r
- * fixtures/{a,b}/**\r
- * ^ true/false ^ always true\r
- */
+function setToArray$1(set) {
+ var index = -1,
+ result = Array(set.size);
+ set.forEach(function (value) {
+ result[++index] = value;
+ });
+ return result;
+}
- if (!pattern.complete && levels > section.length) {
- return true;
- }
+var _setToArray = setToArray$1;
- const match = parts.every((part, index) => {
- const segment = pattern.segments[index];
+var Symbol$3 = _Symbol,
+ Uint8Array = _Uint8Array,
+ eq$1 = eq_1,
+ equalArrays$1 = _equalArrays,
+ mapToArray = _mapToArray,
+ setToArray = _setToArray;
+/** Used to compose bitmasks for value comparisons. */
- if (segment.dynamic && segment.patternRe.test(part)) {
- return true;
- }
+var COMPARE_PARTIAL_FLAG$4 = 1,
+ COMPARE_UNORDERED_FLAG$2 = 2;
+/** `Object#toString` result references. */
- if (!segment.dynamic && segment.pattern === part) {
- return true;
- }
+var boolTag = '[object Boolean]',
+ dateTag = '[object Date]',
+ errorTag = '[object Error]',
+ mapTag$1 = '[object Map]',
+ numberTag = '[object Number]',
+ regexpTag = '[object RegExp]',
+ setTag$1 = '[object Set]',
+ stringTag = '[object String]',
+ symbolTag$1 = '[object Symbol]';
+var arrayBufferTag = '[object ArrayBuffer]',
+ dataViewTag$1 = '[object DataView]';
+/** Used to convert symbols to primitives and strings. */
- return false;
- });
+var symbolProto$1 = Symbol$3 ? Symbol$3.prototype : undefined,
+ symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
+/**
+ * A specialized version of `baseIsEqualDeep` for comparing objects of
+ * the same `toStringTag`.
+ *
+ * **Note:** This function only supports comparing values with tags of
+ * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {string} tag The `toStringTag` of the objects to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
- if (match) {
- return true;
- }
+function equalByTag$1(object, other, tag, bitmask, customizer, equalFunc, stack) {
+ switch (tag) {
+ case dataViewTag$1:
+ if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
+ return false;
}
- return false;
- }
+ object = object.buffer;
+ other = other.buffer;
- }
+ case arrayBufferTag:
+ if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
+ return false;
+ }
- exports.default = PartialMatcher;
-});
+ return true;
-var deep = createCommonjsModule(function (module, exports) {
+ case boolTag:
+ case dateTag:
+ case numberTag:
+ // Coerce booleans to `1` or `0` and dates to milliseconds.
+ // Invalid dates are coerced to `NaN`.
+ return eq$1(+object, +other);
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+ case errorTag:
+ return object.name == other.name && object.message == other.message;
- class DeepFilter {
- constructor(_settings, _micromatchOptions) {
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- }
+ case regexpTag:
+ case stringTag:
+ // Coerce regexes to strings and treat strings, primitives and objects,
+ // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
+ // for more details.
+ return object == other + '';
- getFilter(basePath, positive, negative) {
- const matcher = this._getMatcher(positive);
+ case mapTag$1:
+ var convert = mapToArray;
- const negativeRe = this._getNegativePatternsRe(negative);
+ case setTag$1:
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
+ convert || (convert = setToArray);
- return entry => this._filter(basePath, entry, matcher, negativeRe);
- }
+ if (object.size != other.size && !isPartial) {
+ return false;
+ } // Assume cyclic values are equal.
- _getMatcher(patterns) {
- return new partial.default(patterns, this._settings, this._micromatchOptions);
- }
- _getNegativePatternsRe(patterns) {
- const affectDepthOfReadingPatterns = patterns.filter(utils$2.pattern.isAffectDepthOfReadingPattern);
- return utils$2.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
- }
+ var stacked = stack.get(object);
- _filter(basePath, entry, matcher, negativeRe) {
- if (this._isSkippedByDeep(basePath, entry.path)) {
- return false;
+ if (stacked) {
+ return stacked == other;
}
- if (this._isSkippedSymbolicLink(entry)) {
- return false;
- }
+ bitmask |= COMPARE_UNORDERED_FLAG$2; // Recursively compare objects (susceptible to call stack limits).
- const filepath = utils$2.path.removeLeadingDotSegment(entry.path);
+ stack.set(object, other);
+ var result = equalArrays$1(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
+ stack['delete'](object);
+ return result;
- if (this._isSkippedByPositivePatterns(filepath, matcher)) {
- return false;
+ case symbolTag$1:
+ if (symbolValueOf) {
+ return symbolValueOf.call(object) == symbolValueOf.call(other);
}
- return this._isSkippedByNegativePatterns(filepath, negativeRe);
- }
+ }
- _isSkippedByDeep(basePath, entryPath) {
- /**\r
- * Avoid unnecessary depth calculations when it doesn't matter.\r
- */
- if (this._settings.deep === Infinity) {
- return false;
- }
+ return false;
+}
- return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
- }
+var _equalByTag = equalByTag$1;
- _getEntryLevel(basePath, entryPath) {
- const entryPathDepth = entryPath.split('/').length;
+/**
+ * Appends the elements of `values` to `array`.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to append.
+ * @returns {Array} Returns `array`.
+ */
- if (basePath === '') {
- return entryPathDepth;
- }
+function arrayPush$2(array, values) {
+ var index = -1,
+ length = values.length,
+ offset = array.length;
- const basePathDepth = basePath.split('/').length;
- return entryPathDepth - basePathDepth;
- }
+ while (++index < length) {
+ array[offset + index] = values[index];
+ }
- _isSkippedSymbolicLink(entry) {
- return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
- }
+ return array;
+}
- _isSkippedByPositivePatterns(entryPath, matcher) {
- return !this._settings.baseNameMatch && !matcher.match(entryPath);
- }
+var _arrayPush = arrayPush$2;
- _isSkippedByNegativePatterns(entryPath, patternsRe) {
- return !utils$2.pattern.matchAny(entryPath, patternsRe);
- }
+var arrayPush$1 = _arrayPush,
+ isArray$8 = isArray_1;
+/**
+ * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
+ * `keysFunc` and `symbolsFunc` to get the enumerable property names and
+ * symbols of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @param {Function} symbolsFunc The function to get the symbols of `object`.
+ * @returns {Array} Returns the array of property names and symbols.
+ */
- }
+function baseGetAllKeys$1(object, keysFunc, symbolsFunc) {
+ var result = keysFunc(object);
+ return isArray$8(object) ? result : arrayPush$1(result, symbolsFunc(object));
+}
- exports.default = DeepFilter;
-});
+var _baseGetAllKeys = baseGetAllKeys$1;
-var entry = createCommonjsModule(function (module, exports) {
+/**
+ * A specialized version of `_.filter` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {Array} Returns the new filtered array.
+ */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+function arrayFilter$1(array, predicate) {
+ var index = -1,
+ length = array == null ? 0 : array.length,
+ resIndex = 0,
+ result = [];
- class EntryFilter {
- constructor(_settings, _micromatchOptions) {
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- this.index = new Map();
- }
+ while (++index < length) {
+ var value = array[index];
- getFilter(positive, negative) {
- const positiveRe = utils$2.pattern.convertPatternsToRe(positive, this._micromatchOptions);
- const negativeRe = utils$2.pattern.convertPatternsToRe(negative, this._micromatchOptions);
- return entry => this._filter(entry, positiveRe, negativeRe);
+ if (predicate(value, index, array)) {
+ result[resIndex++] = value;
}
+ }
- _filter(entry, positiveRe, negativeRe) {
- if (this._settings.unique && this._isDuplicateEntry(entry)) {
- return false;
- }
-
- if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
- return false;
- }
-
- if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
- return false;
- }
-
- const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
- const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
-
- if (this._settings.unique && isMatched) {
- this._createIndexRecord(entry);
- }
+ return result;
+}
- return isMatched;
- }
+var _arrayFilter = arrayFilter$1;
- _isDuplicateEntry(entry) {
- return this.index.has(entry.path);
- }
+/**
+ * This method returns a new empty array.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.13.0
+ * @category Util
+ * @returns {Array} Returns the new empty array.
+ * @example
+ *
+ * var arrays = _.times(2, _.stubArray);
+ *
+ * console.log(arrays);
+ * // => [[], []]
+ *
+ * console.log(arrays[0] === arrays[1]);
+ * // => false
+ */
- _createIndexRecord(entry) {
- this.index.set(entry.path, undefined);
- }
+function stubArray$1() {
+ return [];
+}
- _onlyFileFilter(entry) {
- return this._settings.onlyFiles && !entry.dirent.isFile();
- }
+var stubArray_1 = stubArray$1;
- _onlyDirectoryFilter(entry) {
- return this._settings.onlyDirectories && !entry.dirent.isDirectory();
- }
+var arrayFilter = _arrayFilter,
+ stubArray = stubArray_1;
+/** Used for built-in method references. */
- _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
- if (!this._settings.absolute) {
- return false;
- }
+var objectProto$4 = Object.prototype;
+/** Built-in value references. */
- const fullpath = utils$2.path.makeAbsolute(this._settings.cwd, entryPath);
- return utils$2.pattern.matchAny(fullpath, patternsRe);
- }
+var propertyIsEnumerable = objectProto$4.propertyIsEnumerable;
+/* Built-in method references for those with the same name as other `lodash` methods. */
- _isMatchToPatterns(entryPath, patternsRe) {
- const filepath = utils$2.path.removeLeadingDotSegment(entryPath);
- return utils$2.pattern.matchAny(filepath, patternsRe);
- }
+var nativeGetSymbols = Object.getOwnPropertySymbols;
+/**
+ * Creates an array of the own enumerable symbols of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of symbols.
+ */
+var getSymbols$1 = !nativeGetSymbols ? stubArray : function (object) {
+ if (object == null) {
+ return [];
}
- exports.default = EntryFilter;
-});
-
-var error = createCommonjsModule(function (module, exports) {
-
- Object.defineProperty(exports, "__esModule", {
- value: true
+ object = Object(object);
+ return arrayFilter(nativeGetSymbols(object), function (symbol) {
+ return propertyIsEnumerable.call(object, symbol);
});
+};
+var _getSymbols = getSymbols$1;
- class ErrorFilter {
- constructor(_settings) {
- this._settings = _settings;
- }
-
- getFilter() {
- return error => this._isNonFatalError(error);
- }
-
- _isNonFatalError(error) {
- return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
- }
-
- }
-
- exports.default = ErrorFilter;
-});
-
-var entry$1 = createCommonjsModule(function (module, exports) {
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var baseGetAllKeys = _baseGetAllKeys,
+ getSymbols = _getSymbols,
+ keys$1 = keys_1;
+/**
+ * Creates an array of own enumerable property names and symbols of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names and symbols.
+ */
- class EntryTransformer {
- constructor(_settings) {
- this._settings = _settings;
- }
+function getAllKeys$1(object) {
+ return baseGetAllKeys(object, keys$1, getSymbols);
+}
- getTransformer() {
- return entry => this._transform(entry);
- }
+var _getAllKeys = getAllKeys$1;
- _transform(entry) {
- let filepath = entry.path;
+var getAllKeys = _getAllKeys;
+/** Used to compose bitmasks for value comparisons. */
- if (this._settings.absolute) {
- filepath = utils$2.path.makeAbsolute(this._settings.cwd, filepath);
- filepath = utils$2.path.unixify(filepath);
- }
+var COMPARE_PARTIAL_FLAG$3 = 1;
+/** Used for built-in method references. */
- if (this._settings.markDirectories && entry.dirent.isDirectory()) {
- filepath += '/';
- }
+var objectProto$3 = Object.prototype;
+/** Used to check objects for own properties. */
- if (!this._settings.objectMode) {
- return filepath;
- }
+var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
+/**
+ * A specialized version of `baseIsEqualDeep` for objects with support for
+ * partial deep comparisons.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
- return Object.assign(Object.assign({}, entry), {
- path: filepath
- });
- }
+function equalObjects$1(object, other, bitmask, customizer, equalFunc, stack) {
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3,
+ objProps = getAllKeys(object),
+ objLength = objProps.length,
+ othProps = getAllKeys(other),
+ othLength = othProps.length;
+ if (objLength != othLength && !isPartial) {
+ return false;
}
- exports.default = EntryTransformer;
-});
-
-var provider = createCommonjsModule(function (module, exports) {
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+ var index = objLength;
- class Provider {
- constructor(_settings) {
- this._settings = _settings;
- this.errorFilter = new error.default(this._settings);
- this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions());
- this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions());
- this.entryTransformer = new entry$1.default(this._settings);
- }
+ while (index--) {
+ var key = objProps[index];
- _getRootDirectory(task) {
- return path__default['default'].resolve(this._settings.cwd, task.base);
+ if (!(isPartial ? key in other : hasOwnProperty$3.call(other, key))) {
+ return false;
}
+ } // Check that cyclic values are equal.
- _getReaderOptions(task) {
- const basePath = task.base === '.' ? '' : task.base;
- return {
- basePath,
- pathSegmentSeparator: '/',
- concurrency: this._settings.concurrency,
- deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
- entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
- errorFilter: this.errorFilter.getFilter(),
- followSymbolicLinks: this._settings.followSymbolicLinks,
- fs: this._settings.fs,
- stats: this._settings.stats,
- throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
- transform: this.entryTransformer.getTransformer()
- };
- }
- _getMicromatchOptions() {
- return {
- dot: this._settings.dot,
- matchBase: this._settings.baseNameMatch,
- nobrace: !this._settings.braceExpansion,
- nocase: !this._settings.caseSensitiveMatch,
- noext: !this._settings.extglob,
- noglobstar: !this._settings.globstar,
- posix: true,
- strictSlashes: false
- };
- }
+ var objStacked = stack.get(object);
+ var othStacked = stack.get(other);
+ if (objStacked && othStacked) {
+ return objStacked == other && othStacked == object;
}
- exports.default = Provider;
-});
-
-var async$4 = createCommonjsModule(function (module, exports) {
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+ var result = true;
+ stack.set(object, other);
+ stack.set(other, object);
+ var skipCtor = isPartial;
- class ProviderAsync extends provider.default {
- constructor() {
- super(...arguments);
- this._reader = new stream$2.default(this._settings);
- }
+ while (++index < objLength) {
+ key = objProps[index];
+ var objValue = object[key],
+ othValue = other[key];
- read(task) {
- const root = this._getRootDirectory(task);
+ if (customizer) {
+ var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
+ } // Recursively compare objects (susceptible to call stack limits).
- const options = this._getReaderOptions(task);
- const entries = [];
- return new Promise((resolve, reject) => {
- const stream = this.api(root, task, options);
- stream.once('error', reject);
- stream.on('data', entry => entries.push(options.transform(entry)));
- stream.once('end', () => resolve(entries));
- });
+ if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
+ result = false;
+ break;
}
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
- }
+ skipCtor || (skipCtor = key == 'constructor');
+ }
- return this._reader.static(task.patterns, options);
- }
+ if (result && !skipCtor) {
+ var objCtor = object.constructor,
+ othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
+ if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
+ result = false;
+ }
}
- exports.default = ProviderAsync;
-});
+ stack['delete'](object);
+ stack['delete'](other);
+ return result;
+}
-var stream$3 = createCommonjsModule(function (module, exports) {
+var _equalObjects = equalObjects$1;
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var getNative$4 = _getNative,
+ root$3 = _root;
+/* Built-in method references that are verified to be native. */
- class ProviderStream extends provider.default {
- constructor() {
- super(...arguments);
- this._reader = new stream$2.default(this._settings);
- }
+var DataView$1 = getNative$4(root$3, 'DataView');
+var _DataView = DataView$1;
- read(task) {
- const root = this._getRootDirectory(task);
+var getNative$3 = _getNative,
+ root$2 = _root;
+/* Built-in method references that are verified to be native. */
- const options = this._getReaderOptions(task);
+var Promise$2 = getNative$3(root$2, 'Promise');
+var _Promise = Promise$2;
- const source = this.api(root, task, options);
- const destination = new stream_1__default['default'].Readable({
- objectMode: true,
- read: () => {}
- });
- source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
- destination.once('close', () => source.destroy());
- return destination;
- }
+var getNative$2 = _getNative,
+ root$1 = _root;
+/* Built-in method references that are verified to be native. */
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
- }
+var Set$2 = getNative$2(root$1, 'Set');
+var _Set = Set$2;
- return this._reader.static(task.patterns, options);
- }
+var getNative$1 = _getNative,
+ root = _root;
+/* Built-in method references that are verified to be native. */
- }
+var WeakMap$2 = getNative$1(root, 'WeakMap');
+var _WeakMap = WeakMap$2;
- exports.default = ProviderStream;
-});
+var DataView = _DataView,
+ Map$1 = _Map,
+ Promise$1 = _Promise,
+ Set$1 = _Set,
+ WeakMap$1 = _WeakMap,
+ baseGetTag$1 = _baseGetTag,
+ toSource = _toSource;
+/** `Object#toString` result references. */
-var sync$4 = createCommonjsModule(function (module, exports) {
+var mapTag = '[object Map]',
+ objectTag$1 = '[object Object]',
+ promiseTag = '[object Promise]',
+ setTag = '[object Set]',
+ weakMapTag = '[object WeakMap]';
+var dataViewTag = '[object DataView]';
+/** Used to detect maps, sets, and weakmaps. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+var dataViewCtorString = toSource(DataView),
+ mapCtorString = toSource(Map$1),
+ promiseCtorString = toSource(Promise$1),
+ setCtorString = toSource(Set$1),
+ weakMapCtorString = toSource(WeakMap$1);
+/**
+ * Gets the `toStringTag` of `value`.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @returns {string} Returns the `toStringTag`.
+ */
- class ReaderSync extends reader$1.default {
- constructor() {
- super(...arguments);
- this._walkSync = out$2.walkSync;
- this._statSync = out.statSync;
- }
+var getTag$1 = baseGetTag$1; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
- dynamic(root, options) {
- return this._walkSync(root, options);
- }
+if (DataView && getTag$1(new DataView(new ArrayBuffer(1))) != dataViewTag || Map$1 && getTag$1(new Map$1()) != mapTag || Promise$1 && getTag$1(Promise$1.resolve()) != promiseTag || Set$1 && getTag$1(new Set$1()) != setTag || WeakMap$1 && getTag$1(new WeakMap$1()) != weakMapTag) {
+ getTag$1 = function (value) {
+ var result = baseGetTag$1(value),
+ Ctor = result == objectTag$1 ? value.constructor : undefined,
+ ctorString = Ctor ? toSource(Ctor) : '';
- static(patterns, options) {
- const entries = [];
+ if (ctorString) {
+ switch (ctorString) {
+ case dataViewCtorString:
+ return dataViewTag;
- for (const pattern of patterns) {
- const filepath = this._getFullEntryPath(pattern);
+ case mapCtorString:
+ return mapTag;
- const entry = this._getEntry(filepath, pattern, options);
+ case promiseCtorString:
+ return promiseTag;
- if (entry === null || !options.entryFilter(entry)) {
- continue;
- }
+ case setCtorString:
+ return setTag;
- entries.push(entry);
+ case weakMapCtorString:
+ return weakMapTag;
}
-
- return entries;
}
- _getEntry(filepath, pattern, options) {
- try {
- const stats = this._getStat(filepath);
+ return result;
+ };
+}
- return this._makeEntry(stats, pattern);
- } catch (error) {
- if (options.errorFilter(error)) {
- return null;
- }
+var _getTag = getTag$1;
- throw error;
- }
- }
+var Stack$1 = _Stack,
+ equalArrays = _equalArrays,
+ equalByTag = _equalByTag,
+ equalObjects = _equalObjects,
+ getTag = _getTag,
+ isArray$7 = isArray_1,
+ isBuffer = isBuffer$2.exports,
+ isTypedArray = isTypedArray_1;
+/** Used to compose bitmasks for value comparisons. */
- _getStat(filepath) {
- return this._statSync(filepath, this._fsStatSettings);
- }
+var COMPARE_PARTIAL_FLAG$2 = 1;
+/** `Object#toString` result references. */
- }
+var argsTag = '[object Arguments]',
+ arrayTag = '[object Array]',
+ objectTag = '[object Object]';
+/** Used for built-in method references. */
- exports.default = ReaderSync;
-});
+var objectProto$2 = Object.prototype;
+/** Used to check objects for own properties. */
-var sync$5 = createCommonjsModule(function (module, exports) {
+var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
+/**
+ * A specialized version of `baseIsEqual` for arrays and objects which performs
+ * deep comparisons and tracks traversed objects enabling objects with circular
+ * references to be compared.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} [stack] Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
+function baseIsEqualDeep$1(object, other, bitmask, customizer, equalFunc, stack) {
+ var objIsArr = isArray$7(object),
+ othIsArr = isArray$7(other),
+ objTag = objIsArr ? arrayTag : getTag(object),
+ othTag = othIsArr ? arrayTag : getTag(other);
+ objTag = objTag == argsTag ? objectTag : objTag;
+ othTag = othTag == argsTag ? objectTag : othTag;
+ var objIsObj = objTag == objectTag,
+ othIsObj = othTag == objectTag,
+ isSameTag = objTag == othTag;
- class ProviderSync extends provider.default {
- constructor() {
- super(...arguments);
- this._reader = new sync$4.default(this._settings);
+ if (isSameTag && isBuffer(object)) {
+ if (!isBuffer(other)) {
+ return false;
}
- read(task) {
- const root = this._getRootDirectory(task);
-
- const options = this._getReaderOptions(task);
+ objIsArr = true;
+ objIsObj = false;
+ }
- const entries = this.api(root, task, options);
- return entries.map(options.transform);
- }
+ if (isSameTag && !objIsObj) {
+ stack || (stack = new Stack$1());
+ return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
+ }
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
- }
+ if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
+ var objIsWrapped = objIsObj && hasOwnProperty$2.call(object, '__wrapped__'),
+ othIsWrapped = othIsObj && hasOwnProperty$2.call(other, '__wrapped__');
- return this._reader.static(task.patterns, options);
+ if (objIsWrapped || othIsWrapped) {
+ var objUnwrapped = objIsWrapped ? object.value() : object,
+ othUnwrapped = othIsWrapped ? other.value() : other;
+ stack || (stack = new Stack$1());
+ return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
-
}
- exports.default = ProviderSync;
-});
-
-var settings$3 = createCommonjsModule(function (module, exports) {
+ if (!isSameTag) {
+ return false;
+ }
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
- const CPU_COUNT = os__default['default'].cpus().length;
- exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
- lstat: fs__default['default'].lstat,
- lstatSync: fs__default['default'].lstatSync,
- stat: fs__default['default'].stat,
- statSync: fs__default['default'].statSync,
- readdir: fs__default['default'].readdir,
- readdirSync: fs__default['default'].readdirSync
- };
+ stack || (stack = new Stack$1());
+ return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
+}
- class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.absolute = this._getValue(this._options.absolute, false);
- this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
- this.braceExpansion = this._getValue(this._options.braceExpansion, true);
- this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
- this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
- this.cwd = this._getValue(this._options.cwd, process.cwd());
- this.deep = this._getValue(this._options.deep, Infinity);
- this.dot = this._getValue(this._options.dot, false);
- this.extglob = this._getValue(this._options.extglob, true);
- this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
- this.fs = this._getFileSystemMethods(this._options.fs);
- this.globstar = this._getValue(this._options.globstar, true);
- this.ignore = this._getValue(this._options.ignore, []);
- this.markDirectories = this._getValue(this._options.markDirectories, false);
- this.objectMode = this._getValue(this._options.objectMode, false);
- this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
- this.onlyFiles = this._getValue(this._options.onlyFiles, true);
- this.stats = this._getValue(this._options.stats, false);
- this.suppressErrors = this._getValue(this._options.suppressErrors, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
- this.unique = this._getValue(this._options.unique, true);
+var _baseIsEqualDeep = baseIsEqualDeep$1;
- if (this.onlyDirectories) {
- this.onlyFiles = false;
- }
+var baseIsEqualDeep = _baseIsEqualDeep,
+ isObjectLike$1 = isObjectLike_1;
+/**
+ * The base implementation of `_.isEqual` which supports partial comparisons
+ * and tracks traversed objects.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @param {boolean} bitmask The bitmask flags.
+ * 1 - Unordered comparison
+ * 2 - Partial comparison
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @param {Object} [stack] Tracks traversed `value` and `other` objects.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ */
- if (this.stats) {
- this.objectMode = true;
- }
- }
+function baseIsEqual$2(value, other, bitmask, customizer, stack) {
+ if (value === other) {
+ return true;
+ }
- _getValue(option, value) {
- return option === undefined ? value : option;
- }
+ if (value == null || other == null || !isObjectLike$1(value) && !isObjectLike$1(other)) {
+ return value !== value && other !== other;
+ }
- _getFileSystemMethods(methods = {}) {
- return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
- }
+ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual$2, stack);
+}
- }
+var _baseIsEqual = baseIsEqual$2;
- exports.default = Settings;
-});
+var Stack = _Stack,
+ baseIsEqual$1 = _baseIsEqual;
+/** Used to compose bitmasks for value comparisons. */
-async function FastGlob(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, async$4.default, options);
- const result = await Promise.all(works);
- return utils$2.array.flatten(result);
-} // https://github.com/typescript-eslint/typescript-eslint/issues/60
-// eslint-disable-next-line no-redeclare
+var COMPARE_PARTIAL_FLAG$1 = 1,
+ COMPARE_UNORDERED_FLAG$1 = 2;
+/**
+ * The base implementation of `_.isMatch` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The object to inspect.
+ * @param {Object} source The object of property values to match.
+ * @param {Array} matchData The property names, values, and compare flags to match.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @returns {boolean} Returns `true` if `object` is a match, else `false`.
+ */
+function baseIsMatch$1(object, source, matchData, customizer) {
+ var index = matchData.length,
+ length = index,
+ noCustomizer = !customizer;
-(function (FastGlob) {
- function sync(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, sync$5.default, options);
- return utils$2.array.flatten(works);
+ if (object == null) {
+ return !length;
}
- FastGlob.sync = sync;
+ object = Object(object);
- function stream(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, stream$3.default, options);
- /**\r
- * The stream returned by the provider cannot work with an asynchronous iterator.\r
- * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.\r
- * This affects performance (+25%). I don't see best solution right now.\r
- */
+ while (index--) {
+ var data = matchData[index];
- return utils$2.stream.merge(works);
+ if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
+ return false;
+ }
}
- FastGlob.stream = stream;
+ while (++index < length) {
+ data = matchData[index];
+ var key = data[0],
+ objValue = object[key],
+ srcValue = data[1];
- function generateTasks(source, options) {
- assertPatternsInput(source);
- const patterns = [].concat(source);
- const settings = new settings$3.default(options);
- return tasks.generate(patterns, settings);
- }
+ if (noCustomizer && data[2]) {
+ if (objValue === undefined && !(key in object)) {
+ return false;
+ }
+ } else {
+ var stack = new Stack();
- FastGlob.generateTasks = generateTasks;
+ if (customizer) {
+ var result = customizer(objValue, srcValue, key, object, source, stack);
+ }
- function isDynamicPattern(source, options) {
- assertPatternsInput(source);
- const settings = new settings$3.default(options);
- return utils$2.pattern.isDynamicPattern(source, settings);
+ if (!(result === undefined ? baseIsEqual$1(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) : result)) {
+ return false;
+ }
+ }
}
- FastGlob.isDynamicPattern = isDynamicPattern;
+ return true;
+}
- function escapePath(source) {
- assertPatternsInput(source);
- return utils$2.path.escape(source);
- }
+var _baseIsMatch = baseIsMatch$1;
- FastGlob.escapePath = escapePath;
-})(FastGlob || (FastGlob = {}));
+var isObject$1 = isObject_1;
+/**
+ * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` if suitable for strict
+ * equality comparisons, else `false`.
+ */
-function getWorks(source, _Provider, options) {
- const patterns = [].concat(source);
- const settings = new settings$3.default(options);
- const tasks$1 = tasks.generate(patterns, settings);
- const provider = new _Provider(settings);
- return tasks$1.map(provider.read, provider);
+function isStrictComparable$2(value) {
+ return value === value && !isObject$1(value);
}
-function assertPatternsInput(input) {
- const source = [].concat(input);
- const isValidSource = source.every(item => utils$2.string.isString(item) && !utils$2.string.isEmpty(item));
+var _isStrictComparable = isStrictComparable$2;
- if (!isValidSource) {
- throw new TypeError('Patterns must be a string (non empty) or an array of strings');
+var isStrictComparable$1 = _isStrictComparable,
+ keys = keys_1;
+/**
+ * Gets the property names, values, and compare flags of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the match data of `object`.
+ */
+
+function getMatchData$1(object) {
+ var result = keys(object),
+ length = result.length;
+
+ while (length--) {
+ var key = result[length],
+ value = object[key];
+ result[length] = [key, value, isStrictComparable$1(value)];
}
-}
-var out$3 = FastGlob;
+ return result;
+}
-/** @typedef {import('./util').Context} Context */
+var _getMatchData = getMatchData$1;
/**
- * @param {Context} context
+ * A specialized version of `matchesProperty` for source values suitable
+ * for strict equality comparisons, i.e. `===`.
+ *
+ * @private
+ * @param {string} key The key of the property to get.
+ * @param {*} srcValue The value to match.
+ * @returns {Function} Returns the new spec function.
*/
+function matchesStrictComparable$2(key, srcValue) {
+ return function (object) {
+ if (object == null) {
+ return false;
+ }
-function* expandPatterns(context) {
- const cwd = process.cwd();
- const seen = new Set();
- let noResults = true;
-
- for (const pathOrError of expandPatternsInternal(context)) {
- noResults = false;
+ return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
+ };
+}
- if (typeof pathOrError !== "string") {
- yield pathOrError;
- continue;
- }
+var _matchesStrictComparable = matchesStrictComparable$2;
- const relativePath = path__default['default'].relative(cwd, pathOrError); // filter out duplicates
+var baseIsMatch = _baseIsMatch,
+ getMatchData = _getMatchData,
+ matchesStrictComparable$1 = _matchesStrictComparable;
+/**
+ * The base implementation of `_.matches` which doesn't clone `source`.
+ *
+ * @private
+ * @param {Object} source The object of property values to match.
+ * @returns {Function} Returns the new spec function.
+ */
- if (seen.has(relativePath)) {
- continue;
- }
+function baseMatches$1(source) {
+ var matchData = getMatchData(source);
- seen.add(relativePath);
- yield relativePath;
+ if (matchData.length == 1 && matchData[0][2]) {
+ return matchesStrictComparable$1(matchData[0][0], matchData[0][1]);
}
- if (noResults) {
- // If there was no files and no other errors, let's yield a general error.
- yield {
- error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`
- };
- }
+ return function (object) {
+ return object === source || baseIsMatch(object, source, matchData);
+ };
}
-/**
- * @param {Context} context
- */
+var _baseMatches = baseMatches$1;
-function* expandPatternsInternal(context) {
- // Ignores files in version control systems directories and `node_modules`
- const silentlyIgnoredDirs = {
- ".git": true,
- ".svn": true,
- ".hg": true,
- node_modules: context.argv["with-node-modules"] !== true
- };
- const globOptions = {
- dot: true,
- ignore: Object.keys(silentlyIgnoredDirs).filter(dir => silentlyIgnoredDirs[dir]).map(dir => "**/" + dir)
- };
- let supportedFilesGlob;
- const cwd = process.cwd();
- /** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */
-
- const entries = [];
-
- for (const pattern of context.filePatterns) {
- const absolutePath = path__default['default'].resolve(cwd, pattern);
-
- if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) {
- continue;
- }
+var baseGetTag = _baseGetTag,
+ isObjectLike = isObjectLike_1;
+/** `Object#toString` result references. */
- const stat = statSafeSync(absolutePath);
+var symbolTag = '[object Symbol]';
+/**
+ * Checks if `value` is classified as a `Symbol` primitive or object.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
+ * @example
+ *
+ * _.isSymbol(Symbol.iterator);
+ * // => true
+ *
+ * _.isSymbol('abc');
+ * // => false
+ */
- if (stat) {
- if (stat.isFile()) {
- entries.push({
- type: "file",
- glob: escapePathForGlob(fixWindowsSlashes(pattern)),
- input: pattern
- });
- } else if (stat.isDirectory()) {
- entries.push({
- type: "dir",
- glob: escapePathForGlob(fixWindowsSlashes(pattern)) + "/" + getSupportedFilesGlob(),
- input: pattern
- });
- }
- } else if (pattern[0] === "!") {
- // convert negative patterns to `ignore` entries
- globOptions.ignore.push(fixWindowsSlashes(pattern.slice(1)));
- } else {
- entries.push({
- type: "glob",
- glob: fixWindowsSlashes(pattern),
- input: pattern
- });
- }
- }
+function isSymbol$3(value) {
+ return typeof value == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag;
+}
- for (const {
- type,
- glob,
- input
- } of entries) {
- let result;
+var isSymbol_1 = isSymbol$3;
- try {
- result = out$3.sync(glob, globOptions);
- } catch ({
- message
- }) {
- /* istanbul ignore next */
- yield {
- error: `${errorMessages.globError[type]}: ${input}\n${message}`
- };
- /* istanbul ignore next */
+var isArray$6 = isArray_1,
+ isSymbol$2 = isSymbol_1;
+/** Used to match property names within property paths. */
- continue;
- }
+var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
+ reIsPlainProp = /^\w*$/;
+/**
+ * Checks if `value` is a property name and not a property path.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {Object} [object] The object to query keys on.
+ * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
+ */
- if (result.length === 0) {
- yield {
- error: `${errorMessages.emptyResults[type]}: "${input}".`
- };
- } else {
- yield* sortPaths(result);
- }
+function isKey$3(value, object) {
+ if (isArray$6(value)) {
+ return false;
}
- function getSupportedFilesGlob() {
- if (!supportedFilesGlob) {
- const extensions = flatten_1(context.languages.map(lang => lang.extensions || []));
- const filenames = flatten_1(context.languages.map(lang => lang.filenames || []));
- supportedFilesGlob = `**/{${extensions.map(ext => "*" + (ext[0] === "." ? ext : "." + ext)).concat(filenames)}}`;
- }
-
- return supportedFilesGlob;
- }
-}
+ var type = typeof value;
-const errorMessages = {
- globError: {
- file: "Unable to resolve file",
- dir: "Unable to expand directory",
- glob: "Unable to expand glob pattern"
- },
- emptyResults: {
- file: "Explicitly specified file was ignored due to negative glob patterns",
- dir: "No supported files were found in the directory",
- glob: "No files matching the pattern were found"
+ if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol$2(value)) {
+ return true;
}
-};
-/**
- * @param {string} absolutePath
- * @param {string} cwd
- * @param {Record<string, boolean>} ignoredDirectories
- */
-function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) {
- return path__default['default'].relative(cwd, absolutePath).split(path__default['default'].sep).some(dir => ignoredDirectories[dir]);
+ return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
-/**
- * @param {string[]} paths
- */
+var _isKey = isKey$3;
-function sortPaths(paths) {
- return paths.sort((a, b) => a.localeCompare(b));
-}
+var MapCache = _MapCache;
+/** Error message constants. */
+
+var FUNC_ERROR_TEXT = 'Expected a function';
/**
- * Get stats of a given path.
- * @param {string} filePath The path to target file.
- * @returns {fs.Stats | undefined} The stats.
+ * Creates a function that memoizes the result of `func`. If `resolver` is
+ * provided, it determines the cache key for storing the result based on the
+ * arguments provided to the memoized function. By default, the first argument
+ * provided to the memoized function is used as the map cache key. The `func`
+ * is invoked with the `this` binding of the memoized function.
+ *
+ * **Note:** The cache is exposed as the `cache` property on the memoized
+ * function. Its creation may be customized by replacing the `_.memoize.Cache`
+ * constructor with one whose instances implement the
+ * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
+ * method interface of `clear`, `delete`, `get`, `has`, and `set`.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Function
+ * @param {Function} func The function to have its output memoized.
+ * @param {Function} [resolver] The function to resolve the cache key.
+ * @returns {Function} Returns the new memoized function.
+ * @example
+ *
+ * var object = { 'a': 1, 'b': 2 };
+ * var other = { 'c': 3, 'd': 4 };
+ *
+ * var values = _.memoize(_.values);
+ * values(object);
+ * // => [1, 2]
+ *
+ * values(other);
+ * // => [3, 4]
+ *
+ * object.a = 2;
+ * values(object);
+ * // => [1, 2]
+ *
+ * // Modify the result cache.
+ * values.cache.set(object, ['a', 'b']);
+ * values(object);
+ * // => ['a', 'b']
+ *
+ * // Replace `_.memoize.Cache`.
+ * _.memoize.Cache = WeakMap;
*/
+function memoize$1(func, resolver) {
+ if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
-function statSafeSync(filePath) {
- try {
- return fs__default['default'].statSync(filePath);
- } catch (error) {
- /* istanbul ignore next */
- if (error.code !== "ENOENT") {
- throw error;
+ var memoized = function () {
+ var args = arguments,
+ key = resolver ? resolver.apply(this, args) : args[0],
+ cache = memoized.cache;
+
+ if (cache.has(key)) {
+ return cache.get(key);
}
- }
-}
-/**
- * This function should be replaced with `fastGlob.escapePath` when these issues are fixed:
- * - https://github.com/mrmlnc/fast-glob/issues/261
- * - https://github.com/mrmlnc/fast-glob/issues/262
- * @param {string} path
- */
+ var result = func.apply(this, args);
+ memoized.cache = cache.set(key, result) || cache;
+ return result;
+ };
+
+ memoized.cache = new (memoize$1.Cache || MapCache)();
+ return memoized;
+} // Expose `MapCache`.
-function escapePathForGlob(path) {
- return out$3.escapePath(path.replace(/\\/g, "\0") // Workaround for fast-glob#262 (part 1)
- ).replace(/\\!/g, "@(!)") // Workaround for fast-glob#261
- .replace(/\0/g, "@(\\\\)"); // Workaround for fast-glob#262 (part 2)
-}
-const isWindows = path__default['default'].sep === "\\";
+memoize$1.Cache = MapCache;
+var memoize_1 = memoize$1;
+
+var memoize = memoize_1;
+/** Used as the maximum memoize cache size. */
+
+var MAX_MEMOIZE_SIZE = 500;
/**
- * Using backslashes in globs is probably not okay, but not accepting
- * backslashes as path separators on Windows is even more not okay.
- * https://github.com/prettier/prettier/pull/6776#discussion_r380723717
- * https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows
- * @param {string} pattern
+ * A specialized version of `_.memoize` which clears the memoized function's
+ * cache when it exceeds `MAX_MEMOIZE_SIZE`.
+ *
+ * @private
+ * @param {Function} func The function to have its output memoized.
+ * @returns {Function} Returns the new memoized function.
*/
-function fixWindowsSlashes(pattern) {
- return isWindows ? pattern.replace(/\\/g, "/") : pattern;
+function memoizeCapped$1(func) {
+ var result = memoize(func, function (key) {
+ if (cache.size === MAX_MEMOIZE_SIZE) {
+ cache.clear();
+ }
+
+ return key;
+ });
+ var cache = result.cache;
+ return result;
}
-var expandPatterns_1 = {
- expandPatterns,
- fixWindowsSlashes
-};
+var _memoizeCapped = memoizeCapped$1;
-var lib = createCommonjsModule(function (module, exports) {
+var memoizeCapped = _memoizeCapped;
+/** Used to match property names within property paths. */
- Object.defineProperty(exports, "__esModule", {
- value: true
- }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either.
+var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
+/** Used to match backslashes in property paths. */
- function noop() {
- var args = [];
+var reEscapeChar = /\\(\\)?/g;
+/**
+ * Converts `string` to a property path array.
+ *
+ * @private
+ * @param {string} string The string to convert.
+ * @returns {Array} Returns the property path array.
+ */
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- }
+var stringToPath$1 = memoizeCapped(function (string) {
+ var result = [];
- function createWeakMap() {
- if (typeof WeakMap !== 'undefined') {
- return new WeakMap();
- } else {
- return fakeSetOrMap();
- }
+ if (string.charCodeAt(0) === 46
+ /* . */
+ ) {
+ result.push('');
}
- /**
- * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything.
- */
+ string.replace(rePropName, function (match, number, quote, subString) {
+ result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
+ });
+ return result;
+});
+var _stringToPath = stringToPath$1;
- function fakeSetOrMap() {
- return {
- add: noop,
- delete: noop,
- get: noop,
- set: noop,
- has: function (k) {
- return false;
- }
- };
- } // Safe hasOwnProperty
-
+/**
+ * A specialized version of `_.map` for arrays without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the new mapped array.
+ */
- var hop = Object.prototype.hasOwnProperty;
+function arrayMap$1(array, iteratee) {
+ var index = -1,
+ length = array == null ? 0 : array.length,
+ result = Array(length);
- var has = function (obj, prop) {
- return hop.call(obj, prop);
- }; // Copy all own enumerable properties from source to target
+ while (++index < length) {
+ result[index] = iteratee(array[index], index, array);
+ }
+ return result;
+}
- function extend(target, source) {
- for (var prop in source) {
- if (has(source, prop)) {
- target[prop] = source[prop];
- }
- }
+var _arrayMap = arrayMap$1;
- return target;
- }
+var Symbol$2 = _Symbol,
+ arrayMap = _arrayMap,
+ isArray$5 = isArray_1,
+ isSymbol$1 = isSymbol_1;
+/** Used as references for various `Number` constants. */
- var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
- var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
- var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
- var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
- var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
+var INFINITY$1 = 1 / 0;
+/** Used to convert symbols to primitives and strings. */
- function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
- // If first interpolated value is a reference to outdent,
- // determine indentation level from the indentation of the interpolated value.
- var indentationLevel = 0;
- var match = strings[0].match(reDetectIndentation);
+var symbolProto = Symbol$2 ? Symbol$2.prototype : undefined,
+ symbolToString = symbolProto ? symbolProto.toString : undefined;
+/**
+ * The base implementation of `_.toString` which doesn't convert nullish
+ * values to empty strings.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {string} Returns the string.
+ */
- if (match) {
- indentationLevel = match[1].length;
- }
+function baseToString$1(value) {
+ // Exit early for strings to avoid a performance hit in some environments.
+ if (typeof value == 'string') {
+ return value;
+ }
- var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
- var reMatchIndent = new RegExp(reSource, 'g');
+ if (isArray$5(value)) {
+ // Recursively convert values (susceptible to call stack limits).
+ return arrayMap(value, baseToString$1) + '';
+ }
- if (firstInterpolatedValueSetsIndentationLevel) {
- strings = strings.slice(1);
- }
+ if (isSymbol$1(value)) {
+ return symbolToString ? symbolToString.call(value) : '';
+ }
- var newline = options.newline,
- trimLeadingNewline = options.trimLeadingNewline,
- trimTrailingNewline = options.trimTrailingNewline;
- var normalizeNewlines = typeof newline === 'string';
- var l = strings.length;
- var outdentedStrings = strings.map(function (v, i) {
- // Remove leading indentation from all lines
- v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string
+ var result = value + '';
+ return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
+}
- if (i === 0 && trimLeadingNewline) {
- v = v.replace(reLeadingNewline, '');
- } // Trim a trailing newline from the last string
+var _baseToString = baseToString$1;
+var baseToString = _baseToString;
+/**
+ * Converts `value` to a string. An empty string is returned for `null`
+ * and `undefined` values. The sign of `-0` is preserved.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {string} Returns the converted string.
+ * @example
+ *
+ * _.toString(null);
+ * // => ''
+ *
+ * _.toString(-0);
+ * // => '-0'
+ *
+ * _.toString([1, 2, 3]);
+ * // => '1,2,3'
+ */
- if (i === l - 1 && trimTrailingNewline) {
- v = v.replace(reTrailingNewline, '');
- } // Normalize newlines
+function toString$1(value) {
+ return value == null ? '' : baseToString(value);
+}
+var toString_1 = toString$1;
- if (normalizeNewlines) {
- v = v.replace(/\r\n|\n|\r/g, function (_) {
- return newline;
- });
- }
+var isArray$4 = isArray_1,
+ isKey$2 = _isKey,
+ stringToPath = _stringToPath,
+ toString = toString_1;
+/**
+ * Casts `value` to a path array if it's not one.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @param {Object} [object] The object to query keys on.
+ * @returns {Array} Returns the cast property path array.
+ */
- return v;
- });
- return outdentedStrings;
+function castPath$4(value, object) {
+ if (isArray$4(value)) {
+ return value;
}
- function concatStringsAndValues(strings, values) {
- var ret = '';
+ return isKey$2(value, object) ? [value] : stringToPath(toString(value));
+}
- for (var i = 0, l = strings.length; i < l; i++) {
- ret += strings[i];
+var _castPath = castPath$4;
- if (i < l - 1) {
- ret += values[i];
- }
- }
+var isSymbol = isSymbol_1;
+/** Used as references for various `Number` constants. */
- return ret;
- }
+var INFINITY = 1 / 0;
+/**
+ * Converts `value` to a string key if it's not a string or symbol.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @returns {string|symbol} Returns the key.
+ */
- function isTemplateStringsArray(v) {
- return has(v, 'raw') && has(v, 'length');
+function toKey$5(value) {
+ if (typeof value == 'string' || isSymbol(value)) {
+ return value;
}
- /**
- * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to
- * makeInstance
- * @param options
- * @return {outdent}
- */
+ var result = value + '';
+ return result == '0' && 1 / value == -INFINITY ? '-0' : result;
+}
- function createInstance(options) {
- /** Cache of pre-processed template literal arrays */
- var arrayAutoIndentCache = createWeakMap();
- /**
- * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent,
- * before interpolated values are injected.
- */
-
- var arrayFirstInterpSetsIndentCache = createWeakMap();
+var _toKey = toKey$5;
- function outdent(stringsOrOptions) {
- var values = [];
+var castPath$3 = _castPath,
+ toKey$4 = _toKey;
+/**
+ * The base implementation of `_.get` without support for default values.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to get.
+ * @returns {*} Returns the resolved value.
+ */
- for (var _i = 1; _i < arguments.length; _i++) {
- values[_i - 1] = arguments[_i];
- }
- /* tslint:enable:no-shadowed-variable */
+function baseGet$3(object, path) {
+ path = castPath$3(path, object);
+ var index = 0,
+ length = path.length;
+ while (object != null && index < length) {
+ object = object[toKey$4(path[index++])];
+ }
- if (isTemplateStringsArray(stringsOrOptions)) {
- var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace?
+ return index && index == length ? object : undefined;
+}
- var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation
+var _baseGet = baseGet$3;
- var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
- var renderedArray = cache.get(strings);
+var baseGet$2 = _baseGet;
+/**
+ * Gets the value at `path` of `object`. If the resolved value is
+ * `undefined`, the `defaultValue` is returned in its place.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.7.0
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to get.
+ * @param {*} [defaultValue] The value returned for `undefined` resolved values.
+ * @returns {*} Returns the resolved value.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': 3 } }] };
+ *
+ * _.get(object, 'a[0].b.c');
+ * // => 3
+ *
+ * _.get(object, ['a', '0', 'b', 'c']);
+ * // => 3
+ *
+ * _.get(object, 'a.b.c', 'default');
+ * // => 'default'
+ */
- if (!renderedArray) {
- renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
- cache.set(strings, renderedArray);
- }
- /** If no interpolated values, skip concatenation step */
+function get$1(object, path, defaultValue) {
+ var result = object == null ? undefined : baseGet$2(object, path);
+ return result === undefined ? defaultValue : result;
+}
+var get_1 = get$1;
- if (values.length === 0) {
- return renderedArray[0];
- }
- /** Concatenate string literals with interpolated values */
+/**
+ * The base implementation of `_.hasIn` without support for deep paths.
+ *
+ * @private
+ * @param {Object} [object] The object to query.
+ * @param {Array|string} key The key to check.
+ * @returns {boolean} Returns `true` if `key` exists, else `false`.
+ */
+function baseHasIn$1(object, key) {
+ return object != null && key in Object(object);
+}
- var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
- return rendered;
- } else {
- // Create and return a new instance of outdent with the given options
- return createInstance(extend(extend({}, options), stringsOrOptions || {}));
- }
- }
+var _baseHasIn = baseHasIn$1;
- var fullOutdent = extend(outdent, {
- string: function (str) {
- return _outdentArray([str], false, options)[0];
- }
- });
- return fullOutdent;
+var castPath$2 = _castPath,
+ isArguments$1 = isArguments_1,
+ isArray$3 = isArray_1,
+ isIndex$1 = _isIndex,
+ isLength = isLength_1,
+ toKey$3 = _toKey;
+/**
+ * Checks if `path` exists on `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @param {Function} hasFunc The function to check properties.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
+ */
+
+function hasPath$1(object, path, hasFunc) {
+ path = castPath$2(path, object);
+ var index = -1,
+ length = path.length,
+ result = false;
+
+ while (++index < length) {
+ var key = toKey$3(path[index]);
+
+ if (!(result = object != null && hasFunc(object, key))) {
+ break;
+ }
+
+ object = object[key];
}
- var defaultOutdent = createInstance({
- trimLeadingNewline: true,
- trimTrailingNewline: true
- });
- exports.outdent = defaultOutdent; // Named exports. Simple and preferred.
- // import outdent from 'outdent';
+ if (result || ++index != length) {
+ return result;
+ }
- exports.default = defaultOutdent;
+ length = object == null ? 0 : object.length;
+ return !!length && isLength(length) && isIndex$1(key, length) && (isArray$3(object) || isArguments$1(object));
+}
- {
- // In webpack harmony-modules environments, module.exports is read-only,
- // so we fail gracefully.
- try {
- module.exports = defaultOutdent;
- Object.defineProperty(defaultOutdent, '__esModule', {
- value: true
- });
- defaultOutdent.default = defaultOutdent;
- defaultOutdent.outdent = defaultOutdent;
- } catch (e) {}
+var _hasPath = hasPath$1;
+
+var baseHasIn = _baseHasIn,
+ hasPath = _hasPath;
+/**
+ * Checks if `path` is a direct or inherited property of `object`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
+ * @example
+ *
+ * var object = _.create({ 'a': _.create({ 'b': 2 }) });
+ *
+ * _.hasIn(object, 'a');
+ * // => true
+ *
+ * _.hasIn(object, 'a.b');
+ * // => true
+ *
+ * _.hasIn(object, ['a', 'b']);
+ * // => true
+ *
+ * _.hasIn(object, 'b');
+ * // => false
+ */
+
+function hasIn$2(object, path) {
+ return object != null && hasPath(object, path, baseHasIn);
+}
+
+var hasIn_1 = hasIn$2;
+
+var baseIsEqual = _baseIsEqual,
+ get = get_1,
+ hasIn$1 = hasIn_1,
+ isKey$1 = _isKey,
+ isStrictComparable = _isStrictComparable,
+ matchesStrictComparable = _matchesStrictComparable,
+ toKey$2 = _toKey;
+/** Used to compose bitmasks for value comparisons. */
+
+var COMPARE_PARTIAL_FLAG = 1,
+ COMPARE_UNORDERED_FLAG = 2;
+/**
+ * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
+ *
+ * @private
+ * @param {string} path The path of the property to get.
+ * @param {*} srcValue The value to match.
+ * @returns {Function} Returns the new spec function.
+ */
+
+function baseMatchesProperty$1(path, srcValue) {
+ if (isKey$1(path) && isStrictComparable(srcValue)) {
+ return matchesStrictComparable(toKey$2(path), srcValue);
}
-});
-const {
- outdent
-} = lib;
-const {
- coreOptions
-} = prettierInternal;
-const categoryOrder = [coreOptions.CATEGORY_OUTPUT, coreOptions.CATEGORY_FORMAT, coreOptions.CATEGORY_CONFIG, coreOptions.CATEGORY_EDITOR, coreOptions.CATEGORY_OTHER];
+ return function (object) {
+ var objValue = get(object, path);
+ return objValue === undefined && objValue === srcValue ? hasIn$1(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
+ };
+}
+
+var _baseMatchesProperty = baseMatchesProperty$1;
+
/**
- * {
- * [optionName]: {
- * // The type of the option. For 'choice', see also `choices` below.
- * // When passing a type other than the ones listed below, the option is
- * // treated as taking any string as argument, and `--option <${type}>` will
- * // be displayed in --help.
- * type: "boolean" | "choice" | "int" | string;
+ * This method returns the first argument it receives.
*
- * // Default value to be passed to the minimist option `default`.
- * default?: any;
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Util
+ * @param {*} value Any value.
+ * @returns {*} Returns `value`.
+ * @example
*
- * // Alias name to be passed to the minimist option `alias`.
- * alias?: string;
+ * var object = { 'a': 1 };
*
- * // For grouping options by category in --help.
- * category?: string;
+ * console.log(_.identity(object) === object);
+ * // => true
+ */
+
+function identity$2(value) {
+ return value;
+}
+
+var identity_1 = identity$2;
+
+/**
+ * The base implementation of `_.property` without support for deep paths.
*
- * // Description to be displayed in --help. If omitted, the option won't be
- * // shown at all in --help (but see also `oppositeDescription` below).
- * description?: string;
+ * @private
+ * @param {string} key The key of the property to get.
+ * @returns {Function} Returns the new accessor function.
+ */
+
+function baseProperty$1(key) {
+ return function (object) {
+ return object == null ? undefined : object[key];
+ };
+}
+
+var _baseProperty = baseProperty$1;
+
+var baseGet$1 = _baseGet;
+/**
+ * A specialized version of `baseProperty` which supports deep paths.
*
- * // Description for `--no-${name}` to be displayed in --help. If omitted,
- * // `--no-${name}` won't be shown.
- * oppositeDescription?: string;
+ * @private
+ * @param {Array|string} path The path of the property to get.
+ * @returns {Function} Returns the new accessor function.
+ */
+
+function basePropertyDeep$1(path) {
+ return function (object) {
+ return baseGet$1(object, path);
+ };
+}
+
+var _basePropertyDeep = basePropertyDeep$1;
+
+var baseProperty = _baseProperty,
+ basePropertyDeep = _basePropertyDeep,
+ isKey = _isKey,
+ toKey$1 = _toKey;
+/**
+ * Creates a function that returns the value at `path` of a given object.
*
- * // Indicate if this option is simply passed to the API.
- * // true: use camelified name as the API option name.
- * // string: use this value as the API option name.
- * forwardToApi?: boolean | string;
+ * @static
+ * @memberOf _
+ * @since 2.4.0
+ * @category Util
+ * @param {Array|string} path The path of the property to get.
+ * @returns {Function} Returns the new accessor function.
+ * @example
*
- * // Indicate that a CLI flag should be an array when forwarded to the API.
- * array?: boolean;
+ * var objects = [
+ * { 'a': { 'b': 2 } },
+ * { 'a': { 'b': 1 } }
+ * ];
*
- * // Specify available choices for validation. They will also be displayed
- * // in --help as <a|b|c>.
- * // Use an object instead of a string if a choice is deprecated and should
- * // be treated as `redirect` instead, or if you'd like to add description for
- * // the choice.
- * choices?: Array<
- * | string
- * | { value: string, description?: string, deprecated?: boolean, redirect?: string }
- * >;
+ * _.map(objects, _.property('a.b'));
+ * // => [2, 1]
*
- * // If the option has a value that is an exception to the regular value
- * // constraints, indicate that value here (or use a function for more
- * // flexibility).
- * exception?: ((value: any) => boolean);
+ * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
+ * // => [1, 2]
+ */
+
+function property$1(path) {
+ return isKey(path) ? baseProperty(toKey$1(path)) : basePropertyDeep(path);
+}
+
+var property_1 = property$1;
+
+var baseMatches = _baseMatches,
+ baseMatchesProperty = _baseMatchesProperty,
+ identity$1 = identity_1,
+ isArray$2 = isArray_1,
+ property = property_1;
+/**
+ * The base implementation of `_.iteratee`.
*
- * // Indicate that the option is deprecated. Use a string to add an extra
- * // message to --help for the option, for example to suggest a replacement
- * // option.
- * deprecated?: true | string;
- * }
- * }
+ * @private
+ * @param {*} [value=_.identity] The value to convert to an iteratee.
+ * @returns {Function} Returns the iteratee.
+ */
+
+function baseIteratee$1(value) {
+ // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
+ // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
+ if (typeof value == 'function') {
+ return value;
+ }
+
+ if (value == null) {
+ return identity$1;
+ }
+
+ if (typeof value == 'object') {
+ return isArray$2(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
+ }
+
+ return property(value);
+}
+
+var _baseIteratee = baseIteratee$1;
+
+var arrayAggregator = _arrayAggregator,
+ baseAggregator = _baseAggregator,
+ baseIteratee = _baseIteratee,
+ isArray$1 = isArray_1;
+/**
+ * Creates a function like `_.groupBy`.
*
- * Note: The options below are sorted alphabetically.
+ * @private
+ * @param {Function} setter The function to set accumulator values.
+ * @param {Function} [initializer] The accumulator object initializer.
+ * @returns {Function} Returns the new aggregator function.
*/
-const options = {
- check: {
- type: "boolean",
- category: coreOptions.CATEGORY_OUTPUT,
- alias: "c",
- description: outdent`
- Check if the given files are formatted, print a human-friendly summary
- message and paths to unformatted files (see also --list-different).
- `
- },
- color: {
- // The supports-color package (a sub sub dependency) looks directly at
- // `process.argv` for `--no-color` and such-like options. The reason it is
- // listed here is to avoid "Ignored unknown option: --no-color" warnings.
- // See https://github.com/chalk/supports-color/#info for more information.
- type: "boolean",
- default: true,
- description: "Colorize error messages.",
- oppositeDescription: "Do not colorize error messages."
- },
- config: {
- type: "path",
- category: coreOptions.CATEGORY_CONFIG,
- description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
- oppositeDescription: "Do not look for a configuration file.",
- exception: value => value === false
- },
- "config-precedence": {
- type: "choice",
- category: coreOptions.CATEGORY_CONFIG,
- default: "cli-override",
- choices: [{
- value: "cli-override",
- description: "CLI options take precedence over config file"
- }, {
- value: "file-override",
- description: "Config file take precedence over CLI options"
- }, {
- value: "prefer-file",
- description: outdent`
- If a config file is found will evaluate it and ignore other CLI options.
- If no config file is found CLI options will evaluate as normal.
- `
- }],
- description: "Define in which order config files and CLI options should be evaluated."
- },
- "debug-benchmark": {
- // Run the formatting benchmarks. Requires 'benchmark' module to be installed.
- type: "boolean"
- },
- "debug-check": {
- // Run the formatting once again on the formatted output, throw if different.
- type: "boolean"
- },
- "debug-print-doc": {
- type: "boolean"
- },
- "debug-repeat": {
- // Repeat the formatting a few times and measure the average duration.
- type: "int",
- default: 0
- },
- editorconfig: {
- type: "boolean",
- category: coreOptions.CATEGORY_CONFIG,
- description: "Take .editorconfig into account when parsing configuration.",
- oppositeDescription: "Don't take .editorconfig into account when parsing configuration.",
- default: true
- },
- "find-config-path": {
- type: "path",
- category: coreOptions.CATEGORY_CONFIG,
- description: "Find and print the path to a configuration file for the given input file."
- },
- "file-info": {
- type: "path",
- description: outdent`
- Extract the following info (as JSON) for a given file path. Reported fields:
- * ignored (boolean) - true if file path is filtered by --ignore-path
- * inferredParser (string | null) - name of parser inferred from file path
- `
- },
- help: {
- type: "flag",
- alias: "h",
- description: outdent`
- Show CLI usage, or details about the given flag.
- Example: --help write
- `,
- exception: value => value === ""
- },
- "ignore-path": {
- type: "path",
- category: coreOptions.CATEGORY_CONFIG,
- default: ".prettierignore",
- description: "Path to a file with patterns describing files to ignore."
- },
- "ignore-unknown": {
- type: "boolean",
- alias: "u",
- description: "Ignore unknown files."
- },
- "list-different": {
- type: "boolean",
- category: coreOptions.CATEGORY_OUTPUT,
- alias: "l",
- description: "Print the names of files that are different from Prettier's formatting (see also --check)."
- },
- loglevel: {
- type: "choice",
- description: "What level of logs to report.",
- default: "log",
- choices: ["silent", "error", "warn", "log", "debug"]
- },
- "support-info": {
- type: "boolean",
- description: "Print support information as JSON."
- },
- version: {
- type: "boolean",
- alias: "v",
- description: "Print Prettier version."
- },
- "with-node-modules": {
- type: "boolean",
- category: coreOptions.CATEGORY_CONFIG,
- description: "Process files inside 'node_modules' directory."
- },
- write: {
- type: "boolean",
- alias: "w",
- category: coreOptions.CATEGORY_OUTPUT,
- description: "Edit files in-place. (Beware!)"
- }
-};
-const usageSummary = outdent`
- Usage: prettier [options] [file/dir/glob ...]
-
- By default, output is written to stdout.
- Stdin is read if it is piped to Prettier and no files are given.
-`;
-var constant$1 = {
- categoryOrder,
- options,
- usageSummary
-};
+function createAggregator$2(setter, initializer) {
+ return function (collection, iteratee) {
+ var func = isArray$1(collection) ? arrayAggregator : baseAggregator,
+ accumulator = initializer ? initializer() : {};
+ return func(collection, setter, baseIteratee(iteratee), accumulator);
+ };
+}
-const {
- isCI
-} = thirdParty; // Some CI pipelines incorrectly report process.stdout.isTTY status,
-// which causes unwanted lines in the output. An additional check for isCI() helps.
-// See https://github.com/prettier/prettier/issues/5801
+var _createAggregator = createAggregator$2;
-var isTty = function isTTY() {
- return process.stdout.isTTY && !isCI();
-};
+var createAggregator$1 = _createAggregator;
+/**
+ * Creates an array of elements split into two groups, the first of which
+ * contains elements `predicate` returns truthy for, the second of which
+ * contains elements `predicate` returns falsey for. The predicate is
+ * invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} [predicate=_.identity] The function invoked per iteration.
+ * @returns {Array} Returns the array of grouped elements.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': false },
+ * { 'user': 'fred', 'age': 40, 'active': true },
+ * { 'user': 'pebbles', 'age': 1, 'active': false }
+ * ];
+ *
+ * _.partition(users, function(o) { return o.active; });
+ * // => objects for [['fred'], ['barney', 'pebbles']]
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.partition(users, { 'age': 1, 'active': false });
+ * // => objects for [['pebbles'], ['barney', 'fred']]
+ *
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.partition(users, ['active', false]);
+ * // => objects for [['barney', 'pebbles'], ['fred']]
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.partition(users, 'active');
+ * // => objects for [['fred'], ['barney', 'pebbles']]
+ */
-function Diff() {}
+var partition$1 = createAggregator$1(function (result, value, key) {
+ result[key ? 0 : 1].push(value);
+}, function () {
+ return [[], []];
+});
+var partition_1 = partition$1;
-Diff.prototype = {
- diff: function diff(oldString, newString) {
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- var callback = options.callback;
+const partition = partition_1;
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
+var createMinimistOptions$2 = function createMinimistOptions(detailedOptions) {
+ const [boolean, string] = partition(detailedOptions, ({
+ type
+ }) => type === "boolean").map(detailedOptions => detailedOptions.flatMap(({
+ name,
+ alias
+ }) => alias ? [name, alias] : [name]));
+ const defaults = Object.fromEntries(detailedOptions.filter(option => !option.deprecated && (!option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir") && option.default !== undefined).map(option => [option.name, option.default]));
+ return {
+ // we use vnopts' AliasSchema to handle aliases for better error messages
+ alias: {},
+ boolean,
+ string,
+ default: defaults
+ };
+};
- this.options = options;
- var self = this;
+const dashify$1 = dashify$2; // eslint-disable-next-line no-restricted-modules
- function done(value) {
- if (callback) {
- setTimeout(function () {
- callback(undefined, value);
- }, 0);
- return true;
- } else {
- return value;
- }
- } // Allow subclasses to massage the input prior to running
-
-
- oldString = this.castInput(oldString);
- newString = this.castInput(newString);
- oldString = this.removeEmpty(this.tokenize(oldString));
- newString = this.removeEmpty(this.tokenize(newString));
- var newLen = newString.length,
- oldLen = oldString.length;
- var editLength = 1;
- var maxEditLength = newLen + oldLen;
- var bestPath = [{
- newPos: -1,
- components: []
- }]; // Seed editLength = 0, i.e. the content starts with the same values
-
- var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
-
- if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
- // Identity per the equality and tokenizer
- return done([{
- value: this.join(newString),
- count: newString.length
- }]);
- } // Main worker method. checks all permutations of a given edit length for acceptance.
-
-
- function execEditLength() {
- for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
- var basePath = void 0;
-
- var addPath = bestPath[diagonalPath - 1],
- removePath = bestPath[diagonalPath + 1],
- _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
-
- if (addPath) {
- // No one else is going to attempt to use this value, clear it
- bestPath[diagonalPath - 1] = undefined;
- }
+const prettier$5 = require$$3;
+const minimist$1 = minimist_1;
+const {
+ optionsNormalizer
+} = prettierInternal;
+const createMinimistOptions$1 = createMinimistOptions$2;
- var canAdd = addPath && addPath.newPos + 1 < newLen,
- canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
+function getOptions(argv, detailedOptions) {
+ return Object.fromEntries(detailedOptions.filter(({
+ forwardToApi
+ }) => forwardToApi).map(({
+ forwardToApi,
+ name
+ }) => [forwardToApi, argv[name]]));
+}
- if (!canAdd && !canRemove) {
- // If this path is a terminal then prune
- bestPath[diagonalPath] = undefined;
- continue;
- } // Select the diagonal that we want to branch from. We select the prior
- // path whose position in the new string is the farthest from the origin
- // and does not pass the bounds of the diff graph
+function cliifyOptions(object, apiDetailedOptionMap) {
+ return Object.fromEntries(Object.entries(object || {}).map(([key, value]) => {
+ const apiOption = apiDetailedOptionMap[key];
+ const cliKey = apiOption ? apiOption.name : key;
+ return [dashify$1(cliKey), value];
+ }));
+}
+function createApiDetailedOptionMap(detailedOptions) {
+ return Object.fromEntries(detailedOptions.filter(option => option.forwardToApi && option.forwardToApi !== option.name).map(option => [option.forwardToApi, option]));
+}
- if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
- basePath = clonePath(removePath);
- self.pushComponent(basePath.components, undefined, true);
- } else {
- basePath = addPath; // No need to clone, we've pulled it from the list
+function parseArgsToOptions(context, overrideDefaults) {
+ const minimistOptions = createMinimistOptions$1(context.detailedOptions);
+ const apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions);
+ return getOptions(optionsNormalizer.normalizeCliOptions(minimist$1(context.rawArguments, {
+ string: minimistOptions.string,
+ boolean: minimistOptions.boolean,
+ default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
+ }), context.detailedOptions, {
+ logger: false
+ }), context.detailedOptions);
+}
- basePath.newPos++;
- self.pushComponent(basePath.components, true, undefined);
- }
+async function getOptionsOrDie(context, filePath) {
+ try {
+ if (context.argv.config === false) {
+ context.logger.debug("'--no-config' option found, skip loading config file.");
+ return null;
+ }
- _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
+ context.logger.debug(context.argv.config ? `load config file from '${context.argv.config}'` : `resolve config from '${filePath}'`);
+ const options = await prettier$5.resolveConfig(filePath, {
+ editorconfig: context.argv.editorconfig,
+ config: context.argv.config
+ });
+ context.logger.debug("loaded options `" + JSON.stringify(options) + "`");
+ return options;
+ } catch (error) {
+ context.logger.error(`Invalid configuration file \`${filePath}\`: ` + error.message);
+ process.exit(2);
+ }
+}
- if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
- return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
- } else {
- // Otherwise track this path as a potential candidate and continue.
- bestPath[diagonalPath] = basePath;
- }
- }
+function applyConfigPrecedence(context, options) {
+ try {
+ switch (context.argv["config-precedence"]) {
+ case "cli-override":
+ return parseArgsToOptions(context, options);
- editLength++;
- } // Performs the length of edit iteration. Is a bit fugly as this has to support the
- // sync and async mode which is never fun. Loops over execEditLength until a value
- // is produced.
+ case "file-override":
+ return Object.assign(Object.assign({}, parseArgsToOptions(context)), options);
+ case "prefer-file":
+ return options || parseArgsToOptions(context);
+ }
+ } catch (error) {
+ /* istanbul ignore next */
+ context.logger.error(error.toString());
+ /* istanbul ignore next */
- if (callback) {
- (function exec() {
- setTimeout(function () {
- // This should not happen, but we want to be safe.
+ process.exit(2);
+ }
+}
- /* istanbul ignore next */
- if (editLength > maxEditLength) {
- return callback();
- }
+async function getOptionsForFile$1(context, filepath) {
+ const options = await getOptionsOrDie(context, filepath);
+ const hasPlugins = options && options.plugins;
- if (!execEditLength()) {
- exec();
- }
- }, 0);
- })();
- } else {
- while (editLength <= maxEditLength) {
- var ret = execEditLength();
+ if (hasPlugins) {
+ context.pushContextPlugins(options.plugins);
+ }
- if (ret) {
- return ret;
+ const appliedOptions = Object.assign({
+ filepath
+ }, applyConfigPrecedence(context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, {
+ logger: context.logger
+ })));
+ context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`);
+
+ if (hasPlugins) {
+ context.popContextPlugins();
+ }
+
+ return appliedOptions;
+}
+
+var option = {
+ getOptionsForFile: getOptionsForFile$1,
+ createMinimistOptions: createMinimistOptions$1
+};
+
+const {
+ isCI
+} = require$$4; // Some CI pipelines incorrectly report process.stdout.isTTY status,
+// which causes unwanted lines in the output. An additional check for isCI() helps.
+// See https://github.com/prettier/prettier/issues/5801
+
+var isTty = function isTTY() {
+ return process.stdout.isTTY && !isCI();
+};
+
+var lib$1 = {};
+
+var base = {};
+
+/*istanbul ignore start*/
+
+(function (exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports["default"] = Diff;
+ /*istanbul ignore end*/
+
+ function Diff() {}
+
+ Diff.prototype = {
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
+ diff: function diff(oldString, newString) {
+ /*istanbul ignore start*/
+ var
+ /*istanbul ignore end*/
+ options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ var callback = options.callback;
+
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
+
+ this.options = options;
+ var self = this;
+
+ function done(value) {
+ if (callback) {
+ setTimeout(function () {
+ callback(undefined, value);
+ }, 0);
+ return true;
+ } else {
+ return value;
+ }
+ } // Allow subclasses to massage the input prior to running
+
+
+ oldString = this.castInput(oldString);
+ newString = this.castInput(newString);
+ oldString = this.removeEmpty(this.tokenize(oldString));
+ newString = this.removeEmpty(this.tokenize(newString));
+ var newLen = newString.length,
+ oldLen = oldString.length;
+ var editLength = 1;
+ var maxEditLength = newLen + oldLen;
+ var bestPath = [{
+ newPos: -1,
+ components: []
+ }]; // Seed editLength = 0, i.e. the content starts with the same values
+
+ var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
+
+ if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
+ // Identity per the equality and tokenizer
+ return done([{
+ value: this.join(newString),
+ count: newString.length
+ }]);
+ } // Main worker method. checks all permutations of a given edit length for acceptance.
+
+
+ function execEditLength() {
+ for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
+ var basePath =
+ /*istanbul ignore start*/
+ void 0
+ /*istanbul ignore end*/
+ ;
+
+ var addPath = bestPath[diagonalPath - 1],
+ removePath = bestPath[diagonalPath + 1],
+ _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
+
+ if (addPath) {
+ // No one else is going to attempt to use this value, clear it
+ bestPath[diagonalPath - 1] = undefined;
+ }
+
+ var canAdd = addPath && addPath.newPos + 1 < newLen,
+ canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
+
+ if (!canAdd && !canRemove) {
+ // If this path is a terminal then prune
+ bestPath[diagonalPath] = undefined;
+ continue;
+ } // Select the diagonal that we want to branch from. We select the prior
+ // path whose position in the new string is the farthest from the origin
+ // and does not pass the bounds of the diff graph
+
+
+ if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
+ basePath = clonePath(removePath);
+ self.pushComponent(basePath.components, undefined, true);
+ } else {
+ basePath = addPath; // No need to clone, we've pulled it from the list
+
+ basePath.newPos++;
+ self.pushComponent(basePath.components, true, undefined);
+ }
+
+ _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
+
+ if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
+ return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
+ } else {
+ // Otherwise track this path as a potential candidate and continue.
+ bestPath[diagonalPath] = basePath;
+ }
+ }
+
+ editLength++;
+ } // Performs the length of edit iteration. Is a bit fugly as this has to support the
+ // sync and async mode which is never fun. Loops over execEditLength until a value
+ // is produced.
+
+
+ if (callback) {
+ (function exec() {
+ setTimeout(function () {
+ // This should not happen, but we want to be safe.
+
+ /* istanbul ignore next */
+ if (editLength > maxEditLength) {
+ return callback();
+ }
+
+ if (!execEditLength()) {
+ exec();
+ }
+ }, 0);
+ })();
+ } else {
+ while (editLength <= maxEditLength) {
+ var ret = execEditLength();
+
+ if (ret) {
+ return ret;
+ }
}
}
- }
- },
- pushComponent: function pushComponent(components, added, removed) {
- var last = components[components.length - 1];
-
- if (last && last.added === added && last.removed === removed) {
- // We need to clone here as the component clone operation is just
- // as shallow array clone
- components[components.length - 1] = {
- count: last.count + 1,
- added: added,
- removed: removed
- };
- } else {
- components.push({
- count: 1,
- added: added,
- removed: removed
- });
- }
- },
- extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
- var newLen = newString.length,
- oldLen = oldString.length,
- newPos = basePath.newPos,
- oldPos = newPos - diagonalPath,
- commonCount = 0;
-
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
- newPos++;
- oldPos++;
- commonCount++;
- }
-
- if (commonCount) {
- basePath.components.push({
- count: commonCount
- });
- }
+ },
- basePath.newPos = newPos;
- return oldPos;
- },
- equals: function equals(left, right) {
- if (this.options.comparator) {
- return this.options.comparator(left, right);
- } else {
- return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
- }
- },
- removeEmpty: function removeEmpty(array) {
- var ret = [];
+ /*istanbul ignore start*/
- for (var i = 0; i < array.length; i++) {
- if (array[i]) {
- ret.push(array[i]);
+ /*istanbul ignore end*/
+ pushComponent: function pushComponent(components, added, removed) {
+ var last = components[components.length - 1];
+
+ if (last && last.added === added && last.removed === removed) {
+ // We need to clone here as the component clone operation is just
+ // as shallow array clone
+ components[components.length - 1] = {
+ count: last.count + 1,
+ added: added,
+ removed: removed
+ };
+ } else {
+ components.push({
+ count: 1,
+ added: added,
+ removed: removed
+ });
}
- }
+ },
- return ret;
- },
- castInput: function castInput(value) {
- return value;
- },
- tokenize: function tokenize(value) {
- return value.split('');
- },
- join: function join(chars) {
- return chars.join('');
- }
-};
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
+ extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
+ var newLen = newString.length,
+ oldLen = oldString.length,
+ newPos = basePath.newPos,
+ oldPos = newPos - diagonalPath,
+ commonCount = 0;
-function buildValues(diff, components, newString, oldString, useLongestToken) {
- var componentPos = 0,
- componentLen = components.length,
- newPos = 0,
- oldPos = 0;
-
- for (; componentPos < componentLen; componentPos++) {
- var component = components[componentPos];
-
- if (!component.removed) {
- if (!component.added && useLongestToken) {
- var value = newString.slice(newPos, newPos + component.count);
- value = value.map(function (value, i) {
- var oldValue = oldString[oldPos + i];
- return oldValue.length > value.length ? oldValue : value;
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
+ newPos++;
+ oldPos++;
+ commonCount++;
+ }
+
+ if (commonCount) {
+ basePath.components.push({
+ count: commonCount
});
- component.value = diff.join(value);
- } else {
- component.value = diff.join(newString.slice(newPos, newPos + component.count));
}
- newPos += component.count; // Common case
+ basePath.newPos = newPos;
+ return oldPos;
+ },
+
+ /*istanbul ignore start*/
- if (!component.added) {
- oldPos += component.count;
+ /*istanbul ignore end*/
+ equals: function equals(left, right) {
+ if (this.options.comparator) {
+ return this.options.comparator(left, right);
+ } else {
+ return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
}
- } else {
- component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
- oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
- // The diffing algorithm is tied to add then remove output and this is the simplest
- // route to get the desired output with minimal overhead.
-
- if (componentPos && components[componentPos - 1].added) {
- var tmp = components[componentPos - 1];
- components[componentPos - 1] = components[componentPos];
- components[componentPos] = tmp;
+ },
+
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
+ removeEmpty: function removeEmpty(array) {
+ var ret = [];
+
+ for (var i = 0; i < array.length; i++) {
+ if (array[i]) {
+ ret.push(array[i]);
+ }
}
+
+ return ret;
+ },
+
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
+ castInput: function castInput(value) {
+ return value;
+ },
+
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
+ tokenize: function tokenize(value) {
+ return value.split('');
+ },
+
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
+ join: function join(chars) {
+ return chars.join('');
}
- } // Special case handle for when one terminal is ignored (i.e. whitespace).
- // For this case we merge the terminal into the prior string and drop the change.
- // This is only available for string mode.
+ };
+
+ function buildValues(diff, components, newString, oldString, useLongestToken) {
+ var componentPos = 0,
+ componentLen = components.length,
+ newPos = 0,
+ oldPos = 0;
+
+ for (; componentPos < componentLen; componentPos++) {
+ var component = components[componentPos];
+
+ if (!component.removed) {
+ if (!component.added && useLongestToken) {
+ var value = newString.slice(newPos, newPos + component.count);
+ value = value.map(function (value, i) {
+ var oldValue = oldString[oldPos + i];
+ return oldValue.length > value.length ? oldValue : value;
+ });
+ component.value = diff.join(value);
+ } else {
+ component.value = diff.join(newString.slice(newPos, newPos + component.count));
+ }
+
+ newPos += component.count; // Common case
+
+ if (!component.added) {
+ oldPos += component.count;
+ }
+ } else {
+ component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
+ oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
+ // The diffing algorithm is tied to add then remove output and this is the simplest
+ // route to get the desired output with minimal overhead.
+
+ if (componentPos && components[componentPos - 1].added) {
+ var tmp = components[componentPos - 1];
+ components[componentPos - 1] = components[componentPos];
+ components[componentPos] = tmp;
+ }
+ }
+ } // Special case handle for when one terminal is ignored (i.e. whitespace).
+ // For this case we merge the terminal into the prior string and drop the change.
+ // This is only available for string mode.
- var lastComponent = components[componentLen - 1];
+ var lastComponent = components[componentLen - 1];
- if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
- components[componentLen - 2].value += lastComponent.value;
- components.pop();
+ if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
+ components[componentLen - 2].value += lastComponent.value;
+ components.pop();
+ }
+
+ return components;
}
- return components;
-}
+ function clonePath(path) {
+ return {
+ newPos: path.newPos,
+ components: path.components.slice(0)
+ };
+ }
+})(base);
-function clonePath(path) {
- return {
- newPos: path.newPos,
- components: path.components.slice(0)
+var character = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(character, "__esModule", {
+ value: true
+});
+character.diffChars = diffChars;
+character.characterDiff = void 0;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_base$6 = _interopRequireDefault$7(base)
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+
+function _interopRequireDefault$7(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
};
}
+/*istanbul ignore end*/
+
-var characterDiff = new Diff();
+var characterDiff = new
+/*istanbul ignore start*/
+_base$6
+/*istanbul ignore end*/
+[
+/*istanbul ignore start*/
+"default"
+/*istanbul ignore end*/
+]();
+/*istanbul ignore start*/
+
+character.characterDiff = characterDiff;
+/*istanbul ignore end*/
function diffChars(oldStr, newStr, options) {
return characterDiff.diff(oldStr, newStr, options);
}
+var word = {};
+
+var params = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(params, "__esModule", {
+ value: true
+});
+params.generateOptions = generateOptions;
+/*istanbul ignore end*/
+
function generateOptions(options, defaults) {
if (typeof options === 'function') {
defaults.callback = options;
}
return defaults;
-} //
+}
+
+/*istanbul ignore start*/
+
+Object.defineProperty(word, "__esModule", {
+ value: true
+});
+word.diffWords = diffWords;
+word.diffWordsWithSpace = diffWordsWithSpace;
+word.wordDiff = void 0;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_base$5 = _interopRequireDefault$6(base)
+/*istanbul ignore end*/
+;
+
+var
+/*istanbul ignore start*/
+_params$1 = params
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+function _interopRequireDefault$6(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
+ };
+}
+/*istanbul ignore end*/
+// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode
+//
// Ranges and exceptions:
// Latin-1 Supplement, 0080–00FF
// - U+00D7 × Multiplication sign
var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
var reWhitespace = /\S/;
-var wordDiff = new Diff();
+var wordDiff = new
+/*istanbul ignore start*/
+_base$5
+/*istanbul ignore end*/
+[
+/*istanbul ignore start*/
+"default"
+/*istanbul ignore end*/
+]();
+/*istanbul ignore start*/
+
+word.wordDiff = wordDiff;
+/*istanbul ignore end*/
wordDiff.equals = function (left, right) {
if (this.options.ignoreCase) {
};
function diffWords(oldStr, newStr, options) {
- options = generateOptions(options, {
+ options =
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _params$1
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ generateOptions
+ /*istanbul ignore end*/
+ )(options, {
ignoreWhitespace: true
});
return wordDiff.diff(oldStr, newStr, options);
return wordDiff.diff(oldStr, newStr, options);
}
-var lineDiff = new Diff();
+var line = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(line, "__esModule", {
+ value: true
+});
+line.diffLines = diffLines;
+line.diffTrimmedLines = diffTrimmedLines;
+line.lineDiff = void 0;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_base$4 = _interopRequireDefault$5(base)
+/*istanbul ignore end*/
+;
+
+var
+/*istanbul ignore start*/
+_params = params
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+function _interopRequireDefault$5(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
+ };
+}
+/*istanbul ignore end*/
+
+
+var lineDiff = new
+/*istanbul ignore start*/
+_base$4
+/*istanbul ignore end*/
+[
+/*istanbul ignore start*/
+"default"
+/*istanbul ignore end*/
+]();
+/*istanbul ignore start*/
+
+line.lineDiff = lineDiff;
+/*istanbul ignore end*/
lineDiff.tokenize = function (value) {
var retLines = [],
}
function diffTrimmedLines(oldStr, newStr, callback) {
- var options = generateOptions(callback, {
+ var options =
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _params
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ generateOptions
+ /*istanbul ignore end*/
+ )(callback, {
ignoreWhitespace: true
});
return lineDiff.diff(oldStr, newStr, options);
}
-var sentenceDiff = new Diff();
+var sentence = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(sentence, "__esModule", {
+ value: true
+});
+sentence.diffSentences = diffSentences;
+sentence.sentenceDiff = void 0;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_base$3 = _interopRequireDefault$4(base)
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+
+function _interopRequireDefault$4(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
+ };
+}
+/*istanbul ignore end*/
+
+
+var sentenceDiff = new
+/*istanbul ignore start*/
+_base$3
+/*istanbul ignore end*/
+[
+/*istanbul ignore start*/
+"default"
+/*istanbul ignore end*/
+]();
+/*istanbul ignore start*/
+
+sentence.sentenceDiff = sentenceDiff;
+/*istanbul ignore end*/
sentenceDiff.tokenize = function (value) {
return value.split(/(\S.+?[.!?])(?=\s+|$)/);
return sentenceDiff.diff(oldStr, newStr, callback);
}
-var cssDiff = new Diff();
+var css = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(css, "__esModule", {
+ value: true
+});
+css.diffCss = diffCss;
+css.cssDiff = void 0;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_base$2 = _interopRequireDefault$3(base)
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+
+function _interopRequireDefault$3(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
+ };
+}
+/*istanbul ignore end*/
+
+
+var cssDiff = new
+/*istanbul ignore start*/
+_base$2
+/*istanbul ignore end*/
+[
+/*istanbul ignore start*/
+"default"
+/*istanbul ignore end*/
+]();
+/*istanbul ignore start*/
+
+css.cssDiff = cssDiff;
+/*istanbul ignore end*/
cssDiff.tokenize = function (value) {
return value.split(/([{}:;,]|\s+)/);
return cssDiff.diff(oldStr, newStr, callback);
}
+var json = {};
+
+Object.defineProperty(json, "__esModule", {
+ value: true
+});
+json.diffJson = diffJson;
+json.canonicalize = canonicalize;
+json.jsonDiff = void 0;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_base$1 = _interopRequireDefault$2(base)
+/*istanbul ignore end*/
+;
+
+var
+/*istanbul ignore start*/
+_line$1 = line
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+function _interopRequireDefault$2(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
+ };
+}
+
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function (obj) {
+ _typeof = function _typeof(obj) {
return typeof obj;
};
} else {
- _typeof = function (obj) {
+ _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
+/*istanbul ignore end*/
-function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
-}
-
-function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
-}
-
-function _iterableToArray(iter) {
- if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
-}
-
-function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
-}
-
-function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
-
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
-
- return arr2;
-}
-
-function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
var objectPrototypeToString = Object.prototype.toString;
-var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
+var jsonDiff = new
+/*istanbul ignore start*/
+_base$1
+/*istanbul ignore end*/
+[
+/*istanbul ignore start*/
+"default"
+/*istanbul ignore end*/
+](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
+/*istanbul ignore start*/
+
+json.jsonDiff = jsonDiff;
+/*istanbul ignore end*/
+
jsonDiff.useLongestToken = true;
-jsonDiff.tokenize = lineDiff.tokenize;
+jsonDiff.tokenize =
+/*istanbul ignore start*/
+_line$1
+/*istanbul ignore end*/
+.
+/*istanbul ignore start*/
+lineDiff
+/*istanbul ignore end*/
+.tokenize;
jsonDiff.castInput = function (value) {
- var _this$options = this.options,
+ /*istanbul ignore start*/
+ var _this$options =
+ /*istanbul ignore end*/
+ this.options,
undefinedReplacement = _this$options.undefinedReplacement,
_this$options$stringi = _this$options.stringifyReplacer,
- stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
- return typeof v === 'undefined' ? undefinedReplacement : v;
+ stringifyReplacer = _this$options$stringi === void 0 ? function (k, v)
+ /*istanbul ignore start*/
+ {
+ return (
+ /*istanbul ignore end*/
+ typeof v === 'undefined' ? undefinedReplacement : v
+ );
} : _this$options$stringi;
return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
};
jsonDiff.equals = function (left, right) {
- return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
+ return (
+ /*istanbul ignore start*/
+ _base$1
+ /*istanbul ignore end*/
+ [
+ /*istanbul ignore start*/
+ "default"
+ /*istanbul ignore end*/
+ ].prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'))
+ );
};
function diffJson(oldObj, newObj, options) {
obj = obj.toJSON();
}
- if (_typeof(obj) === 'object' && obj !== null) {
+ if (
+ /*istanbul ignore start*/
+ _typeof(
+ /*istanbul ignore end*/
+ obj) === 'object' && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
replacementStack.push(canonicalizedObj);
return canonicalizedObj;
}
-var arrayDiff = new Diff();
+var array$1 = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(array$1, "__esModule", {
+ value: true
+});
+array$1.diffArrays = diffArrays;
+array$1.arrayDiff = void 0;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_base = _interopRequireDefault$1(base)
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+
+function _interopRequireDefault$1(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
+ };
+}
+/*istanbul ignore end*/
+
+
+var arrayDiff = new
+/*istanbul ignore start*/
+_base
+/*istanbul ignore end*/
+[
+/*istanbul ignore start*/
+"default"
+/*istanbul ignore end*/
+]();
+/*istanbul ignore start*/
+
+array$1.arrayDiff = arrayDiff;
+/*istanbul ignore end*/
arrayDiff.tokenize = function (value) {
return value.slice();
return arrayDiff.diff(oldArr, newArr, callback);
}
+var apply$2 = {};
+
+var parse = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(parse, "__esModule", {
+ value: true
+});
+parse.parsePatch = parsePatch;
+/*istanbul ignore end*/
+
function parsePatch(uniDiff) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ /*istanbul ignore start*/
+ var
+ /*istanbul ignore end*/
+ options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
list = [],
}
return list;
-} // Iterator that traverses in the range of [min, max], stepping
-// by distance from a given start position. I.e. for [0, 4], with
-// start of 2, this will iterate 2, 3, 1, 4, 0.
-
-
-function distanceIterator(start, minLine, maxLine) {
- var wantForward = true,
- backwardExhausted = false,
- forwardExhausted = false,
- localOffset = 1;
- return function iterator() {
- if (wantForward && !forwardExhausted) {
- if (backwardExhausted) {
- localOffset++;
- } else {
- wantForward = false;
- } // Check if trying to fit beyond text length, and if not, check it fits
- // after offset location (or desired location on first iteration)
+}
+var distanceIterator = {};
- if (start + localOffset <= maxLine) {
- return localOffset;
- }
+/*istanbul ignore start*/
- forwardExhausted = true;
- }
+(function (exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports["default"] = _default;
+ /*istanbul ignore end*/
+ // Iterator that traverses in the range of [min, max], stepping
+ // by distance from a given start position. I.e. for [0, 4], with
+ // start of 2, this will iterate 2, 3, 1, 4, 0.
+
+ function
+ /*istanbul ignore start*/
+ _default
+ /*istanbul ignore end*/
+ (start, minLine, maxLine) {
+ var wantForward = true,
+ backwardExhausted = false,
+ forwardExhausted = false,
+ localOffset = 1;
+ return function iterator() {
+ if (wantForward && !forwardExhausted) {
+ if (backwardExhausted) {
+ localOffset++;
+ } else {
+ wantForward = false;
+ } // Check if trying to fit beyond text length, and if not, check it fits
+ // after offset location (or desired location on first iteration)
- if (!backwardExhausted) {
- if (!forwardExhausted) {
- wantForward = true;
- } // Check if trying to fit before text beginning, and if not, check it fits
- // before offset location
+ if (start + localOffset <= maxLine) {
+ return localOffset;
+ }
- if (minLine <= start - localOffset) {
- return -localOffset++;
+ forwardExhausted = true;
}
- backwardExhausted = true;
- return iterator();
- } // We tried to fit hunk before text beginning and beyond text length, then
- // hunk can't fit on the text. Return undefined
+ if (!backwardExhausted) {
+ if (!forwardExhausted) {
+ wantForward = true;
+ } // Check if trying to fit before text beginning, and if not, check it fits
+ // before offset location
- };
-}
-function applyPatch(source, uniDiff) {
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ if (minLine <= start - localOffset) {
+ return -localOffset++;
+ }
- if (typeof uniDiff === 'string') {
- uniDiff = parsePatch(uniDiff);
+ backwardExhausted = true;
+ return iterator();
+ } // We tried to fit hunk before text beginning and beyond text length, then
+ // hunk can't fit on the text. Return undefined
+
+ };
}
+})(distanceIterator);
- if (Array.isArray(uniDiff)) {
- if (uniDiff.length > 1) {
+/*istanbul ignore start*/
+
+Object.defineProperty(apply$2, "__esModule", {
+ value: true
+});
+apply$2.applyPatch = applyPatch;
+apply$2.applyPatches = applyPatches;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_parse$1 = parse
+/*istanbul ignore end*/
+;
+
+var
+/*istanbul ignore start*/
+_distanceIterator = _interopRequireDefault(distanceIterator)
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+
+function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
+ };
+}
+/*istanbul ignore end*/
+
+
+function applyPatch(source, uniDiff) {
+ /*istanbul ignore start*/
+ var
+ /*istanbul ignore end*/
+ options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+
+ if (typeof uniDiff === 'string') {
+ uniDiff =
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _parse$1
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ parsePatch
+ /*istanbul ignore end*/
+ )(uniDiff);
+ }
+
+ if (Array.isArray(uniDiff)) {
+ if (uniDiff.length > 1) {
throw new Error('applyPatch only works with a single input.');
}
var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
hunks = uniDiff.hunks,
- compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
- return line === patchContent;
+ compareLine = options.compareLine || function (lineNumber, line, operation, patchContent)
+ /*istanbul ignore start*/
+ {
+ return (
+ /*istanbul ignore end*/
+ line === patchContent
+ );
},
errorCount = 0,
fuzzFactor = options.fuzzFactor || 0,
maxLine = lines.length - hunk.oldLines,
localOffset = 0,
toPos = offset + hunk.oldStart - 1;
- var iterator = distanceIterator(toPos, minLine, maxLine);
+ var iterator =
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _distanceIterator
+ /*istanbul ignore end*/
+ [
+ /*istanbul ignore start*/
+ "default"
+ /*istanbul ignore end*/
+ ])(toPos, minLine, maxLine);
for (; localOffset !== undefined; localOffset = iterator()) {
if (hunkFits(hunk, toPos + localOffset)) {
function applyPatches(uniDiff, options) {
if (typeof uniDiff === 'string') {
- uniDiff = parsePatch(uniDiff);
+ uniDiff =
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _parse$1
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ parsePatch
+ /*istanbul ignore end*/
+ )(uniDiff);
}
var currentIndex = 0;
processIndex();
}
+var merge$1 = {};
+
+var create$1 = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(create$1, "__esModule", {
+ value: true
+});
+create$1.structuredPatch = structuredPatch;
+create$1.formatPatch = formatPatch;
+create$1.createTwoFilesPatch = createTwoFilesPatch;
+create$1.createPatch = createPatch;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_line = line
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+function _toConsumableArray$1(arr) {
+ return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1();
+}
+
+function _nonIterableSpread$1() {
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+}
+
+function _unsupportedIterableToArray$1(o, minLen) {
+ if (!o) return;
+ if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
+ var n = Object.prototype.toString.call(o).slice(8, -1);
+ if (n === "Object" && o.constructor) n = o.constructor.name;
+ if (n === "Map" || n === "Set") return Array.from(o);
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
+}
+
+function _iterableToArray$1(iter) {
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
+}
+
+function _arrayWithoutHoles$1(arr) {
+ if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
+}
+
+function _arrayLikeToArray$1(arr, len) {
+ if (len == null || len > arr.length) len = arr.length;
+
+ for (var i = 0, arr2 = new Array(len); i < len; i++) {
+ arr2[i] = arr[i];
+ }
+
+ return arr2;
+}
+/*istanbul ignore end*/
+
+
function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
if (!options) {
options = {};
options.context = 4;
}
- var diff = diffLines(oldStr, newStr, options);
+ var diff =
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _line
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ diffLines
+ /*istanbul ignore end*/
+ )(oldStr, newStr, options);
diff.push({
value: '',
lines: []
curRange = [],
oldLine = 1,
newLine = 1;
+ /*istanbul ignore start*/
- var _loop = function _loop(i) {
+ var _loop = function _loop(
+ /*istanbul ignore end*/
+ i) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
- var _curRange; // If we have previous context, start with that
+ /*istanbul ignore start*/
+ var _curRange;
+ /*istanbul ignore end*/
+ // If we have previous context, start with that
if (!oldRangeStart) {
}
} // Output our changes
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+
- (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
+ (_curRange =
+ /*istanbul ignore end*/
+ curRange).push.apply(
+ /*istanbul ignore start*/
+ _curRange
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray$1(
+ /*istanbul ignore end*/
+ lines.map(function (entry) {
return (current.added ? '+' : '-') + entry;
}))); // Track the updated file position
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= options.context * 2 && i < diff.length - 2) {
- var _curRange2; // Overlapping
+ /*istanbul ignore start*/
+ var _curRange2;
+ /*istanbul ignore end*/
+ // Overlapping
+ /*istanbul ignore start*/
- (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
+ /*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+
+
+ (_curRange2 =
+ /*istanbul ignore end*/
+ curRange).push.apply(
+ /*istanbul ignore start*/
+ _curRange2
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray$1(
+ /*istanbul ignore end*/
+ contextLines(lines)));
} else {
- var _curRange3; // end the range and output
+ /*istanbul ignore start*/
+ var _curRange3;
+ /*istanbul ignore end*/
+ // end the range and output
var contextSize = Math.min(lines.length, options.context);
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
- (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
+ /*istanbul ignore start*/
+
+ (_curRange3 =
+ /*istanbul ignore end*/
+ curRange).push.apply(
+ /*istanbul ignore start*/
+ _curRange3
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray$1(
+ /*istanbul ignore end*/
+ contextLines(lines.slice(0, contextSize))));
var hunk = {
oldStart: oldRangeStart,
};
for (var i = 0; i < diff.length; i++) {
- _loop(i);
+ /*istanbul ignore start*/
+ _loop(
+ /*istanbul ignore end*/
+ i);
}
return {
return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
}
+var array = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(array, "__esModule", {
+ value: true
+});
+array.arrayEqual = arrayEqual;
+array.arrayStartsWith = arrayStartsWith;
+/*istanbul ignore end*/
+
function arrayEqual(a, b) {
if (a.length !== b.length) {
return false;
return true;
}
+/*istanbul ignore start*/
+
+Object.defineProperty(merge$1, "__esModule", {
+ value: true
+});
+merge$1.calcLineCount = calcLineCount;
+merge$1.merge = merge;
+/*istanbul ignore end*/
+
+var
+/*istanbul ignore start*/
+_create = create$1
+/*istanbul ignore end*/
+;
+var
+/*istanbul ignore start*/
+_parse = parse
+/*istanbul ignore end*/
+;
+var
+/*istanbul ignore start*/
+_array = array
+/*istanbul ignore end*/
+;
+/*istanbul ignore start*/
+
+function _toConsumableArray(arr) {
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
+}
+
+function _nonIterableSpread() {
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+}
+
+function _unsupportedIterableToArray(o, minLen) {
+ if (!o) return;
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
+ var n = Object.prototype.toString.call(o).slice(8, -1);
+ if (n === "Object" && o.constructor) n = o.constructor.name;
+ if (n === "Map" || n === "Set") return Array.from(o);
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
+}
+
+function _iterableToArray(iter) {
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
+}
+
+function _arrayWithoutHoles(arr) {
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
+}
+
+function _arrayLikeToArray(arr, len) {
+ if (len == null || len > arr.length) len = arr.length;
+
+ for (var i = 0, arr2 = new Array(len); i < len; i++) {
+ arr2[i] = arr[i];
+ }
+
+ return arr2;
+}
+/*istanbul ignore end*/
+
+
function calcLineCount(hunk) {
- var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
+ /*istanbul ignore start*/
+ var _calcOldNewLineCount =
+ /*istanbul ignore end*/
+ calcOldNewLineCount(hunk.lines),
oldLines = _calcOldNewLineCount.oldLines,
newLines = _calcOldNewLineCount.newLines;
function loadPatch(param, base) {
if (typeof param === 'string') {
if (/^@@/m.test(param) || /^Index:/m.test(param)) {
- return parsePatch(param)[0];
+ return (
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _parse
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ parsePatch
+ /*istanbul ignore end*/
+ )(param)[0]
+ );
}
if (!base) {
throw new Error('Must provide a base reference or pass in a patch');
}
- return structuredPatch(undefined, undefined, base, param);
+ return (
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _create
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ structuredPatch
+ /*istanbul ignore end*/
+ )(undefined, undefined, base, param)
+ );
}
return param;
// Both modified ...
mutualChange(hunk, mine, their);
} else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
- var _hunk$lines; // Mine inserted
+ /*istanbul ignore start*/
+ var _hunk$lines;
+ /*istanbul ignore end*/
+ // Mine inserted
+ /*istanbul ignore start*/
- (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
+ /*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+
+
+ (_hunk$lines =
+ /*istanbul ignore end*/
+ hunk.lines).push.apply(
+ /*istanbul ignore start*/
+ _hunk$lines
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray(
+ /*istanbul ignore end*/
+ collectChange(mine)));
} else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
- var _hunk$lines2; // Theirs inserted
+ /*istanbul ignore start*/
+ var _hunk$lines2;
+ /*istanbul ignore end*/
+ // Theirs inserted
+
+ /*istanbul ignore start*/
+ /*istanbul ignore end*/
- (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
+ /*istanbul ignore start*/
+
+
+ (_hunk$lines2 =
+ /*istanbul ignore end*/
+ hunk.lines).push.apply(
+ /*istanbul ignore start*/
+ _hunk$lines2
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray(
+ /*istanbul ignore end*/
+ collectChange(their)));
} else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
// Mine removed or edited
removal(hunk, mine, their);
if (allRemoves(myChanges) && allRemoves(theirChanges)) {
// Special case for remove changes that are supersets of one another
- if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
+ if (
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _array
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ arrayStartsWith
+ /*istanbul ignore end*/
+ )(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
+ /*istanbul ignore start*/
var _hunk$lines3;
+ /*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
- (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
+ /*istanbul ignore start*/
+
+
+ (_hunk$lines3 =
+ /*istanbul ignore end*/
+ hunk.lines).push.apply(
+ /*istanbul ignore start*/
+ _hunk$lines3
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray(
+ /*istanbul ignore end*/
+ myChanges));
return;
- } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
+ } else if (
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _array
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ arrayStartsWith
+ /*istanbul ignore end*/
+ )(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
+ /*istanbul ignore start*/
var _hunk$lines4;
+ /*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
- (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
+ /*istanbul ignore start*/
+
+
+ (_hunk$lines4 =
+ /*istanbul ignore end*/
+ hunk.lines).push.apply(
+ /*istanbul ignore start*/
+ _hunk$lines4
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray(
+ /*istanbul ignore end*/
+ theirChanges));
return;
}
- } else if (arrayEqual(myChanges, theirChanges)) {
+ } else if (
+ /*istanbul ignore start*/
+ (/*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+ 0, _array
+ /*istanbul ignore end*/
+ .
+ /*istanbul ignore start*/
+ arrayEqual
+ /*istanbul ignore end*/
+ )(myChanges, theirChanges)) {
+ /*istanbul ignore start*/
var _hunk$lines5;
+ /*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
- (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
+ /*istanbul ignore start*/
+
+
+ (_hunk$lines5 =
+ /*istanbul ignore end*/
+ hunk.lines).push.apply(
+ /*istanbul ignore start*/
+ _hunk$lines5
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray(
+ /*istanbul ignore end*/
+ myChanges));
return;
}
theirChanges = collectContext(their, myChanges);
if (theirChanges.merged) {
+ /*istanbul ignore start*/
var _hunk$lines6;
+ /*istanbul ignore end*/
+
+ /*istanbul ignore start*/
+
+ /*istanbul ignore end*/
- (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
+ /*istanbul ignore start*/
+
+
+ (_hunk$lines6 =
+ /*istanbul ignore end*/
+ hunk.lines).push.apply(
+ /*istanbul ignore start*/
+ _hunk$lines6
+ /*istanbul ignore end*/
+ ,
+ /*istanbul ignore start*/
+ _toConsumableArray(
+ /*istanbul ignore end*/
+ theirChanges.merged));
} else {
conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
}
}
}
- return ret;
-}
-
-function collectContext(state, matchChanges) {
- var changes = [],
- merged = [],
- matchIndex = 0,
- contextChanges = false,
- conflicted = false;
-
- while (matchIndex < matchChanges.length && state.index < state.lines.length) {
- var change = state.lines[state.index],
- match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
-
- if (match[0] === '+') {
- break;
- }
+ return ret;
+}
+
+function collectContext(state, matchChanges) {
+ var changes = [],
+ merged = [],
+ matchIndex = 0,
+ contextChanges = false,
+ conflicted = false;
+
+ while (matchIndex < matchChanges.length && state.index < state.lines.length) {
+ var change = state.lines[state.index],
+ match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
+
+ if (match[0] === '+') {
+ break;
+ }
+
+ contextChanges = contextChanges || change[0] !== ' ';
+ merged.push(match);
+ matchIndex++; // Consume any additions in the other block as a conflict to attempt
+ // to pull in the remaining context after this
+
+ if (change[0] === '+') {
+ conflicted = true;
+
+ while (change[0] === '+') {
+ changes.push(change);
+ change = state.lines[++state.index];
+ }
+ }
+
+ if (match.substr(1) === change.substr(1)) {
+ changes.push(change);
+ state.index++;
+ } else {
+ conflicted = true;
+ }
+ }
+
+ if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
+ conflicted = true;
+ }
+
+ if (conflicted) {
+ return changes;
+ }
+
+ while (matchIndex < matchChanges.length) {
+ merged.push(matchChanges[matchIndex++]);
+ }
+
+ return {
+ merged: merged,
+ changes: changes
+ };
+}
+
+function allRemoves(changes) {
+ return changes.reduce(function (prev, change) {
+ return prev && change[0] === '-';
+ }, true);
+}
+
+function skipRemoveSuperset(state, removeChanges, delta) {
+ for (var i = 0; i < delta; i++) {
+ var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
+
+ if (state.lines[state.index + i] !== ' ' + changeContent) {
+ return false;
+ }
+ }
+
+ state.index += delta;
+ return true;
+}
+
+function calcOldNewLineCount(lines) {
+ var oldLines = 0;
+ var newLines = 0;
+ lines.forEach(function (line) {
+ if (typeof line !== 'string') {
+ var myCount = calcOldNewLineCount(line.mine);
+ var theirCount = calcOldNewLineCount(line.theirs);
+
+ if (oldLines !== undefined) {
+ if (myCount.oldLines === theirCount.oldLines) {
+ oldLines += myCount.oldLines;
+ } else {
+ oldLines = undefined;
+ }
+ }
+
+ if (newLines !== undefined) {
+ if (myCount.newLines === theirCount.newLines) {
+ newLines += myCount.newLines;
+ } else {
+ newLines = undefined;
+ }
+ }
+ } else {
+ if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
+ newLines++;
+ }
+
+ if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
+ oldLines++;
+ }
+ }
+ });
+ return {
+ oldLines: oldLines,
+ newLines: newLines
+ };
+}
+
+var dmp = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(dmp, "__esModule", {
+ value: true
+});
+dmp.convertChangesToDMP = convertChangesToDMP;
+/*istanbul ignore end*/
+// See: http://code.google.com/p/google-diff-match-patch/wiki/API
+
+function convertChangesToDMP(changes) {
+ var ret = [],
+ change,
+ operation;
+
+ for (var i = 0; i < changes.length; i++) {
+ change = changes[i];
+
+ if (change.added) {
+ operation = 1;
+ } else if (change.removed) {
+ operation = -1;
+ } else {
+ operation = 0;
+ }
+
+ ret.push([operation, change.value]);
+ }
+
+ return ret;
+}
+
+var xml = {};
+
+/*istanbul ignore start*/
+
+Object.defineProperty(xml, "__esModule", {
+ value: true
+});
+xml.convertChangesToXML = convertChangesToXML;
+/*istanbul ignore end*/
+
+function convertChangesToXML(changes) {
+ var ret = [];
+
+ for (var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+
+ if (change.added) {
+ ret.push('<ins>');
+ } else if (change.removed) {
+ ret.push('<del>');
+ }
+
+ ret.push(escapeHTML(change.value));
+
+ if (change.added) {
+ ret.push('</ins>');
+ } else if (change.removed) {
+ ret.push('</del>');
+ }
+ }
+
+ return ret.join('');
+}
+
+function escapeHTML(s) {
+ var n = s;
+ n = n.replace(/&/g, '&');
+ n = n.replace(/</g, '<');
+ n = n.replace(/>/g, '>');
+ n = n.replace(/"/g, '"');
+ return n;
+}
+
+/*istanbul ignore start*/
+
+(function (exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ Object.defineProperty(exports, "Diff", {
+ enumerable: true,
+ get: function get() {
+ return _base["default"];
+ }
+ });
+ Object.defineProperty(exports, "diffChars", {
+ enumerable: true,
+ get: function get() {
+ return _character.diffChars;
+ }
+ });
+ Object.defineProperty(exports, "diffWords", {
+ enumerable: true,
+ get: function get() {
+ return _word.diffWords;
+ }
+ });
+ Object.defineProperty(exports, "diffWordsWithSpace", {
+ enumerable: true,
+ get: function get() {
+ return _word.diffWordsWithSpace;
+ }
+ });
+ Object.defineProperty(exports, "diffLines", {
+ enumerable: true,
+ get: function get() {
+ return _line.diffLines;
+ }
+ });
+ Object.defineProperty(exports, "diffTrimmedLines", {
+ enumerable: true,
+ get: function get() {
+ return _line.diffTrimmedLines;
+ }
+ });
+ Object.defineProperty(exports, "diffSentences", {
+ enumerable: true,
+ get: function get() {
+ return _sentence.diffSentences;
+ }
+ });
+ Object.defineProperty(exports, "diffCss", {
+ enumerable: true,
+ get: function get() {
+ return _css.diffCss;
+ }
+ });
+ Object.defineProperty(exports, "diffJson", {
+ enumerable: true,
+ get: function get() {
+ return _json.diffJson;
+ }
+ });
+ Object.defineProperty(exports, "canonicalize", {
+ enumerable: true,
+ get: function get() {
+ return _json.canonicalize;
+ }
+ });
+ Object.defineProperty(exports, "diffArrays", {
+ enumerable: true,
+ get: function get() {
+ return _array.diffArrays;
+ }
+ });
+ Object.defineProperty(exports, "applyPatch", {
+ enumerable: true,
+ get: function get() {
+ return _apply.applyPatch;
+ }
+ });
+ Object.defineProperty(exports, "applyPatches", {
+ enumerable: true,
+ get: function get() {
+ return _apply.applyPatches;
+ }
+ });
+ Object.defineProperty(exports, "parsePatch", {
+ enumerable: true,
+ get: function get() {
+ return _parse.parsePatch;
+ }
+ });
+ Object.defineProperty(exports, "merge", {
+ enumerable: true,
+ get: function get() {
+ return _merge.merge;
+ }
+ });
+ Object.defineProperty(exports, "structuredPatch", {
+ enumerable: true,
+ get: function get() {
+ return _create.structuredPatch;
+ }
+ });
+ Object.defineProperty(exports, "createTwoFilesPatch", {
+ enumerable: true,
+ get: function get() {
+ return _create.createTwoFilesPatch;
+ }
+ });
+ Object.defineProperty(exports, "createPatch", {
+ enumerable: true,
+ get: function get() {
+ return _create.createPatch;
+ }
+ });
+ Object.defineProperty(exports, "convertChangesToDMP", {
+ enumerable: true,
+ get: function get() {
+ return _dmp.convertChangesToDMP;
+ }
+ });
+ Object.defineProperty(exports, "convertChangesToXML", {
+ enumerable: true,
+ get: function get() {
+ return _xml.convertChangesToXML;
+ }
+ });
+ /*istanbul ignore end*/
+
+ var
+ /*istanbul ignore start*/
+ _base = _interopRequireDefault(base)
+ /*istanbul ignore end*/
+ ;
+
+ var
+ /*istanbul ignore start*/
+ _character = character
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _word = word
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _line = line
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _sentence = sentence
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _css = css
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _json = json
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _array = array$1
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _apply = apply$2
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _parse = parse
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _merge = merge$1
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _create = create$1
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _dmp = dmp
+ /*istanbul ignore end*/
+ ;
+ var
+ /*istanbul ignore start*/
+ _xml = xml
+ /*istanbul ignore end*/
+ ;
+ /*istanbul ignore start*/
+
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : {
+ "default": obj
+ };
+ }
+ /*istanbul ignore end*/
+
+})(lib$1);
+
+const {
+ promises: fs
+} = require$$0__default$4["default"];
+const path$1 = require$$0__default$1["default"];
+const chalk$1 = source; // eslint-disable-next-line no-restricted-modules
+
+const prettier$4 = require$$3; // eslint-disable-next-line no-restricted-modules
+
+const {
+ getStdin
+} = require$$4;
+const {
+ createIgnorer,
+ errors
+} = prettierInternal;
+const {
+ expandPatterns,
+ fixWindowsSlashes
+} = expandPatterns_1;
+const {
+ getOptionsForFile
+} = option;
+const isTTY = isTty;
+
+function diff(a, b) {
+ return lib$1.createTwoFilesPatch("", "", a, b, "", "", {
+ context: 2
+ });
+}
+
+function handleError(context, filename, error, printedFilename) {
+ if (error instanceof errors.UndefinedParserError) {
+ // Can't test on CI, `isTTY()` is always false, see ./is-tty.js
+
+ /* istanbul ignore next */
+ if ((context.argv.write || context.argv["ignore-unknown"]) && printedFilename) {
+ printedFilename.clear();
+ }
+
+ if (context.argv["ignore-unknown"]) {
+ return;
+ }
+
+ if (!context.argv.check && !context.argv["list-different"]) {
+ process.exitCode = 2;
+ }
+
+ context.logger.error(error.message);
+ return;
+ }
+
+ if (context.argv.write) {
+ // Add newline to split errors from filename line.
+ process.stdout.write("\n");
+ }
+
+ const isParseError = Boolean(error && error.loc);
+ const isValidationError = /^Invalid \S+ value\./.test(error && error.message);
+
+ if (isParseError) {
+ // `invalid.js: SyntaxError: Unexpected token (1:1)`.
+ context.logger.error(`${filename}: ${String(error)}`);
+ } else if (isValidationError || error instanceof errors.ConfigError) {
+ // `Invalid printWidth value. Expected an integer, but received 0.5.`
+ context.logger.error(error.message); // If validation fails for one file, it will fail for all of them.
+
+ process.exit(1);
+ } else if (error instanceof errors.DebugError) {
+ // `invalid.js: Some debug error message`
+ context.logger.error(`${filename}: ${error.message}`);
+ } else {
+ // `invalid.js: Error: Some unexpected error\n[stack trace]`
+
+ /* istanbul ignore next */
+ context.logger.error(filename + ": " + (error.stack || error));
+ } // Don't exit the process if one file failed
+
+
+ process.exitCode = 2;
+}
+
+function writeOutput(context, result, options) {
+ // Don't use `console.log` here since it adds an extra newline at the end.
+ process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted);
+
+ if (options && options.cursorOffset >= 0) {
+ process.stderr.write(result.cursorOffset + "\n");
+ }
+}
+
+function listDifferent(context, input, options, filename) {
+ if (!context.argv.check && !context.argv["list-different"]) {
+ return;
+ }
+
+ try {
+ if (!options.filepath && !options.parser) {
+ throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
+ }
+
+ if (!prettier$4.check(input, options)) {
+ if (!context.argv.write) {
+ context.logger.log(filename);
+ process.exitCode = 1;
+ }
+ }
+ } catch (error) {
+ context.logger.error(error.message);
+ }
+
+ return true;
+}
+
+function format$1(context, input, opt) {
+ if (!opt.parser && !opt.filepath) {
+ throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
+ }
+
+ if (context.argv["debug-print-doc"]) {
+ const doc = prettier$4.__debug.printToDoc(input, opt);
+
+ return {
+ formatted: prettier$4.__debug.formatDoc(doc) + "\n"
+ };
+ }
+
+ if (context.argv["debug-print-comments"]) {
+ return {
+ formatted: prettier$4.format(JSON.stringify(prettier$4.formatWithCursor(input, opt).comments || []), {
+ parser: "json"
+ })
+ };
+ }
+
+ if (context.argv["debug-print-ast"]) {
+ const {
+ ast
+ } = prettier$4.__debug.parse(input, opt);
+
+ return {
+ formatted: JSON.stringify(ast)
+ };
+ }
+
+ if (context.argv["debug-check"]) {
+ const pp = prettier$4.format(input, opt);
+ const pppp = prettier$4.format(pp, opt);
+
+ if (pp !== pppp) {
+ throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp));
+ } else {
+ const stringify = obj => JSON.stringify(obj, null, 2);
+
+ const ast = stringify(prettier$4.__debug.parse(input, opt,
+ /* massage */
+ true).ast);
+ const past = stringify(prettier$4.__debug.parse(pp, opt,
+ /* massage */
+ true).ast);
+ /* istanbul ignore next */
+
+ if (ast !== past) {
+ const MAX_AST_SIZE = 2097152; // 2MB
+
+ const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
+ throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp));
+ }
+ }
+
+ return {
+ formatted: pp,
+ filepath: opt.filepath || "(stdin)\n"
+ };
+ }
+ /* istanbul ignore next */
+
+
+ if (context.argv["debug-benchmark"]) {
+ let benchmark;
+
+ try {
+ // eslint-disable-next-line import/no-extraneous-dependencies
+ benchmark = require("benchmark");
+ } catch {
+ context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed.");
+ process.exit(2);
+ }
+
+ context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.");
+ const suite = new benchmark.Suite();
+ suite.add("format", () => {
+ prettier$4.formatWithCursor(input, opt);
+ }).on("cycle", event => {
+ const results = {
+ benchmark: String(event.target),
+ hz: event.target.hz,
+ ms: event.target.times.cycle * 1000
+ };
+ context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
+ }).run({
+ async: false
+ });
+ } else if (context.argv["debug-repeat"] > 0) {
+ const repeat = context.argv["debug-repeat"];
+ context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times.");
+ let totalMs = 0;
+
+ for (let i = 0; i < repeat; ++i) {
+ // should be using `performance.now()`, but only `Date` is cross-platform enough
+ const startMs = Date.now();
+ prettier$4.formatWithCursor(input, opt);
+ totalMs += Date.now() - startMs;
+ }
+
+ const averageMs = totalMs / repeat;
+ const results = {
+ repeat,
+ hz: 1000 / averageMs,
+ ms: averageMs
+ };
+ context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
+ }
+
+ return prettier$4.formatWithCursor(input, opt);
+}
+
+async function createIgnorerFromContextOrDie(context) {
+ try {
+ return await createIgnorer(context.argv["ignore-path"], context.argv["with-node-modules"]);
+ } catch (e) {
+ context.logger.error(e.message);
+ process.exit(2);
+ }
+}
+
+async function formatStdin$1(context) {
+ const filepath = context.argv["stdin-filepath"] ? path$1.resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd();
+ const ignorer = await createIgnorerFromContextOrDie(context); // If there's an ignore-path set, the filename must be relative to the
+ // ignore path, not the current working directory.
+
+ const relativeFilepath = context.argv["ignore-path"] ? path$1.relative(path$1.dirname(context.argv["ignore-path"]), filepath) : path$1.relative(process.cwd(), filepath);
+
+ try {
+ const input = await getStdin();
+
+ if (relativeFilepath && ignorer.ignores(fixWindowsSlashes(relativeFilepath))) {
+ writeOutput(context, {
+ formatted: input
+ });
+ return;
+ }
+
+ const options = await getOptionsForFile(context, filepath);
+
+ if (listDifferent(context, input, options, "(stdin)")) {
+ return;
+ }
+
+ writeOutput(context, format$1(context, input, options), options);
+ } catch (error) {
+ handleError(context, relativeFilepath || "stdin", error);
+ }
+}
+
+async function formatFiles$1(context) {
+ // The ignorer will be used to filter file paths after the glob is checked,
+ // before any files are actually written
+ const ignorer = await createIgnorerFromContextOrDie(context);
+ let numberOfUnformattedFilesFound = 0;
+
+ if (context.argv.check) {
+ context.logger.log("Checking formatting...");
+ }
+
+ for await (const pathOrError of expandPatterns(context)) {
+ if (typeof pathOrError === "object") {
+ context.logger.error(pathOrError.error); // Don't exit, but set the exit code to 2
+
+ process.exitCode = 2;
+ continue;
+ }
+
+ const filename = pathOrError; // If there's an ignore-path set, the filename must be relative to the
+ // ignore path, not the current working directory.
+
+ const ignoreFilename = context.argv["ignore-path"] ? path$1.relative(path$1.dirname(context.argv["ignore-path"]), filename) : filename;
+ const fileIgnored = ignorer.ignores(fixWindowsSlashes(ignoreFilename));
+
+ if (fileIgnored && (context.argv["debug-check"] || context.argv.write || context.argv.check || context.argv["list-different"])) {
+ continue;
+ }
+
+ const options = Object.assign(Object.assign({}, await getOptionsForFile(context, filename)), {}, {
+ filepath: filename
+ });
+ let printedFilename;
+
+ if (isTTY()) {
+ printedFilename = context.logger.log(filename, {
+ newline: false,
+ clearable: true
+ });
+ }
+
+ let input;
+
+ try {
+ input = await fs.readFile(filename, "utf8");
+ } catch (error) {
+ // Add newline to split errors from filename line.
+
+ /* istanbul ignore next */
+ context.logger.log("");
+ /* istanbul ignore next */
+
+ context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
+
+ /* istanbul ignore next */
+
+ process.exitCode = 2;
+ /* istanbul ignore next */
+
+ continue;
+ }
+
+ if (fileIgnored) {
+ writeOutput(context, {
+ formatted: input
+ }, options);
+ continue;
+ }
+
+ const start = Date.now();
+ let result;
+ let output;
+
+ try {
+ result = format$1(context, input, options);
+ output = result.formatted;
+ } catch (error) {
+ handleError(context, filename, error, printedFilename);
+ continue;
+ }
+
+ const isDifferent = output !== input;
+
+ if (printedFilename) {
+ // Remove previously printed filename to log it with duration.
+ printedFilename.clear();
+ }
+
+ if (context.argv.write) {
+ // Don't write the file if it won't change in order not to invalidate
+ // mtime based caches.
+ if (isDifferent) {
+ if (!context.argv.check && !context.argv["list-different"]) {
+ context.logger.log(`${filename} ${Date.now() - start}ms`);
+ }
+
+ try {
+ await fs.writeFile(filename, output, "utf8");
+ } catch (error) {
+ /* istanbul ignore next */
+ context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
+
+ /* istanbul ignore next */
+
+ process.exitCode = 2;
+ }
+ } else if (!context.argv.check && !context.argv["list-different"]) {
+ context.logger.log(`${chalk$1.grey(filename)} ${Date.now() - start}ms`);
+ }
+ } else if (context.argv["debug-check"]) {
+ /* istanbul ignore else */
+ if (result.filepath) {
+ context.logger.log(result.filepath);
+ } else {
+ process.exitCode = 2;
+ }
+ } else if (!context.argv.check && !context.argv["list-different"]) {
+ writeOutput(context, result, options);
+ }
+
+ if (isDifferent) {
+ if (context.argv.check) {
+ context.logger.warn(filename);
+ } else if (context.argv["list-different"]) {
+ context.logger.log(filename);
+ }
+
+ numberOfUnformattedFilesFound += 1;
+ }
+ } // Print check summary based on expected exit code
+
+
+ if (context.argv.check) {
+ if (numberOfUnformattedFilesFound === 0) {
+ context.logger.log("All matched files use Prettier code style!");
+ } else {
+ context.logger.warn(context.argv.write ? "Code style issues fixed in the above file(s)." : "Code style issues found in the above file(s). Forgot to run Prettier?");
+ }
+ } // Ensure non-zero exitCode when using --check/list-different is not combined with --write
+
+
+ if ((context.argv.check || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv.write) {
+ process.exitCode = 1;
+ }
+}
+
+var format_1 = {
+ format: format$1,
+ formatStdin: formatStdin$1,
+ formatFiles: formatFiles$1
+};
+
+var getNative = _getNative;
+
+var defineProperty$2 = function () {
+ try {
+ var func = getNative(Object, 'defineProperty');
+ func({}, '', {});
+ return func;
+ } catch (e) {}
+}();
+
+var _defineProperty = defineProperty$2;
+
+var defineProperty$1 = _defineProperty;
+/**
+ * The base implementation of `assignValue` and `assignMergeValue` without
+ * value checks.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
+ */
+
+function baseAssignValue$2(object, key, value) {
+ if (key == '__proto__' && defineProperty$1) {
+ defineProperty$1(object, key, {
+ 'configurable': true,
+ 'enumerable': true,
+ 'value': value,
+ 'writable': true
+ });
+ } else {
+ object[key] = value;
+ }
+}
+
+var _baseAssignValue = baseAssignValue$2;
+
+var baseAssignValue$1 = _baseAssignValue,
+ eq = eq_1;
+/** Used for built-in method references. */
+
+var objectProto$1 = Object.prototype;
+/** Used to check objects for own properties. */
+
+var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
+/**
+ * Assigns `value` to `key` of `object` if the existing value is not equivalent
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
+ * for equality comparisons.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
+ */
+
+function assignValue$1(object, key, value) {
+ var objValue = object[key];
+
+ if (!(hasOwnProperty$1.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) {
+ baseAssignValue$1(object, key, value);
+ }
+}
+
+var _assignValue = assignValue$1;
+
+var assignValue = _assignValue,
+ castPath$1 = _castPath,
+ isIndex = _isIndex,
+ isObject = isObject_1,
+ toKey = _toKey;
+/**
+ * The base implementation of `_.set`.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {Array|string} path The path of the property to set.
+ * @param {*} value The value to set.
+ * @param {Function} [customizer] The function to customize path creation.
+ * @returns {Object} Returns `object`.
+ */
+
+function baseSet$1(object, path, value, customizer) {
+ if (!isObject(object)) {
+ return object;
+ }
+
+ path = castPath$1(path, object);
+ var index = -1,
+ length = path.length,
+ lastIndex = length - 1,
+ nested = object;
+
+ while (nested != null && ++index < length) {
+ var key = toKey(path[index]),
+ newValue = value;
+
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
+ return object;
+ }
+
+ if (index != lastIndex) {
+ var objValue = nested[key];
+ newValue = customizer ? customizer(objValue, key, nested) : undefined;
+
+ if (newValue === undefined) {
+ newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {};
+ }
+ }
+
+ assignValue(nested, key, newValue);
+ nested = nested[key];
+ }
+
+ return object;
+}
+
+var _baseSet = baseSet$1;
+
+var baseGet = _baseGet,
+ baseSet = _baseSet,
+ castPath = _castPath;
+/**
+ * The base implementation of `_.pickBy` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {string[]} paths The property paths to pick.
+ * @param {Function} predicate The function invoked per property.
+ * @returns {Object} Returns the new object.
+ */
+
+function basePickBy$1(object, paths, predicate) {
+ var index = -1,
+ length = paths.length,
+ result = {};
+
+ while (++index < length) {
+ var path = paths[index],
+ value = baseGet(object, path);
+
+ if (predicate(value, path)) {
+ baseSet(result, castPath(path, object), value);
+ }
+ }
+
+ return result;
+}
+
+var _basePickBy = basePickBy$1;
+
+var basePickBy = _basePickBy,
+ hasIn = hasIn_1;
+/**
+ * The base implementation of `_.pick` without support for individual
+ * property identifiers.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {string[]} paths The property paths to pick.
+ * @returns {Object} Returns the new object.
+ */
+
+function basePick$1(object, paths) {
+ return basePickBy(object, paths, function (value, path) {
+ return hasIn(object, path);
+ });
+}
+
+var _basePick = basePick$1;
+
+var Symbol$1 = _Symbol,
+ isArguments = isArguments_1,
+ isArray = isArray_1;
+/** Built-in value references. */
+
+var spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : undefined;
+/**
+ * Checks if `value` is a flattenable `arguments` object or array.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
+ */
+
+function isFlattenable$1(value) {
+ return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
+}
+
+var _isFlattenable = isFlattenable$1;
+
+var arrayPush = _arrayPush,
+ isFlattenable = _isFlattenable;
+/**
+ * The base implementation of `_.flatten` with support for restricting flattening.
+ *
+ * @private
+ * @param {Array} array The array to flatten.
+ * @param {number} depth The maximum recursion depth.
+ * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
+ * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
+ * @param {Array} [result=[]] The initial result value.
+ * @returns {Array} Returns the new flattened array.
+ */
+
+function baseFlatten$1(array, depth, predicate, isStrict, result) {
+ var index = -1,
+ length = array.length;
+ predicate || (predicate = isFlattenable);
+ result || (result = []);
+
+ while (++index < length) {
+ var value = array[index];
+
+ if (depth > 0 && predicate(value)) {
+ if (depth > 1) {
+ // Recursively flatten arrays (susceptible to call stack limits).
+ baseFlatten$1(value, depth - 1, predicate, isStrict, result);
+ } else {
+ arrayPush(result, value);
+ }
+ } else if (!isStrict) {
+ result[result.length] = value;
+ }
+ }
+
+ return result;
+}
+
+var _baseFlatten = baseFlatten$1;
+
+var baseFlatten = _baseFlatten;
+/**
+ * Flattens `array` a single level deep.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Array
+ * @param {Array} array The array to flatten.
+ * @returns {Array} Returns the new flattened array.
+ * @example
+ *
+ * _.flatten([1, [2, [3, [4]], 5]]);
+ * // => [1, 2, [3, [4]], 5]
+ */
+
+function flatten$1(array) {
+ var length = array == null ? 0 : array.length;
+ return length ? baseFlatten(array, 1) : [];
+}
+
+var flatten_1 = flatten$1;
+
+/**
+ * A faster alternative to `Function#apply`, this function invokes `func`
+ * with the `this` binding of `thisArg` and the arguments of `args`.
+ *
+ * @private
+ * @param {Function} func The function to invoke.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {Array} args The arguments to invoke `func` with.
+ * @returns {*} Returns the result of `func`.
+ */
+
+function apply$1(func, thisArg, args) {
+ switch (args.length) {
+ case 0:
+ return func.call(thisArg);
+
+ case 1:
+ return func.call(thisArg, args[0]);
+
+ case 2:
+ return func.call(thisArg, args[0], args[1]);
+
+ case 3:
+ return func.call(thisArg, args[0], args[1], args[2]);
+ }
+
+ return func.apply(thisArg, args);
+}
+
+var _apply = apply$1;
+
+var apply = _apply;
+/* Built-in method references for those with the same name as other `lodash` methods. */
+
+var nativeMax = Math.max;
+/**
+ * A specialized version of `baseRest` which transforms the rest array.
+ *
+ * @private
+ * @param {Function} func The function to apply a rest parameter to.
+ * @param {number} [start=func.length-1] The start position of the rest parameter.
+ * @param {Function} transform The rest array transform.
+ * @returns {Function} Returns the new function.
+ */
+
+function overRest$1(func, start, transform) {
+ start = nativeMax(start === undefined ? func.length - 1 : start, 0);
+ return function () {
+ var args = arguments,
+ index = -1,
+ length = nativeMax(args.length - start, 0),
+ array = Array(length);
+
+ while (++index < length) {
+ array[index] = args[start + index];
+ }
+
+ index = -1;
+ var otherArgs = Array(start + 1);
+
+ while (++index < start) {
+ otherArgs[index] = args[index];
+ }
+
+ otherArgs[start] = transform(array);
+ return apply(func, this, otherArgs);
+ };
+}
+
+var _overRest = overRest$1;
+
+/**
+ * Creates a function that returns `value`.
+ *
+ * @static
+ * @memberOf _
+ * @since 2.4.0
+ * @category Util
+ * @param {*} value The value to return from the new function.
+ * @returns {Function} Returns the new constant function.
+ * @example
+ *
+ * var objects = _.times(2, _.constant({ 'a': 1 }));
+ *
+ * console.log(objects);
+ * // => [{ 'a': 1 }, { 'a': 1 }]
+ *
+ * console.log(objects[0] === objects[1]);
+ * // => true
+ */
+
+function constant$4(value) {
+ return function () {
+ return value;
+ };
+}
+
+var constant_1 = constant$4;
+
+var constant$3 = constant_1,
+ defineProperty = _defineProperty,
+ identity = identity_1;
+/**
+ * The base implementation of `setToString` without support for hot loop shorting.
+ *
+ * @private
+ * @param {Function} func The function to modify.
+ * @param {Function} string The `toString` result.
+ * @returns {Function} Returns `func`.
+ */
+
+var baseSetToString$1 = !defineProperty ? identity : function (func, string) {
+ return defineProperty(func, 'toString', {
+ 'configurable': true,
+ 'enumerable': false,
+ 'value': constant$3(string),
+ 'writable': true
+ });
+};
+var _baseSetToString = baseSetToString$1;
+
+/** Used to detect hot functions by number of calls within a span of milliseconds. */
+var HOT_COUNT = 800,
+ HOT_SPAN = 16;
+/* Built-in method references for those with the same name as other `lodash` methods. */
+
+var nativeNow = Date.now;
+/**
+ * Creates a function that'll short out and invoke `identity` instead
+ * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
+ * milliseconds.
+ *
+ * @private
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new shortable function.
+ */
+
+function shortOut$1(func) {
+ var count = 0,
+ lastCalled = 0;
+ return function () {
+ var stamp = nativeNow(),
+ remaining = HOT_SPAN - (stamp - lastCalled);
+ lastCalled = stamp;
+
+ if (remaining > 0) {
+ if (++count >= HOT_COUNT) {
+ return arguments[0];
+ }
+ } else {
+ count = 0;
+ }
+
+ return func.apply(undefined, arguments);
+ };
+}
+
+var _shortOut = shortOut$1;
+
+var baseSetToString = _baseSetToString,
+ shortOut = _shortOut;
+/**
+ * Sets the `toString` method of `func` to return `string`.
+ *
+ * @private
+ * @param {Function} func The function to modify.
+ * @param {Function} string The `toString` result.
+ * @returns {Function} Returns `func`.
+ */
+
+var setToString$1 = shortOut(baseSetToString);
+var _setToString = setToString$1;
+
+var flatten = flatten_1,
+ overRest = _overRest,
+ setToString = _setToString;
+/**
+ * A specialized version of `baseRest` which flattens the rest array.
+ *
+ * @private
+ * @param {Function} func The function to apply a rest parameter to.
+ * @returns {Function} Returns the new function.
+ */
+
+function flatRest$1(func) {
+ return setToString(overRest(func, undefined, flatten), func + '');
+}
+
+var _flatRest = flatRest$1;
+
+var basePick = _basePick,
+ flatRest = _flatRest;
+/**
+ * Creates an object composed of the picked `object` properties.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The source object.
+ * @param {...(string|string[])} [paths] The property paths to pick.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * var object = { 'a': 1, 'b': '2', 'c': 3 };
+ *
+ * _.pick(object, ['a', 'c']);
+ * // => { 'a': 1, 'c': 3 }
+ */
+
+var pick$1 = flatRest(function (object, paths) {
+ return object == null ? {} : basePick(object, paths);
+});
+var pick_1 = pick$1;
+
+var lib = {exports: {}};
+
+(function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.outdent = void 0; // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either.
+
+ function noop() {
+ var args = [];
+
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ }
+
+ function createWeakMap() {
+ if (typeof WeakMap !== "undefined") {
+ return new WeakMap();
+ } else {
+ return fakeSetOrMap();
+ }
+ }
+ /**
+ * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything.
+ */
+
+
+ function fakeSetOrMap() {
+ return {
+ add: noop,
+ delete: noop,
+ get: noop,
+ set: noop,
+ has: function (k) {
+ return false;
+ }
+ };
+ } // Safe hasOwnProperty
+
+
+ var hop = Object.prototype.hasOwnProperty;
+
+ var has = function (obj, prop) {
+ return hop.call(obj, prop);
+ }; // Copy all own enumerable properties from source to target
+
+
+ function extend(target, source) {
+ for (var prop in source) {
+ if (has(source, prop)) {
+ target[prop] = source[prop];
+ }
+ }
+
+ return target;
+ }
+
+ var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
+ var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
+ var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
+ var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
+ var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
+
+ function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
+ // If first interpolated value is a reference to outdent,
+ // determine indentation level from the indentation of the interpolated value.
+ var indentationLevel = 0;
+ var match = strings[0].match(reDetectIndentation);
+
+ if (match) {
+ indentationLevel = match[1].length;
+ }
+
+ var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
+ var reMatchIndent = new RegExp(reSource, "g");
+
+ if (firstInterpolatedValueSetsIndentationLevel) {
+ strings = strings.slice(1);
+ }
+
+ var newline = options.newline,
+ trimLeadingNewline = options.trimLeadingNewline,
+ trimTrailingNewline = options.trimTrailingNewline;
+ var normalizeNewlines = typeof newline === "string";
+ var l = strings.length;
+ var outdentedStrings = strings.map(function (v, i) {
+ // Remove leading indentation from all lines
+ v = v.replace(reMatchIndent, "$1"); // Trim a leading newline from the first string
+
+ if (i === 0 && trimLeadingNewline) {
+ v = v.replace(reLeadingNewline, "");
+ } // Trim a trailing newline from the last string
+
+
+ if (i === l - 1 && trimTrailingNewline) {
+ v = v.replace(reTrailingNewline, "");
+ } // Normalize newlines
+
+
+ if (normalizeNewlines) {
+ v = v.replace(/\r\n|\n|\r/g, function (_) {
+ return newline;
+ });
+ }
+
+ return v;
+ });
+ return outdentedStrings;
+ }
+
+ function concatStringsAndValues(strings, values) {
+ var ret = "";
+
+ for (var i = 0, l = strings.length; i < l; i++) {
+ ret += strings[i];
+
+ if (i < l - 1) {
+ ret += values[i];
+ }
+ }
+
+ return ret;
+ }
+
+ function isTemplateStringsArray(v) {
+ return has(v, "raw") && has(v, "length");
+ }
+ /**
+ * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to
+ * makeInstance
+ * @param options
+ * @return {outdent}
+ */
+
+
+ function createInstance(options) {
+ /** Cache of pre-processed template literal arrays */
+ var arrayAutoIndentCache = createWeakMap();
+ /**
+ * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent,
+ * before interpolated values are injected.
+ */
+
+ var arrayFirstInterpSetsIndentCache = createWeakMap();
+
+ function outdent(stringsOrOptions) {
+ var values = [];
+
+ for (var _i = 1; _i < arguments.length; _i++) {
+ values[_i - 1] = arguments[_i];
+ }
+ /* tslint:enable:no-shadowed-variable */
+
+
+ if (isTemplateStringsArray(stringsOrOptions)) {
+ var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace?
+
+ var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation
+
+ var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
+ var renderedArray = cache.get(strings);
+
+ if (!renderedArray) {
+ renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
+ cache.set(strings, renderedArray);
+ }
+ /** If no interpolated values, skip concatenation step */
+
+
+ if (values.length === 0) {
+ return renderedArray[0];
+ }
+ /** Concatenate string literals with interpolated values */
+
+
+ var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
+ return rendered;
+ } else {
+ // Create and return a new instance of outdent with the given options
+ return createInstance(extend(extend({}, options), stringsOrOptions || {}));
+ }
+ }
+
+ var fullOutdent = extend(outdent, {
+ string: function (str) {
+ return _outdentArray([str], false, options)[0];
+ }
+ });
+ return fullOutdent;
+ }
+
+ var defaultOutdent = createInstance({
+ trimLeadingNewline: true,
+ trimTrailingNewline: true
+ });
+ exports.outdent = defaultOutdent; // Named exports. Simple and preferred.
+ // import outdent from 'outdent';
+
+ exports.default = defaultOutdent;
+
+ {
+ // In webpack harmony-modules environments, module.exports is read-only,
+ // so we fail gracefully.
+ try {
+ module.exports = defaultOutdent;
+ Object.defineProperty(defaultOutdent, "__esModule", {
+ value: true
+ });
+ defaultOutdent.default = defaultOutdent;
+ defaultOutdent.outdent = defaultOutdent;
+ } catch (e) {}
+ }
+})(lib, lib.exports);
+
+const {
+ outdent
+} = lib.exports;
+const {
+ coreOptions: coreOptions$1
+} = prettierInternal;
+const categoryOrder = [coreOptions$1.CATEGORY_OUTPUT, coreOptions$1.CATEGORY_FORMAT, coreOptions$1.CATEGORY_CONFIG, coreOptions$1.CATEGORY_EDITOR, coreOptions$1.CATEGORY_OTHER];
+/**
+ * {
+ * [optionName]: {
+ * // The type of the option. For 'choice', see also `choices` below.
+ * // When passing a type other than the ones listed below, the option is
+ * // treated as taking any string as argument, and `--option <${type}>` will
+ * // be displayed in --help.
+ * type: "boolean" | "choice" | "int" | string;
+ *
+ * // Default value to be passed to the minimist option `default`.
+ * default?: any;
+ *
+ * // Alias name to be passed to the minimist option `alias`.
+ * alias?: string;
+ *
+ * // For grouping options by category in --help.
+ * category?: string;
+ *
+ * // Description to be displayed in --help. If omitted, the option won't be
+ * // shown at all in --help (but see also `oppositeDescription` below).
+ * description?: string;
+ *
+ * // Description for `--no-${name}` to be displayed in --help. If omitted,
+ * // `--no-${name}` won't be shown.
+ * oppositeDescription?: string;
+ *
+ * // Indicate if this option is simply passed to the API.
+ * // true: use camelified name as the API option name.
+ * // string: use this value as the API option name.
+ * forwardToApi?: boolean | string;
+ *
+ * // Indicate that a CLI flag should be an array when forwarded to the API.
+ * array?: boolean;
+ *
+ * // Specify available choices for validation. They will also be displayed
+ * // in --help as <a|b|c>.
+ * // Use an object instead of a string if a choice is deprecated and should
+ * // be treated as `redirect` instead, or if you'd like to add description for
+ * // the choice.
+ * choices?: Array<
+ * | string
+ * | { value: string, description?: string, deprecated?: boolean, redirect?: string }
+ * >;
+ *
+ * // If the option has a value that is an exception to the regular value
+ * // constraints, indicate that value here (or use a function for more
+ * // flexibility).
+ * exception?: ((value: any) => boolean);
+ *
+ * // Indicate that the option is deprecated. Use a string to add an extra
+ * // message to --help for the option, for example to suggest a replacement
+ * // option.
+ * deprecated?: true | string;
+ * }
+ * }
+ *
+ * Note: The options below are sorted alphabetically.
+ */
+
+const options = {
+ check: {
+ type: "boolean",
+ category: coreOptions$1.CATEGORY_OUTPUT,
+ alias: "c",
+ description: outdent`
+ Check if the given files are formatted, print a human-friendly summary
+ message and paths to unformatted files (see also --list-different).
+ `
+ },
+ color: {
+ // The supports-color package (a sub sub dependency) looks directly at
+ // `process.argv` for `--no-color` and such-like options. The reason it is
+ // listed here is to avoid "Ignored unknown option: --no-color" warnings.
+ // See https://github.com/chalk/supports-color/#info for more information.
+ type: "boolean",
+ default: true,
+ description: "Colorize error messages.",
+ oppositeDescription: "Do not colorize error messages."
+ },
+ config: {
+ type: "path",
+ category: coreOptions$1.CATEGORY_CONFIG,
+ description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
+ oppositeDescription: "Do not look for a configuration file.",
+ exception: value => value === false
+ },
+ "config-precedence": {
+ type: "choice",
+ category: coreOptions$1.CATEGORY_CONFIG,
+ default: "cli-override",
+ choices: [{
+ value: "cli-override",
+ description: "CLI options take precedence over config file"
+ }, {
+ value: "file-override",
+ description: "Config file take precedence over CLI options"
+ }, {
+ value: "prefer-file",
+ description: outdent`
+ If a config file is found will evaluate it and ignore other CLI options.
+ If no config file is found CLI options will evaluate as normal.
+ `
+ }],
+ description: "Define in which order config files and CLI options should be evaluated."
+ },
+ "debug-benchmark": {
+ // Run the formatting benchmarks. Requires 'benchmark' module to be installed.
+ type: "boolean"
+ },
+ "debug-check": {
+ // Run the formatting once again on the formatted output, throw if different.
+ type: "boolean"
+ },
+ "debug-print-doc": {
+ type: "boolean"
+ },
+ "debug-print-comments": {
+ type: "boolean"
+ },
+ "debug-print-ast": {
+ type: "boolean"
+ },
+ "debug-repeat": {
+ // Repeat the formatting a few times and measure the average duration.
+ type: "int",
+ default: 0
+ },
+ editorconfig: {
+ type: "boolean",
+ category: coreOptions$1.CATEGORY_CONFIG,
+ description: "Take .editorconfig into account when parsing configuration.",
+ oppositeDescription: "Don't take .editorconfig into account when parsing configuration.",
+ default: true
+ },
+ "error-on-unmatched-pattern": {
+ type: "boolean",
+ oppositeDescription: "Prevent errors when pattern is unmatched."
+ },
+ "find-config-path": {
+ type: "path",
+ category: coreOptions$1.CATEGORY_CONFIG,
+ description: "Find and print the path to a configuration file for the given input file."
+ },
+ "file-info": {
+ type: "path",
+ description: outdent`
+ Extract the following info (as JSON) for a given file path. Reported fields:
+ * ignored (boolean) - true if file path is filtered by --ignore-path
+ * inferredParser (string | null) - name of parser inferred from file path
+ `
+ },
+ help: {
+ type: "flag",
+ alias: "h",
+ description: outdent`
+ Show CLI usage, or details about the given flag.
+ Example: --help write
+ `,
+ exception: value => value === ""
+ },
+ "ignore-path": {
+ type: "path",
+ category: coreOptions$1.CATEGORY_CONFIG,
+ default: ".prettierignore",
+ description: "Path to a file with patterns describing files to ignore."
+ },
+ "ignore-unknown": {
+ type: "boolean",
+ alias: "u",
+ description: "Ignore unknown files."
+ },
+ "list-different": {
+ type: "boolean",
+ category: coreOptions$1.CATEGORY_OUTPUT,
+ alias: "l",
+ description: "Print the names of files that are different from Prettier's formatting (see also --check)."
+ },
+ loglevel: {
+ type: "choice",
+ description: "What level of logs to report.",
+ default: "log",
+ choices: ["silent", "error", "warn", "log", "debug"]
+ },
+ "support-info": {
+ type: "boolean",
+ description: "Print support information as JSON."
+ },
+ version: {
+ type: "boolean",
+ alias: "v",
+ description: "Print Prettier version."
+ },
+ "with-node-modules": {
+ type: "boolean",
+ category: coreOptions$1.CATEGORY_CONFIG,
+ description: "Process files inside 'node_modules' directory."
+ },
+ write: {
+ type: "boolean",
+ alias: "w",
+ category: coreOptions$1.CATEGORY_OUTPUT,
+ description: "Edit files in-place. (Beware!)"
+ }
+};
+const usageSummary = outdent`
+ Usage: prettier [options] [file/dir/glob ...]
+
+ By default, output is written to stdout.
+ Stdin is read if it is piped to Prettier and no files are given.
+`;
+var constant$2 = {
+ categoryOrder,
+ options,
+ usageSummary
+};
- contextChanges = contextChanges || change[0] !== ' ';
- merged.push(match);
- matchIndex++; // Consume any additions in the other block as a conflict to attempt
- // to pull in the remaining context after this
+const dashify = dashify$2;
+const {
+ coreOptions
+} = prettierInternal;
- if (change[0] === '+') {
- conflicted = true;
+function normalizeDetailedOption(name, option) {
+ return Object.assign(Object.assign({
+ category: coreOptions.CATEGORY_OTHER
+ }, option), {}, {
+ choices: option.choices && option.choices.map(choice => {
+ const newChoice = Object.assign({
+ description: "",
+ deprecated: false
+ }, typeof choice === "object" ? choice : {
+ value: choice
+ });
+ /* istanbul ignore next */
- while (change[0] === '+') {
- changes.push(change);
- change = state.lines[++state.index];
+ if (newChoice.value === true) {
+ newChoice.value = ""; // backward compatibility for original boolean option
}
- }
-
- if (match.substr(1) === change.substr(1)) {
- changes.push(change);
- state.index++;
- } else {
- conflicted = true;
- }
- }
-
- if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
- conflicted = true;
- }
-
- if (conflicted) {
- return changes;
- }
-
- while (matchIndex < matchChanges.length) {
- merged.push(matchChanges[matchIndex++]);
- }
- return {
- merged: merged,
- changes: changes
- };
+ return newChoice;
+ })
+ });
}
-function allRemoves(changes) {
- return changes.reduce(function (prev, change) {
- return prev && change[0] === '-';
- }, true);
+function normalizeDetailedOptionMap$2(detailedOptionMap) {
+ return Object.fromEntries(Object.entries(detailedOptionMap).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)).map(([name, option]) => [name, normalizeDetailedOption(name, option)]));
}
-function skipRemoveSuperset(state, removeChanges, delta) {
- for (var i = 0; i < delta; i++) {
- var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
+function createDetailedOptionMap$2(supportOptions) {
+ return Object.fromEntries(supportOptions.map(option => {
+ const newOption = Object.assign(Object.assign({}, option), {}, {
+ name: option.cliName || dashify(option.name),
+ description: option.cliDescription || option.description,
+ category: option.cliCategory || coreOptions.CATEGORY_FORMAT,
+ forwardToApi: option.name
+ });
+ /* istanbul ignore next */
- if (state.lines[state.index + i] !== ' ' + changeContent) {
- return false;
+ if (option.deprecated) {
+ delete newOption.forwardToApi;
+ delete newOption.description;
+ delete newOption.oppositeDescription;
+ newOption.deprecated = true;
}
- }
- state.index += delta;
- return true;
+ return [newOption.name, newOption];
+ }));
}
-function calcOldNewLineCount(lines) {
- var oldLines = 0;
- var newLines = 0;
- lines.forEach(function (line) {
- if (typeof line !== 'string') {
- var myCount = calcOldNewLineCount(line.mine);
- var theirCount = calcOldNewLineCount(line.theirs);
-
- if (oldLines !== undefined) {
- if (myCount.oldLines === theirCount.oldLines) {
- oldLines += myCount.oldLines;
- } else {
- oldLines = undefined;
- }
- }
-
- if (newLines !== undefined) {
- if (myCount.newLines === theirCount.newLines) {
- newLines += myCount.newLines;
- } else {
- newLines = undefined;
- }
- }
- } else {
- if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
- newLines++;
- }
-
- if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
- oldLines++;
- }
- }
- });
- return {
- oldLines: oldLines,
- newLines: newLines
- };
-} // See: http://code.google.com/p/google-diff-match-patch/wiki/API
-
-
-function convertChangesToDMP(changes) {
- var ret = [],
- change,
- operation;
-
- for (var i = 0; i < changes.length; i++) {
- change = changes[i];
+var optionMap = {
+ normalizeDetailedOptionMap: normalizeDetailedOptionMap$2,
+ createDetailedOptionMap: createDetailedOptionMap$2
+};
- if (change.added) {
- operation = 1;
- } else if (change.removed) {
- operation = -1;
- } else {
- operation = 0;
- }
+const pick = pick_1; // eslint-disable-next-line no-restricted-modules
- ret.push([operation, change.value]);
+const prettier$3 = require$$3;
+const {
+ optionsModule,
+ optionsNormalizer: {
+ normalizeCliOptions
+ },
+ utils: {
+ arrayify
}
+} = prettierInternal;
+const minimist = minimist_1;
+const constant$1 = constant$2;
+const {
+ createDetailedOptionMap: createDetailedOptionMap$1,
+ normalizeDetailedOptionMap: normalizeDetailedOptionMap$1
+} = optionMap;
+const createMinimistOptions = createMinimistOptions$2;
+/**
+ * @typedef {Object} Context
+ * @property logger
+ * @property {string[]} rawArguments
+ * @property argv
+ * @property {string[]} filePatterns
+ * @property {any[]} supportOptions
+ * @property detailedOptions
+ * @property detailedOptionMap
+ * @property apiDefaultOptions
+ * @property languages
+ * @property {Partial<Context>[]} stack
+ * @property pushContextPlugins
+ * @property popContextPlugins
+ */
- return ret;
-}
-
-function convertChangesToXML(changes) {
- var ret = [];
-
- for (var i = 0; i < changes.length; i++) {
- var change = changes[i];
-
- if (change.added) {
- ret.push('<ins>');
- } else if (change.removed) {
- ret.push('<del>');
- }
+class Context$1 {
+ constructor({
+ rawArguments,
+ logger
+ }) {
+ this.rawArguments = rawArguments;
+ this.logger = logger;
+ this.stack = [];
+ const {
+ plugin: plugins,
+ "plugin-search-dir": pluginSearchDirs
+ } = parseArgvWithoutPlugins$1(rawArguments, logger, ["plugin", "plugin-search-dir"]);
+ this.pushContextPlugins(plugins, pluginSearchDirs);
+ const argv = parseArgv(rawArguments, this.detailedOptions, logger);
+ this.argv = argv;
+ this.filePatterns = argv._.map(file => String(file));
+ }
+ /**
+ * @param {string[]} plugins
+ * @param {string[]=} pluginSearchDirs
+ */
- ret.push(escapeHTML(change.value));
- if (change.added) {
- ret.push('</ins>');
- } else if (change.removed) {
- ret.push('</del>');
- }
+ pushContextPlugins(plugins, pluginSearchDirs) {
+ this.stack.push(pick(this, ["supportOptions", "detailedOptions", "detailedOptionMap", "apiDefaultOptions", "languages"]));
+ Object.assign(this, getContextOptions(plugins, pluginSearchDirs));
}
- return ret.join('');
-}
+ popContextPlugins() {
+ Object.assign(this, this.stack.pop());
+ }
-function escapeHTML(s) {
- var n = s;
- n = n.replace(/&/g, '&');
- n = n.replace(/</g, '<');
- n = n.replace(/>/g, '>');
- n = n.replace(/"/g, '"');
- return n;
}
-var index_es6 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- Diff: Diff,
- applyPatch: applyPatch,
- applyPatches: applyPatches,
- canonicalize: canonicalize,
- convertChangesToDMP: convertChangesToDMP,
- convertChangesToXML: convertChangesToXML,
- createPatch: createPatch,
- createTwoFilesPatch: createTwoFilesPatch,
- diffArrays: diffArrays,
- diffChars: diffChars,
- diffCss: diffCss,
- diffJson: diffJson,
- diffLines: diffLines,
- diffSentences: diffSentences,
- diffTrimmedLines: diffTrimmedLines,
- diffWords: diffWords,
- diffWordsWithSpace: diffWordsWithSpace,
- merge: merge,
- parsePatch: parsePatch,
- structuredPatch: structuredPatch
-});
-
-// eslint-disable-next-line no-restricted-modules
-
-
-const {
- getStdin
-} = thirdParty;
-const {
- createIgnorer,
- errors,
- coreOptions: coreOptions$1,
- optionsModule,
- optionsNormalizer,
- utils: {
- arrayify
- }
-} = prettierInternal;
-const {
- expandPatterns: expandPatterns$1,
- fixWindowsSlashes: fixWindowsSlashes$1
-} = expandPatterns_1;
-const OPTION_USAGE_THRESHOLD = 25;
-const CHOICE_USAGE_MARGIN = 3;
-const CHOICE_USAGE_INDENTATION = 2;
-
-function getOptions(argv, detailedOptions) {
- return fromPairs_1(detailedOptions.filter(({
- forwardToApi
- }) => forwardToApi).map(({
- forwardToApi,
- name
- }) => [forwardToApi, argv[name]]));
+function getContextOptions(plugins, pluginSearchDirs) {
+ const {
+ options: supportOptions,
+ languages
+ } = prettier$3.getSupportInfo({
+ showDeprecated: true,
+ showUnreleased: true,
+ showInternal: true,
+ plugins,
+ pluginSearchDirs
+ });
+ const detailedOptionMap = normalizeDetailedOptionMap$1(Object.assign(Object.assign({}, createDetailedOptionMap$1(supportOptions)), constant$1.options));
+ const detailedOptions = arrayify(detailedOptionMap, "name");
+ const apiDefaultOptions = Object.assign(Object.assign({}, optionsModule.hiddenDefaults), Object.fromEntries(supportOptions.filter(({
+ deprecated
+ }) => !deprecated).map(option => [option.name, option.default])));
+ return {
+ supportOptions,
+ detailedOptions,
+ detailedOptionMap,
+ apiDefaultOptions,
+ languages
+ };
}
-function cliifyOptions(object, apiDetailedOptionMap) {
- return Object.keys(object || {}).reduce((output, key) => {
- const apiOption = apiDetailedOptionMap[key];
- const cliKey = apiOption ? apiOption.name : key;
- output[dashify(cliKey)] = object[key];
- return output;
- }, {});
-}
+function parseArgv(rawArguments, detailedOptions, logger, keys) {
+ const minimistOptions = createMinimistOptions(detailedOptions);
+ let argv = minimist(rawArguments, minimistOptions);
-function diff(a, b) {
- return index_es6.createTwoFilesPatch("", "", a, b, "", "", {
- context: 2
+ if (keys) {
+ detailedOptions = detailedOptions.filter(option => keys.includes(option.name));
+ argv = pick(argv, keys);
+ }
+
+ return normalizeCliOptions(argv, detailedOptions, {
+ logger
});
}
-function handleError(context, filename, error) {
- if (error instanceof errors.UndefinedParserError) {
- // Can't test on CI, `isTTY()` is always false, see ./is-tty.js
-
- /* istanbul ignore next */
- if ((context.argv.write || context.argv["ignore-unknown"]) && isTty()) {
- readline__default['default'].clearLine(process.stdout, 0);
- readline__default['default'].cursorTo(process.stdout, 0, null);
- }
-
- if (context.argv["ignore-unknown"]) {
- return;
- }
+const detailedOptionsWithoutPlugins = getContextOptions().detailedOptions;
- if (!context.argv.check && !context.argv["list-different"]) {
- process.exitCode = 2;
- }
+function parseArgvWithoutPlugins$1(rawArguments, logger, keys) {
+ return parseArgv(rawArguments, detailedOptionsWithoutPlugins, logger, typeof keys === "string" ? [keys] : keys);
+}
- context.logger.error(error.message);
- return;
- }
+var context = {
+ Context: Context$1,
+ parseArgvWithoutPlugins: parseArgvWithoutPlugins$1
+};
- if (context.argv.write) {
- // Add newline to split errors from filename line.
- process.stdout.write("\n");
+var $ = _export;
+var flattenIntoArray = flattenIntoArray_1;
+var toObject = toObject$4;
+var lengthOfArrayLike = lengthOfArrayLike$6;
+var toIntegerOrInfinity = toIntegerOrInfinity$3;
+var arraySpeciesCreate = arraySpeciesCreate$2;
+
+// `Array.prototype.flat` method
+// https://tc39.es/ecma262/#sec-array.prototype.flat
+$({ target: 'Array', proto: true }, {
+ flat: function flat(/* depthArg = 1 */) {
+ var depthArg = arguments.length ? arguments[0] : undefined;
+ var O = toObject(this);
+ var sourceLen = lengthOfArrayLike(O);
+ var A = arraySpeciesCreate(O, 0);
+ A.length = flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toIntegerOrInfinity(depthArg));
+ return A;
}
+});
- const isParseError = Boolean(error && error.loc);
- const isValidationError = /^Invalid \S+ value\./.test(error && error.message);
+var internalObjectKeys = objectKeysInternal;
+var enumBugKeys$1 = enumBugKeys$3;
- if (isParseError) {
- // `invalid.js: SyntaxError: Unexpected token (1:1)`.
- context.logger.error(`${filename}: ${String(error)}`);
- } else if (isValidationError || error instanceof errors.ConfigError) {
- // `Invalid printWidth value. Expected an integer, but received 0.5.`
- context.logger.error(error.message); // If validation fails for one file, it will fail for all of them.
+// `Object.keys` method
+// https://tc39.es/ecma262/#sec-object.keys
+// eslint-disable-next-line es/no-object-keys -- safe
+var objectKeys$1 = Object.keys || function keys(O) {
+ return internalObjectKeys(O, enumBugKeys$1);
+};
- process.exit(1);
- } else if (error instanceof errors.DebugError) {
- // `invalid.js: Some debug error message`
- context.logger.error(`${filename}: ${error.message}`);
- } else {
- // `invalid.js: Error: Some unexpected error\n[stack trace]`
+var DESCRIPTORS = descriptors;
+var definePropertyModule$1 = objectDefineProperty;
+var anObject$1 = anObject$7;
+var toIndexedObject = toIndexedObject$4;
+var objectKeys = objectKeys$1;
+
+// `Object.defineProperties` method
+// https://tc39.es/ecma262/#sec-object.defineproperties
+// eslint-disable-next-line es/no-object-defineproperties -- safe
+var objectDefineProperties = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {
+ anObject$1(O);
+ var props = toIndexedObject(Properties);
+ var keys = objectKeys(Properties);
+ var length = keys.length;
+ var index = 0;
+ var key;
+ while (length > index) definePropertyModule$1.f(O, key = keys[index++], props[key]);
+ return O;
+};
- /* istanbul ignore next */
- context.logger.error(filename + ": " + (error.stack || error));
- } // Don't exit the process if one file failed
+var getBuiltIn = getBuiltIn$5;
+var html$1 = getBuiltIn('document', 'documentElement');
- process.exitCode = 2;
-}
+/* global ActiveXObject -- old IE, WSH */
-function logResolvedConfigPathOrDie(context) {
- const configFile = src.resolveConfigFile.sync(context.argv["find-config-path"]);
+var anObject = anObject$7;
+var defineProperties = objectDefineProperties;
+var enumBugKeys = enumBugKeys$3;
+var hiddenKeys = hiddenKeys$4;
+var html = html$1;
+var documentCreateElement = documentCreateElement$1;
+var sharedKey = sharedKey$2;
- if (configFile) {
- context.logger.log(path__default['default'].relative(process.cwd(), configFile));
- } else {
- process.exit(1);
- }
-}
+var GT = '>';
+var LT = '<';
+var PROTOTYPE = 'prototype';
+var SCRIPT = 'script';
+var IE_PROTO = sharedKey('IE_PROTO');
-function logFileInfoOrDie(context) {
- const options = {
- ignorePath: context.argv["ignore-path"],
- withNodeModules: context.argv["with-node-modules"],
- plugins: context.argv.plugin,
- pluginSearchDirs: context.argv["plugin-search-dir"],
- resolveConfig: context.argv.config !== false
- };
- context.logger.log(src.format(fastJsonStableStringify(src.getFileInfo.sync(context.argv["file-info"], options)), {
- parser: "json"
- }));
-}
+var EmptyConstructor = function () { /* empty */ };
-function writeOutput(context, result, options) {
- // Don't use `console.log` here since it adds an extra newline at the end.
- process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted);
+var scriptTag = function (content) {
+ return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
+};
- if (options && options.cursorOffset >= 0) {
- process.stderr.write(result.cursorOffset + "\n");
- }
-}
+// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
+var NullProtoObjectViaActiveX = function (activeXDocument) {
+ activeXDocument.write(scriptTag(''));
+ activeXDocument.close();
+ var temp = activeXDocument.parentWindow.Object;
+ activeXDocument = null; // avoid memory leak
+ return temp;
+};
-function listDifferent(context, input, options, filename) {
- if (!context.argv.check && !context.argv["list-different"]) {
- return;
- }
+// Create object with fake `null` prototype: use iframe Object with cleared prototype
+var NullProtoObjectViaIFrame = function () {
+ // Thrash, waste and sodomy: IE GC bug
+ var iframe = documentCreateElement('iframe');
+ var JS = 'java' + SCRIPT + ':';
+ var iframeDocument;
+ iframe.style.display = 'none';
+ html.appendChild(iframe);
+ // https://github.com/zloirock/core-js/issues/475
+ iframe.src = String(JS);
+ iframeDocument = iframe.contentWindow.document;
+ iframeDocument.open();
+ iframeDocument.write(scriptTag('document.F=Object'));
+ iframeDocument.close();
+ return iframeDocument.F;
+};
+// Check for document.domain and active x support
+// No need to use active x approach when document.domain is not set
+// see https://github.com/es-shims/es5-shim/issues/150
+// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
+// avoid IE GC bug
+var activeXDocument;
+var NullProtoObject = function () {
try {
- if (!options.filepath && !options.parser) {
- throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
- }
+ activeXDocument = new ActiveXObject('htmlfile');
+ } catch (error) { /* ignore */ }
+ NullProtoObject = typeof document != 'undefined'
+ ? document.domain && activeXDocument
+ ? NullProtoObjectViaActiveX(activeXDocument) // old IE
+ : NullProtoObjectViaIFrame()
+ : NullProtoObjectViaActiveX(activeXDocument); // WSH
+ var length = enumBugKeys.length;
+ while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
+ return NullProtoObject();
+};
- if (!src.check(input, options)) {
- if (!context.argv.write) {
- context.logger.log(filename);
- process.exitCode = 1;
- }
- }
- } catch (error) {
- context.logger.error(error.message);
- }
+hiddenKeys[IE_PROTO] = true;
+
+// `Object.create` method
+// https://tc39.es/ecma262/#sec-object.create
+var objectCreate = Object.create || function create(O, Properties) {
+ var result;
+ if (O !== null) {
+ EmptyConstructor[PROTOTYPE] = anObject(O);
+ result = new EmptyConstructor();
+ EmptyConstructor[PROTOTYPE] = null;
+ // add "__proto__" for Object.getPrototypeOf polyfill
+ result[IE_PROTO] = O;
+ } else result = NullProtoObject();
+ return Properties === undefined ? result : defineProperties(result, Properties);
+};
- return true;
+var wellKnownSymbol = wellKnownSymbol$7;
+var create = objectCreate;
+var definePropertyModule = objectDefineProperty;
+
+var UNSCOPABLES = wellKnownSymbol('unscopables');
+var ArrayPrototype = Array.prototype;
+
+// Array.prototype[@@unscopables]
+// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
+if (ArrayPrototype[UNSCOPABLES] == undefined) {
+ definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {
+ configurable: true,
+ value: create(null)
+ });
}
-function format(context, input, opt) {
- if (!opt.parser && !opt.filepath) {
- throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
- }
+// add a key to Array.prototype[@@unscopables]
+var addToUnscopables$1 = function (key) {
+ ArrayPrototype[UNSCOPABLES][key] = true;
+};
- if (context.argv["debug-print-doc"]) {
- const doc = src.__debug.printToDoc(input, opt);
+// this method was added to unscopables after implementation
+// in popular engines, so it's moved to a separate module
+var addToUnscopables = addToUnscopables$1;
- return {
- formatted: src.__debug.formatDoc(doc)
- };
+// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
+addToUnscopables('flat');
+
+var baseAssignValue = _baseAssignValue,
+ createAggregator = _createAggregator;
+/** Used for built-in method references. */
+
+var objectProto = Object.prototype;
+/** Used to check objects for own properties. */
+
+var hasOwnProperty = objectProto.hasOwnProperty;
+/**
+ * Creates an object composed of keys generated from the results of running
+ * each element of `collection` thru `iteratee`. The order of grouped values
+ * is determined by the order they occur in `collection`. The corresponding
+ * value of each key is an array of elements responsible for generating the
+ * key. The iteratee is invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
+ * @returns {Object} Returns the composed aggregate object.
+ * @example
+ *
+ * _.groupBy([6.1, 4.2, 6.3], Math.floor);
+ * // => { '4': [4.2], '6': [6.1, 6.3] }
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.groupBy(['one', 'two', 'three'], 'length');
+ * // => { '3': ['one', 'two'], '5': ['three'] }
+ */
+
+var groupBy$1 = createAggregator(function (result, value, key) {
+ if (hasOwnProperty.call(result, key)) {
+ result[key].push(value);
+ } else {
+ baseAssignValue(result, key, [value]);
}
+});
+var groupBy_1 = groupBy$1;
- if (context.argv["debug-check"]) {
- const pp = src.format(input, opt);
- const pppp = src.format(pp, opt);
+var camelcase = {exports: {}};
- if (pp !== pppp) {
- throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp));
- } else {
- const stringify = obj => JSON.stringify(obj, null, 2);
+const UPPERCASE = /[\p{Lu}]/u;
+const LOWERCASE = /[\p{Ll}]/u;
+const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
+const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
+const SEPARATORS = /[_.\- ]+/;
+const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);
+const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu');
+const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu');
- const ast = stringify(src.__debug.parse(input, opt,
- /* massage */
- true).ast);
- const past = stringify(src.__debug.parse(pp, opt,
- /* massage */
- true).ast);
- /* istanbul ignore next */
+const preserveCamelCase = (string, locale) => {
+ let isLastCharLower = false;
+ let isLastCharUpper = false;
+ let isLastLastCharUpper = false;
- if (ast !== past) {
- const MAX_AST_SIZE = 2097152; // 2MB
+ for (let i = 0; i < string.length; i++) {
+ const character = string[i];
- const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
- throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp));
- }
+ if (isLastCharLower && UPPERCASE.test(character)) {
+ string = string.slice(0, i) + '-' + string.slice(i);
+ isLastCharLower = false;
+ isLastLastCharUpper = isLastCharUpper;
+ isLastCharUpper = true;
+ i++;
+ } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {
+ string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
+ isLastLastCharUpper = isLastCharUpper;
+ isLastCharUpper = false;
+ isLastCharLower = true;
+ } else {
+ isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
+ isLastLastCharUpper = isLastCharUpper;
+ isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
}
+ }
- return {
- formatted: pp,
- filepath: opt.filepath || "(stdin)\n"
- };
+ return string;
+};
+
+const preserveConsecutiveUppercase = input => {
+ LEADING_CAPITAL.lastIndex = 0;
+ return input.replace(LEADING_CAPITAL, m1 => m1.toLowerCase());
+};
+
+const postProcess = (input, options) => {
+ SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
+ NUMBERS_AND_IDENTIFIER.lastIndex = 0;
+ return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => identifier.toLocaleUpperCase(options.locale)).replace(NUMBERS_AND_IDENTIFIER, m => m.toLocaleUpperCase(options.locale));
+};
+
+const camelCase$1 = (input, options) => {
+ if (!(typeof input === 'string' || Array.isArray(input))) {
+ throw new TypeError('Expected the input to be `string | string[]`');
}
- /* istanbul ignore next */
+ options = Object.assign({
+ pascalCase: false,
+ preserveConsecutiveUppercase: false
+ }, options);
- if (context.argv["debug-benchmark"]) {
- let benchmark;
+ if (Array.isArray(input)) {
+ input = input.map(x => x.trim()).filter(x => x.length).join('-');
+ } else {
+ input = input.trim();
+ }
- try {
- benchmark = require("benchmark");
- } catch (err) {
- context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed.");
- process.exit(2);
- }
+ if (input.length === 0) {
+ return '';
+ }
- context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.");
- const suite = new benchmark.Suite();
- suite.add("format", () => {
- src.formatWithCursor(input, opt);
- }).on("cycle", event => {
- const results = {
- benchmark: String(event.target),
- hz: event.target.hz,
- ms: event.target.times.cycle * 1000
- };
- context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
- }).run({
- async: false
- });
- } else if (context.argv["debug-repeat"] > 0) {
- const repeat = context.argv["debug-repeat"];
- context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times."); // should be using `performance.now()`, but only `Date` is cross-platform enough
+ if (input.length === 1) {
+ return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
+ }
- const now = Date.now ? () => Date.now() : () => +new Date();
- let totalMs = 0;
+ const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
- for (let i = 0; i < repeat; ++i) {
- const startMs = now();
- src.formatWithCursor(input, opt);
- totalMs += now() - startMs;
- }
+ if (hasUpperCase) {
+ input = preserveCamelCase(input, options.locale);
+ }
- const averageMs = totalMs / repeat;
- const results = {
- repeat,
- hz: 1000 / averageMs,
- ms: averageMs
- };
- context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
+ input = input.replace(LEADING_SEPARATORS, '');
+
+ if (options.preserveConsecutiveUppercase) {
+ input = preserveConsecutiveUppercase(input);
+ } else {
+ input = input.toLocaleLowerCase();
+ }
+
+ if (options.pascalCase) {
+ input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
}
- return src.formatWithCursor(input, opt);
-}
+ return postProcess(input, options);
+};
+
+camelcase.exports = camelCase$1; // TODO: Remove this for the next major release
-function getOptionsOrDie(context, filePath) {
- try {
- if (context.argv.config === false) {
- context.logger.debug("'--no-config' option found, skip loading config file.");
- return null;
- }
+camelcase.exports.default = camelCase$1;
- context.logger.debug(context.argv.config ? `load config file from '${context.argv.config}'` : `resolve config from '${filePath}'`);
- const options = src.resolveConfig.sync(filePath, {
- editorconfig: context.argv.editorconfig,
- config: context.argv.config
- });
- context.logger.debug("loaded options `" + JSON.stringify(options) + "`");
- return options;
- } catch (error) {
- context.logger.error(`Invalid configuration file \`${filePath}\`: ` + error.message);
- process.exit(2);
- }
+const groupBy = groupBy_1;
+const camelCase = camelcase.exports;
+const constant = constant$2;
+const OPTION_USAGE_THRESHOLD = 25;
+const CHOICE_USAGE_MARGIN = 3;
+const CHOICE_USAGE_INDENTATION = 2;
+
+function indent(str, spaces) {
+ return str.replace(/^/gm, " ".repeat(spaces));
}
-function getOptionsForFile(context, filepath) {
- const options = getOptionsOrDie(context, filepath);
- const hasPlugins = options && options.plugins;
+function createDefaultValueDisplay(value) {
+ return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
+}
- if (hasPlugins) {
- pushContextPlugins(context, options.plugins);
+function getOptionDefaultValue(context, optionName) {
+ // --no-option
+ if (!(optionName in context.detailedOptionMap)) {
+ return;
}
- const appliedOptions = Object.assign({
- filepath
- }, applyConfigPrecedence(context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, {
- logger: context.logger
- })));
- context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`);
+ const option = context.detailedOptionMap[optionName];
- if (hasPlugins) {
- popContextPlugins(context);
+ if (option.default !== undefined) {
+ return option.default;
}
- return appliedOptions;
+ const optionCamelName = camelCase(optionName);
+
+ if (optionCamelName in context.apiDefaultOptions) {
+ return context.apiDefaultOptions[optionCamelName];
+ }
}
-function parseArgsToOptions(context, overrideDefaults) {
- const minimistOptions = createMinimistOptions(context.detailedOptions);
- const apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions);
- return getOptions(optionsNormalizer.normalizeCliOptions(minimist_1(context.args, {
- string: minimistOptions.string,
- boolean: minimistOptions.boolean,
- default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
- }), context.detailedOptions, {
- logger: false
- }), context.detailedOptions);
+function createOptionUsageHeader(option) {
+ const name = `--${option.name}`;
+ const alias = option.alias ? `-${option.alias},` : null;
+ const type = createOptionUsageType(option);
+ return [alias, name, type].filter(Boolean).join(" ");
}
-function applyConfigPrecedence(context, options) {
- try {
- switch (context.argv["config-precedence"]) {
- case "cli-override":
- return parseArgsToOptions(context, options);
+function createOptionUsageRow(header, content, threshold) {
+ const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
+ const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`);
+ return `${header}${separator}${description}`;
+}
- case "file-override":
- return Object.assign({}, parseArgsToOptions(context), options);
+function createOptionUsageType(option) {
+ switch (option.type) {
+ case "boolean":
+ return null;
- case "prefer-file":
- return options || parseArgsToOptions(context);
- }
- } catch (error) {
- /* istanbul ignore next */
- context.logger.error(error.toString());
- /* istanbul ignore next */
+ case "choice":
+ return `<${option.choices.filter(choice => !choice.deprecated && choice.since !== null).map(choice => choice.value).join("|")}>`;
- process.exit(2);
+ default:
+ return `<${option.type}>`;
}
}
-function formatStdin(context) {
- const filepath = context.argv["stdin-filepath"] ? path__default['default'].resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd();
- const ignorer = createIgnorerFromContextOrDie(context); // If there's an ignore-path set, the filename must be relative to the
- // ignore path, not the current working directory.
-
- const relativeFilepath = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filepath) : path__default['default'].relative(process.cwd(), filepath);
- getStdin().then(input => {
- if (relativeFilepath && ignorer.ignores(fixWindowsSlashes$1(relativeFilepath))) {
- writeOutput(context, {
- formatted: input
- });
- return;
- }
+function createChoiceUsages(choices, margin, indentation) {
+ const activeChoices = choices.filter(choice => !choice.deprecated && choice.since !== null);
+ const threshold = Math.max(0, ...activeChoices.map(choice => choice.value.length)) + margin;
+ return activeChoices.map(choice => indent(createOptionUsageRow(choice.value, choice.description, threshold), indentation));
+}
- const options = getOptionsForFile(context, filepath);
+function createOptionUsage(context, option, threshold) {
+ const header = createOptionUsageHeader(option);
+ const optionDefaultValue = getOptionDefaultValue(context, option.name);
+ return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold);
+}
- if (listDifferent(context, input, options, "(stdin)")) {
- return;
- }
+function getOptionsWithOpposites(options) {
+ // Add --no-foo after --foo.
+ const optionsWithOpposites = options.map(option => [option.description ? option : null, option.oppositeDescription ? Object.assign(Object.assign({}, option), {}, {
+ name: `no-${option.name}`,
+ type: "boolean",
+ description: option.oppositeDescription
+ }) : null]);
+ return optionsWithOpposites.flat().filter(Boolean);
+}
- writeOutput(context, format(context, input, options), options);
- }).catch(error => {
- handleError(context, relativeFilepath || "stdin", error);
+function createUsage$1(context) {
+ const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
+ option => !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-")));
+ const groupedOptions = groupBy(options, option => option.category);
+ const firstCategories = constant.categoryOrder.slice(0, -1);
+ const lastCategories = constant.categoryOrder.slice(-1);
+ const restCategories = Object.keys(groupedOptions).filter(category => !constant.categoryOrder.includes(category));
+ const allCategories = [...firstCategories, ...restCategories, ...lastCategories];
+ const optionsUsage = allCategories.map(category => {
+ const categoryOptions = groupedOptions[category].map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)).join("\n");
+ return `${category} options:\n\n${indent(categoryOptions, 2)}`;
});
+ return [constant.usageSummary, ...optionsUsage, ""].join("\n\n");
}
-function createIgnorerFromContextOrDie(context) {
- try {
- return createIgnorer.sync(context.argv["ignore-path"], context.argv["with-node-modules"]);
- } catch (e) {
- context.logger.error(e.message);
- process.exit(2);
- }
+function createDetailedUsage$1(context, flag) {
+ const option = getOptionsWithOpposites(context.detailedOptions).find(option => option.name === flag || option.alias === flag);
+ const header = createOptionUsageHeader(option);
+ const description = `\n\n${indent(option.description, 2)}`;
+ const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`;
+ const optionDefaultValue = getOptionDefaultValue(context, option.name);
+ const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
+ const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length > 0 ? `\nPlugin defaults:${Object.entries(option.pluginDefaults).map(([key, value]) => `\n* ${key}: ${createDefaultValueDisplay(value)}`)}` : "";
+ return `${header}${description}${choices}${defaults}${pluginDefaults}`;
}
-function formatFiles(context) {
- // The ignorer will be used to filter file paths after the glob is checked,
- // before any files are actually written
- const ignorer = createIgnorerFromContextOrDie(context);
- let numberOfUnformattedFilesFound = 0;
-
- if (context.argv.check) {
- context.logger.log("Checking formatting...");
- }
+var usage = {
+ createUsage: createUsage$1,
+ createDetailedUsage: createDetailedUsage$1
+};
- for (const pathOrError of expandPatterns$1(context)) {
- if (typeof pathOrError === "object") {
- context.logger.error(pathOrError.error); // Don't exit, but set the exit code to 2
+var ansiRegex$1 = ({
+ onlyFirst = false
+} = {}) => {
+ const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
+ return new RegExp(pattern, onlyFirst ? undefined : 'g');
+};
- process.exitCode = 2;
- continue;
- }
+const ansiRegex = ansiRegex$1;
- const filename = pathOrError; // If there's an ignore-path set, the filename must be relative to the
- // ignore path, not the current working directory.
+var stripAnsi$1 = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
- const ignoreFilename = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filename) : filename;
- const fileIgnored = ignorer.ignores(fixWindowsSlashes$1(ignoreFilename));
+var wcwidth$2 = {exports: {}};
- if (fileIgnored && (context.argv["debug-check"] || context.argv.write || context.argv.check || context.argv["list-different"])) {
- continue;
- }
+var clone$1 = {exports: {}};
- const options = Object.assign({}, getOptionsForFile(context, filename), {
- filepath: filename
- });
+(function (module) {
+ var clone = function () {
+ /**
+ * Clones (copies) an Object using deep copying.
+ *
+ * This function supports circular references by default, but if you are certain
+ * there are no circular references in your object, you can save some CPU time
+ * by calling clone(obj, false).
+ *
+ * Caution: if `circular` is false and `parent` contains circular references,
+ * your program may enter an infinite loop and crash.
+ *
+ * @param `parent` - the object to be cloned
+ * @param `circular` - set to true if the object to be cloned may contain
+ * circular references. (optional - true by default)
+ * @param `depth` - set to a number if the object is only to be cloned to
+ * a particular depth. (optional - defaults to Infinity)
+ * @param `prototype` - sets the prototype to be used when cloning an object.
+ * (optional - defaults to parent prototype).
+ */
+
+ function clone(parent, circular, depth, prototype) {
+
+ if (typeof circular === 'object') {
+ depth = circular.depth;
+ prototype = circular.prototype;
+ circular = circular.circular;
+ } // maintain two arrays for circular references, where corresponding parents
+ // and children have the same index
+
+
+ var allParents = [];
+ var allChildren = [];
+ var useBuffer = typeof Buffer != 'undefined';
+ if (typeof circular == 'undefined') circular = true;
+ if (typeof depth == 'undefined') depth = Infinity; // recurse this function so we don't reset allParents and allChildren
+
+ function _clone(parent, depth) {
+ // cloning null always returns null
+ if (parent === null) return null;
+ if (depth == 0) return parent;
+ var child;
+ var proto;
+
+ if (typeof parent != 'object') {
+ return parent;
+ }
- if (isTty()) {
- context.logger.log(filename, {
- newline: false
- });
- }
+ if (clone.__isArray(parent)) {
+ child = [];
+ } else if (clone.__isRegExp(parent)) {
+ child = new RegExp(parent.source, __getRegExpFlags(parent));
+ if (parent.lastIndex) child.lastIndex = parent.lastIndex;
+ } else if (clone.__isDate(parent)) {
+ child = new Date(parent.getTime());
+ } else if (useBuffer && Buffer.isBuffer(parent)) {
+ if (Buffer.allocUnsafe) {
+ // Node.js >= 4.5.0
+ child = Buffer.allocUnsafe(parent.length);
+ } else {
+ // Older Node.js versions
+ child = new Buffer(parent.length);
+ }
- let input;
+ parent.copy(child);
+ return child;
+ } else {
+ if (typeof prototype == 'undefined') {
+ proto = Object.getPrototypeOf(parent);
+ child = Object.create(proto);
+ } else {
+ child = Object.create(prototype);
+ proto = prototype;
+ }
+ }
- try {
- input = fs__default['default'].readFileSync(filename, "utf8");
- } catch (error) {
- // Add newline to split errors from filename line.
+ if (circular) {
+ var index = allParents.indexOf(parent);
- /* istanbul ignore next */
- context.logger.log("");
- /* istanbul ignore next */
+ if (index != -1) {
+ return allChildren[index];
+ }
- context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
+ allParents.push(parent);
+ allChildren.push(child);
+ }
- /* istanbul ignore next */
+ for (var i in parent) {
+ var attrs;
- process.exitCode = 2;
- /* istanbul ignore next */
+ if (proto) {
+ attrs = Object.getOwnPropertyDescriptor(proto, i);
+ }
- continue;
- }
+ if (attrs && attrs.set == null) {
+ continue;
+ }
- if (fileIgnored) {
- writeOutput(context, {
- formatted: input
- }, options);
- continue;
- }
+ child[i] = _clone(parent[i], depth - 1);
+ }
- const start = Date.now();
- let result;
- let output;
+ return child;
+ }
- try {
- result = format(context, input, options);
- output = result.formatted;
- } catch (error) {
- handleError(context, filename, error);
- continue;
+ return _clone(parent, depth);
}
+ /**
+ * Simple flat clone using prototype, accepts only objects, usefull for property
+ * override on FLAT configuration object (no nested props).
+ *
+ * USE WITH CAUTION! This may not behave as you wish if you do not know how this
+ * works.
+ */
- const isDifferent = output !== input;
- if (isTty()) {
- // Remove previously printed filename to log it with duration.
- readline__default['default'].clearLine(process.stdout, 0);
- readline__default['default'].cursorTo(process.stdout, 0, null);
- }
+ clone.clonePrototype = function clonePrototype(parent) {
+ if (parent === null) return null;
- if (context.argv.write) {
- // Don't write the file if it won't change in order not to invalidate
- // mtime based caches.
- if (isDifferent) {
- if (!context.argv.check && !context.argv["list-different"]) {
- context.logger.log(`${filename} ${Date.now() - start}ms`);
- }
+ var c = function () {};
- try {
- fs__default['default'].writeFileSync(filename, output, "utf8");
- } catch (error) {
- /* istanbul ignore next */
- context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
+ c.prototype = parent;
+ return new c();
+ }; // private utility functions
- /* istanbul ignore next */
- process.exitCode = 2;
- }
- } else if (!context.argv.check && !context.argv["list-different"]) {
- context.logger.log(`${source.grey(filename)} ${Date.now() - start}ms`);
- }
- } else if (context.argv["debug-check"]) {
- /* istanbul ignore else */
- if (result.filepath) {
- context.logger.log(result.filepath);
- } else {
- process.exitCode = 2;
- }
- } else if (!context.argv.check && !context.argv["list-different"]) {
- writeOutput(context, result, options);
+ function __objToStr(o) {
+ return Object.prototype.toString.call(o);
}
+ clone.__objToStr = __objToStr;
- if (isDifferent) {
- if (context.argv.check) {
- context.logger.warn(filename);
- } else if (context.argv["list-different"]) {
- context.logger.log(filename);
- }
-
- numberOfUnformattedFilesFound += 1;
+ function __isDate(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object Date]';
}
- } // Print check summary based on expected exit code
-
+ clone.__isDate = __isDate;
- if (context.argv.check) {
- if (numberOfUnformattedFilesFound === 0) {
- context.logger.log("All matched files use Prettier code style!");
- } else {
- context.logger.warn(context.argv.write ? "Code style issues fixed in the above file(s)." : "Code style issues found in the above file(s). Forgot to run Prettier?");
+ function __isArray(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object Array]';
}
- } // Ensure non-zero exitCode when using --check/list-different is not combined with --write
+ clone.__isArray = __isArray;
+ function __isRegExp(o) {
+ return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
+ }
+ clone.__isRegExp = __isRegExp;
- if ((context.argv.check || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv.write) {
- process.exitCode = 1;
- }
-}
-
-function getOptionsWithOpposites(options) {
- // Add --no-foo after --foo.
- const optionsWithOpposites = options.map(option => [option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, {
- name: `no-${option.name}`,
- type: "boolean",
- description: option.oppositeDescription
- }) : null]);
- return flatten_1(optionsWithOpposites).filter(Boolean);
-}
+ function __getRegExpFlags(re) {
+ var flags = '';
+ if (re.global) flags += 'g';
+ if (re.ignoreCase) flags += 'i';
+ if (re.multiline) flags += 'm';
+ return flags;
+ }
+ clone.__getRegExpFlags = __getRegExpFlags;
+ return clone;
+ }();
-function createUsage(context) {
- const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
- option => !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-")));
- const groupedOptions = groupBy_1(options, option => option.category);
- const firstCategories = constant$1.categoryOrder.slice(0, -1);
- const lastCategories = constant$1.categoryOrder.slice(-1);
- const restCategories = Object.keys(groupedOptions).filter(category => !constant$1.categoryOrder.includes(category));
- const allCategories = [...firstCategories, ...restCategories, ...lastCategories];
- const optionsUsage = allCategories.map(category => {
- const categoryOptions = groupedOptions[category].map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)).join("\n");
- return `${category} options:\n\n${indent(categoryOptions, 2)}`;
+ if (module.exports) {
+ module.exports = clone;
+ }
+})(clone$1);
+
+var clone = clone$1.exports;
+
+var defaults$1 = function (options, defaults) {
+ options = options || {};
+ Object.keys(defaults).forEach(function (key) {
+ if (typeof options[key] === 'undefined') {
+ options[key] = clone(defaults[key]);
+ }
});
- return [constant$1.usageSummary].concat(optionsUsage, [""]).join("\n\n");
-}
+ return options;
+};
-function createOptionUsage(context, option, threshold) {
- const header = createOptionUsageHeader(option);
- const optionDefaultValue = getOptionDefaultValue(context, option.name);
- return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold);
-}
+var combining$1 = [[0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489], [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2], [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603], [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670], [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED], [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A], [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902], [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D], [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981], [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD], [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C], [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D], [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC], [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD], [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C], [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D], [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0], [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48], [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC], [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD], [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D], [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6], [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E], [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC], [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35], [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E], [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97], [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030], [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039], [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F], [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753], [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD], [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD], [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922], [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B], [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34], [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42], [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF], [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063], [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F], [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B], [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F], [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB], [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F], [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169], [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD], [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F], [0xE0100, 0xE01EF]];
-function createDefaultValueDisplay(value) {
- return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
-}
+var defaults = defaults$1;
+var combining = combining$1;
+var DEFAULTS = {
+ nul: 0,
+ control: 0
+};
-function createOptionUsageHeader(option) {
- const name = `--${option.name}`;
- const alias = option.alias ? `-${option.alias},` : null;
- const type = createOptionUsageType(option);
- return [alias, name, type].filter(Boolean).join(" ");
-}
+wcwidth$2.exports = function wcwidth(str) {
+ return wcswidth(str, DEFAULTS);
+};
-function createOptionUsageRow(header, content, threshold) {
- const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
- const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`);
- return `${header}${separator}${description}`;
-}
+wcwidth$2.exports.config = function (opts) {
+ opts = defaults(opts || {}, DEFAULTS);
+ return function wcwidth(str) {
+ return wcswidth(str, opts);
+ };
+};
+/*
+ * The following functions define the column width of an ISO 10646
+ * character as follows:
+ * - The null character (U+0000) has a column width of 0.
+ * - Other C0/C1 control characters and DEL will lead to a return value
+ * of -1.
+ * - Non-spacing and enclosing combining characters (general category
+ * code Mn or Me in the
+ * Unicode database) have a column width of 0.
+ * - SOFT HYPHEN (U+00AD) has a column width of 1.
+ * - Other format characters (general category code Cf in the Unicode
+ * database) and ZERO WIDTH
+ * SPACE (U+200B) have a column width of 0.
+ * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
+ * have a column width of 0.
+ * - Spacing characters in the East Asian Wide (W) or East Asian
+ * Full-width (F) category as
+ * defined in Unicode Technical Report #11 have a column width of 2.
+ * - All remaining characters (including all printable ISO 8859-1 and
+ * WGL4 characters, Unicode control characters, etc.) have a column
+ * width of 1.
+ * This implementation assumes that characters are encoded in ISO 10646.
+*/
-function createOptionUsageType(option) {
- switch (option.type) {
- case "boolean":
- return null;
- case "choice":
- return `<${option.choices.filter(choice => !choice.deprecated && choice.since !== null).map(choice => choice.value).join("|")}>`;
+function wcswidth(str, opts) {
+ if (typeof str !== 'string') return wcwidth$1(str, opts);
+ var s = 0;
- default:
- return `<${option.type}>`;
+ for (var i = 0; i < str.length; i++) {
+ var n = wcwidth$1(str.charCodeAt(i), opts);
+ if (n < 0) return -1;
+ s += n;
}
-}
-function createChoiceUsages(choices, margin, indentation) {
- const activeChoices = choices.filter(choice => !choice.deprecated && choice.since !== null);
- const threshold = activeChoices.map(choice => choice.value.length).reduce((current, length) => Math.max(current, length), 0) + margin;
- return activeChoices.map(choice => indent(createOptionUsageRow(choice.value, choice.description, threshold), indentation));
+ return s;
}
-function createDetailedUsage(context, flag) {
- const option = getOptionsWithOpposites(context.detailedOptions).find(option => option.name === flag || option.alias === flag);
- const header = createOptionUsageHeader(option);
- const description = `\n\n${indent(option.description, 2)}`;
- const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`;
- const optionDefaultValue = getOptionDefaultValue(context, option.name);
- const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
- const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map(key => `\n* ${key}: ${createDefaultValueDisplay(option.pluginDefaults[key])}`)}` : "";
- return `${header}${description}${choices}${defaults}${pluginDefaults}`;
+function wcwidth$1(ucs, opts) {
+ // test for 8-bit control characters
+ if (ucs === 0) return opts.nul;
+ if (ucs < 32 || ucs >= 0x7f && ucs < 0xa0) return opts.control; // binary search in table of non-spacing characters
+
+ if (bisearch(ucs)) return 0; // if we arrive here, ucs is not a combining or C0/C1 control character
+
+ return 1 + (ucs >= 0x1100 && (ucs <= 0x115f || // Hangul Jamo init. consonants
+ ucs == 0x2329 || ucs == 0x232a || ucs >= 0x2e80 && ucs <= 0xa4cf && ucs != 0x303f || // CJK ... Yi
+ ucs >= 0xac00 && ucs <= 0xd7a3 || // Hangul Syllables
+ ucs >= 0xf900 && ucs <= 0xfaff || // CJK Compatibility Ideographs
+ ucs >= 0xfe10 && ucs <= 0xfe19 || // Vertical forms
+ ucs >= 0xfe30 && ucs <= 0xfe6f || // CJK Compatibility Forms
+ ucs >= 0xff00 && ucs <= 0xff60 || // Fullwidth Forms
+ ucs >= 0xffe0 && ucs <= 0xffe6 || ucs >= 0x20000 && ucs <= 0x2fffd || ucs >= 0x30000 && ucs <= 0x3fffd));
}
-function getOptionDefaultValue(context, optionName) {
- // --no-option
- if (!(optionName in context.detailedOptionMap)) {
- return;
+function bisearch(ucs) {
+ var min = 0;
+ var max = combining.length - 1;
+ var mid;
+ if (ucs < combining[0][0] || ucs > combining[max][1]) return false;
+
+ while (max >= min) {
+ mid = Math.floor((min + max) / 2);
+ if (ucs > combining[mid][1]) min = mid + 1;else if (ucs < combining[mid][0]) max = mid - 1;else return true;
}
- const option = context.detailedOptionMap[optionName];
+ return false;
+}
- if (option.default !== undefined) {
- return option.default;
+const readline = require$$0__default$6["default"];
+const chalk = source;
+const stripAnsi = stripAnsi$1;
+const wcwidth = wcwidth$2.exports;
+
+const countLines = (stream, text) => {
+ const columns = stream.columns || 80;
+ let lineCount = 0;
+
+ for (const line of stripAnsi(text).split("\n")) {
+ lineCount += Math.max(1, Math.ceil(wcwidth(line) / columns));
}
- const optionCamelName = camelcase(optionName);
+ return lineCount;
+};
- if (optionCamelName in context.apiDefaultOptions) {
- return context.apiDefaultOptions[optionCamelName];
+const clear = (stream, text) => () => {
+ const lineCount = countLines(stream, text);
+
+ for (let line = 0; line < lineCount; line++) {
+ if (line > 0) {
+ readline.moveCursor(stream, 0, -1);
+ }
+
+ readline.clearLine(stream, 0);
+ readline.cursorTo(stream, 0);
}
-}
+};
-function indent(str, spaces) {
- return str.replace(/^/gm, " ".repeat(spaces));
-}
+const emptyLogResult = {
+ clear() {}
+
+};
-function createLogger(logLevel) {
+function createLogger$1(logLevel = "log") {
return {
+ logLevel,
warn: createLogFunc("warn", "yellow"),
error: createLogFunc("error", "red"),
debug: createLogFunc("debug", "blue"),
function createLogFunc(loggerName, color) {
if (!shouldLog(loggerName)) {
- return () => {};
+ return () => emptyLogResult;
}
- const prefix = color ? `[${source[color](loggerName)}] ` : "";
- return function (message, opts) {
- opts = Object.assign({
- newline: true
- }, opts);
- const stream = process[loggerName === "log" ? "stdout" : "stderr"];
- stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : ""));
+ const prefix = color ? `[${chalk[color](loggerName)}] ` : "";
+ const stream = process[loggerName === "log" ? "stdout" : "stderr"];
+ return (message, options) => {
+ options = Object.assign({
+ newline: true,
+ clearable: false
+ }, options);
+ message = message.replace(/^/gm, prefix) + (options.newline ? "\n" : "");
+ stream.write(message);
+
+ if (options.clearable) {
+ return {
+ clear: clear(stream, message)
+ };
+ }
};
}
}
}
-function normalizeDetailedOption(name, option) {
- return Object.assign({
- category: coreOptions$1.CATEGORY_OTHER
- }, option, {
- choices: option.choices && option.choices.map(choice => {
- const newChoice = Object.assign({
- description: "",
- deprecated: false
- }, typeof choice === "object" ? choice : {
- value: choice
- });
- /* istanbul ignore next */
-
- if (newChoice.value === true) {
- newChoice.value = ""; // backward compatibility for original boolean option
- }
+var logger = {
+ createLogger: createLogger$1
+};
- return newChoice;
- })
- });
-}
+const path = require$$0__default$1["default"];
+const stringify$1 = fastJsonStableStringify; // eslint-disable-next-line no-restricted-modules
-function normalizeDetailedOptionMap(detailedOptionMap) {
- return fromPairs_1(Object.entries(detailedOptionMap).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)).map(([name, option]) => [name, normalizeDetailedOption(name, option)]));
-}
+const prettier$2 = require$$3;
+const {
+ format,
+ formatStdin,
+ formatFiles
+} = format_1;
+const {
+ Context,
+ parseArgvWithoutPlugins
+} = context;
+const {
+ normalizeDetailedOptionMap,
+ createDetailedOptionMap
+} = optionMap;
+const {
+ createDetailedUsage,
+ createUsage
+} = usage;
+const {
+ createLogger
+} = logger;
-function createMinimistOptions(detailedOptions) {
- const [boolean, string] = partition_1(detailedOptions, ({
- type
- }) => type === "boolean").map(detailedOptions => flatten_1(detailedOptions.map(({
- name,
- alias
- }) => alias ? [name, alias] : [name])));
- const defaults = fromPairs_1(detailedOptions.filter(option => !option.deprecated && (!option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir") && option.default !== undefined).map(option => [option.name, option.default]));
- return {
- // we use vnopts' AliasSchema to handle aliases for better error messages
- alias: {},
- boolean,
- string,
- default: defaults
- };
-}
+async function logResolvedConfigPathOrDie(context) {
+ const file = context.argv["find-config-path"];
+ const configFile = await prettier$2.resolveConfigFile(file);
-function createApiDetailedOptionMap(detailedOptions) {
- return fromPairs_1(detailedOptions.filter(option => option.forwardToApi && option.forwardToApi !== option.name).map(option => [option.forwardToApi, option]));
+ if (configFile) {
+ context.logger.log(path.relative(process.cwd(), configFile));
+ } else {
+ throw new Error(`Can not find configure file for "${file}"`);
+ }
}
-function createDetailedOptionMap(supportOptions) {
- return fromPairs_1(supportOptions.map(option => {
- const newOption = Object.assign({}, option, {
- name: option.cliName || dashify(option.name),
- description: option.cliDescription || option.description,
- category: option.cliCategory || coreOptions$1.CATEGORY_FORMAT,
- forwardToApi: option.name
- });
- /* istanbul ignore next */
-
- if (option.deprecated) {
- delete newOption.forwardToApi;
- delete newOption.description;
- delete newOption.oppositeDescription;
- newOption.deprecated = true;
- }
-
- return [newOption.name, newOption];
- }));
-} //-----------------------------context-util-start-------------------------------
-
-/**
- * @typedef {Object} Context
- * @property logger
- * @property {string[]} args
- * @property argv
- * @property {string[]} filePatterns
- * @property {any[]} supportOptions
- * @property detailedOptions
- * @property detailedOptionMap
- * @property apiDefaultOptions
- * @property languages
- * @property {Partial<Context>[]} stack
- */
-
-/** @returns {Context} */
-
-
-function createContext(args) {
- const context = {
- args,
- stack: []
+async function logFileInfoOrDie(context) {
+ const options = {
+ ignorePath: context.argv["ignore-path"],
+ withNodeModules: context.argv["with-node-modules"],
+ plugins: context.argv.plugin,
+ pluginSearchDirs: context.argv["plugin-search-dir"],
+ resolveConfig: context.argv.config !== false
};
- updateContextArgv(context);
- normalizeContextArgv(context, ["loglevel", "plugin", "plugin-search-dir"]);
- context.logger = createLogger(context.argv.loglevel);
- updateContextArgv(context, context.argv.plugin, context.argv["plugin-search-dir"]);
- return (
- /** @type {Context} */
- context
- );
-}
-
-function initContext(context) {
- // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js
- normalizeContextArgv(context);
-}
-/**
- * @param {Context} context
- * @param {string[]} plugins
- * @param {string[]=} pluginSearchDirs
- */
-
-
-function updateContextOptions(context, plugins, pluginSearchDirs) {
- const {
- options: supportOptions,
- languages
- } = src.getSupportInfo({
- showDeprecated: true,
- showUnreleased: true,
- showInternal: true,
- plugins,
- pluginSearchDirs
- });
- const detailedOptionMap = normalizeDetailedOptionMap(Object.assign({}, createDetailedOptionMap(supportOptions), constant$1.options));
- const detailedOptions = arrayify(detailedOptionMap, "name");
- const apiDefaultOptions = Object.assign({}, optionsModule.hiddenDefaults, fromPairs_1(supportOptions.filter(({
- deprecated
- }) => !deprecated).map(option => [option.name, option.default])));
- Object.assign(context, {
- supportOptions,
- detailedOptions,
- detailedOptionMap,
- apiDefaultOptions,
- languages
- });
-}
-/**
- * @param {Context} context
- * @param {string[]} plugins
- * @param {string[]=} pluginSearchDirs
- */
-
-
-function pushContextPlugins(context, plugins, pluginSearchDirs) {
- context.stack.push(pick_1(context, ["supportOptions", "detailedOptions", "detailedOptionMap", "apiDefaultOptions", "languages"]));
- updateContextOptions(context, plugins, pluginSearchDirs);
-}
-/**
- * @param {Context} context
- */
-
-
-function popContextPlugins(context) {
- Object.assign(context, context.stack.pop());
-}
-
-function updateContextArgv(context, plugins, pluginSearchDirs) {
- pushContextPlugins(context, plugins, pluginSearchDirs);
- const minimistOptions = createMinimistOptions(context.detailedOptions);
- const argv = minimist_1(context.args, minimistOptions);
- context.argv = argv;
- context.filePatterns = argv._.map(file => String(file));
+ context.logger.log(prettier$2.format(stringify$1(await prettier$2.getFileInfo(context.argv["file-info"], options)), {
+ parser: "json"
+ }));
}
-function normalizeContextArgv(context, keys) {
- const detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter(option => keys.includes(option.name));
- const argv = !keys ? context.argv : pick_1(context.argv, keys);
- context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, {
- logger: context.logger
- });
-} //------------------------------context-util-end--------------------------------
-
-
-var util$1 = {
- createContext,
+var core$1 = {
+ Context,
createDetailedOptionMap,
createDetailedUsage,
createUsage,
format,
formatFiles,
formatStdin,
- initContext,
logResolvedConfigPathOrDie,
logFileInfoOrDie,
- normalizeDetailedOptionMap
+ normalizeDetailedOptionMap,
+ parseArgvWithoutPlugins,
+ createLogger
};
-pleaseUpgradeNode(require$$1); // eslint-disable-next-line no-restricted-modules
+const packageJson = require$$0;
+pleaseUpgradeNode(packageJson); // eslint-disable-next-line import/order
+
+const stringify = fastJsonStableStringify; // eslint-disable-next-line no-restricted-modules
-function run(args) {
- const context = util$1.createContext(args);
+const prettier$1 = require$$3;
+const core = core$1;
+
+async function run(rawArguments) {
+ // Create a default level logger, so we can log errors during `logLevel` parsing
+ let logger = core.createLogger();
try {
- util$1.initContext(context);
- context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
+ const logLevel = core.parseArgvWithoutPlugins(rawArguments, logger, "loglevel").loglevel;
- if (context.argv.check && context.argv["list-different"]) {
- context.logger.error("Cannot use --check and --list-different together.");
- process.exit(1);
+ if (logLevel !== logger.logLevel) {
+ logger = core.createLogger(logLevel);
}
- if (context.argv.write && context.argv["debug-check"]) {
- context.logger.error("Cannot use --write and --debug-check together.");
- process.exit(1);
- }
+ await main(rawArguments, logger);
+ } catch (error) {
+ logger.error(error.message);
+ process.exitCode = 1;
+ }
+}
- if (context.argv["find-config-path"] && context.filePatterns.length) {
- context.logger.error("Cannot use --find-config-path with multiple files");
- process.exit(1);
- }
+async function main(rawArguments, logger) {
+ const context = new core.Context({
+ rawArguments,
+ logger
+ });
+ logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
- if (context.argv["file-info"] && context.filePatterns.length) {
- context.logger.error("Cannot use --file-info with multiple files");
- process.exit(1);
- }
+ if (context.argv.check && context.argv["list-different"]) {
+ throw new Error("Cannot use --check and --list-different together.");
+ }
- if (context.argv.version) {
- context.logger.log(src.version);
- process.exit(0);
- }
+ if (context.argv.write && context.argv["debug-check"]) {
+ throw new Error("Cannot use --write and --debug-check together.");
+ }
- if (context.argv.help !== undefined) {
- context.logger.log(typeof context.argv.help === "string" && context.argv.help !== "" ? util$1.createDetailedUsage(context, context.argv.help) : util$1.createUsage(context));
- process.exit(0);
- }
+ if (context.argv["find-config-path"] && context.filePatterns.length > 0) {
+ throw new Error("Cannot use --find-config-path with multiple files");
+ }
- if (context.argv["support-info"]) {
- context.logger.log(src.format(fastJsonStableStringify(src.getSupportInfo()), {
- parser: "json"
- }));
- process.exit(0);
- }
+ if (context.argv["file-info"] && context.filePatterns.length > 0) {
+ throw new Error("Cannot use --file-info with multiple files");
+ }
+
+ if (context.argv.version) {
+ logger.log(prettier$1.version);
+ return;
+ }
- const hasFilePatterns = context.filePatterns.length !== 0;
- const useStdin = !hasFilePatterns && (!process.stdin.isTTY || context.args["stdin-filepath"]);
+ if (context.argv.help !== undefined) {
+ logger.log(typeof context.argv.help === "string" && context.argv.help !== "" ? core.createDetailedUsage(context, context.argv.help) : core.createUsage(context));
+ return;
+ }
- if (context.argv["find-config-path"]) {
- util$1.logResolvedConfigPathOrDie(context);
- } else if (context.argv["file-info"]) {
- util$1.logFileInfoOrDie(context);
- } else if (useStdin) {
- util$1.formatStdin(context);
- } else if (hasFilePatterns) {
- util$1.formatFiles(context);
- } else {
- context.logger.log(util$1.createUsage(context));
- process.exit(1);
- }
- } catch (error) {
- context.logger.error(error.message);
- process.exit(1);
+ if (context.argv["support-info"]) {
+ logger.log(prettier$1.format(stringify(prettier$1.getSupportInfo()), {
+ parser: "json"
+ }));
+ return;
+ }
+
+ const hasFilePatterns = context.filePatterns.length > 0;
+ const useStdin = !hasFilePatterns && (!process.stdin.isTTY || context.argv["stdin-filepath"]);
+
+ if (context.argv["find-config-path"]) {
+ await core.logResolvedConfigPathOrDie(context);
+ } else if (context.argv["file-info"]) {
+ await core.logFileInfoOrDie(context);
+ } else if (useStdin) {
+ await core.formatStdin(context);
+ } else if (hasFilePatterns) {
+ await core.formatFiles(context);
+ } else {
+ logger.log(core.createUsage(context));
+ process.exitCode = 1;
}
}
run
};
-cli.run(process.argv.slice(2));
-var prettier = {};
+var prettier = cli.run(process.argv.slice(2));
module.exports = prettier;