pluginutils.es.js 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280
  1. import path, { extname, sep, resolve } from 'path';
  2. import { walk } from 'estree-walker';
  3. import util from 'util';
  4. const addExtension = function addExtension(filename, ext = '.js') {
  5. if (!extname(filename))
  6. filename += ext;
  7. return filename;
  8. };
  9. const extractors = {
  10. ArrayPattern(names, param) {
  11. for (const element of param.elements) {
  12. if (element)
  13. extractors[element.type](names, element);
  14. }
  15. },
  16. AssignmentPattern(names, param) {
  17. extractors[param.left.type](names, param.left);
  18. },
  19. Identifier(names, param) {
  20. names.push(param.name);
  21. },
  22. MemberExpression() { },
  23. ObjectPattern(names, param) {
  24. for (const prop of param.properties) {
  25. if (prop.type === 'RestElement') {
  26. extractors.RestElement(names, prop);
  27. }
  28. else {
  29. extractors[prop.value.type](names, prop.value);
  30. }
  31. }
  32. },
  33. RestElement(names, param) {
  34. extractors[param.argument.type](names, param.argument);
  35. }
  36. };
  37. const extractAssignedNames = function extractAssignedNames(param) {
  38. const names = [];
  39. extractors[param.type](names, param);
  40. return names;
  41. };
  42. const blockDeclarations = {
  43. const: true,
  44. let: true
  45. };
  46. class Scope {
  47. constructor(options = {}) {
  48. this.parent = options.parent;
  49. this.isBlockScope = !!options.block;
  50. this.declarations = Object.create(null);
  51. if (options.params) {
  52. options.params.forEach(param => {
  53. extractAssignedNames(param).forEach(name => {
  54. this.declarations[name] = true;
  55. });
  56. });
  57. }
  58. }
  59. addDeclaration(node, isBlockDeclaration, isVar) {
  60. if (!isBlockDeclaration && this.isBlockScope) {
  61. // it's a `var` or function node, and this
  62. // is a block scope, so we need to go up
  63. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  64. }
  65. else if (node.id) {
  66. extractAssignedNames(node.id).forEach(name => {
  67. this.declarations[name] = true;
  68. });
  69. }
  70. }
  71. contains(name) {
  72. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  73. }
  74. }
  75. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  76. let scope = new Scope();
  77. walk(ast, {
  78. enter(node, parent) {
  79. // function foo () {...}
  80. // class Foo {...}
  81. if (/(Function|Class)Declaration/.test(node.type)) {
  82. scope.addDeclaration(node, false, false);
  83. }
  84. // var foo = 1
  85. if (node.type === 'VariableDeclaration') {
  86. const kind = node.kind;
  87. const isBlockDeclaration = blockDeclarations[kind];
  88. node.declarations.forEach((declaration) => {
  89. scope.addDeclaration(declaration, isBlockDeclaration, true);
  90. });
  91. }
  92. let newScope;
  93. // create new function scope
  94. if (/Function/.test(node.type)) {
  95. newScope = new Scope({
  96. parent: scope,
  97. block: false,
  98. params: node.params
  99. });
  100. // named function expressions - the name is considered
  101. // part of the function's scope
  102. if (node.type === 'FunctionExpression' && node.id) {
  103. newScope.addDeclaration(node, false, false);
  104. }
  105. }
  106. // create new block scope
  107. if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
  108. newScope = new Scope({
  109. parent: scope,
  110. block: true
  111. });
  112. }
  113. // catch clause has its own block scope
  114. if (node.type === 'CatchClause') {
  115. newScope = new Scope({
  116. parent: scope,
  117. params: node.param ? [node.param] : [],
  118. block: true
  119. });
  120. }
  121. if (newScope) {
  122. Object.defineProperty(node, propertyName, {
  123. value: newScope,
  124. configurable: true
  125. });
  126. scope = newScope;
  127. }
  128. },
  129. leave(node) {
  130. if (node[propertyName])
  131. scope = scope.parent;
  132. }
  133. });
  134. return scope;
  135. };
  136. function createCommonjsModule(fn, module) {
  137. return module = { exports: {} }, fn(module, module.exports), module.exports;
  138. }
  139. var utils = createCommonjsModule(function (module, exports) {
  140. exports.isInteger = num => {
  141. if (typeof num === 'number') {
  142. return Number.isInteger(num);
  143. }
  144. if (typeof num === 'string' && num.trim() !== '') {
  145. return Number.isInteger(Number(num));
  146. }
  147. return false;
  148. };
  149. /**
  150. * Find a node of the given type
  151. */
  152. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  153. /**
  154. * Find a node of the given type
  155. */
  156. exports.exceedsLimit = (min, max, step = 1, limit) => {
  157. if (limit === false)
  158. return false;
  159. if (!exports.isInteger(min) || !exports.isInteger(max))
  160. return false;
  161. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  162. };
  163. /**
  164. * Escape the given node with '\\' before node.value
  165. */
  166. exports.escapeNode = (block, n = 0, type) => {
  167. let node = block.nodes[n];
  168. if (!node)
  169. return;
  170. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  171. if (node.escaped !== true) {
  172. node.value = '\\' + node.value;
  173. node.escaped = true;
  174. }
  175. }
  176. };
  177. /**
  178. * Returns true if the given brace node should be enclosed in literal braces
  179. */
  180. exports.encloseBrace = node => {
  181. if (node.type !== 'brace')
  182. return false;
  183. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  184. node.invalid = true;
  185. return true;
  186. }
  187. return false;
  188. };
  189. /**
  190. * Returns true if a brace node is invalid.
  191. */
  192. exports.isInvalidBrace = block => {
  193. if (block.type !== 'brace')
  194. return false;
  195. if (block.invalid === true || block.dollar)
  196. return true;
  197. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  198. block.invalid = true;
  199. return true;
  200. }
  201. if (block.open !== true || block.close !== true) {
  202. block.invalid = true;
  203. return true;
  204. }
  205. return false;
  206. };
  207. /**
  208. * Returns true if a node is an open or close node
  209. */
  210. exports.isOpenOrClose = node => {
  211. if (node.type === 'open' || node.type === 'close') {
  212. return true;
  213. }
  214. return node.open === true || node.close === true;
  215. };
  216. /**
  217. * Reduce an array of text nodes.
  218. */
  219. exports.reduce = nodes => nodes.reduce((acc, node) => {
  220. if (node.type === 'text')
  221. acc.push(node.value);
  222. if (node.type === 'range')
  223. node.type = 'text';
  224. return acc;
  225. }, []);
  226. /**
  227. * Flatten an array
  228. */
  229. exports.flatten = (...args) => {
  230. const result = [];
  231. const flat = arr => {
  232. for (let i = 0; i < arr.length; i++) {
  233. let ele = arr[i];
  234. Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele);
  235. }
  236. return result;
  237. };
  238. flat(args);
  239. return result;
  240. };
  241. });
  242. var utils_1 = utils.isInteger;
  243. var utils_2 = utils.find;
  244. var utils_3 = utils.exceedsLimit;
  245. var utils_4 = utils.escapeNode;
  246. var utils_5 = utils.encloseBrace;
  247. var utils_6 = utils.isInvalidBrace;
  248. var utils_7 = utils.isOpenOrClose;
  249. var utils_8 = utils.reduce;
  250. var utils_9 = utils.flatten;
  251. var stringify = (ast, options = {}) => {
  252. let stringify = (node, parent = {}) => {
  253. let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
  254. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  255. let output = '';
  256. if (node.value) {
  257. if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
  258. return '\\' + node.value;
  259. }
  260. return node.value;
  261. }
  262. if (node.value) {
  263. return node.value;
  264. }
  265. if (node.nodes) {
  266. for (let child of node.nodes) {
  267. output += stringify(child);
  268. }
  269. }
  270. return output;
  271. };
  272. return stringify(ast);
  273. };
  274. /*!
  275. * is-number <https://github.com/jonschlinkert/is-number>
  276. *
  277. * Copyright (c) 2014-present, Jon Schlinkert.
  278. * Released under the MIT License.
  279. */
  280. var isNumber = function (num) {
  281. if (typeof num === 'number') {
  282. return num - num === 0;
  283. }
  284. if (typeof num === 'string' && num.trim() !== '') {
  285. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  286. }
  287. return false;
  288. };
  289. const toRegexRange = (min, max, options) => {
  290. if (isNumber(min) === false) {
  291. throw new TypeError('toRegexRange: expected the first argument to be a number');
  292. }
  293. if (max === void 0 || min === max) {
  294. return String(min);
  295. }
  296. if (isNumber(max) === false) {
  297. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  298. }
  299. let opts = Object.assign({ relaxZeros: true }, options);
  300. if (typeof opts.strictZeros === 'boolean') {
  301. opts.relaxZeros = opts.strictZeros === false;
  302. }
  303. let relax = String(opts.relaxZeros);
  304. let shorthand = String(opts.shorthand);
  305. let capture = String(opts.capture);
  306. let wrap = String(opts.wrap);
  307. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  308. if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
  309. return toRegexRange.cache[cacheKey].result;
  310. }
  311. let a = Math.min(min, max);
  312. let b = Math.max(min, max);
  313. if (Math.abs(a - b) === 1) {
  314. let result = min + '|' + max;
  315. if (opts.capture) {
  316. return `(${result})`;
  317. }
  318. if (opts.wrap === false) {
  319. return result;
  320. }
  321. return `(?:${result})`;
  322. }
  323. let isPadded = hasPadding(min) || hasPadding(max);
  324. let state = { min, max, a, b };
  325. let positives = [];
  326. let negatives = [];
  327. if (isPadded) {
  328. state.isPadded = isPadded;
  329. state.maxLen = String(state.max).length;
  330. }
  331. if (a < 0) {
  332. let newMin = b < 0 ? Math.abs(b) : 1;
  333. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  334. a = state.a = 0;
  335. }
  336. if (b >= 0) {
  337. positives = splitToPatterns(a, b, state, opts);
  338. }
  339. state.negatives = negatives;
  340. state.positives = positives;
  341. state.result = collatePatterns(negatives, positives, opts);
  342. if (opts.capture === true) {
  343. state.result = `(${state.result})`;
  344. }
  345. else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  346. state.result = `(?:${state.result})`;
  347. }
  348. toRegexRange.cache[cacheKey] = state;
  349. return state.result;
  350. };
  351. function collatePatterns(neg, pos, options) {
  352. let onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
  353. let onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
  354. let intersected = filterPatterns(neg, pos, '-?', true, options) || [];
  355. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  356. return subpatterns.join('|');
  357. }
  358. function splitToRanges(min, max) {
  359. let nines = 1;
  360. let zeros = 1;
  361. let stop = countNines(min, nines);
  362. let stops = new Set([max]);
  363. while (min <= stop && stop <= max) {
  364. stops.add(stop);
  365. nines += 1;
  366. stop = countNines(min, nines);
  367. }
  368. stop = countZeros(max + 1, zeros) - 1;
  369. while (min < stop && stop <= max) {
  370. stops.add(stop);
  371. zeros += 1;
  372. stop = countZeros(max + 1, zeros) - 1;
  373. }
  374. stops = [...stops];
  375. stops.sort(compare);
  376. return stops;
  377. }
  378. /**
  379. * Convert a range to a regex pattern
  380. * @param {Number} `start`
  381. * @param {Number} `stop`
  382. * @return {String}
  383. */
  384. function rangeToPattern(start, stop, options) {
  385. if (start === stop) {
  386. return { pattern: start, count: [], digits: 0 };
  387. }
  388. let zipped = zip(start, stop);
  389. let digits = zipped.length;
  390. let pattern = '';
  391. let count = 0;
  392. for (let i = 0; i < digits; i++) {
  393. let [startDigit, stopDigit] = zipped[i];
  394. if (startDigit === stopDigit) {
  395. pattern += startDigit;
  396. }
  397. else if (startDigit !== '0' || stopDigit !== '9') {
  398. pattern += toCharacterClass(startDigit, stopDigit, options);
  399. }
  400. else {
  401. count++;
  402. }
  403. }
  404. if (count) {
  405. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  406. }
  407. return { pattern, count: [count], digits };
  408. }
  409. function splitToPatterns(min, max, tok, options) {
  410. let ranges = splitToRanges(min, max);
  411. let tokens = [];
  412. let start = min;
  413. let prev;
  414. for (let i = 0; i < ranges.length; i++) {
  415. let max = ranges[i];
  416. let obj = rangeToPattern(String(start), String(max), options);
  417. let zeros = '';
  418. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  419. if (prev.count.length > 1) {
  420. prev.count.pop();
  421. }
  422. prev.count.push(obj.count[0]);
  423. prev.string = prev.pattern + toQuantifier(prev.count);
  424. start = max + 1;
  425. continue;
  426. }
  427. if (tok.isPadded) {
  428. zeros = padZeros(max, tok, options);
  429. }
  430. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  431. tokens.push(obj);
  432. start = max + 1;
  433. prev = obj;
  434. }
  435. return tokens;
  436. }
  437. function filterPatterns(arr, comparison, prefix, intersection, options) {
  438. let result = [];
  439. for (let ele of arr) {
  440. let { string } = ele;
  441. // only push if _both_ are negative...
  442. if (!intersection && !contains(comparison, 'string', string)) {
  443. result.push(prefix + string);
  444. }
  445. // or _both_ are positive
  446. if (intersection && contains(comparison, 'string', string)) {
  447. result.push(prefix + string);
  448. }
  449. }
  450. return result;
  451. }
  452. /**
  453. * Zip strings
  454. */
  455. function zip(a, b) {
  456. let arr = [];
  457. for (let i = 0; i < a.length; i++)
  458. arr.push([a[i], b[i]]);
  459. return arr;
  460. }
  461. function compare(a, b) {
  462. return a > b ? 1 : b > a ? -1 : 0;
  463. }
  464. function contains(arr, key, val) {
  465. return arr.some(ele => ele[key] === val);
  466. }
  467. function countNines(min, len) {
  468. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  469. }
  470. function countZeros(integer, zeros) {
  471. return integer - (integer % Math.pow(10, zeros));
  472. }
  473. function toQuantifier(digits) {
  474. let [start = 0, stop = ''] = digits;
  475. if (stop || start > 1) {
  476. return `{${start + (stop ? ',' + stop : '')}}`;
  477. }
  478. return '';
  479. }
  480. function toCharacterClass(a, b, options) {
  481. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  482. }
  483. function hasPadding(str) {
  484. return /^-?(0+)\d/.test(str);
  485. }
  486. function padZeros(value, tok, options) {
  487. if (!tok.isPadded) {
  488. return value;
  489. }
  490. let diff = Math.abs(tok.maxLen - String(value).length);
  491. let relax = options.relaxZeros !== false;
  492. switch (diff) {
  493. case 0:
  494. return '';
  495. case 1:
  496. return relax ? '0?' : '0';
  497. case 2:
  498. return relax ? '0{0,2}' : '00';
  499. default: {
  500. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  501. }
  502. }
  503. }
  504. /**
  505. * Cache
  506. */
  507. toRegexRange.cache = {};
  508. toRegexRange.clearCache = () => (toRegexRange.cache = {});
  509. /**
  510. * Expose `toRegexRange`
  511. */
  512. var toRegexRange_1 = toRegexRange;
  513. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  514. const transform = toNumber => {
  515. return value => toNumber === true ? Number(value) : String(value);
  516. };
  517. const isValidValue = value => {
  518. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  519. };
  520. const isNumber$1 = num => Number.isInteger(+num);
  521. const zeros = input => {
  522. let value = `${input}`;
  523. let index = -1;
  524. if (value[0] === '-')
  525. value = value.slice(1);
  526. if (value === '0')
  527. return false;
  528. while (value[++index] === '0')
  529. ;
  530. return index > 0;
  531. };
  532. const stringify$1 = (start, end, options) => {
  533. if (typeof start === 'string' || typeof end === 'string') {
  534. return true;
  535. }
  536. return options.stringify === true;
  537. };
  538. const pad = (input, maxLength, toNumber) => {
  539. if (maxLength > 0) {
  540. let dash = input[0] === '-' ? '-' : '';
  541. if (dash)
  542. input = input.slice(1);
  543. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  544. }
  545. if (toNumber === false) {
  546. return String(input);
  547. }
  548. return input;
  549. };
  550. const toMaxLen = (input, maxLength) => {
  551. let negative = input[0] === '-' ? '-' : '';
  552. if (negative) {
  553. input = input.slice(1);
  554. maxLength--;
  555. }
  556. while (input.length < maxLength)
  557. input = '0' + input;
  558. return negative ? ('-' + input) : input;
  559. };
  560. const toSequence = (parts, options) => {
  561. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  562. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  563. let prefix = options.capture ? '' : '?:';
  564. let positives = '';
  565. let negatives = '';
  566. let result;
  567. if (parts.positives.length) {
  568. positives = parts.positives.join('|');
  569. }
  570. if (parts.negatives.length) {
  571. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  572. }
  573. if (positives && negatives) {
  574. result = `${positives}|${negatives}`;
  575. }
  576. else {
  577. result = positives || negatives;
  578. }
  579. if (options.wrap) {
  580. return `(${prefix}${result})`;
  581. }
  582. return result;
  583. };
  584. const toRange = (a, b, isNumbers, options) => {
  585. if (isNumbers) {
  586. return toRegexRange_1(a, b, Object.assign({ wrap: false }, options));
  587. }
  588. let start = String.fromCharCode(a);
  589. if (a === b)
  590. return start;
  591. let stop = String.fromCharCode(b);
  592. return `[${start}-${stop}]`;
  593. };
  594. const toRegex = (start, end, options) => {
  595. if (Array.isArray(start)) {
  596. let wrap = options.wrap === true;
  597. let prefix = options.capture ? '' : '?:';
  598. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  599. }
  600. return toRegexRange_1(start, end, options);
  601. };
  602. const rangeError = (...args) => {
  603. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  604. };
  605. const invalidRange = (start, end, options) => {
  606. if (options.strictRanges === true)
  607. throw rangeError([start, end]);
  608. return [];
  609. };
  610. const invalidStep = (step, options) => {
  611. if (options.strictRanges === true) {
  612. throw new TypeError(`Expected step "${step}" to be a number`);
  613. }
  614. return [];
  615. };
  616. const fillNumbers = (start, end, step = 1, options = {}) => {
  617. let a = Number(start);
  618. let b = Number(end);
  619. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  620. if (options.strictRanges === true)
  621. throw rangeError([start, end]);
  622. return [];
  623. }
  624. // fix negative zero
  625. if (a === 0)
  626. a = 0;
  627. if (b === 0)
  628. b = 0;
  629. let descending = a > b;
  630. let startString = String(start);
  631. let endString = String(end);
  632. let stepString = String(step);
  633. step = Math.max(Math.abs(step), 1);
  634. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  635. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  636. let toNumber = padded === false && stringify$1(start, end, options) === false;
  637. let format = options.transform || transform(toNumber);
  638. if (options.toRegex && step === 1) {
  639. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  640. }
  641. let parts = { negatives: [], positives: [] };
  642. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  643. let range = [];
  644. let index = 0;
  645. while (descending ? a >= b : a <= b) {
  646. if (options.toRegex === true && step > 1) {
  647. push(a);
  648. }
  649. else {
  650. range.push(pad(format(a, index), maxLen, toNumber));
  651. }
  652. a = descending ? a - step : a + step;
  653. index++;
  654. }
  655. if (options.toRegex === true) {
  656. return step > 1
  657. ? toSequence(parts, options)
  658. : toRegex(range, null, Object.assign({ wrap: false }, options));
  659. }
  660. return range;
  661. };
  662. const fillLetters = (start, end, step = 1, options = {}) => {
  663. if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {
  664. return invalidRange(start, end, options);
  665. }
  666. let format = options.transform || (val => String.fromCharCode(val));
  667. let a = `${start}`.charCodeAt(0);
  668. let b = `${end}`.charCodeAt(0);
  669. let descending = a > b;
  670. let min = Math.min(a, b);
  671. let max = Math.max(a, b);
  672. if (options.toRegex && step === 1) {
  673. return toRange(min, max, false, options);
  674. }
  675. let range = [];
  676. let index = 0;
  677. while (descending ? a >= b : a <= b) {
  678. range.push(format(a, index));
  679. a = descending ? a - step : a + step;
  680. index++;
  681. }
  682. if (options.toRegex === true) {
  683. return toRegex(range, null, { wrap: false, options });
  684. }
  685. return range;
  686. };
  687. const fill = (start, end, step, options = {}) => {
  688. if (end == null && isValidValue(start)) {
  689. return [start];
  690. }
  691. if (!isValidValue(start) || !isValidValue(end)) {
  692. return invalidRange(start, end, options);
  693. }
  694. if (typeof step === 'function') {
  695. return fill(start, end, 1, { transform: step });
  696. }
  697. if (isObject(step)) {
  698. return fill(start, end, 0, step);
  699. }
  700. let opts = Object.assign({}, options);
  701. if (opts.capture === true)
  702. opts.wrap = true;
  703. step = step || opts.step || 1;
  704. if (!isNumber$1(step)) {
  705. if (step != null && !isObject(step))
  706. return invalidStep(step, opts);
  707. return fill(start, end, 1, step);
  708. }
  709. if (isNumber$1(start) && isNumber$1(end)) {
  710. return fillNumbers(start, end, step, opts);
  711. }
  712. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  713. };
  714. var fillRange = fill;
  715. const compile = (ast, options = {}) => {
  716. let walk = (node, parent = {}) => {
  717. let invalidBlock = utils.isInvalidBrace(parent);
  718. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  719. let invalid = invalidBlock === true || invalidNode === true;
  720. let prefix = options.escapeInvalid === true ? '\\' : '';
  721. let output = '';
  722. if (node.isOpen === true) {
  723. return prefix + node.value;
  724. }
  725. if (node.isClose === true) {
  726. return prefix + node.value;
  727. }
  728. if (node.type === 'open') {
  729. return invalid ? (prefix + node.value) : '(';
  730. }
  731. if (node.type === 'close') {
  732. return invalid ? (prefix + node.value) : ')';
  733. }
  734. if (node.type === 'comma') {
  735. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  736. }
  737. if (node.value) {
  738. return node.value;
  739. }
  740. if (node.nodes && node.ranges > 0) {
  741. let args = utils.reduce(node.nodes);
  742. let range = fillRange(...args, Object.assign({}, options, { wrap: false, toRegex: true }));
  743. if (range.length !== 0) {
  744. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  745. }
  746. }
  747. if (node.nodes) {
  748. for (let child of node.nodes) {
  749. output += walk(child, node);
  750. }
  751. }
  752. return output;
  753. };
  754. return walk(ast);
  755. };
  756. var compile_1 = compile;
  757. const append = (queue = '', stash = '', enclose = false) => {
  758. let result = [];
  759. queue = [].concat(queue);
  760. stash = [].concat(stash);
  761. if (!stash.length)
  762. return queue;
  763. if (!queue.length) {
  764. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  765. }
  766. for (let item of queue) {
  767. if (Array.isArray(item)) {
  768. for (let value of item) {
  769. result.push(append(value, stash, enclose));
  770. }
  771. }
  772. else {
  773. for (let ele of stash) {
  774. if (enclose === true && typeof ele === 'string')
  775. ele = `{${ele}}`;
  776. result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
  777. }
  778. }
  779. }
  780. return utils.flatten(result);
  781. };
  782. const expand = (ast, options = {}) => {
  783. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  784. let walk = (node, parent = {}) => {
  785. node.queue = [];
  786. let p = parent;
  787. let q = parent.queue;
  788. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  789. p = p.parent;
  790. q = p.queue;
  791. }
  792. if (node.invalid || node.dollar) {
  793. q.push(append(q.pop(), stringify(node, options)));
  794. return;
  795. }
  796. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  797. q.push(append(q.pop(), ['{}']));
  798. return;
  799. }
  800. if (node.nodes && node.ranges > 0) {
  801. let args = utils.reduce(node.nodes);
  802. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  803. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  804. }
  805. let range = fillRange(...args, options);
  806. if (range.length === 0) {
  807. range = stringify(node, options);
  808. }
  809. q.push(append(q.pop(), range));
  810. node.nodes = [];
  811. return;
  812. }
  813. let enclose = utils.encloseBrace(node);
  814. let queue = node.queue;
  815. let block = node;
  816. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  817. block = block.parent;
  818. queue = block.queue;
  819. }
  820. for (let i = 0; i < node.nodes.length; i++) {
  821. let child = node.nodes[i];
  822. if (child.type === 'comma' && node.type === 'brace') {
  823. if (i === 1)
  824. queue.push('');
  825. queue.push('');
  826. continue;
  827. }
  828. if (child.type === 'close') {
  829. q.push(append(q.pop(), queue, enclose));
  830. continue;
  831. }
  832. if (child.value && child.type !== 'open') {
  833. queue.push(append(queue.pop(), child.value));
  834. continue;
  835. }
  836. if (child.nodes) {
  837. walk(child, node);
  838. }
  839. }
  840. return queue;
  841. };
  842. return utils.flatten(walk(ast));
  843. };
  844. var expand_1 = expand;
  845. var constants = {
  846. MAX_LENGTH: 1024 * 64,
  847. // Digits
  848. CHAR_0: '0',
  849. CHAR_9: '9',
  850. // Alphabet chars.
  851. CHAR_UPPERCASE_A: 'A',
  852. CHAR_LOWERCASE_A: 'a',
  853. CHAR_UPPERCASE_Z: 'Z',
  854. CHAR_LOWERCASE_Z: 'z',
  855. CHAR_LEFT_PARENTHESES: '(',
  856. CHAR_RIGHT_PARENTHESES: ')',
  857. CHAR_ASTERISK: '*',
  858. // Non-alphabetic chars.
  859. CHAR_AMPERSAND: '&',
  860. CHAR_AT: '@',
  861. CHAR_BACKSLASH: '\\',
  862. CHAR_BACKTICK: '`',
  863. CHAR_CARRIAGE_RETURN: '\r',
  864. CHAR_CIRCUMFLEX_ACCENT: '^',
  865. CHAR_COLON: ':',
  866. CHAR_COMMA: ',',
  867. CHAR_DOLLAR: '$',
  868. CHAR_DOT: '.',
  869. CHAR_DOUBLE_QUOTE: '"',
  870. CHAR_EQUAL: '=',
  871. CHAR_EXCLAMATION_MARK: '!',
  872. CHAR_FORM_FEED: '\f',
  873. CHAR_FORWARD_SLASH: '/',
  874. CHAR_HASH: '#',
  875. CHAR_HYPHEN_MINUS: '-',
  876. CHAR_LEFT_ANGLE_BRACKET: '<',
  877. CHAR_LEFT_CURLY_BRACE: '{',
  878. CHAR_LEFT_SQUARE_BRACKET: '[',
  879. CHAR_LINE_FEED: '\n',
  880. CHAR_NO_BREAK_SPACE: '\u00A0',
  881. CHAR_PERCENT: '%',
  882. CHAR_PLUS: '+',
  883. CHAR_QUESTION_MARK: '?',
  884. CHAR_RIGHT_ANGLE_BRACKET: '>',
  885. CHAR_RIGHT_CURLY_BRACE: '}',
  886. CHAR_RIGHT_SQUARE_BRACKET: ']',
  887. CHAR_SEMICOLON: ';',
  888. CHAR_SINGLE_QUOTE: '\'',
  889. CHAR_SPACE: ' ',
  890. CHAR_TAB: '\t',
  891. CHAR_UNDERSCORE: '_',
  892. CHAR_VERTICAL_LINE: '|',
  893. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  894. };
  895. /**
  896. * Constants
  897. */
  898. const { MAX_LENGTH, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_RIGHT_SQUARE_BRACKET, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants;
  899. /**
  900. * parse
  901. */
  902. const parse = (input, options = {}) => {
  903. if (typeof input !== 'string') {
  904. throw new TypeError('Expected a string');
  905. }
  906. let opts = options || {};
  907. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  908. if (input.length > max) {
  909. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  910. }
  911. let ast = { type: 'root', input, nodes: [] };
  912. let stack = [ast];
  913. let block = ast;
  914. let prev = ast;
  915. let brackets = 0;
  916. let length = input.length;
  917. let index = 0;
  918. let depth = 0;
  919. let value;
  920. /**
  921. * Helpers
  922. */
  923. const advance = () => input[index++];
  924. const push = node => {
  925. if (node.type === 'text' && prev.type === 'dot') {
  926. prev.type = 'text';
  927. }
  928. if (prev && prev.type === 'text' && node.type === 'text') {
  929. prev.value += node.value;
  930. return;
  931. }
  932. block.nodes.push(node);
  933. node.parent = block;
  934. node.prev = prev;
  935. prev = node;
  936. return node;
  937. };
  938. push({ type: 'bos' });
  939. while (index < length) {
  940. block = stack[stack.length - 1];
  941. value = advance();
  942. /**
  943. * Invalid chars
  944. */
  945. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  946. continue;
  947. }
  948. /**
  949. * Escaped chars
  950. */
  951. if (value === CHAR_BACKSLASH) {
  952. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  953. continue;
  954. }
  955. /**
  956. * Right square bracket (literal): ']'
  957. */
  958. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  959. push({ type: 'text', value: '\\' + value });
  960. continue;
  961. }
  962. /**
  963. * Left square bracket: '['
  964. */
  965. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  966. brackets++;
  967. let next;
  968. while (index < length && (next = advance())) {
  969. value += next;
  970. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  971. brackets++;
  972. continue;
  973. }
  974. if (next === CHAR_BACKSLASH) {
  975. value += advance();
  976. continue;
  977. }
  978. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  979. brackets--;
  980. if (brackets === 0) {
  981. break;
  982. }
  983. }
  984. }
  985. push({ type: 'text', value });
  986. continue;
  987. }
  988. /**
  989. * Parentheses
  990. */
  991. if (value === CHAR_LEFT_PARENTHESES) {
  992. block = push({ type: 'paren', nodes: [] });
  993. stack.push(block);
  994. push({ type: 'text', value });
  995. continue;
  996. }
  997. if (value === CHAR_RIGHT_PARENTHESES) {
  998. if (block.type !== 'paren') {
  999. push({ type: 'text', value });
  1000. continue;
  1001. }
  1002. block = stack.pop();
  1003. push({ type: 'text', value });
  1004. block = stack[stack.length - 1];
  1005. continue;
  1006. }
  1007. /**
  1008. * Quotes: '|"|`
  1009. */
  1010. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  1011. let open = value;
  1012. let next;
  1013. if (options.keepQuotes !== true) {
  1014. value = '';
  1015. }
  1016. while (index < length && (next = advance())) {
  1017. if (next === CHAR_BACKSLASH) {
  1018. value += next + advance();
  1019. continue;
  1020. }
  1021. if (next === open) {
  1022. if (options.keepQuotes === true)
  1023. value += next;
  1024. break;
  1025. }
  1026. value += next;
  1027. }
  1028. push({ type: 'text', value });
  1029. continue;
  1030. }
  1031. /**
  1032. * Left curly brace: '{'
  1033. */
  1034. if (value === CHAR_LEFT_CURLY_BRACE) {
  1035. depth++;
  1036. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  1037. let brace = {
  1038. type: 'brace',
  1039. open: true,
  1040. close: false,
  1041. dollar,
  1042. depth,
  1043. commas: 0,
  1044. ranges: 0,
  1045. nodes: []
  1046. };
  1047. block = push(brace);
  1048. stack.push(block);
  1049. push({ type: 'open', value });
  1050. continue;
  1051. }
  1052. /**
  1053. * Right curly brace: '}'
  1054. */
  1055. if (value === CHAR_RIGHT_CURLY_BRACE) {
  1056. if (block.type !== 'brace') {
  1057. push({ type: 'text', value });
  1058. continue;
  1059. }
  1060. let type = 'close';
  1061. block = stack.pop();
  1062. block.close = true;
  1063. push({ type, value });
  1064. depth--;
  1065. block = stack[stack.length - 1];
  1066. continue;
  1067. }
  1068. /**
  1069. * Comma: ','
  1070. */
  1071. if (value === CHAR_COMMA && depth > 0) {
  1072. if (block.ranges > 0) {
  1073. block.ranges = 0;
  1074. let open = block.nodes.shift();
  1075. block.nodes = [open, { type: 'text', value: stringify(block) }];
  1076. }
  1077. push({ type: 'comma', value });
  1078. block.commas++;
  1079. continue;
  1080. }
  1081. /**
  1082. * Dot: '.'
  1083. */
  1084. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  1085. let siblings = block.nodes;
  1086. if (depth === 0 || siblings.length === 0) {
  1087. push({ type: 'text', value });
  1088. continue;
  1089. }
  1090. if (prev.type === 'dot') {
  1091. block.range = [];
  1092. prev.value += value;
  1093. prev.type = 'range';
  1094. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  1095. block.invalid = true;
  1096. block.ranges = 0;
  1097. prev.type = 'text';
  1098. continue;
  1099. }
  1100. block.ranges++;
  1101. block.args = [];
  1102. continue;
  1103. }
  1104. if (prev.type === 'range') {
  1105. siblings.pop();
  1106. let before = siblings[siblings.length - 1];
  1107. before.value += prev.value + value;
  1108. prev = before;
  1109. block.ranges--;
  1110. continue;
  1111. }
  1112. push({ type: 'dot', value });
  1113. continue;
  1114. }
  1115. /**
  1116. * Text
  1117. */
  1118. push({ type: 'text', value });
  1119. }
  1120. // Mark imbalanced braces and brackets as invalid
  1121. do {
  1122. block = stack.pop();
  1123. if (block.type !== 'root') {
  1124. block.nodes.forEach(node => {
  1125. if (!node.nodes) {
  1126. if (node.type === 'open')
  1127. node.isOpen = true;
  1128. if (node.type === 'close')
  1129. node.isClose = true;
  1130. if (!node.nodes)
  1131. node.type = 'text';
  1132. node.invalid = true;
  1133. }
  1134. });
  1135. // get the location of the block on parent.nodes (block's siblings)
  1136. let parent = stack[stack.length - 1];
  1137. let index = parent.nodes.indexOf(block);
  1138. // replace the (invalid) block with it's nodes
  1139. parent.nodes.splice(index, 1, ...block.nodes);
  1140. }
  1141. } while (stack.length > 0);
  1142. push({ type: 'eos' });
  1143. return ast;
  1144. };
  1145. var parse_1 = parse;
  1146. /**
  1147. * Expand the given pattern or create a regex-compatible string.
  1148. *
  1149. * ```js
  1150. * const braces = require('braces');
  1151. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  1152. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  1153. * ```
  1154. * @param {String} `str`
  1155. * @param {Object} `options`
  1156. * @return {String}
  1157. * @api public
  1158. */
  1159. const braces = (input, options = {}) => {
  1160. let output = [];
  1161. if (Array.isArray(input)) {
  1162. for (let pattern of input) {
  1163. let result = braces.create(pattern, options);
  1164. if (Array.isArray(result)) {
  1165. output.push(...result);
  1166. }
  1167. else {
  1168. output.push(result);
  1169. }
  1170. }
  1171. }
  1172. else {
  1173. output = [].concat(braces.create(input, options));
  1174. }
  1175. if (options && options.expand === true && options.nodupes === true) {
  1176. output = [...new Set(output)];
  1177. }
  1178. return output;
  1179. };
  1180. /**
  1181. * Parse the given `str` with the given `options`.
  1182. *
  1183. * ```js
  1184. * // braces.parse(pattern, [, options]);
  1185. * const ast = braces.parse('a/{b,c}/d');
  1186. * console.log(ast);
  1187. * ```
  1188. * @param {String} pattern Brace pattern to parse
  1189. * @param {Object} options
  1190. * @return {Object} Returns an AST
  1191. * @api public
  1192. */
  1193. braces.parse = (input, options = {}) => parse_1(input, options);
  1194. /**
  1195. * Creates a braces string from an AST, or an AST node.
  1196. *
  1197. * ```js
  1198. * const braces = require('braces');
  1199. * let ast = braces.parse('foo/{a,b}/bar');
  1200. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  1201. * ```
  1202. * @param {String} `input` Brace pattern or AST.
  1203. * @param {Object} `options`
  1204. * @return {Array} Returns an array of expanded values.
  1205. * @api public
  1206. */
  1207. braces.stringify = (input, options = {}) => {
  1208. if (typeof input === 'string') {
  1209. return stringify(braces.parse(input, options), options);
  1210. }
  1211. return stringify(input, options);
  1212. };
  1213. /**
  1214. * Compiles a brace pattern into a regex-compatible, optimized string.
  1215. * This method is called by the main [braces](#braces) function by default.
  1216. *
  1217. * ```js
  1218. * const braces = require('braces');
  1219. * console.log(braces.compile('a/{b,c}/d'));
  1220. * //=> ['a/(b|c)/d']
  1221. * ```
  1222. * @param {String} `input` Brace pattern or AST.
  1223. * @param {Object} `options`
  1224. * @return {Array} Returns an array of expanded values.
  1225. * @api public
  1226. */
  1227. braces.compile = (input, options = {}) => {
  1228. if (typeof input === 'string') {
  1229. input = braces.parse(input, options);
  1230. }
  1231. return compile_1(input, options);
  1232. };
  1233. /**
  1234. * Expands a brace pattern into an array. This method is called by the
  1235. * main [braces](#braces) function when `options.expand` is true. Before
  1236. * using this method it's recommended that you read the [performance notes](#performance))
  1237. * and advantages of using [.compile](#compile) instead.
  1238. *
  1239. * ```js
  1240. * const braces = require('braces');
  1241. * console.log(braces.expand('a/{b,c}/d'));
  1242. * //=> ['a/b/d', 'a/c/d'];
  1243. * ```
  1244. * @param {String} `pattern` Brace pattern
  1245. * @param {Object} `options`
  1246. * @return {Array} Returns an array of expanded values.
  1247. * @api public
  1248. */
  1249. braces.expand = (input, options = {}) => {
  1250. if (typeof input === 'string') {
  1251. input = braces.parse(input, options);
  1252. }
  1253. let result = expand_1(input, options);
  1254. // filter out empty strings if specified
  1255. if (options.noempty === true) {
  1256. result = result.filter(Boolean);
  1257. }
  1258. // filter out duplicates if specified
  1259. if (options.nodupes === true) {
  1260. result = [...new Set(result)];
  1261. }
  1262. return result;
  1263. };
  1264. /**
  1265. * Processes a brace pattern and returns either an expanded array
  1266. * (if `options.expand` is true), a highly optimized regex-compatible string.
  1267. * This method is called by the main [braces](#braces) function.
  1268. *
  1269. * ```js
  1270. * const braces = require('braces');
  1271. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  1272. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  1273. * ```
  1274. * @param {String} `pattern` Brace pattern
  1275. * @param {Object} `options`
  1276. * @return {Array} Returns an array of expanded values.
  1277. * @api public
  1278. */
  1279. braces.create = (input, options = {}) => {
  1280. if (input === '' || input.length < 3) {
  1281. return [input];
  1282. }
  1283. return options.expand !== true
  1284. ? braces.compile(input, options)
  1285. : braces.expand(input, options);
  1286. };
  1287. /**
  1288. * Expose "braces"
  1289. */
  1290. var braces_1 = braces;
  1291. const WIN_SLASH = '\\\\/';
  1292. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  1293. /**
  1294. * Posix glob regex
  1295. */
  1296. const DOT_LITERAL = '\\.';
  1297. const PLUS_LITERAL = '\\+';
  1298. const QMARK_LITERAL = '\\?';
  1299. const SLASH_LITERAL = '\\/';
  1300. const ONE_CHAR = '(?=.)';
  1301. const QMARK = '[^/]';
  1302. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  1303. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  1304. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  1305. const NO_DOT = `(?!${DOT_LITERAL})`;
  1306. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  1307. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  1308. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  1309. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  1310. const STAR = `${QMARK}*?`;
  1311. const POSIX_CHARS = {
  1312. DOT_LITERAL,
  1313. PLUS_LITERAL,
  1314. QMARK_LITERAL,
  1315. SLASH_LITERAL,
  1316. ONE_CHAR,
  1317. QMARK,
  1318. END_ANCHOR,
  1319. DOTS_SLASH,
  1320. NO_DOT,
  1321. NO_DOTS,
  1322. NO_DOT_SLASH,
  1323. NO_DOTS_SLASH,
  1324. QMARK_NO_DOT,
  1325. STAR,
  1326. START_ANCHOR
  1327. };
  1328. /**
  1329. * Windows glob regex
  1330. */
  1331. 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}]|$)` });
  1332. /**
  1333. * POSIX Bracket Regex
  1334. */
  1335. const POSIX_REGEX_SOURCE = {
  1336. alnum: 'a-zA-Z0-9',
  1337. alpha: 'a-zA-Z',
  1338. ascii: '\\x00-\\x7F',
  1339. blank: ' \\t',
  1340. cntrl: '\\x00-\\x1F\\x7F',
  1341. digit: '0-9',
  1342. graph: '\\x21-\\x7E',
  1343. lower: 'a-z',
  1344. print: '\\x20-\\x7E ',
  1345. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1346. space: ' \\t\\r\\n\\v\\f',
  1347. upper: 'A-Z',
  1348. word: 'A-Za-z0-9_',
  1349. xdigit: 'A-Fa-f0-9'
  1350. };
  1351. var constants$1 = {
  1352. MAX_LENGTH: 1024 * 64,
  1353. POSIX_REGEX_SOURCE,
  1354. // regular expressions
  1355. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1356. REGEX_NON_SPECIAL_CHAR: /^[^@![\].,$*+?^{}()|\\/]+/,
  1357. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1358. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1359. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1360. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1361. // Replace globs with equivalent patterns to reduce parsing time.
  1362. REPLACEMENTS: {
  1363. '***': '*',
  1364. '**/**': '**',
  1365. '**/**/**': '**'
  1366. },
  1367. // Digits
  1368. CHAR_0: 48,
  1369. CHAR_9: 57,
  1370. // Alphabet chars.
  1371. CHAR_UPPERCASE_A: 65,
  1372. CHAR_LOWERCASE_A: 97,
  1373. CHAR_UPPERCASE_Z: 90,
  1374. CHAR_LOWERCASE_Z: 122,
  1375. CHAR_LEFT_PARENTHESES: 40,
  1376. CHAR_RIGHT_PARENTHESES: 41,
  1377. CHAR_ASTERISK: 42,
  1378. // Non-alphabetic chars.
  1379. CHAR_AMPERSAND: 38,
  1380. CHAR_AT: 64,
  1381. CHAR_BACKWARD_SLASH: 92,
  1382. CHAR_CARRIAGE_RETURN: 13,
  1383. CHAR_CIRCUMFLEX_ACCENT: 94,
  1384. CHAR_COLON: 58,
  1385. CHAR_COMMA: 44,
  1386. CHAR_DOT: 46,
  1387. CHAR_DOUBLE_QUOTE: 34,
  1388. CHAR_EQUAL: 61,
  1389. CHAR_EXCLAMATION_MARK: 33,
  1390. CHAR_FORM_FEED: 12,
  1391. CHAR_FORWARD_SLASH: 47,
  1392. CHAR_GRAVE_ACCENT: 96,
  1393. CHAR_HASH: 35,
  1394. CHAR_HYPHEN_MINUS: 45,
  1395. CHAR_LEFT_ANGLE_BRACKET: 60,
  1396. CHAR_LEFT_CURLY_BRACE: 123,
  1397. CHAR_LEFT_SQUARE_BRACKET: 91,
  1398. CHAR_LINE_FEED: 10,
  1399. CHAR_NO_BREAK_SPACE: 160,
  1400. CHAR_PERCENT: 37,
  1401. CHAR_PLUS: 43,
  1402. CHAR_QUESTION_MARK: 63,
  1403. CHAR_RIGHT_ANGLE_BRACKET: 62,
  1404. CHAR_RIGHT_CURLY_BRACE: 125,
  1405. CHAR_RIGHT_SQUARE_BRACKET: 93,
  1406. CHAR_SEMICOLON: 59,
  1407. CHAR_SINGLE_QUOTE: 39,
  1408. CHAR_SPACE: 32,
  1409. CHAR_TAB: 9,
  1410. CHAR_UNDERSCORE: 95,
  1411. CHAR_VERTICAL_LINE: 124,
  1412. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
  1413. SEP: path.sep,
  1414. /**
  1415. * Create EXTGLOB_CHARS
  1416. */
  1417. extglobChars(chars) {
  1418. return {
  1419. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1420. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1421. '+': { type: 'plus', open: '(?:', close: ')+' },
  1422. '*': { type: 'star', open: '(?:', close: ')*' },
  1423. '@': { type: 'at', open: '(?:', close: ')' }
  1424. };
  1425. },
  1426. /**
  1427. * Create GLOB_CHARS
  1428. */
  1429. globChars(win32) {
  1430. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1431. }
  1432. };
  1433. var utils$1 = createCommonjsModule(function (module, exports) {
  1434. const win32 = process.platform === 'win32';
  1435. const { REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL, REGEX_REMOVE_BACKSLASH } = constants$1;
  1436. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1437. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1438. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  1439. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1440. exports.toPosixSlashes = str => str.replace(/\\/g, '/');
  1441. exports.removeBackslashes = str => {
  1442. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1443. return match === '\\' ? '' : match;
  1444. });
  1445. };
  1446. exports.supportsLookbehinds = () => {
  1447. let segs = process.version.slice(1).split('.');
  1448. if (segs.length === 3 && +segs[0] >= 9 || (+segs[0] === 8 && +segs[1] >= 10)) {
  1449. return true;
  1450. }
  1451. return false;
  1452. };
  1453. exports.isWindows = options => {
  1454. if (options && typeof options.windows === 'boolean') {
  1455. return options.windows;
  1456. }
  1457. return win32 === true || path.sep === '\\';
  1458. };
  1459. exports.escapeLast = (input, char, lastIdx) => {
  1460. let idx = input.lastIndexOf(char, lastIdx);
  1461. if (idx === -1)
  1462. return input;
  1463. if (input[idx - 1] === '\\')
  1464. return exports.escapeLast(input, char, idx - 1);
  1465. return input.slice(0, idx) + '\\' + input.slice(idx);
  1466. };
  1467. });
  1468. var utils_1$1 = utils$1.isObject;
  1469. var utils_2$1 = utils$1.hasRegexChars;
  1470. var utils_3$1 = utils$1.isRegexChar;
  1471. var utils_4$1 = utils$1.escapeRegex;
  1472. var utils_5$1 = utils$1.toPosixSlashes;
  1473. var utils_6$1 = utils$1.removeBackslashes;
  1474. var utils_7$1 = utils$1.supportsLookbehinds;
  1475. var utils_8$1 = utils$1.isWindows;
  1476. var utils_9$1 = utils$1.escapeLast;
  1477. const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ } = constants$1;
  1478. const isPathSeparator = code => {
  1479. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1480. };
  1481. /**
  1482. * Quickly scans a glob pattern and returns an object with a handful of
  1483. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1484. * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
  1485. *
  1486. * ```js
  1487. * const pm = require('picomatch');
  1488. * console.log(pm.scan('foo/bar/*.js'));
  1489. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1490. * ```
  1491. * @param {String} `str`
  1492. * @param {Object} `options`
  1493. * @return {Object} Returns an object with tokens and regex source string.
  1494. * @api public
  1495. */
  1496. var scan = (input, options) => {
  1497. let opts = options || {};
  1498. let length = input.length - 1;
  1499. let index = -1;
  1500. let start = 0;
  1501. let lastIndex = 0;
  1502. let isGlob = false;
  1503. let backslashes = false;
  1504. let negated = false;
  1505. let braces = 0;
  1506. let prev;
  1507. let code;
  1508. let braceEscaped = false;
  1509. let eos = () => index >= length;
  1510. let advance = () => {
  1511. prev = code;
  1512. return input.charCodeAt(++index);
  1513. };
  1514. while (index < length) {
  1515. code = advance();
  1516. let next;
  1517. if (code === CHAR_BACKWARD_SLASH) {
  1518. backslashes = true;
  1519. next = advance();
  1520. if (next === CHAR_LEFT_CURLY_BRACE$1) {
  1521. braceEscaped = true;
  1522. }
  1523. continue;
  1524. }
  1525. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
  1526. braces++;
  1527. while (!eos() && (next = advance())) {
  1528. if (next === CHAR_BACKWARD_SLASH) {
  1529. backslashes = true;
  1530. next = advance();
  1531. continue;
  1532. }
  1533. if (next === CHAR_LEFT_CURLY_BRACE$1) {
  1534. braces++;
  1535. continue;
  1536. }
  1537. if (!braceEscaped && next === CHAR_DOT$1 && (next = advance()) === CHAR_DOT$1) {
  1538. isGlob = true;
  1539. break;
  1540. }
  1541. if (!braceEscaped && next === CHAR_COMMA$1) {
  1542. isGlob = true;
  1543. break;
  1544. }
  1545. if (next === CHAR_RIGHT_CURLY_BRACE$1) {
  1546. braces--;
  1547. if (braces === 0) {
  1548. braceEscaped = false;
  1549. break;
  1550. }
  1551. }
  1552. }
  1553. }
  1554. if (code === CHAR_FORWARD_SLASH) {
  1555. if (prev === CHAR_DOT$1 && index === (start + 1)) {
  1556. start += 2;
  1557. continue;
  1558. }
  1559. lastIndex = index + 1;
  1560. continue;
  1561. }
  1562. if (code === CHAR_ASTERISK) {
  1563. isGlob = true;
  1564. break;
  1565. }
  1566. if (code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK) {
  1567. isGlob = true;
  1568. break;
  1569. }
  1570. if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
  1571. while (!eos() && (next = advance())) {
  1572. if (next === CHAR_BACKWARD_SLASH) {
  1573. backslashes = true;
  1574. next = advance();
  1575. continue;
  1576. }
  1577. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  1578. isGlob = true;
  1579. break;
  1580. }
  1581. }
  1582. }
  1583. let isExtglobChar = code === CHAR_PLUS
  1584. || code === CHAR_AT
  1585. || code === CHAR_EXCLAMATION_MARK;
  1586. if (isExtglobChar && input.charCodeAt(index + 1) === CHAR_LEFT_PARENTHESES$1) {
  1587. isGlob = true;
  1588. break;
  1589. }
  1590. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  1591. negated = true;
  1592. start++;
  1593. continue;
  1594. }
  1595. if (code === CHAR_LEFT_PARENTHESES$1) {
  1596. while (!eos() && (next = advance())) {
  1597. if (next === CHAR_BACKWARD_SLASH) {
  1598. backslashes = true;
  1599. next = advance();
  1600. continue;
  1601. }
  1602. if (next === CHAR_RIGHT_PARENTHESES$1) {
  1603. isGlob = true;
  1604. break;
  1605. }
  1606. }
  1607. }
  1608. if (isGlob) {
  1609. break;
  1610. }
  1611. }
  1612. let prefix = '';
  1613. let orig = input;
  1614. let base = input;
  1615. let glob = '';
  1616. if (start > 0) {
  1617. prefix = input.slice(0, start);
  1618. input = input.slice(start);
  1619. lastIndex -= start;
  1620. }
  1621. if (base && isGlob === true && lastIndex > 0) {
  1622. base = input.slice(0, lastIndex);
  1623. glob = input.slice(lastIndex);
  1624. }
  1625. else if (isGlob === true) {
  1626. base = '';
  1627. glob = input;
  1628. }
  1629. else {
  1630. base = input;
  1631. }
  1632. if (base && base !== '' && base !== '/' && base !== input) {
  1633. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  1634. base = base.slice(0, -1);
  1635. }
  1636. }
  1637. if (opts.unescape === true) {
  1638. if (glob)
  1639. glob = utils$1.removeBackslashes(glob);
  1640. if (base && backslashes === true) {
  1641. base = utils$1.removeBackslashes(base);
  1642. }
  1643. }
  1644. return { prefix, input: orig, base, glob, negated, isGlob };
  1645. };
  1646. /**
  1647. * Constants
  1648. */
  1649. const { MAX_LENGTH: MAX_LENGTH$1, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, REGEX_NON_SPECIAL_CHAR, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
  1650. /**
  1651. * Helpers
  1652. */
  1653. const expandRange = (args, options) => {
  1654. if (typeof options.expandRange === 'function') {
  1655. return options.expandRange(...args, options);
  1656. }
  1657. args.sort();
  1658. let value = `[${args.join('-')}]`;
  1659. try {
  1660. }
  1661. catch (ex) {
  1662. return args.map(v => utils$1.escapeRegex(v)).join('..');
  1663. }
  1664. return value;
  1665. };
  1666. const negate = state => {
  1667. let count = 1;
  1668. while (state.peek() === '!' && (state.peek(2) !== '(' || state.peek(3) === '?')) {
  1669. state.advance();
  1670. state.start++;
  1671. count++;
  1672. }
  1673. if (count % 2 === 0) {
  1674. return false;
  1675. }
  1676. state.negated = true;
  1677. state.start++;
  1678. return true;
  1679. };
  1680. /**
  1681. * Create the message for a syntax error
  1682. */
  1683. const syntaxError = (type, char) => {
  1684. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  1685. };
  1686. /**
  1687. * Parse the given input string.
  1688. * @param {String} input
  1689. * @param {Object} options
  1690. * @return {Object}
  1691. */
  1692. const parse$1 = (input, options) => {
  1693. if (typeof input !== 'string') {
  1694. throw new TypeError('Expected a string');
  1695. }
  1696. input = REPLACEMENTS[input] || input;
  1697. let opts = Object.assign({}, options);
  1698. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  1699. let len = input.length;
  1700. if (len > max) {
  1701. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1702. }
  1703. let bos = { type: 'bos', value: '', output: opts.prepend || '' };
  1704. let tokens = [bos];
  1705. let capture = opts.capture ? '' : '?:';
  1706. let win32 = utils$1.isWindows(options);
  1707. // create constants based on platform, for windows or posix
  1708. const PLATFORM_CHARS = constants$1.globChars(win32);
  1709. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  1710. 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;
  1711. const globstar = (opts) => {
  1712. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1713. };
  1714. let nodot = opts.dot ? '' : NO_DOT;
  1715. let star = opts.bash === true ? globstar(opts) : STAR;
  1716. let qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  1717. if (opts.capture) {
  1718. star = `(${star})`;
  1719. }
  1720. // minimatch options support
  1721. if (typeof opts.noext === 'boolean') {
  1722. opts.noextglob = opts.noext;
  1723. }
  1724. let state = {
  1725. index: -1,
  1726. start: 0,
  1727. consumed: '',
  1728. output: '',
  1729. backtrack: false,
  1730. brackets: 0,
  1731. braces: 0,
  1732. parens: 0,
  1733. quotes: 0,
  1734. tokens
  1735. };
  1736. let extglobs = [];
  1737. let stack = [];
  1738. let prev = bos;
  1739. let value;
  1740. /**
  1741. * Tokenizing helpers
  1742. */
  1743. const eos = () => state.index === len - 1;
  1744. const peek = state.peek = (n = 1) => input[state.index + n];
  1745. const advance = state.advance = () => input[++state.index];
  1746. const append = token => {
  1747. state.output += token.output != null ? token.output : token.value;
  1748. state.consumed += token.value || '';
  1749. };
  1750. const increment = type => {
  1751. state[type]++;
  1752. stack.push(type);
  1753. };
  1754. const decrement = type => {
  1755. state[type]--;
  1756. stack.pop();
  1757. };
  1758. /**
  1759. * Push tokens onto the tokens array. This helper speeds up
  1760. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1761. * and 2) helping us avoid creating extra tokens when consecutive
  1762. * characters are plain text. This improves performance and simplifies
  1763. * lookbehinds.
  1764. */
  1765. const push = tok => {
  1766. if (prev.type === 'globstar') {
  1767. let isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1768. let isExtglob = extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
  1769. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1770. state.output = state.output.slice(0, -prev.output.length);
  1771. prev.type = 'star';
  1772. prev.value = '*';
  1773. prev.output = star;
  1774. state.output += prev.output;
  1775. }
  1776. }
  1777. if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
  1778. extglobs[extglobs.length - 1].inner += tok.value;
  1779. }
  1780. if (tok.value || tok.output)
  1781. append(tok);
  1782. if (prev && prev.type === 'text' && tok.type === 'text') {
  1783. prev.value += tok.value;
  1784. return;
  1785. }
  1786. tok.prev = prev;
  1787. tokens.push(tok);
  1788. prev = tok;
  1789. };
  1790. const extglobOpen = (type, value) => {
  1791. let token = Object.assign({}, EXTGLOB_CHARS[value], { conditions: 1, inner: '' });
  1792. token.prev = prev;
  1793. token.parens = state.parens;
  1794. token.output = state.output;
  1795. let output = (opts.capture ? '(' : '') + token.open;
  1796. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1797. push({ type: 'paren', extglob: true, value: advance(), output });
  1798. increment('parens');
  1799. extglobs.push(token);
  1800. };
  1801. const extglobClose = token => {
  1802. let output = token.close + (opts.capture ? ')' : '');
  1803. if (token.type === 'negate') {
  1804. let extglobStar = star;
  1805. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1806. extglobStar = globstar(opts);
  1807. }
  1808. if (extglobStar !== star || eos() || /^\)+$/.test(input.slice(state.index + 1))) {
  1809. output = token.close = ')$))' + extglobStar;
  1810. }
  1811. if (token.prev.type === 'bos' && eos()) {
  1812. state.negatedExtglob = true;
  1813. }
  1814. }
  1815. push({ type: 'paren', extglob: true, value, output });
  1816. decrement('parens');
  1817. };
  1818. if (opts.fastpaths !== false && !/(^[*!]|[/{[()\]}"])/.test(input)) {
  1819. let backslashes = false;
  1820. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1821. if (first === '\\') {
  1822. backslashes = true;
  1823. return m;
  1824. }
  1825. if (first === '?') {
  1826. if (esc) {
  1827. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1828. }
  1829. if (index === 0) {
  1830. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1831. }
  1832. return QMARK.repeat(chars.length);
  1833. }
  1834. if (first === '.') {
  1835. return DOT_LITERAL.repeat(chars.length);
  1836. }
  1837. if (first === '*') {
  1838. if (esc) {
  1839. return esc + first + (rest ? star : '');
  1840. }
  1841. return star;
  1842. }
  1843. return esc ? m : '\\' + m;
  1844. });
  1845. if (backslashes === true) {
  1846. if (opts.unescape === true) {
  1847. output = output.replace(/\\/g, '');
  1848. }
  1849. else {
  1850. output = output.replace(/\\+/g, m => {
  1851. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1852. });
  1853. }
  1854. }
  1855. state.output = output;
  1856. return state;
  1857. }
  1858. /**
  1859. * Tokenize input until we reach end-of-string
  1860. */
  1861. while (!eos()) {
  1862. value = advance();
  1863. if (value === '\u0000') {
  1864. continue;
  1865. }
  1866. /**
  1867. * Escaped characters
  1868. */
  1869. if (value === '\\') {
  1870. let next = peek();
  1871. if (next === '/' && opts.bash !== true) {
  1872. continue;
  1873. }
  1874. if (next === '.' || next === ';') {
  1875. continue;
  1876. }
  1877. if (!next) {
  1878. value += '\\';
  1879. push({ type: 'text', value });
  1880. continue;
  1881. }
  1882. // collapse slashes to reduce potential for exploits
  1883. let match = /^\\+/.exec(input.slice(state.index + 1));
  1884. let slashes = 0;
  1885. if (match && match[0].length > 2) {
  1886. slashes = match[0].length;
  1887. state.index += slashes;
  1888. if (slashes % 2 !== 0) {
  1889. value += '\\';
  1890. }
  1891. }
  1892. if (opts.unescape === true) {
  1893. value = advance() || '';
  1894. }
  1895. else {
  1896. value += advance() || '';
  1897. }
  1898. if (state.brackets === 0) {
  1899. push({ type: 'text', value });
  1900. continue;
  1901. }
  1902. }
  1903. /**
  1904. * If we're inside a regex character class, continue
  1905. * until we reach the closing bracket.
  1906. */
  1907. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1908. if (opts.posix !== false && value === ':') {
  1909. let inner = prev.value.slice(1);
  1910. if (inner.includes('[')) {
  1911. prev.posix = true;
  1912. if (inner.includes(':')) {
  1913. let idx = prev.value.lastIndexOf('[');
  1914. let pre = prev.value.slice(0, idx);
  1915. let rest = prev.value.slice(idx + 2);
  1916. let posix = POSIX_REGEX_SOURCE$1[rest];
  1917. if (posix) {
  1918. prev.value = pre + posix;
  1919. state.backtrack = true;
  1920. advance();
  1921. if (!bos.output && tokens.indexOf(prev) === 1) {
  1922. bos.output = ONE_CHAR;
  1923. }
  1924. continue;
  1925. }
  1926. }
  1927. }
  1928. }
  1929. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1930. value = '\\' + value;
  1931. }
  1932. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1933. value = '\\' + value;
  1934. }
  1935. if (opts.posix === true && value === '!' && prev.value === '[') {
  1936. value = '^';
  1937. }
  1938. prev.value += value;
  1939. append({ value });
  1940. continue;
  1941. }
  1942. /**
  1943. * If we're inside a quoted string, continue
  1944. * until we reach the closing double quote.
  1945. */
  1946. if (state.quotes === 1 && value !== '"') {
  1947. value = utils$1.escapeRegex(value);
  1948. prev.value += value;
  1949. append({ value });
  1950. continue;
  1951. }
  1952. /**
  1953. * Double quotes
  1954. */
  1955. if (value === '"') {
  1956. state.quotes = state.quotes === 1 ? 0 : 1;
  1957. if (opts.keepQuotes === true) {
  1958. push({ type: 'text', value });
  1959. }
  1960. continue;
  1961. }
  1962. /**
  1963. * Parentheses
  1964. */
  1965. if (value === '(') {
  1966. push({ type: 'paren', value });
  1967. increment('parens');
  1968. continue;
  1969. }
  1970. if (value === ')') {
  1971. if (state.parens === 0 && opts.strictBrackets === true) {
  1972. throw new SyntaxError(syntaxError('opening', '('));
  1973. }
  1974. let extglob = extglobs[extglobs.length - 1];
  1975. if (extglob && state.parens === extglob.parens + 1) {
  1976. extglobClose(extglobs.pop());
  1977. continue;
  1978. }
  1979. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1980. decrement('parens');
  1981. continue;
  1982. }
  1983. /**
  1984. * Brackets
  1985. */
  1986. if (value === '[') {
  1987. if (opts.nobracket === true || !input.slice(state.index + 1).includes(']')) {
  1988. if (opts.nobracket !== true && opts.strictBrackets === true) {
  1989. throw new SyntaxError(syntaxError('closing', ']'));
  1990. }
  1991. value = '\\' + value;
  1992. }
  1993. else {
  1994. increment('brackets');
  1995. }
  1996. push({ type: 'bracket', value });
  1997. continue;
  1998. }
  1999. if (value === ']') {
  2000. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  2001. push({ type: 'text', value, output: '\\' + value });
  2002. continue;
  2003. }
  2004. if (state.brackets === 0) {
  2005. if (opts.strictBrackets === true) {
  2006. throw new SyntaxError(syntaxError('opening', '['));
  2007. }
  2008. push({ type: 'text', value, output: '\\' + value });
  2009. continue;
  2010. }
  2011. decrement('brackets');
  2012. let prevValue = prev.value.slice(1);
  2013. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  2014. value = '/' + value;
  2015. }
  2016. prev.value += value;
  2017. append({ value });
  2018. // when literal brackets are explicitly disabled
  2019. // assume we should match with a regex character class
  2020. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  2021. continue;
  2022. }
  2023. let escaped = utils$1.escapeRegex(prev.value);
  2024. state.output = state.output.slice(0, -prev.value.length);
  2025. // when literal brackets are explicitly enabled
  2026. // assume we should escape the brackets to match literal characters
  2027. if (opts.literalBrackets === true) {
  2028. state.output += escaped;
  2029. prev.value = escaped;
  2030. continue;
  2031. }
  2032. // when the user specifies nothing, try to match both
  2033. prev.value = `(${capture}${escaped}|${prev.value})`;
  2034. state.output += prev.value;
  2035. continue;
  2036. }
  2037. /**
  2038. * Braces
  2039. */
  2040. if (value === '{' && opts.nobrace !== true) {
  2041. push({ type: 'brace', value, output: '(' });
  2042. increment('braces');
  2043. continue;
  2044. }
  2045. if (value === '}') {
  2046. if (opts.nobrace === true || state.braces === 0) {
  2047. push({ type: 'text', value, output: '\\' + value });
  2048. continue;
  2049. }
  2050. let output = ')';
  2051. if (state.dots === true) {
  2052. let arr = tokens.slice();
  2053. let range = [];
  2054. for (let i = arr.length - 1; i >= 0; i--) {
  2055. tokens.pop();
  2056. if (arr[i].type === 'brace') {
  2057. break;
  2058. }
  2059. if (arr[i].type !== 'dots') {
  2060. range.unshift(arr[i].value);
  2061. }
  2062. }
  2063. output = expandRange(range, opts);
  2064. state.backtrack = true;
  2065. }
  2066. push({ type: 'brace', value, output });
  2067. decrement('braces');
  2068. continue;
  2069. }
  2070. /**
  2071. * Pipes
  2072. */
  2073. if (value === '|') {
  2074. if (extglobs.length > 0) {
  2075. extglobs[extglobs.length - 1].conditions++;
  2076. }
  2077. push({ type: 'text', value });
  2078. continue;
  2079. }
  2080. /**
  2081. * Commas
  2082. */
  2083. if (value === ',') {
  2084. let output = value;
  2085. if (state.braces > 0 && stack[stack.length - 1] === 'braces') {
  2086. output = '|';
  2087. }
  2088. push({ type: 'comma', value, output });
  2089. continue;
  2090. }
  2091. /**
  2092. * Slashes
  2093. */
  2094. if (value === '/') {
  2095. // if the beginning of the glob is "./", advance the start
  2096. // to the current index, and don't add the "./" characters
  2097. // to the state. This greatly simplifies lookbehinds when
  2098. // checking for BOS characters like "!" and "." (not "./")
  2099. if (prev.type === 'dot' && state.index === 1) {
  2100. state.start = state.index + 1;
  2101. state.consumed = '';
  2102. state.output = '';
  2103. tokens.pop();
  2104. prev = bos; // reset "prev" to the first token
  2105. continue;
  2106. }
  2107. push({ type: 'slash', value, output: SLASH_LITERAL });
  2108. continue;
  2109. }
  2110. /**
  2111. * Dots
  2112. */
  2113. if (value === '.') {
  2114. if (state.braces > 0 && prev.type === 'dot') {
  2115. if (prev.value === '.')
  2116. prev.output = DOT_LITERAL;
  2117. prev.type = 'dots';
  2118. prev.output += value;
  2119. prev.value += value;
  2120. state.dots = true;
  2121. continue;
  2122. }
  2123. push({ type: 'dot', value, output: DOT_LITERAL });
  2124. continue;
  2125. }
  2126. /**
  2127. * Question marks
  2128. */
  2129. if (value === '?') {
  2130. if (prev && prev.type === 'paren') {
  2131. let next = peek();
  2132. let output = value;
  2133. if (next === '<' && !utils$1.supportsLookbehinds()) {
  2134. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  2135. }
  2136. if (prev.value === '(' && !/[!=<:]/.test(next) || (next === '<' && !/[!=]/.test(peek(2)))) {
  2137. output = '\\' + value;
  2138. }
  2139. push({ type: 'text', value, output });
  2140. continue;
  2141. }
  2142. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2143. extglobOpen('qmark', value);
  2144. continue;
  2145. }
  2146. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2147. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2148. continue;
  2149. }
  2150. push({ type: 'qmark', value, output: QMARK });
  2151. continue;
  2152. }
  2153. /**
  2154. * Exclamation
  2155. */
  2156. if (value === '!') {
  2157. if (opts.noextglob !== true && peek() === '(') {
  2158. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2159. extglobOpen('negate', value);
  2160. continue;
  2161. }
  2162. }
  2163. if (opts.nonegate !== true && state.index === 0) {
  2164. negate(state);
  2165. continue;
  2166. }
  2167. }
  2168. /**
  2169. * Plus
  2170. */
  2171. if (value === '+') {
  2172. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2173. extglobOpen('plus', value);
  2174. continue;
  2175. }
  2176. if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) {
  2177. let output = prev.extglob === true ? '\\' + value : value;
  2178. push({ type: 'plus', value, output });
  2179. continue;
  2180. }
  2181. // use regex behavior inside parens
  2182. if (state.parens > 0 && opts.regex !== false) {
  2183. push({ type: 'plus', value });
  2184. continue;
  2185. }
  2186. push({ type: 'plus', value: PLUS_LITERAL });
  2187. continue;
  2188. }
  2189. /**
  2190. * Plain text
  2191. */
  2192. if (value === '@') {
  2193. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2194. push({ type: 'at', value, output: '' });
  2195. continue;
  2196. }
  2197. push({ type: 'text', value });
  2198. continue;
  2199. }
  2200. /**
  2201. * Plain text
  2202. */
  2203. if (value !== '*') {
  2204. if (value === '$' || value === '^') {
  2205. value = '\\' + value;
  2206. }
  2207. let match = REGEX_NON_SPECIAL_CHAR.exec(input.slice(state.index + 1));
  2208. if (match) {
  2209. value += match[0];
  2210. state.index += match[0].length;
  2211. }
  2212. push({ type: 'text', value });
  2213. continue;
  2214. }
  2215. /**
  2216. * Stars
  2217. */
  2218. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2219. prev.type = 'star';
  2220. prev.star = true;
  2221. prev.value += value;
  2222. prev.output = star;
  2223. state.backtrack = true;
  2224. state.consumed += value;
  2225. continue;
  2226. }
  2227. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2228. extglobOpen('star', value);
  2229. continue;
  2230. }
  2231. if (prev.type === 'star') {
  2232. if (opts.noglobstar === true) {
  2233. state.consumed += value;
  2234. continue;
  2235. }
  2236. let prior = prev.prev;
  2237. let before = prior.prev;
  2238. let isStart = prior.type === 'slash' || prior.type === 'bos';
  2239. let afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2240. if (opts.bash === true && (!isStart || (!eos() && peek() !== '/'))) {
  2241. push({ type: 'star', value, output: '' });
  2242. continue;
  2243. }
  2244. let isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2245. let isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2246. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2247. push({ type: 'star', value, output: '' });
  2248. continue;
  2249. }
  2250. // strip consecutive `/**/`
  2251. while (input.slice(state.index + 1, state.index + 4) === '/**') {
  2252. let after = input[state.index + 4];
  2253. if (after && after !== '/') {
  2254. break;
  2255. }
  2256. state.consumed += '/**';
  2257. state.index += 3;
  2258. }
  2259. if (prior.type === 'bos' && eos()) {
  2260. prev.type = 'globstar';
  2261. prev.value += value;
  2262. prev.output = globstar(opts);
  2263. state.output = prev.output;
  2264. state.consumed += value;
  2265. continue;
  2266. }
  2267. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2268. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2269. prior.output = '(?:' + prior.output;
  2270. prev.type = 'globstar';
  2271. prev.output = globstar(opts) + '|$)';
  2272. prev.value += value;
  2273. state.output += prior.output + prev.output;
  2274. state.consumed += value;
  2275. continue;
  2276. }
  2277. let next = peek();
  2278. if (prior.type === 'slash' && prior.prev.type !== 'bos' && next === '/') {
  2279. let end = peek(2) !== void 0 ? '|$' : '';
  2280. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2281. prior.output = '(?:' + prior.output;
  2282. prev.type = 'globstar';
  2283. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2284. prev.value += value;
  2285. state.output += prior.output + prev.output;
  2286. state.consumed += value + advance();
  2287. push({ type: 'slash', value, output: '' });
  2288. continue;
  2289. }
  2290. if (prior.type === 'bos' && next === '/') {
  2291. prev.type = 'globstar';
  2292. prev.value += value;
  2293. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2294. state.output = prev.output;
  2295. state.consumed += value + advance();
  2296. push({ type: 'slash', value, output: '' });
  2297. continue;
  2298. }
  2299. // remove single star from output
  2300. state.output = state.output.slice(0, -prev.output.length);
  2301. // reset previous token to globstar
  2302. prev.type = 'globstar';
  2303. prev.output = globstar(opts);
  2304. prev.value += value;
  2305. // reset output with globstar
  2306. state.output += prev.output;
  2307. state.consumed += value;
  2308. continue;
  2309. }
  2310. let token = { type: 'star', value, output: star };
  2311. if (opts.bash === true) {
  2312. token.output = '.*?';
  2313. if (prev.type === 'bos' || prev.type === 'slash') {
  2314. token.output = nodot + token.output;
  2315. }
  2316. push(token);
  2317. continue;
  2318. }
  2319. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2320. token.output = value;
  2321. push(token);
  2322. continue;
  2323. }
  2324. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2325. if (prev.type === 'dot') {
  2326. state.output += NO_DOT_SLASH;
  2327. prev.output += NO_DOT_SLASH;
  2328. }
  2329. else if (opts.dot === true) {
  2330. state.output += NO_DOTS_SLASH;
  2331. prev.output += NO_DOTS_SLASH;
  2332. }
  2333. else {
  2334. state.output += nodot;
  2335. prev.output += nodot;
  2336. }
  2337. if (peek() !== '*') {
  2338. state.output += ONE_CHAR;
  2339. prev.output += ONE_CHAR;
  2340. }
  2341. }
  2342. push(token);
  2343. }
  2344. while (state.brackets > 0) {
  2345. if (opts.strictBrackets === true)
  2346. throw new SyntaxError(syntaxError('closing', ']'));
  2347. state.output = utils$1.escapeLast(state.output, '[');
  2348. decrement('brackets');
  2349. }
  2350. while (state.parens > 0) {
  2351. if (opts.strictBrackets === true)
  2352. throw new SyntaxError(syntaxError('closing', ')'));
  2353. state.output = utils$1.escapeLast(state.output, '(');
  2354. decrement('parens');
  2355. }
  2356. while (state.braces > 0) {
  2357. if (opts.strictBrackets === true)
  2358. throw new SyntaxError(syntaxError('closing', '}'));
  2359. state.output = utils$1.escapeLast(state.output, '{');
  2360. decrement('braces');
  2361. }
  2362. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2363. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2364. }
  2365. // rebuild the output if we had to backtrack at any point
  2366. if (state.backtrack === true) {
  2367. state.output = '';
  2368. for (let token of state.tokens) {
  2369. state.output += token.output != null ? token.output : token.value;
  2370. if (token.suffix) {
  2371. state.output += token.suffix;
  2372. }
  2373. }
  2374. }
  2375. return state;
  2376. };
  2377. /**
  2378. * Fast paths for creating regular expressions for common glob patterns.
  2379. * This can significantly speed up processing and has very little downside
  2380. * impact when none of the fast paths match.
  2381. */
  2382. parse$1.fastpaths = (input, options) => {
  2383. let opts = Object.assign({}, options);
  2384. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  2385. let len = input.length;
  2386. if (len > max) {
  2387. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2388. }
  2389. input = REPLACEMENTS[input] || input;
  2390. let win32 = utils$1.isWindows(options);
  2391. // create constants based on platform, for windows or posix
  2392. const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$1.globChars(win32);
  2393. let capture = opts.capture ? '' : '?:';
  2394. let star = opts.bash === true ? '.*?' : STAR;
  2395. let nodot = opts.dot ? NO_DOTS : NO_DOT;
  2396. let slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2397. if (opts.capture) {
  2398. star = `(${star})`;
  2399. }
  2400. const globstar = (opts) => {
  2401. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2402. };
  2403. const create = str => {
  2404. switch (str) {
  2405. case '*':
  2406. return `${nodot}${ONE_CHAR}${star}`;
  2407. case '.*':
  2408. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2409. case '*.*':
  2410. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2411. case '*/*':
  2412. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2413. case '**':
  2414. return nodot + globstar(opts);
  2415. case '**/*':
  2416. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2417. case '**/*.*':
  2418. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2419. case '**/.*':
  2420. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2421. default: {
  2422. let match = /^(.*?)\.(\w+)$/.exec(str);
  2423. if (!match)
  2424. return;
  2425. let source = create(match[1], options);
  2426. if (!source)
  2427. return;
  2428. return source + DOT_LITERAL + match[2];
  2429. }
  2430. }
  2431. };
  2432. let output = create(input);
  2433. if (output && opts.strictSlashes !== true) {
  2434. output += `${SLASH_LITERAL}?`;
  2435. }
  2436. return output;
  2437. };
  2438. var parse_1$1 = parse$1;
  2439. /**
  2440. * Creates a matcher function from one or more glob patterns. The
  2441. * returned function takes a string to match as its first argument,
  2442. * and returns true if the string is a match. The returned matcher
  2443. * function also takes a boolean as the second argument that, when true,
  2444. * returns an object with additional information.
  2445. *
  2446. * ```js
  2447. * const picomatch = require('picomatch');
  2448. * // picomatch(glob[, options]);
  2449. *
  2450. * const isMatch = picomatch('*.!(*a)');
  2451. * console.log(isMatch('a.a')); //=> false
  2452. * console.log(isMatch('a.b')); //=> true
  2453. * ```
  2454. * @name picomatch
  2455. * @param {String|Array} `globs` One or more glob patterns.
  2456. * @param {Object=} `options`
  2457. * @return {Function=} Returns a matcher function.
  2458. * @api public
  2459. */
  2460. const picomatch = (glob, options, returnState = false) => {
  2461. if (Array.isArray(glob)) {
  2462. let fns = glob.map(input => picomatch(input, options, returnState));
  2463. return str => {
  2464. for (let isMatch of fns) {
  2465. let state = isMatch(str);
  2466. if (state)
  2467. return state;
  2468. }
  2469. return false;
  2470. };
  2471. }
  2472. if (typeof glob !== 'string' || glob === '') {
  2473. throw new TypeError('Expected pattern to be a non-empty string');
  2474. }
  2475. let opts = options || {};
  2476. let posix = utils$1.isWindows(options);
  2477. let regex = picomatch.makeRe(glob, options, false, true);
  2478. let state = regex.state;
  2479. delete regex.state;
  2480. let isIgnored = () => false;
  2481. if (opts.ignore) {
  2482. let ignoreOpts = Object.assign({}, options, { ignore: null, onMatch: null, onResult: null });
  2483. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  2484. }
  2485. const matcher = (input, returnObject = false) => {
  2486. let { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  2487. let result = { glob, state, regex, posix, input, output, match, isMatch };
  2488. if (typeof opts.onResult === 'function') {
  2489. opts.onResult(result);
  2490. }
  2491. if (isMatch === false) {
  2492. result.isMatch = false;
  2493. return returnObject ? result : false;
  2494. }
  2495. if (isIgnored(input)) {
  2496. if (typeof opts.onIgnore === 'function') {
  2497. opts.onIgnore(result);
  2498. }
  2499. result.isMatch = false;
  2500. return returnObject ? result : false;
  2501. }
  2502. if (typeof opts.onMatch === 'function') {
  2503. opts.onMatch(result);
  2504. }
  2505. return returnObject ? result : true;
  2506. };
  2507. if (returnState) {
  2508. matcher.state = state;
  2509. }
  2510. return matcher;
  2511. };
  2512. /**
  2513. * Test `input` with the given `regex`. This is used by the main
  2514. * `picomatch()` function to test the input string.
  2515. *
  2516. * ```js
  2517. * const picomatch = require('picomatch');
  2518. * // picomatch.test(input, regex[, options]);
  2519. *
  2520. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  2521. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  2522. * ```
  2523. * @param {String} `input` String to test.
  2524. * @param {RegExp} `regex`
  2525. * @return {Object} Returns an object with matching info.
  2526. * @api public
  2527. */
  2528. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  2529. if (typeof input !== 'string') {
  2530. throw new TypeError('Expected input to be a string');
  2531. }
  2532. if (input === '') {
  2533. return { isMatch: false, output: '' };
  2534. }
  2535. let opts = options || {};
  2536. let format = opts.format || (posix ? utils$1.toPosixSlashes : null);
  2537. let match = input === glob;
  2538. let output = (match && format) ? format(input) : input;
  2539. if (match === false) {
  2540. output = format ? format(input) : input;
  2541. match = output === glob;
  2542. }
  2543. if (match === false || opts.capture === true) {
  2544. if (opts.matchBase === true || opts.basename === true) {
  2545. match = picomatch.matchBase(input, regex, options, posix);
  2546. }
  2547. else {
  2548. match = regex.exec(output);
  2549. }
  2550. }
  2551. return { isMatch: !!match, match, output };
  2552. };
  2553. /**
  2554. * Match the basename of a filepath.
  2555. *
  2556. * ```js
  2557. * const picomatch = require('picomatch');
  2558. * // picomatch.matchBase(input, glob[, options]);
  2559. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  2560. * ```
  2561. * @param {String} `input` String to test.
  2562. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  2563. * @return {Boolean}
  2564. * @api public
  2565. */
  2566. picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => {
  2567. let regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  2568. return regex.test(path.basename(input));
  2569. };
  2570. /**
  2571. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2572. *
  2573. * ```js
  2574. * const picomatch = require('picomatch');
  2575. * // picomatch.isMatch(string, patterns[, options]);
  2576. *
  2577. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2578. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  2579. * ```
  2580. * @param {String|Array} str The string to test.
  2581. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2582. * @param {Object} [options] See available [options](#options).
  2583. * @return {Boolean} Returns true if any patterns match `str`
  2584. * @api public
  2585. */
  2586. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  2587. /**
  2588. * Parse a glob pattern to create the source string for a regular
  2589. * expression.
  2590. *
  2591. * ```js
  2592. * const picomatch = require('picomatch');
  2593. * const result = picomatch.parse(glob[, options]);
  2594. * ```
  2595. * @param {String} `glob`
  2596. * @param {Object} `options`
  2597. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  2598. * @api public
  2599. */
  2600. picomatch.parse = (glob, options) => parse_1$1(glob, options);
  2601. /**
  2602. * Scan a glob pattern to separate the pattern into segments.
  2603. *
  2604. * ```js
  2605. * const picomatch = require('picomatch');
  2606. * // picomatch.scan(input[, options]);
  2607. *
  2608. * const result = picomatch.scan('!./foo/*.js');
  2609. * console.log(result);
  2610. * // { prefix: '!./',
  2611. * // input: '!./foo/*.js',
  2612. * // base: 'foo',
  2613. * // glob: '*.js',
  2614. * // negated: true,
  2615. * // isGlob: true }
  2616. * ```
  2617. * @param {String} `input` Glob pattern to scan.
  2618. * @param {Object} `options`
  2619. * @return {Object} Returns an object with
  2620. * @api public
  2621. */
  2622. picomatch.scan = (input, options) => scan(input, options);
  2623. /**
  2624. * Create a regular expression from a glob pattern.
  2625. *
  2626. * ```js
  2627. * const picomatch = require('picomatch');
  2628. * // picomatch.makeRe(input[, options]);
  2629. *
  2630. * console.log(picomatch.makeRe('*.js'));
  2631. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2632. * ```
  2633. * @param {String} `input` A glob pattern to convert to regex.
  2634. * @param {Object} `options`
  2635. * @return {RegExp} Returns a regex created from the given pattern.
  2636. * @api public
  2637. */
  2638. picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
  2639. if (!input || typeof input !== 'string') {
  2640. throw new TypeError('Expected a non-empty string');
  2641. }
  2642. let opts = options || {};
  2643. let prepend = opts.contains ? '' : '^';
  2644. let append = opts.contains ? '' : '$';
  2645. let state = { negated: false, fastpaths: true };
  2646. let prefix = '';
  2647. let output;
  2648. if (input.startsWith('./')) {
  2649. input = input.slice(2);
  2650. prefix = state.prefix = './';
  2651. }
  2652. if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2653. output = parse_1$1.fastpaths(input, options);
  2654. }
  2655. if (output === void 0) {
  2656. state = picomatch.parse(input, options);
  2657. state.prefix = prefix + (state.prefix || '');
  2658. output = state.output;
  2659. }
  2660. if (returnOutput === true) {
  2661. return output;
  2662. }
  2663. let source = `${prepend}(?:${output})${append}`;
  2664. if (state && state.negated === true) {
  2665. source = `^(?!${source}).*$`;
  2666. }
  2667. let regex = picomatch.toRegex(source, options);
  2668. if (returnState === true) {
  2669. regex.state = state;
  2670. }
  2671. return regex;
  2672. };
  2673. /**
  2674. * Create a regular expression from the given regex source string.
  2675. *
  2676. * ```js
  2677. * const picomatch = require('picomatch');
  2678. * // picomatch.toRegex(source[, options]);
  2679. *
  2680. * const { output } = picomatch.parse('*.js');
  2681. * console.log(picomatch.toRegex(output));
  2682. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2683. * ```
  2684. * @param {String} `source` Regular expression source string.
  2685. * @param {Object} `options`
  2686. * @return {RegExp}
  2687. * @api public
  2688. */
  2689. picomatch.toRegex = (source, options) => {
  2690. try {
  2691. let opts = options || {};
  2692. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2693. }
  2694. catch (err) {
  2695. if (options && options.debug === true)
  2696. throw err;
  2697. return /$^/;
  2698. }
  2699. };
  2700. /**
  2701. * Picomatch constants.
  2702. * @return {Object}
  2703. */
  2704. picomatch.constants = constants$1;
  2705. /**
  2706. * Expose "picomatch"
  2707. */
  2708. var picomatch_1 = picomatch;
  2709. var picomatch$1 = picomatch_1;
  2710. const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
  2711. /**
  2712. * Returns an array of strings that match one or more glob patterns.
  2713. *
  2714. * ```js
  2715. * const mm = require('micromatch');
  2716. * // mm(list, patterns[, options]);
  2717. *
  2718. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  2719. * //=> [ 'a.js' ]
  2720. * ```
  2721. * @param {String|Array<string>} list List of strings to match.
  2722. * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
  2723. * @param {Object} options See available [options](#options)
  2724. * @return {Array} Returns an array of matches
  2725. * @summary false
  2726. * @api public
  2727. */
  2728. const micromatch = (list, patterns, options) => {
  2729. patterns = [].concat(patterns);
  2730. list = [].concat(list);
  2731. let omit = new Set();
  2732. let keep = new Set();
  2733. let items = new Set();
  2734. let negatives = 0;
  2735. let onResult = state => {
  2736. items.add(state.output);
  2737. if (options && options.onResult) {
  2738. options.onResult(state);
  2739. }
  2740. };
  2741. for (let i = 0; i < patterns.length; i++) {
  2742. let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, { onResult }), true);
  2743. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  2744. if (negated)
  2745. negatives++;
  2746. for (let item of list) {
  2747. let matched = isMatch(item, true);
  2748. let match = negated ? !matched.isMatch : matched.isMatch;
  2749. if (!match)
  2750. continue;
  2751. if (negated) {
  2752. omit.add(matched.output);
  2753. }
  2754. else {
  2755. omit.delete(matched.output);
  2756. keep.add(matched.output);
  2757. }
  2758. }
  2759. }
  2760. let result = negatives === patterns.length ? [...items] : [...keep];
  2761. let matches = result.filter(item => !omit.has(item));
  2762. if (options && matches.length === 0) {
  2763. if (options.failglob === true) {
  2764. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  2765. }
  2766. if (options.nonull === true || options.nullglob === true) {
  2767. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  2768. }
  2769. }
  2770. return matches;
  2771. };
  2772. /**
  2773. * Backwards compatibility
  2774. */
  2775. micromatch.match = micromatch;
  2776. /**
  2777. * Returns a matcher function from the given glob `pattern` and `options`.
  2778. * The returned function takes a string to match as its only argument and returns
  2779. * true if the string is a match.
  2780. *
  2781. * ```js
  2782. * const mm = require('micromatch');
  2783. * // mm.matcher(pattern[, options]);
  2784. *
  2785. * const isMatch = mm.matcher('*.!(*a)');
  2786. * console.log(isMatch('a.a')); //=> false
  2787. * console.log(isMatch('a.b')); //=> true
  2788. * ```
  2789. * @param {String} `pattern` Glob pattern
  2790. * @param {Object} `options`
  2791. * @return {Function} Returns a matcher function.
  2792. * @api public
  2793. */
  2794. micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
  2795. /**
  2796. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2797. *
  2798. * ```js
  2799. * const mm = require('micromatch');
  2800. * // mm.isMatch(string, patterns[, options]);
  2801. *
  2802. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2803. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  2804. * ```
  2805. * @param {String} str The string to test.
  2806. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2807. * @param {Object} [options] See available [options](#options).
  2808. * @return {Boolean} Returns true if any patterns match `str`
  2809. * @api public
  2810. */
  2811. micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  2812. /**
  2813. * Backwards compatibility
  2814. */
  2815. micromatch.any = micromatch.isMatch;
  2816. /**
  2817. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  2818. *
  2819. * ```js
  2820. * const mm = require('micromatch');
  2821. * // mm.not(list, patterns[, options]);
  2822. *
  2823. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  2824. * //=> ['b.b', 'c.c']
  2825. * ```
  2826. * @param {Array} `list` Array of strings to match.
  2827. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  2828. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2829. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  2830. * @api public
  2831. */
  2832. micromatch.not = (list, patterns, options = {}) => {
  2833. patterns = [].concat(patterns).map(String);
  2834. let result = new Set();
  2835. let items = [];
  2836. let onResult = state => {
  2837. if (options.onResult)
  2838. options.onResult(state);
  2839. items.push(state.output);
  2840. };
  2841. let matches = micromatch(list, patterns, Object.assign({}, options, { onResult }));
  2842. for (let item of items) {
  2843. if (!matches.includes(item)) {
  2844. result.add(item);
  2845. }
  2846. }
  2847. return [...result];
  2848. };
  2849. /**
  2850. * Returns true if the given `string` contains the given pattern. Similar
  2851. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  2852. *
  2853. * ```js
  2854. * var mm = require('micromatch');
  2855. * // mm.contains(string, pattern[, options]);
  2856. *
  2857. * console.log(mm.contains('aa/bb/cc', '*b'));
  2858. * //=> true
  2859. * console.log(mm.contains('aa/bb/cc', '*d'));
  2860. * //=> false
  2861. * ```
  2862. * @param {String} `str` The string to match.
  2863. * @param {String|Array} `patterns` Glob pattern to use for matching.
  2864. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2865. * @return {Boolean} Returns true if the patter matches any part of `str`.
  2866. * @api public
  2867. */
  2868. micromatch.contains = (str, pattern, options) => {
  2869. if (typeof str !== 'string') {
  2870. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  2871. }
  2872. if (Array.isArray(pattern)) {
  2873. return pattern.some(p => micromatch.contains(str, p, options));
  2874. }
  2875. if (typeof pattern === 'string') {
  2876. if (isEmptyString(str) || isEmptyString(pattern)) {
  2877. return false;
  2878. }
  2879. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  2880. return true;
  2881. }
  2882. }
  2883. return micromatch.isMatch(str, pattern, Object.assign({}, options, { contains: true }));
  2884. };
  2885. /**
  2886. * Filter the keys of the given object with the given `glob` pattern
  2887. * and `options`. Does not attempt to match nested keys. If you need this feature,
  2888. * use [glob-object][] instead.
  2889. *
  2890. * ```js
  2891. * const mm = require('micromatch');
  2892. * // mm.matchKeys(object, patterns[, options]);
  2893. *
  2894. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  2895. * console.log(mm.matchKeys(obj, '*b'));
  2896. * //=> { ab: 'b' }
  2897. * ```
  2898. * @param {Object} `object` The object with keys to filter.
  2899. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  2900. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2901. * @return {Object} Returns an object with only keys that match the given patterns.
  2902. * @api public
  2903. */
  2904. micromatch.matchKeys = (obj, patterns, options) => {
  2905. if (!utils$1.isObject(obj)) {
  2906. throw new TypeError('Expected the first argument to be an object');
  2907. }
  2908. let keys = micromatch(Object.keys(obj), patterns, options);
  2909. let res = {};
  2910. for (let key of keys)
  2911. res[key] = obj[key];
  2912. return res;
  2913. };
  2914. /**
  2915. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  2916. *
  2917. * ```js
  2918. * const mm = require('micromatch');
  2919. * // mm.some(list, patterns[, options]);
  2920. *
  2921. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  2922. * // true
  2923. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  2924. * // false
  2925. * ```
  2926. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  2927. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  2928. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2929. * @return {Boolean} Returns true if any patterns match `str`
  2930. * @api public
  2931. */
  2932. micromatch.some = (list, patterns, options) => {
  2933. let items = [].concat(list);
  2934. for (let pattern of [].concat(patterns)) {
  2935. let isMatch = picomatch$1(String(pattern), options);
  2936. if (items.some(item => isMatch(item))) {
  2937. return true;
  2938. }
  2939. }
  2940. return false;
  2941. };
  2942. /**
  2943. * Returns true if every string in the given `list` matches
  2944. * any of the given glob `patterns`.
  2945. *
  2946. * ```js
  2947. * const mm = require('micromatch');
  2948. * // mm.every(list, patterns[, options]);
  2949. *
  2950. * console.log(mm.every('foo.js', ['foo.js']));
  2951. * // true
  2952. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  2953. * // true
  2954. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  2955. * // false
  2956. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  2957. * // false
  2958. * ```
  2959. * @param {String|Array} `list` The string or array of strings to test.
  2960. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  2961. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2962. * @return {Boolean} Returns true if any patterns match `str`
  2963. * @api public
  2964. */
  2965. micromatch.every = (list, patterns, options) => {
  2966. let items = [].concat(list);
  2967. for (let pattern of [].concat(patterns)) {
  2968. let isMatch = picomatch$1(String(pattern), options);
  2969. if (!items.every(item => isMatch(item))) {
  2970. return false;
  2971. }
  2972. }
  2973. return true;
  2974. };
  2975. /**
  2976. * Returns true if **all** of the given `patterns` match
  2977. * the specified string.
  2978. *
  2979. * ```js
  2980. * const mm = require('micromatch');
  2981. * // mm.all(string, patterns[, options]);
  2982. *
  2983. * console.log(mm.all('foo.js', ['foo.js']));
  2984. * // true
  2985. *
  2986. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  2987. * // false
  2988. *
  2989. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  2990. * // true
  2991. *
  2992. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  2993. * // true
  2994. * ```
  2995. * @param {String|Array} `str` The string to test.
  2996. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  2997. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2998. * @return {Boolean} Returns true if any patterns match `str`
  2999. * @api public
  3000. */
  3001. micromatch.all = (str, patterns, options) => {
  3002. if (typeof str !== 'string') {
  3003. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  3004. }
  3005. return [].concat(patterns).every(p => picomatch$1(p, options)(str));
  3006. };
  3007. /**
  3008. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  3009. *
  3010. * ```js
  3011. * const mm = require('micromatch');
  3012. * // mm.capture(pattern, string[, options]);
  3013. *
  3014. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  3015. * //=> ['foo']
  3016. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  3017. * //=> null
  3018. * ```
  3019. * @param {String} `glob` Glob pattern to use for matching.
  3020. * @param {String} `input` String to match
  3021. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3022. * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  3023. * @api public
  3024. */
  3025. micromatch.capture = (glob, input, options) => {
  3026. let posix = utils$1.isWindows(options);
  3027. let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, { capture: true }));
  3028. let match = regex.exec(posix ? utils$1.toPosixSlashes(input) : input);
  3029. if (match) {
  3030. return match.slice(1).map(v => v === void 0 ? '' : v);
  3031. }
  3032. };
  3033. /**
  3034. * Create a regular expression from the given glob `pattern`.
  3035. *
  3036. * ```js
  3037. * const mm = require('micromatch');
  3038. * // mm.makeRe(pattern[, options]);
  3039. *
  3040. * console.log(mm.makeRe('*.js'));
  3041. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  3042. * ```
  3043. * @param {String} `pattern` A glob pattern to convert to regex.
  3044. * @param {Object} `options`
  3045. * @return {RegExp} Returns a regex created from the given pattern.
  3046. * @api public
  3047. */
  3048. micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
  3049. /**
  3050. * Scan a glob pattern to separate the pattern into segments. Used
  3051. * by the [split](#split) method.
  3052. *
  3053. * ```js
  3054. * const mm = require('micromatch');
  3055. * const state = mm.scan(pattern[, options]);
  3056. * ```
  3057. * @param {String} `pattern`
  3058. * @param {Object} `options`
  3059. * @return {Object} Returns an object with
  3060. * @api public
  3061. */
  3062. micromatch.scan = (...args) => picomatch$1.scan(...args);
  3063. /**
  3064. * Parse a glob pattern to create the source string for a regular
  3065. * expression.
  3066. *
  3067. * ```js
  3068. * const mm = require('micromatch');
  3069. * const state = mm(pattern[, options]);
  3070. * ```
  3071. * @param {String} `glob`
  3072. * @param {Object} `options`
  3073. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  3074. * @api public
  3075. */
  3076. micromatch.parse = (patterns, options) => {
  3077. let res = [];
  3078. for (let pattern of [].concat(patterns || [])) {
  3079. for (let str of braces_1(String(pattern), options)) {
  3080. res.push(picomatch$1.parse(str, options));
  3081. }
  3082. }
  3083. return res;
  3084. };
  3085. /**
  3086. * Process the given brace `pattern`.
  3087. *
  3088. * ```js
  3089. * const { braces } = require('micromatch');
  3090. * console.log(braces('foo/{a,b,c}/bar'));
  3091. * //=> [ 'foo/(a|b|c)/bar' ]
  3092. *
  3093. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  3094. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  3095. * ```
  3096. * @param {String} `pattern` String with brace pattern to process.
  3097. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  3098. * @return {Array}
  3099. * @api public
  3100. */
  3101. micromatch.braces = (pattern, options) => {
  3102. if (typeof pattern !== 'string')
  3103. throw new TypeError('Expected a string');
  3104. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  3105. return [pattern];
  3106. }
  3107. return braces_1(pattern, options);
  3108. };
  3109. /**
  3110. * Expand braces
  3111. */
  3112. micromatch.braceExpand = (pattern, options) => {
  3113. if (typeof pattern !== 'string')
  3114. throw new TypeError('Expected a string');
  3115. return micromatch.braces(pattern, Object.assign({}, options, { expand: true }));
  3116. };
  3117. /**
  3118. * Expose micromatch
  3119. */
  3120. var micromatch_1 = micromatch;
  3121. function ensureArray(thing) {
  3122. if (Array.isArray(thing))
  3123. return thing;
  3124. if (thing == undefined)
  3125. return [];
  3126. return [thing];
  3127. }
  3128. function getMatcherString(id, resolutionBase) {
  3129. if (resolutionBase === false) {
  3130. return id;
  3131. }
  3132. return resolve(...(typeof resolutionBase === 'string' ? [resolutionBase, id] : [id]));
  3133. }
  3134. const createFilter = function createFilter(include, exclude, options) {
  3135. const resolutionBase = options && options.resolve;
  3136. const getMatcher = (id) => {
  3137. return id instanceof RegExp
  3138. ? id
  3139. : {
  3140. test: micromatch_1.matcher(getMatcherString(id, resolutionBase)
  3141. .split(sep)
  3142. .join('/'), { dot: true })
  3143. };
  3144. };
  3145. const includeMatchers = ensureArray(include).map(getMatcher);
  3146. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  3147. return function (id) {
  3148. if (typeof id !== 'string')
  3149. return false;
  3150. if (/\0/.test(id))
  3151. return false;
  3152. id = id.split(sep).join('/');
  3153. for (let i = 0; i < excludeMatchers.length; ++i) {
  3154. const matcher = excludeMatchers[i];
  3155. if (matcher.test(id))
  3156. return false;
  3157. }
  3158. for (let i = 0; i < includeMatchers.length; ++i) {
  3159. const matcher = includeMatchers[i];
  3160. if (matcher.test(id))
  3161. return true;
  3162. }
  3163. return !includeMatchers.length;
  3164. };
  3165. };
  3166. const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  3167. const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  3168. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  3169. forbiddenIdentifiers.add('');
  3170. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  3171. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, '_');
  3172. if (/\d/.test(str[0]) || forbiddenIdentifiers.has(str)) {
  3173. str = `_${str}`;
  3174. }
  3175. return str || '_';
  3176. };
  3177. function stringify$2(obj) {
  3178. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, char => `\\u${('000' + char.charCodeAt(0).toString(16)).slice(-4)}`);
  3179. }
  3180. function serializeArray(arr, indent, baseIndent) {
  3181. let output = '[';
  3182. const separator = indent ? '\n' + baseIndent + indent : '';
  3183. for (let i = 0; i < arr.length; i++) {
  3184. const key = arr[i];
  3185. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  3186. }
  3187. return output + `${indent ? '\n' + baseIndent : ''}]`;
  3188. }
  3189. function serializeObject(obj, indent, baseIndent) {
  3190. let output = '{';
  3191. const separator = indent ? '\n' + baseIndent + indent : '';
  3192. const keys = Object.keys(obj);
  3193. for (let i = 0; i < keys.length; i++) {
  3194. const key = keys[i];
  3195. const stringKey = makeLegalIdentifier(key) === key ? key : stringify$2(key);
  3196. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(obj[key], indent, baseIndent + indent)}`;
  3197. }
  3198. return output + `${indent ? '\n' + baseIndent : ''}}`;
  3199. }
  3200. function serialize(obj, indent, baseIndent) {
  3201. if (obj === Infinity)
  3202. return 'Infinity';
  3203. if (obj === -Infinity)
  3204. return '-Infinity';
  3205. if (obj === 0 && 1 / obj === -Infinity)
  3206. return '-0';
  3207. if (obj instanceof Date)
  3208. return 'new Date(' + obj.getTime() + ')';
  3209. if (obj instanceof RegExp)
  3210. return obj.toString();
  3211. if (obj !== obj)
  3212. return 'NaN';
  3213. if (Array.isArray(obj))
  3214. return serializeArray(obj, indent, baseIndent);
  3215. if (obj === null)
  3216. return 'null';
  3217. if (typeof obj === 'object')
  3218. return serializeObject(obj, indent, baseIndent);
  3219. return stringify$2(obj);
  3220. }
  3221. const dataToEsm = function dataToEsm(data, options = {}) {
  3222. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  3223. const _ = options.compact ? '' : ' ';
  3224. const n = options.compact ? '' : '\n';
  3225. const declarationType = options.preferConst ? 'const' : 'var';
  3226. if (options.namedExports === false ||
  3227. typeof data !== 'object' ||
  3228. Array.isArray(data) ||
  3229. data instanceof Date ||
  3230. data instanceof RegExp ||
  3231. data === null) {
  3232. const code = serialize(data, options.compact ? null : t, '');
  3233. const __ = _ || (/^[{[\-\/]/.test(code) ? '' : ' ');
  3234. return `export default${__}${code};`;
  3235. }
  3236. let namedExportCode = '';
  3237. const defaultExportRows = [];
  3238. const dataKeys = Object.keys(data);
  3239. for (let i = 0; i < dataKeys.length; i++) {
  3240. const key = dataKeys[i];
  3241. if (key === makeLegalIdentifier(key)) {
  3242. if (options.objectShorthand)
  3243. defaultExportRows.push(key);
  3244. else
  3245. defaultExportRows.push(`${key}:${_}${key}`);
  3246. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(data[key], options.compact ? null : t, '')};${n}`;
  3247. }
  3248. else {
  3249. defaultExportRows.push(`${stringify$2(key)}:${_}${serialize(data[key], options.compact ? null : t, '')}`);
  3250. }
  3251. }
  3252. return (namedExportCode + `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`);
  3253. };
  3254. export { addExtension, attachScopes, createFilter, dataToEsm, extractAssignedNames, makeLegalIdentifier };