index.js 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568
  1. /*
  2. @license
  3. Rollup.js v2.79.1
  4. Thu, 22 Sep 2022 04:55:29 GMT - commit 69ff4181e701a0fe0026d0ba147f31bc86beffa8
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. const rollup = require('./rollup.js');
  10. const require$$0$1 = require('fs');
  11. const require$$2 = require('util');
  12. const require$$1 = require('stream');
  13. const require$$0$2 = require('path');
  14. const require$$2$1 = require('os');
  15. const require$$0$3 = require('events');
  16. var chokidar = {};
  17. const fs$3 = require$$0$1;
  18. const { Readable } = require$$1;
  19. const sysPath$3 = require$$0$2;
  20. const { promisify: promisify$3 } = require$$2;
  21. const picomatch$1 = rollup.picomatch.exports;
  22. const readdir$1 = promisify$3(fs$3.readdir);
  23. const stat$3 = promisify$3(fs$3.stat);
  24. const lstat$2 = promisify$3(fs$3.lstat);
  25. const realpath$1 = promisify$3(fs$3.realpath);
  26. /**
  27. * @typedef {Object} EntryInfo
  28. * @property {String} path
  29. * @property {String} fullPath
  30. * @property {fs.Stats=} stats
  31. * @property {fs.Dirent=} dirent
  32. * @property {String} basename
  33. */
  34. const BANG$2 = '!';
  35. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  36. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  37. const FILE_TYPE = 'files';
  38. const DIR_TYPE = 'directories';
  39. const FILE_DIR_TYPE = 'files_directories';
  40. const EVERYTHING_TYPE = 'all';
  41. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  42. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  43. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  44. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  45. const normalizeFilter = filter => {
  46. if (filter === undefined) return;
  47. if (typeof filter === 'function') return filter;
  48. if (typeof filter === 'string') {
  49. const glob = picomatch$1(filter.trim());
  50. return entry => glob(entry.basename);
  51. }
  52. if (Array.isArray(filter)) {
  53. const positive = [];
  54. const negative = [];
  55. for (const item of filter) {
  56. const trimmed = item.trim();
  57. if (trimmed.charAt(0) === BANG$2) {
  58. negative.push(picomatch$1(trimmed.slice(1)));
  59. } else {
  60. positive.push(picomatch$1(trimmed));
  61. }
  62. }
  63. if (negative.length > 0) {
  64. if (positive.length > 0) {
  65. return entry =>
  66. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  67. }
  68. return entry => !negative.some(f => f(entry.basename));
  69. }
  70. return entry => positive.some(f => f(entry.basename));
  71. }
  72. };
  73. class ReaddirpStream extends Readable {
  74. static get defaultOptions() {
  75. return {
  76. root: '.',
  77. /* eslint-disable no-unused-vars */
  78. fileFilter: (path) => true,
  79. directoryFilter: (path) => true,
  80. /* eslint-enable no-unused-vars */
  81. type: FILE_TYPE,
  82. lstat: false,
  83. depth: 2147483648,
  84. alwaysStat: false
  85. };
  86. }
  87. constructor(options = {}) {
  88. super({
  89. objectMode: true,
  90. autoDestroy: true,
  91. highWaterMark: options.highWaterMark || 4096
  92. });
  93. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  94. const { root, type } = opts;
  95. this._fileFilter = normalizeFilter(opts.fileFilter);
  96. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  97. const statMethod = opts.lstat ? lstat$2 : stat$3;
  98. // Use bigint stats if it's windows and stat() supports options (node 10+).
  99. if (wantBigintFsStats) {
  100. this._stat = path => statMethod(path, { bigint: true });
  101. } else {
  102. this._stat = statMethod;
  103. }
  104. this._maxDepth = opts.depth;
  105. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  106. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  107. this._wantsEverything = type === EVERYTHING_TYPE;
  108. this._root = sysPath$3.resolve(root);
  109. this._isDirent = ('Dirent' in fs$3) && !opts.alwaysStat;
  110. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  111. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  112. // Launch stream with one parent, the root dir.
  113. this.parents = [this._exploreDir(root, 1)];
  114. this.reading = false;
  115. this.parent = undefined;
  116. }
  117. async _read(batch) {
  118. if (this.reading) return;
  119. this.reading = true;
  120. try {
  121. while (!this.destroyed && batch > 0) {
  122. const { path, depth, files = [] } = this.parent || {};
  123. if (files.length > 0) {
  124. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  125. for (const entry of await Promise.all(slice)) {
  126. if (this.destroyed) return;
  127. const entryType = await this._getEntryType(entry);
  128. if (entryType === 'directory' && this._directoryFilter(entry)) {
  129. if (depth <= this._maxDepth) {
  130. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  131. }
  132. if (this._wantsDir) {
  133. this.push(entry);
  134. batch--;
  135. }
  136. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  137. if (this._wantsFile) {
  138. this.push(entry);
  139. batch--;
  140. }
  141. }
  142. }
  143. } else {
  144. const parent = this.parents.pop();
  145. if (!parent) {
  146. this.push(null);
  147. break;
  148. }
  149. this.parent = await parent;
  150. if (this.destroyed) return;
  151. }
  152. }
  153. } catch (error) {
  154. this.destroy(error);
  155. } finally {
  156. this.reading = false;
  157. }
  158. }
  159. async _exploreDir(path, depth) {
  160. let files;
  161. try {
  162. files = await readdir$1(path, this._rdOptions);
  163. } catch (error) {
  164. this._onError(error);
  165. }
  166. return { files, depth, path };
  167. }
  168. async _formatEntry(dirent, path) {
  169. let entry;
  170. try {
  171. const basename = this._isDirent ? dirent.name : dirent;
  172. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  173. entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
  174. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  175. } catch (err) {
  176. this._onError(err);
  177. }
  178. return entry;
  179. }
  180. _onError(err) {
  181. if (isNormalFlowError(err) && !this.destroyed) {
  182. this.emit('warn', err);
  183. } else {
  184. this.destroy(err);
  185. }
  186. }
  187. async _getEntryType(entry) {
  188. // entry may be undefined, because a warning or an error were emitted
  189. // and the statsProp is undefined
  190. const stats = entry && entry[this._statsProp];
  191. if (!stats) {
  192. return;
  193. }
  194. if (stats.isFile()) {
  195. return 'file';
  196. }
  197. if (stats.isDirectory()) {
  198. return 'directory';
  199. }
  200. if (stats && stats.isSymbolicLink()) {
  201. const full = entry.fullPath;
  202. try {
  203. const entryRealPath = await realpath$1(full);
  204. const entryRealPathStats = await lstat$2(entryRealPath);
  205. if (entryRealPathStats.isFile()) {
  206. return 'file';
  207. }
  208. if (entryRealPathStats.isDirectory()) {
  209. const len = entryRealPath.length;
  210. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  211. const recursiveError = new Error(
  212. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  213. );
  214. recursiveError.code = RECURSIVE_ERROR_CODE;
  215. return this._onError(recursiveError);
  216. }
  217. return 'directory';
  218. }
  219. } catch (error) {
  220. this._onError(error);
  221. }
  222. }
  223. }
  224. _includeAsFile(entry) {
  225. const stats = entry && entry[this._statsProp];
  226. return stats && this._wantsEverything && !stats.isDirectory();
  227. }
  228. }
  229. /**
  230. * @typedef {Object} ReaddirpArguments
  231. * @property {Function=} fileFilter
  232. * @property {Function=} directoryFilter
  233. * @property {String=} type
  234. * @property {Number=} depth
  235. * @property {String=} root
  236. * @property {Boolean=} lstat
  237. * @property {Boolean=} bigint
  238. */
  239. /**
  240. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  241. * @param {String} root Root directory
  242. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  243. */
  244. const readdirp$1 = (root, options = {}) => {
  245. let type = options.entryType || options.type;
  246. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  247. if (type) options.type = type;
  248. if (!root) {
  249. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  250. } else if (typeof root !== 'string') {
  251. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  252. } else if (type && !ALL_TYPES.includes(type)) {
  253. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  254. }
  255. options.root = root;
  256. return new ReaddirpStream(options);
  257. };
  258. const readdirpPromise = (root, options = {}) => {
  259. return new Promise((resolve, reject) => {
  260. const files = [];
  261. readdirp$1(root, options)
  262. .on('data', entry => files.push(entry))
  263. .on('end', () => resolve(files))
  264. .on('error', error => reject(error));
  265. });
  266. };
  267. readdirp$1.promise = readdirpPromise;
  268. readdirp$1.ReaddirpStream = ReaddirpStream;
  269. readdirp$1.default = readdirp$1;
  270. var readdirp_1 = readdirp$1;
  271. var anymatch$2 = {exports: {}};
  272. /*!
  273. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  274. *
  275. * Copyright (c) 2014-2018, Jon Schlinkert.
  276. * Released under the MIT License.
  277. */
  278. var normalizePath$2 = function(path, stripTrailing) {
  279. if (typeof path !== 'string') {
  280. throw new TypeError('expected path to be a string');
  281. }
  282. if (path === '\\' || path === '/') return '/';
  283. var len = path.length;
  284. if (len <= 1) return path;
  285. // ensure that win32 namespaces has two leading slashes, so that the path is
  286. // handled properly by the win32 version of path.parse() after being normalized
  287. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  288. var prefix = '';
  289. if (len > 4 && path[3] === '\\') {
  290. var ch = path[2];
  291. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  292. path = path.slice(2);
  293. prefix = '//';
  294. }
  295. }
  296. var segs = path.split(/[/\\]+/);
  297. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  298. segs.pop();
  299. }
  300. return prefix + segs.join('/');
  301. };
  302. Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
  303. const picomatch = rollup.picomatch.exports;
  304. const normalizePath$1 = normalizePath$2;
  305. /**
  306. * @typedef {(testString: string) => boolean} AnymatchFn
  307. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  308. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  309. */
  310. const BANG$1 = '!';
  311. const DEFAULT_OPTIONS = {returnIndex: false};
  312. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  313. /**
  314. * @param {AnymatchPattern} matcher
  315. * @param {object} options
  316. * @returns {AnymatchFn}
  317. */
  318. const createPattern = (matcher, options) => {
  319. if (typeof matcher === 'function') {
  320. return matcher;
  321. }
  322. if (typeof matcher === 'string') {
  323. const glob = picomatch(matcher, options);
  324. return (string) => matcher === string || glob(string);
  325. }
  326. if (matcher instanceof RegExp) {
  327. return (string) => matcher.test(string);
  328. }
  329. return (string) => false;
  330. };
  331. /**
  332. * @param {Array<Function>} patterns
  333. * @param {Array<Function>} negPatterns
  334. * @param {String|Array} args
  335. * @param {Boolean} returnIndex
  336. * @returns {boolean|number}
  337. */
  338. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  339. const isList = Array.isArray(args);
  340. const _path = isList ? args[0] : args;
  341. if (!isList && typeof _path !== 'string') {
  342. throw new TypeError('anymatch: second argument must be a string: got ' +
  343. Object.prototype.toString.call(_path))
  344. }
  345. const path = normalizePath$1(_path);
  346. for (let index = 0; index < negPatterns.length; index++) {
  347. const nglob = negPatterns[index];
  348. if (nglob(path)) {
  349. return returnIndex ? -1 : false;
  350. }
  351. }
  352. const applied = isList && [path].concat(args.slice(1));
  353. for (let index = 0; index < patterns.length; index++) {
  354. const pattern = patterns[index];
  355. if (isList ? pattern(...applied) : pattern(path)) {
  356. return returnIndex ? index : true;
  357. }
  358. }
  359. return returnIndex ? -1 : false;
  360. };
  361. /**
  362. * @param {AnymatchMatcher} matchers
  363. * @param {Array|string} testString
  364. * @param {object} options
  365. * @returns {boolean|number|Function}
  366. */
  367. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  368. if (matchers == null) {
  369. throw new TypeError('anymatch: specify first argument');
  370. }
  371. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  372. const returnIndex = opts.returnIndex || false;
  373. // Early cache for matchers.
  374. const mtchers = arrify$1(matchers);
  375. const negatedGlobs = mtchers
  376. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  377. .map(item => item.slice(1))
  378. .map(item => picomatch(item, opts));
  379. const patterns = mtchers
  380. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
  381. .map(matcher => createPattern(matcher, opts));
  382. if (testString == null) {
  383. return (testString, ri = false) => {
  384. const returnIndex = typeof ri === 'boolean' ? ri : false;
  385. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  386. }
  387. }
  388. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  389. };
  390. anymatch$1.default = anymatch$1;
  391. anymatch$2.exports = anymatch$1;
  392. /*!
  393. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  394. *
  395. * Copyright (c) 2014-2016, Jon Schlinkert.
  396. * Licensed under the MIT License.
  397. */
  398. var isExtglob$1 = function isExtglob(str) {
  399. if (typeof str !== 'string' || str === '') {
  400. return false;
  401. }
  402. var match;
  403. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  404. if (match[2]) return true;
  405. str = str.slice(match.index + match[0].length);
  406. }
  407. return false;
  408. };
  409. /*!
  410. * is-glob <https://github.com/jonschlinkert/is-glob>
  411. *
  412. * Copyright (c) 2014-2017, Jon Schlinkert.
  413. * Released under the MIT License.
  414. */
  415. var isExtglob = isExtglob$1;
  416. var chars = { '{': '}', '(': ')', '[': ']'};
  417. var strictCheck = function(str) {
  418. if (str[0] === '!') {
  419. return true;
  420. }
  421. var index = 0;
  422. var pipeIndex = -2;
  423. var closeSquareIndex = -2;
  424. var closeCurlyIndex = -2;
  425. var closeParenIndex = -2;
  426. var backSlashIndex = -2;
  427. while (index < str.length) {
  428. if (str[index] === '*') {
  429. return true;
  430. }
  431. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  432. return true;
  433. }
  434. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  435. if (closeSquareIndex < index) {
  436. closeSquareIndex = str.indexOf(']', index);
  437. }
  438. if (closeSquareIndex > index) {
  439. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  440. return true;
  441. }
  442. backSlashIndex = str.indexOf('\\', index);
  443. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  444. return true;
  445. }
  446. }
  447. }
  448. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  449. closeCurlyIndex = str.indexOf('}', index);
  450. if (closeCurlyIndex > index) {
  451. backSlashIndex = str.indexOf('\\', index);
  452. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  453. return true;
  454. }
  455. }
  456. }
  457. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  458. closeParenIndex = str.indexOf(')', index);
  459. if (closeParenIndex > index) {
  460. backSlashIndex = str.indexOf('\\', index);
  461. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  462. return true;
  463. }
  464. }
  465. }
  466. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  467. if (pipeIndex < index) {
  468. pipeIndex = str.indexOf('|', index);
  469. }
  470. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  471. closeParenIndex = str.indexOf(')', pipeIndex);
  472. if (closeParenIndex > pipeIndex) {
  473. backSlashIndex = str.indexOf('\\', pipeIndex);
  474. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  475. return true;
  476. }
  477. }
  478. }
  479. }
  480. if (str[index] === '\\') {
  481. var open = str[index + 1];
  482. index += 2;
  483. var close = chars[open];
  484. if (close) {
  485. var n = str.indexOf(close, index);
  486. if (n !== -1) {
  487. index = n + 1;
  488. }
  489. }
  490. if (str[index] === '!') {
  491. return true;
  492. }
  493. } else {
  494. index++;
  495. }
  496. }
  497. return false;
  498. };
  499. var relaxedCheck = function(str) {
  500. if (str[0] === '!') {
  501. return true;
  502. }
  503. var index = 0;
  504. while (index < str.length) {
  505. if (/[*?{}()[\]]/.test(str[index])) {
  506. return true;
  507. }
  508. if (str[index] === '\\') {
  509. var open = str[index + 1];
  510. index += 2;
  511. var close = chars[open];
  512. if (close) {
  513. var n = str.indexOf(close, index);
  514. if (n !== -1) {
  515. index = n + 1;
  516. }
  517. }
  518. if (str[index] === '!') {
  519. return true;
  520. }
  521. } else {
  522. index++;
  523. }
  524. }
  525. return false;
  526. };
  527. var isGlob$2 = function isGlob(str, options) {
  528. if (typeof str !== 'string' || str === '') {
  529. return false;
  530. }
  531. if (isExtglob(str)) {
  532. return true;
  533. }
  534. var check = strictCheck;
  535. // optionally relax check
  536. if (options && options.strict === false) {
  537. check = relaxedCheck;
  538. }
  539. return check(str);
  540. };
  541. var isGlob$1 = isGlob$2;
  542. var pathPosixDirname = require$$0$2.posix.dirname;
  543. var isWin32 = require$$2$1.platform() === 'win32';
  544. var slash = '/';
  545. var backslash = /\\/g;
  546. var enclosure = /[\{\[].*[\}\]]$/;
  547. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  548. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  549. /**
  550. * @param {string} str
  551. * @param {Object} opts
  552. * @param {boolean} [opts.flipBackslashes=true]
  553. * @returns {string}
  554. */
  555. var globParent$1 = function globParent(str, opts) {
  556. var options = Object.assign({ flipBackslashes: true }, opts);
  557. // flip windows path separators
  558. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  559. str = str.replace(backslash, slash);
  560. }
  561. // special case for strings ending in enclosure containing path separator
  562. if (enclosure.test(str)) {
  563. str += slash;
  564. }
  565. // preserves full path in case of trailing path separator
  566. str += 'a';
  567. // remove path parts that are globby
  568. do {
  569. str = pathPosixDirname(str);
  570. } while (isGlob$1(str) || globby.test(str));
  571. // remove escape chars and return result
  572. return str.replace(escaped, '$1');
  573. };
  574. var utils$3 = {};
  575. (function (exports) {
  576. exports.isInteger = num => {
  577. if (typeof num === 'number') {
  578. return Number.isInteger(num);
  579. }
  580. if (typeof num === 'string' && num.trim() !== '') {
  581. return Number.isInteger(Number(num));
  582. }
  583. return false;
  584. };
  585. /**
  586. * Find a node of the given type
  587. */
  588. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  589. /**
  590. * Find a node of the given type
  591. */
  592. exports.exceedsLimit = (min, max, step = 1, limit) => {
  593. if (limit === false) return false;
  594. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  595. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  596. };
  597. /**
  598. * Escape the given node with '\\' before node.value
  599. */
  600. exports.escapeNode = (block, n = 0, type) => {
  601. let node = block.nodes[n];
  602. if (!node) return;
  603. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  604. if (node.escaped !== true) {
  605. node.value = '\\' + node.value;
  606. node.escaped = true;
  607. }
  608. }
  609. };
  610. /**
  611. * Returns true if the given brace node should be enclosed in literal braces
  612. */
  613. exports.encloseBrace = node => {
  614. if (node.type !== 'brace') return false;
  615. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  616. node.invalid = true;
  617. return true;
  618. }
  619. return false;
  620. };
  621. /**
  622. * Returns true if a brace node is invalid.
  623. */
  624. exports.isInvalidBrace = block => {
  625. if (block.type !== 'brace') return false;
  626. if (block.invalid === true || block.dollar) return true;
  627. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  628. block.invalid = true;
  629. return true;
  630. }
  631. if (block.open !== true || block.close !== true) {
  632. block.invalid = true;
  633. return true;
  634. }
  635. return false;
  636. };
  637. /**
  638. * Returns true if a node is an open or close node
  639. */
  640. exports.isOpenOrClose = node => {
  641. if (node.type === 'open' || node.type === 'close') {
  642. return true;
  643. }
  644. return node.open === true || node.close === true;
  645. };
  646. /**
  647. * Reduce an array of text nodes.
  648. */
  649. exports.reduce = nodes => nodes.reduce((acc, node) => {
  650. if (node.type === 'text') acc.push(node.value);
  651. if (node.type === 'range') node.type = 'text';
  652. return acc;
  653. }, []);
  654. /**
  655. * Flatten an array
  656. */
  657. exports.flatten = (...args) => {
  658. const result = [];
  659. const flat = arr => {
  660. for (let i = 0; i < arr.length; i++) {
  661. let ele = arr[i];
  662. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  663. }
  664. return result;
  665. };
  666. flat(args);
  667. return result;
  668. };
  669. } (utils$3));
  670. const utils$2 = utils$3;
  671. var stringify$4 = (ast, options = {}) => {
  672. let stringify = (node, parent = {}) => {
  673. let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);
  674. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  675. let output = '';
  676. if (node.value) {
  677. if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {
  678. return '\\' + node.value;
  679. }
  680. return node.value;
  681. }
  682. if (node.value) {
  683. return node.value;
  684. }
  685. if (node.nodes) {
  686. for (let child of node.nodes) {
  687. output += stringify(child);
  688. }
  689. }
  690. return output;
  691. };
  692. return stringify(ast);
  693. };
  694. /*!
  695. * is-number <https://github.com/jonschlinkert/is-number>
  696. *
  697. * Copyright (c) 2014-present, Jon Schlinkert.
  698. * Released under the MIT License.
  699. */
  700. var isNumber$2 = function(num) {
  701. if (typeof num === 'number') {
  702. return num - num === 0;
  703. }
  704. if (typeof num === 'string' && num.trim() !== '') {
  705. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  706. }
  707. return false;
  708. };
  709. /*!
  710. * to-regex-range <https://github.com/micromatch/to-regex-range>
  711. *
  712. * Copyright (c) 2015-present, Jon Schlinkert.
  713. * Released under the MIT License.
  714. */
  715. const isNumber$1 = isNumber$2;
  716. const toRegexRange$1 = (min, max, options) => {
  717. if (isNumber$1(min) === false) {
  718. throw new TypeError('toRegexRange: expected the first argument to be a number');
  719. }
  720. if (max === void 0 || min === max) {
  721. return String(min);
  722. }
  723. if (isNumber$1(max) === false) {
  724. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  725. }
  726. let opts = { relaxZeros: true, ...options };
  727. if (typeof opts.strictZeros === 'boolean') {
  728. opts.relaxZeros = opts.strictZeros === false;
  729. }
  730. let relax = String(opts.relaxZeros);
  731. let shorthand = String(opts.shorthand);
  732. let capture = String(opts.capture);
  733. let wrap = String(opts.wrap);
  734. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  735. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  736. return toRegexRange$1.cache[cacheKey].result;
  737. }
  738. let a = Math.min(min, max);
  739. let b = Math.max(min, max);
  740. if (Math.abs(a - b) === 1) {
  741. let result = min + '|' + max;
  742. if (opts.capture) {
  743. return `(${result})`;
  744. }
  745. if (opts.wrap === false) {
  746. return result;
  747. }
  748. return `(?:${result})`;
  749. }
  750. let isPadded = hasPadding(min) || hasPadding(max);
  751. let state = { min, max, a, b };
  752. let positives = [];
  753. let negatives = [];
  754. if (isPadded) {
  755. state.isPadded = isPadded;
  756. state.maxLen = String(state.max).length;
  757. }
  758. if (a < 0) {
  759. let newMin = b < 0 ? Math.abs(b) : 1;
  760. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  761. a = state.a = 0;
  762. }
  763. if (b >= 0) {
  764. positives = splitToPatterns(a, b, state, opts);
  765. }
  766. state.negatives = negatives;
  767. state.positives = positives;
  768. state.result = collatePatterns(negatives, positives);
  769. if (opts.capture === true) {
  770. state.result = `(${state.result})`;
  771. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  772. state.result = `(?:${state.result})`;
  773. }
  774. toRegexRange$1.cache[cacheKey] = state;
  775. return state.result;
  776. };
  777. function collatePatterns(neg, pos, options) {
  778. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  779. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  780. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  781. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  782. return subpatterns.join('|');
  783. }
  784. function splitToRanges(min, max) {
  785. let nines = 1;
  786. let zeros = 1;
  787. let stop = countNines(min, nines);
  788. let stops = new Set([max]);
  789. while (min <= stop && stop <= max) {
  790. stops.add(stop);
  791. nines += 1;
  792. stop = countNines(min, nines);
  793. }
  794. stop = countZeros(max + 1, zeros) - 1;
  795. while (min < stop && stop <= max) {
  796. stops.add(stop);
  797. zeros += 1;
  798. stop = countZeros(max + 1, zeros) - 1;
  799. }
  800. stops = [...stops];
  801. stops.sort(compare);
  802. return stops;
  803. }
  804. /**
  805. * Convert a range to a regex pattern
  806. * @param {Number} `start`
  807. * @param {Number} `stop`
  808. * @return {String}
  809. */
  810. function rangeToPattern(start, stop, options) {
  811. if (start === stop) {
  812. return { pattern: start, count: [], digits: 0 };
  813. }
  814. let zipped = zip(start, stop);
  815. let digits = zipped.length;
  816. let pattern = '';
  817. let count = 0;
  818. for (let i = 0; i < digits; i++) {
  819. let [startDigit, stopDigit] = zipped[i];
  820. if (startDigit === stopDigit) {
  821. pattern += startDigit;
  822. } else if (startDigit !== '0' || stopDigit !== '9') {
  823. pattern += toCharacterClass(startDigit, stopDigit);
  824. } else {
  825. count++;
  826. }
  827. }
  828. if (count) {
  829. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  830. }
  831. return { pattern, count: [count], digits };
  832. }
  833. function splitToPatterns(min, max, tok, options) {
  834. let ranges = splitToRanges(min, max);
  835. let tokens = [];
  836. let start = min;
  837. let prev;
  838. for (let i = 0; i < ranges.length; i++) {
  839. let max = ranges[i];
  840. let obj = rangeToPattern(String(start), String(max), options);
  841. let zeros = '';
  842. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  843. if (prev.count.length > 1) {
  844. prev.count.pop();
  845. }
  846. prev.count.push(obj.count[0]);
  847. prev.string = prev.pattern + toQuantifier(prev.count);
  848. start = max + 1;
  849. continue;
  850. }
  851. if (tok.isPadded) {
  852. zeros = padZeros(max, tok, options);
  853. }
  854. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  855. tokens.push(obj);
  856. start = max + 1;
  857. prev = obj;
  858. }
  859. return tokens;
  860. }
  861. function filterPatterns(arr, comparison, prefix, intersection, options) {
  862. let result = [];
  863. for (let ele of arr) {
  864. let { string } = ele;
  865. // only push if _both_ are negative...
  866. if (!intersection && !contains(comparison, 'string', string)) {
  867. result.push(prefix + string);
  868. }
  869. // or _both_ are positive
  870. if (intersection && contains(comparison, 'string', string)) {
  871. result.push(prefix + string);
  872. }
  873. }
  874. return result;
  875. }
  876. /**
  877. * Zip strings
  878. */
  879. function zip(a, b) {
  880. let arr = [];
  881. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  882. return arr;
  883. }
  884. function compare(a, b) {
  885. return a > b ? 1 : b > a ? -1 : 0;
  886. }
  887. function contains(arr, key, val) {
  888. return arr.some(ele => ele[key] === val);
  889. }
  890. function countNines(min, len) {
  891. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  892. }
  893. function countZeros(integer, zeros) {
  894. return integer - (integer % Math.pow(10, zeros));
  895. }
  896. function toQuantifier(digits) {
  897. let [start = 0, stop = ''] = digits;
  898. if (stop || start > 1) {
  899. return `{${start + (stop ? ',' + stop : '')}}`;
  900. }
  901. return '';
  902. }
  903. function toCharacterClass(a, b, options) {
  904. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  905. }
  906. function hasPadding(str) {
  907. return /^-?(0+)\d/.test(str);
  908. }
  909. function padZeros(value, tok, options) {
  910. if (!tok.isPadded) {
  911. return value;
  912. }
  913. let diff = Math.abs(tok.maxLen - String(value).length);
  914. let relax = options.relaxZeros !== false;
  915. switch (diff) {
  916. case 0:
  917. return '';
  918. case 1:
  919. return relax ? '0?' : '0';
  920. case 2:
  921. return relax ? '0{0,2}' : '00';
  922. default: {
  923. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  924. }
  925. }
  926. }
  927. /**
  928. * Cache
  929. */
  930. toRegexRange$1.cache = {};
  931. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  932. /**
  933. * Expose `toRegexRange`
  934. */
  935. var toRegexRange_1 = toRegexRange$1;
  936. /*!
  937. * fill-range <https://github.com/jonschlinkert/fill-range>
  938. *
  939. * Copyright (c) 2014-present, Jon Schlinkert.
  940. * Licensed under the MIT License.
  941. */
  942. const util = require$$2;
  943. const toRegexRange = toRegexRange_1;
  944. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  945. const transform = toNumber => {
  946. return value => toNumber === true ? Number(value) : String(value);
  947. };
  948. const isValidValue = value => {
  949. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  950. };
  951. const isNumber = num => Number.isInteger(+num);
  952. const zeros = input => {
  953. let value = `${input}`;
  954. let index = -1;
  955. if (value[0] === '-') value = value.slice(1);
  956. if (value === '0') return false;
  957. while (value[++index] === '0');
  958. return index > 0;
  959. };
  960. const stringify$3 = (start, end, options) => {
  961. if (typeof start === 'string' || typeof end === 'string') {
  962. return true;
  963. }
  964. return options.stringify === true;
  965. };
  966. const pad = (input, maxLength, toNumber) => {
  967. if (maxLength > 0) {
  968. let dash = input[0] === '-' ? '-' : '';
  969. if (dash) input = input.slice(1);
  970. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  971. }
  972. if (toNumber === false) {
  973. return String(input);
  974. }
  975. return input;
  976. };
  977. const toMaxLen = (input, maxLength) => {
  978. let negative = input[0] === '-' ? '-' : '';
  979. if (negative) {
  980. input = input.slice(1);
  981. maxLength--;
  982. }
  983. while (input.length < maxLength) input = '0' + input;
  984. return negative ? ('-' + input) : input;
  985. };
  986. const toSequence = (parts, options) => {
  987. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  988. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  989. let prefix = options.capture ? '' : '?:';
  990. let positives = '';
  991. let negatives = '';
  992. let result;
  993. if (parts.positives.length) {
  994. positives = parts.positives.join('|');
  995. }
  996. if (parts.negatives.length) {
  997. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  998. }
  999. if (positives && negatives) {
  1000. result = `${positives}|${negatives}`;
  1001. } else {
  1002. result = positives || negatives;
  1003. }
  1004. if (options.wrap) {
  1005. return `(${prefix}${result})`;
  1006. }
  1007. return result;
  1008. };
  1009. const toRange = (a, b, isNumbers, options) => {
  1010. if (isNumbers) {
  1011. return toRegexRange(a, b, { wrap: false, ...options });
  1012. }
  1013. let start = String.fromCharCode(a);
  1014. if (a === b) return start;
  1015. let stop = String.fromCharCode(b);
  1016. return `[${start}-${stop}]`;
  1017. };
  1018. const toRegex = (start, end, options) => {
  1019. if (Array.isArray(start)) {
  1020. let wrap = options.wrap === true;
  1021. let prefix = options.capture ? '' : '?:';
  1022. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  1023. }
  1024. return toRegexRange(start, end, options);
  1025. };
  1026. const rangeError = (...args) => {
  1027. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  1028. };
  1029. const invalidRange = (start, end, options) => {
  1030. if (options.strictRanges === true) throw rangeError([start, end]);
  1031. return [];
  1032. };
  1033. const invalidStep = (step, options) => {
  1034. if (options.strictRanges === true) {
  1035. throw new TypeError(`Expected step "${step}" to be a number`);
  1036. }
  1037. return [];
  1038. };
  1039. const fillNumbers = (start, end, step = 1, options = {}) => {
  1040. let a = Number(start);
  1041. let b = Number(end);
  1042. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  1043. if (options.strictRanges === true) throw rangeError([start, end]);
  1044. return [];
  1045. }
  1046. // fix negative zero
  1047. if (a === 0) a = 0;
  1048. if (b === 0) b = 0;
  1049. let descending = a > b;
  1050. let startString = String(start);
  1051. let endString = String(end);
  1052. let stepString = String(step);
  1053. step = Math.max(Math.abs(step), 1);
  1054. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  1055. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  1056. let toNumber = padded === false && stringify$3(start, end, options) === false;
  1057. let format = options.transform || transform(toNumber);
  1058. if (options.toRegex && step === 1) {
  1059. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  1060. }
  1061. let parts = { negatives: [], positives: [] };
  1062. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  1063. let range = [];
  1064. let index = 0;
  1065. while (descending ? a >= b : a <= b) {
  1066. if (options.toRegex === true && step > 1) {
  1067. push(a);
  1068. } else {
  1069. range.push(pad(format(a, index), maxLen, toNumber));
  1070. }
  1071. a = descending ? a - step : a + step;
  1072. index++;
  1073. }
  1074. if (options.toRegex === true) {
  1075. return step > 1
  1076. ? toSequence(parts, options)
  1077. : toRegex(range, null, { wrap: false, ...options });
  1078. }
  1079. return range;
  1080. };
  1081. const fillLetters = (start, end, step = 1, options = {}) => {
  1082. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  1083. return invalidRange(start, end, options);
  1084. }
  1085. let format = options.transform || (val => String.fromCharCode(val));
  1086. let a = `${start}`.charCodeAt(0);
  1087. let b = `${end}`.charCodeAt(0);
  1088. let descending = a > b;
  1089. let min = Math.min(a, b);
  1090. let max = Math.max(a, b);
  1091. if (options.toRegex && step === 1) {
  1092. return toRange(min, max, false, options);
  1093. }
  1094. let range = [];
  1095. let index = 0;
  1096. while (descending ? a >= b : a <= b) {
  1097. range.push(format(a, index));
  1098. a = descending ? a - step : a + step;
  1099. index++;
  1100. }
  1101. if (options.toRegex === true) {
  1102. return toRegex(range, null, { wrap: false, options });
  1103. }
  1104. return range;
  1105. };
  1106. const fill$2 = (start, end, step, options = {}) => {
  1107. if (end == null && isValidValue(start)) {
  1108. return [start];
  1109. }
  1110. if (!isValidValue(start) || !isValidValue(end)) {
  1111. return invalidRange(start, end, options);
  1112. }
  1113. if (typeof step === 'function') {
  1114. return fill$2(start, end, 1, { transform: step });
  1115. }
  1116. if (isObject(step)) {
  1117. return fill$2(start, end, 0, step);
  1118. }
  1119. let opts = { ...options };
  1120. if (opts.capture === true) opts.wrap = true;
  1121. step = step || opts.step || 1;
  1122. if (!isNumber(step)) {
  1123. if (step != null && !isObject(step)) return invalidStep(step, opts);
  1124. return fill$2(start, end, 1, step);
  1125. }
  1126. if (isNumber(start) && isNumber(end)) {
  1127. return fillNumbers(start, end, step, opts);
  1128. }
  1129. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  1130. };
  1131. var fillRange = fill$2;
  1132. const fill$1 = fillRange;
  1133. const utils$1 = utils$3;
  1134. const compile$1 = (ast, options = {}) => {
  1135. let walk = (node, parent = {}) => {
  1136. let invalidBlock = utils$1.isInvalidBrace(parent);
  1137. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  1138. let invalid = invalidBlock === true || invalidNode === true;
  1139. let prefix = options.escapeInvalid === true ? '\\' : '';
  1140. let output = '';
  1141. if (node.isOpen === true) {
  1142. return prefix + node.value;
  1143. }
  1144. if (node.isClose === true) {
  1145. return prefix + node.value;
  1146. }
  1147. if (node.type === 'open') {
  1148. return invalid ? (prefix + node.value) : '(';
  1149. }
  1150. if (node.type === 'close') {
  1151. return invalid ? (prefix + node.value) : ')';
  1152. }
  1153. if (node.type === 'comma') {
  1154. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  1155. }
  1156. if (node.value) {
  1157. return node.value;
  1158. }
  1159. if (node.nodes && node.ranges > 0) {
  1160. let args = utils$1.reduce(node.nodes);
  1161. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  1162. if (range.length !== 0) {
  1163. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  1164. }
  1165. }
  1166. if (node.nodes) {
  1167. for (let child of node.nodes) {
  1168. output += walk(child, node);
  1169. }
  1170. }
  1171. return output;
  1172. };
  1173. return walk(ast);
  1174. };
  1175. var compile_1 = compile$1;
  1176. const fill = fillRange;
  1177. const stringify$2 = stringify$4;
  1178. const utils = utils$3;
  1179. const append = (queue = '', stash = '', enclose = false) => {
  1180. let result = [];
  1181. queue = [].concat(queue);
  1182. stash = [].concat(stash);
  1183. if (!stash.length) return queue;
  1184. if (!queue.length) {
  1185. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  1186. }
  1187. for (let item of queue) {
  1188. if (Array.isArray(item)) {
  1189. for (let value of item) {
  1190. result.push(append(value, stash, enclose));
  1191. }
  1192. } else {
  1193. for (let ele of stash) {
  1194. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  1195. result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
  1196. }
  1197. }
  1198. }
  1199. return utils.flatten(result);
  1200. };
  1201. const expand$1 = (ast, options = {}) => {
  1202. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  1203. let walk = (node, parent = {}) => {
  1204. node.queue = [];
  1205. let p = parent;
  1206. let q = parent.queue;
  1207. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  1208. p = p.parent;
  1209. q = p.queue;
  1210. }
  1211. if (node.invalid || node.dollar) {
  1212. q.push(append(q.pop(), stringify$2(node, options)));
  1213. return;
  1214. }
  1215. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  1216. q.push(append(q.pop(), ['{}']));
  1217. return;
  1218. }
  1219. if (node.nodes && node.ranges > 0) {
  1220. let args = utils.reduce(node.nodes);
  1221. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  1222. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  1223. }
  1224. let range = fill(...args, options);
  1225. if (range.length === 0) {
  1226. range = stringify$2(node, options);
  1227. }
  1228. q.push(append(q.pop(), range));
  1229. node.nodes = [];
  1230. return;
  1231. }
  1232. let enclose = utils.encloseBrace(node);
  1233. let queue = node.queue;
  1234. let block = node;
  1235. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  1236. block = block.parent;
  1237. queue = block.queue;
  1238. }
  1239. for (let i = 0; i < node.nodes.length; i++) {
  1240. let child = node.nodes[i];
  1241. if (child.type === 'comma' && node.type === 'brace') {
  1242. if (i === 1) queue.push('');
  1243. queue.push('');
  1244. continue;
  1245. }
  1246. if (child.type === 'close') {
  1247. q.push(append(q.pop(), queue, enclose));
  1248. continue;
  1249. }
  1250. if (child.value && child.type !== 'open') {
  1251. queue.push(append(queue.pop(), child.value));
  1252. continue;
  1253. }
  1254. if (child.nodes) {
  1255. walk(child, node);
  1256. }
  1257. }
  1258. return queue;
  1259. };
  1260. return utils.flatten(walk(ast));
  1261. };
  1262. var expand_1 = expand$1;
  1263. var constants$1 = {
  1264. MAX_LENGTH: 1024 * 64,
  1265. // Digits
  1266. CHAR_0: '0', /* 0 */
  1267. CHAR_9: '9', /* 9 */
  1268. // Alphabet chars.
  1269. CHAR_UPPERCASE_A: 'A', /* A */
  1270. CHAR_LOWERCASE_A: 'a', /* a */
  1271. CHAR_UPPERCASE_Z: 'Z', /* Z */
  1272. CHAR_LOWERCASE_Z: 'z', /* z */
  1273. CHAR_LEFT_PARENTHESES: '(', /* ( */
  1274. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  1275. CHAR_ASTERISK: '*', /* * */
  1276. // Non-alphabetic chars.
  1277. CHAR_AMPERSAND: '&', /* & */
  1278. CHAR_AT: '@', /* @ */
  1279. CHAR_BACKSLASH: '\\', /* \ */
  1280. CHAR_BACKTICK: '`', /* ` */
  1281. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  1282. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  1283. CHAR_COLON: ':', /* : */
  1284. CHAR_COMMA: ',', /* , */
  1285. CHAR_DOLLAR: '$', /* . */
  1286. CHAR_DOT: '.', /* . */
  1287. CHAR_DOUBLE_QUOTE: '"', /* " */
  1288. CHAR_EQUAL: '=', /* = */
  1289. CHAR_EXCLAMATION_MARK: '!', /* ! */
  1290. CHAR_FORM_FEED: '\f', /* \f */
  1291. CHAR_FORWARD_SLASH: '/', /* / */
  1292. CHAR_HASH: '#', /* # */
  1293. CHAR_HYPHEN_MINUS: '-', /* - */
  1294. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  1295. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  1296. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  1297. CHAR_LINE_FEED: '\n', /* \n */
  1298. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  1299. CHAR_PERCENT: '%', /* % */
  1300. CHAR_PLUS: '+', /* + */
  1301. CHAR_QUESTION_MARK: '?', /* ? */
  1302. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  1303. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  1304. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  1305. CHAR_SEMICOLON: ';', /* ; */
  1306. CHAR_SINGLE_QUOTE: '\'', /* ' */
  1307. CHAR_SPACE: ' ', /* */
  1308. CHAR_TAB: '\t', /* \t */
  1309. CHAR_UNDERSCORE: '_', /* _ */
  1310. CHAR_VERTICAL_LINE: '|', /* | */
  1311. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  1312. };
  1313. const stringify$1 = stringify$4;
  1314. /**
  1315. * Constants
  1316. */
  1317. const {
  1318. MAX_LENGTH,
  1319. CHAR_BACKSLASH, /* \ */
  1320. CHAR_BACKTICK, /* ` */
  1321. CHAR_COMMA, /* , */
  1322. CHAR_DOT, /* . */
  1323. CHAR_LEFT_PARENTHESES, /* ( */
  1324. CHAR_RIGHT_PARENTHESES, /* ) */
  1325. CHAR_LEFT_CURLY_BRACE, /* { */
  1326. CHAR_RIGHT_CURLY_BRACE, /* } */
  1327. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1328. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  1329. CHAR_DOUBLE_QUOTE, /* " */
  1330. CHAR_SINGLE_QUOTE, /* ' */
  1331. CHAR_NO_BREAK_SPACE,
  1332. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  1333. } = constants$1;
  1334. /**
  1335. * parse
  1336. */
  1337. const parse$1 = (input, options = {}) => {
  1338. if (typeof input !== 'string') {
  1339. throw new TypeError('Expected a string');
  1340. }
  1341. let opts = options || {};
  1342. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1343. if (input.length > max) {
  1344. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  1345. }
  1346. let ast = { type: 'root', input, nodes: [] };
  1347. let stack = [ast];
  1348. let block = ast;
  1349. let prev = ast;
  1350. let brackets = 0;
  1351. let length = input.length;
  1352. let index = 0;
  1353. let depth = 0;
  1354. let value;
  1355. /**
  1356. * Helpers
  1357. */
  1358. const advance = () => input[index++];
  1359. const push = node => {
  1360. if (node.type === 'text' && prev.type === 'dot') {
  1361. prev.type = 'text';
  1362. }
  1363. if (prev && prev.type === 'text' && node.type === 'text') {
  1364. prev.value += node.value;
  1365. return;
  1366. }
  1367. block.nodes.push(node);
  1368. node.parent = block;
  1369. node.prev = prev;
  1370. prev = node;
  1371. return node;
  1372. };
  1373. push({ type: 'bos' });
  1374. while (index < length) {
  1375. block = stack[stack.length - 1];
  1376. value = advance();
  1377. /**
  1378. * Invalid chars
  1379. */
  1380. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  1381. continue;
  1382. }
  1383. /**
  1384. * Escaped chars
  1385. */
  1386. if (value === CHAR_BACKSLASH) {
  1387. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  1388. continue;
  1389. }
  1390. /**
  1391. * Right square bracket (literal): ']'
  1392. */
  1393. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  1394. push({ type: 'text', value: '\\' + value });
  1395. continue;
  1396. }
  1397. /**
  1398. * Left square bracket: '['
  1399. */
  1400. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  1401. brackets++;
  1402. let next;
  1403. while (index < length && (next = advance())) {
  1404. value += next;
  1405. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  1406. brackets++;
  1407. continue;
  1408. }
  1409. if (next === CHAR_BACKSLASH) {
  1410. value += advance();
  1411. continue;
  1412. }
  1413. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1414. brackets--;
  1415. if (brackets === 0) {
  1416. break;
  1417. }
  1418. }
  1419. }
  1420. push({ type: 'text', value });
  1421. continue;
  1422. }
  1423. /**
  1424. * Parentheses
  1425. */
  1426. if (value === CHAR_LEFT_PARENTHESES) {
  1427. block = push({ type: 'paren', nodes: [] });
  1428. stack.push(block);
  1429. push({ type: 'text', value });
  1430. continue;
  1431. }
  1432. if (value === CHAR_RIGHT_PARENTHESES) {
  1433. if (block.type !== 'paren') {
  1434. push({ type: 'text', value });
  1435. continue;
  1436. }
  1437. block = stack.pop();
  1438. push({ type: 'text', value });
  1439. block = stack[stack.length - 1];
  1440. continue;
  1441. }
  1442. /**
  1443. * Quotes: '|"|`
  1444. */
  1445. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  1446. let open = value;
  1447. let next;
  1448. if (options.keepQuotes !== true) {
  1449. value = '';
  1450. }
  1451. while (index < length && (next = advance())) {
  1452. if (next === CHAR_BACKSLASH) {
  1453. value += next + advance();
  1454. continue;
  1455. }
  1456. if (next === open) {
  1457. if (options.keepQuotes === true) value += next;
  1458. break;
  1459. }
  1460. value += next;
  1461. }
  1462. push({ type: 'text', value });
  1463. continue;
  1464. }
  1465. /**
  1466. * Left curly brace: '{'
  1467. */
  1468. if (value === CHAR_LEFT_CURLY_BRACE) {
  1469. depth++;
  1470. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  1471. let brace = {
  1472. type: 'brace',
  1473. open: true,
  1474. close: false,
  1475. dollar,
  1476. depth,
  1477. commas: 0,
  1478. ranges: 0,
  1479. nodes: []
  1480. };
  1481. block = push(brace);
  1482. stack.push(block);
  1483. push({ type: 'open', value });
  1484. continue;
  1485. }
  1486. /**
  1487. * Right curly brace: '}'
  1488. */
  1489. if (value === CHAR_RIGHT_CURLY_BRACE) {
  1490. if (block.type !== 'brace') {
  1491. push({ type: 'text', value });
  1492. continue;
  1493. }
  1494. let type = 'close';
  1495. block = stack.pop();
  1496. block.close = true;
  1497. push({ type, value });
  1498. depth--;
  1499. block = stack[stack.length - 1];
  1500. continue;
  1501. }
  1502. /**
  1503. * Comma: ','
  1504. */
  1505. if (value === CHAR_COMMA && depth > 0) {
  1506. if (block.ranges > 0) {
  1507. block.ranges = 0;
  1508. let open = block.nodes.shift();
  1509. block.nodes = [open, { type: 'text', value: stringify$1(block) }];
  1510. }
  1511. push({ type: 'comma', value });
  1512. block.commas++;
  1513. continue;
  1514. }
  1515. /**
  1516. * Dot: '.'
  1517. */
  1518. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  1519. let siblings = block.nodes;
  1520. if (depth === 0 || siblings.length === 0) {
  1521. push({ type: 'text', value });
  1522. continue;
  1523. }
  1524. if (prev.type === 'dot') {
  1525. block.range = [];
  1526. prev.value += value;
  1527. prev.type = 'range';
  1528. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  1529. block.invalid = true;
  1530. block.ranges = 0;
  1531. prev.type = 'text';
  1532. continue;
  1533. }
  1534. block.ranges++;
  1535. block.args = [];
  1536. continue;
  1537. }
  1538. if (prev.type === 'range') {
  1539. siblings.pop();
  1540. let before = siblings[siblings.length - 1];
  1541. before.value += prev.value + value;
  1542. prev = before;
  1543. block.ranges--;
  1544. continue;
  1545. }
  1546. push({ type: 'dot', value });
  1547. continue;
  1548. }
  1549. /**
  1550. * Text
  1551. */
  1552. push({ type: 'text', value });
  1553. }
  1554. // Mark imbalanced braces and brackets as invalid
  1555. do {
  1556. block = stack.pop();
  1557. if (block.type !== 'root') {
  1558. block.nodes.forEach(node => {
  1559. if (!node.nodes) {
  1560. if (node.type === 'open') node.isOpen = true;
  1561. if (node.type === 'close') node.isClose = true;
  1562. if (!node.nodes) node.type = 'text';
  1563. node.invalid = true;
  1564. }
  1565. });
  1566. // get the location of the block on parent.nodes (block's siblings)
  1567. let parent = stack[stack.length - 1];
  1568. let index = parent.nodes.indexOf(block);
  1569. // replace the (invalid) block with it's nodes
  1570. parent.nodes.splice(index, 1, ...block.nodes);
  1571. }
  1572. } while (stack.length > 0);
  1573. push({ type: 'eos' });
  1574. return ast;
  1575. };
  1576. var parse_1 = parse$1;
  1577. const stringify = stringify$4;
  1578. const compile = compile_1;
  1579. const expand = expand_1;
  1580. const parse = parse_1;
  1581. /**
  1582. * Expand the given pattern or create a regex-compatible string.
  1583. *
  1584. * ```js
  1585. * const braces = require('braces');
  1586. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  1587. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  1588. * ```
  1589. * @param {String} `str`
  1590. * @param {Object} `options`
  1591. * @return {String}
  1592. * @api public
  1593. */
  1594. const braces$1 = (input, options = {}) => {
  1595. let output = [];
  1596. if (Array.isArray(input)) {
  1597. for (let pattern of input) {
  1598. let result = braces$1.create(pattern, options);
  1599. if (Array.isArray(result)) {
  1600. output.push(...result);
  1601. } else {
  1602. output.push(result);
  1603. }
  1604. }
  1605. } else {
  1606. output = [].concat(braces$1.create(input, options));
  1607. }
  1608. if (options && options.expand === true && options.nodupes === true) {
  1609. output = [...new Set(output)];
  1610. }
  1611. return output;
  1612. };
  1613. /**
  1614. * Parse the given `str` with the given `options`.
  1615. *
  1616. * ```js
  1617. * // braces.parse(pattern, [, options]);
  1618. * const ast = braces.parse('a/{b,c}/d');
  1619. * console.log(ast);
  1620. * ```
  1621. * @param {String} pattern Brace pattern to parse
  1622. * @param {Object} options
  1623. * @return {Object} Returns an AST
  1624. * @api public
  1625. */
  1626. braces$1.parse = (input, options = {}) => parse(input, options);
  1627. /**
  1628. * Creates a braces string from an AST, or an AST node.
  1629. *
  1630. * ```js
  1631. * const braces = require('braces');
  1632. * let ast = braces.parse('foo/{a,b}/bar');
  1633. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  1634. * ```
  1635. * @param {String} `input` Brace pattern or AST.
  1636. * @param {Object} `options`
  1637. * @return {Array} Returns an array of expanded values.
  1638. * @api public
  1639. */
  1640. braces$1.stringify = (input, options = {}) => {
  1641. if (typeof input === 'string') {
  1642. return stringify(braces$1.parse(input, options), options);
  1643. }
  1644. return stringify(input, options);
  1645. };
  1646. /**
  1647. * Compiles a brace pattern into a regex-compatible, optimized string.
  1648. * This method is called by the main [braces](#braces) function by default.
  1649. *
  1650. * ```js
  1651. * const braces = require('braces');
  1652. * console.log(braces.compile('a/{b,c}/d'));
  1653. * //=> ['a/(b|c)/d']
  1654. * ```
  1655. * @param {String} `input` Brace pattern or AST.
  1656. * @param {Object} `options`
  1657. * @return {Array} Returns an array of expanded values.
  1658. * @api public
  1659. */
  1660. braces$1.compile = (input, options = {}) => {
  1661. if (typeof input === 'string') {
  1662. input = braces$1.parse(input, options);
  1663. }
  1664. return compile(input, options);
  1665. };
  1666. /**
  1667. * Expands a brace pattern into an array. This method is called by the
  1668. * main [braces](#braces) function when `options.expand` is true. Before
  1669. * using this method it's recommended that you read the [performance notes](#performance))
  1670. * and advantages of using [.compile](#compile) instead.
  1671. *
  1672. * ```js
  1673. * const braces = require('braces');
  1674. * console.log(braces.expand('a/{b,c}/d'));
  1675. * //=> ['a/b/d', 'a/c/d'];
  1676. * ```
  1677. * @param {String} `pattern` Brace pattern
  1678. * @param {Object} `options`
  1679. * @return {Array} Returns an array of expanded values.
  1680. * @api public
  1681. */
  1682. braces$1.expand = (input, options = {}) => {
  1683. if (typeof input === 'string') {
  1684. input = braces$1.parse(input, options);
  1685. }
  1686. let result = expand(input, options);
  1687. // filter out empty strings if specified
  1688. if (options.noempty === true) {
  1689. result = result.filter(Boolean);
  1690. }
  1691. // filter out duplicates if specified
  1692. if (options.nodupes === true) {
  1693. result = [...new Set(result)];
  1694. }
  1695. return result;
  1696. };
  1697. /**
  1698. * Processes a brace pattern and returns either an expanded array
  1699. * (if `options.expand` is true), a highly optimized regex-compatible string.
  1700. * This method is called by the main [braces](#braces) function.
  1701. *
  1702. * ```js
  1703. * const braces = require('braces');
  1704. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  1705. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  1706. * ```
  1707. * @param {String} `pattern` Brace pattern
  1708. * @param {Object} `options`
  1709. * @return {Array} Returns an array of expanded values.
  1710. * @api public
  1711. */
  1712. braces$1.create = (input, options = {}) => {
  1713. if (input === '' || input.length < 3) {
  1714. return [input];
  1715. }
  1716. return options.expand !== true
  1717. ? braces$1.compile(input, options)
  1718. : braces$1.expand(input, options);
  1719. };
  1720. /**
  1721. * Expose "braces"
  1722. */
  1723. var braces_1 = braces$1;
  1724. var binaryExtensions$1 = {exports: {}};
  1725. const require$$0 = [
  1726. "3dm",
  1727. "3ds",
  1728. "3g2",
  1729. "3gp",
  1730. "7z",
  1731. "a",
  1732. "aac",
  1733. "adp",
  1734. "ai",
  1735. "aif",
  1736. "aiff",
  1737. "alz",
  1738. "ape",
  1739. "apk",
  1740. "appimage",
  1741. "ar",
  1742. "arj",
  1743. "asf",
  1744. "au",
  1745. "avi",
  1746. "bak",
  1747. "baml",
  1748. "bh",
  1749. "bin",
  1750. "bk",
  1751. "bmp",
  1752. "btif",
  1753. "bz2",
  1754. "bzip2",
  1755. "cab",
  1756. "caf",
  1757. "cgm",
  1758. "class",
  1759. "cmx",
  1760. "cpio",
  1761. "cr2",
  1762. "cur",
  1763. "dat",
  1764. "dcm",
  1765. "deb",
  1766. "dex",
  1767. "djvu",
  1768. "dll",
  1769. "dmg",
  1770. "dng",
  1771. "doc",
  1772. "docm",
  1773. "docx",
  1774. "dot",
  1775. "dotm",
  1776. "dra",
  1777. "DS_Store",
  1778. "dsk",
  1779. "dts",
  1780. "dtshd",
  1781. "dvb",
  1782. "dwg",
  1783. "dxf",
  1784. "ecelp4800",
  1785. "ecelp7470",
  1786. "ecelp9600",
  1787. "egg",
  1788. "eol",
  1789. "eot",
  1790. "epub",
  1791. "exe",
  1792. "f4v",
  1793. "fbs",
  1794. "fh",
  1795. "fla",
  1796. "flac",
  1797. "flatpak",
  1798. "fli",
  1799. "flv",
  1800. "fpx",
  1801. "fst",
  1802. "fvt",
  1803. "g3",
  1804. "gh",
  1805. "gif",
  1806. "graffle",
  1807. "gz",
  1808. "gzip",
  1809. "h261",
  1810. "h263",
  1811. "h264",
  1812. "icns",
  1813. "ico",
  1814. "ief",
  1815. "img",
  1816. "ipa",
  1817. "iso",
  1818. "jar",
  1819. "jpeg",
  1820. "jpg",
  1821. "jpgv",
  1822. "jpm",
  1823. "jxr",
  1824. "key",
  1825. "ktx",
  1826. "lha",
  1827. "lib",
  1828. "lvp",
  1829. "lz",
  1830. "lzh",
  1831. "lzma",
  1832. "lzo",
  1833. "m3u",
  1834. "m4a",
  1835. "m4v",
  1836. "mar",
  1837. "mdi",
  1838. "mht",
  1839. "mid",
  1840. "midi",
  1841. "mj2",
  1842. "mka",
  1843. "mkv",
  1844. "mmr",
  1845. "mng",
  1846. "mobi",
  1847. "mov",
  1848. "movie",
  1849. "mp3",
  1850. "mp4",
  1851. "mp4a",
  1852. "mpeg",
  1853. "mpg",
  1854. "mpga",
  1855. "mxu",
  1856. "nef",
  1857. "npx",
  1858. "numbers",
  1859. "nupkg",
  1860. "o",
  1861. "odp",
  1862. "ods",
  1863. "odt",
  1864. "oga",
  1865. "ogg",
  1866. "ogv",
  1867. "otf",
  1868. "ott",
  1869. "pages",
  1870. "pbm",
  1871. "pcx",
  1872. "pdb",
  1873. "pdf",
  1874. "pea",
  1875. "pgm",
  1876. "pic",
  1877. "png",
  1878. "pnm",
  1879. "pot",
  1880. "potm",
  1881. "potx",
  1882. "ppa",
  1883. "ppam",
  1884. "ppm",
  1885. "pps",
  1886. "ppsm",
  1887. "ppsx",
  1888. "ppt",
  1889. "pptm",
  1890. "pptx",
  1891. "psd",
  1892. "pya",
  1893. "pyc",
  1894. "pyo",
  1895. "pyv",
  1896. "qt",
  1897. "rar",
  1898. "ras",
  1899. "raw",
  1900. "resources",
  1901. "rgb",
  1902. "rip",
  1903. "rlc",
  1904. "rmf",
  1905. "rmvb",
  1906. "rpm",
  1907. "rtf",
  1908. "rz",
  1909. "s3m",
  1910. "s7z",
  1911. "scpt",
  1912. "sgi",
  1913. "shar",
  1914. "snap",
  1915. "sil",
  1916. "sketch",
  1917. "slk",
  1918. "smv",
  1919. "snk",
  1920. "so",
  1921. "stl",
  1922. "suo",
  1923. "sub",
  1924. "swf",
  1925. "tar",
  1926. "tbz",
  1927. "tbz2",
  1928. "tga",
  1929. "tgz",
  1930. "thmx",
  1931. "tif",
  1932. "tiff",
  1933. "tlz",
  1934. "ttc",
  1935. "ttf",
  1936. "txz",
  1937. "udf",
  1938. "uvh",
  1939. "uvi",
  1940. "uvm",
  1941. "uvp",
  1942. "uvs",
  1943. "uvu",
  1944. "viv",
  1945. "vob",
  1946. "war",
  1947. "wav",
  1948. "wax",
  1949. "wbmp",
  1950. "wdp",
  1951. "weba",
  1952. "webm",
  1953. "webp",
  1954. "whl",
  1955. "wim",
  1956. "wm",
  1957. "wma",
  1958. "wmv",
  1959. "wmx",
  1960. "woff",
  1961. "woff2",
  1962. "wrm",
  1963. "wvx",
  1964. "xbm",
  1965. "xif",
  1966. "xla",
  1967. "xlam",
  1968. "xls",
  1969. "xlsb",
  1970. "xlsm",
  1971. "xlsx",
  1972. "xlt",
  1973. "xltm",
  1974. "xltx",
  1975. "xm",
  1976. "xmind",
  1977. "xpi",
  1978. "xpm",
  1979. "xwd",
  1980. "xz",
  1981. "z",
  1982. "zip",
  1983. "zipx"
  1984. ];
  1985. (function (module) {
  1986. module.exports = require$$0;
  1987. } (binaryExtensions$1));
  1988. const path = require$$0$2;
  1989. const binaryExtensions = binaryExtensions$1.exports;
  1990. const extensions = new Set(binaryExtensions);
  1991. var isBinaryPath$1 = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());
  1992. var constants = {};
  1993. (function (exports) {
  1994. const {sep} = require$$0$2;
  1995. const {platform} = process;
  1996. const os = require$$2$1;
  1997. exports.EV_ALL = 'all';
  1998. exports.EV_READY = 'ready';
  1999. exports.EV_ADD = 'add';
  2000. exports.EV_CHANGE = 'change';
  2001. exports.EV_ADD_DIR = 'addDir';
  2002. exports.EV_UNLINK = 'unlink';
  2003. exports.EV_UNLINK_DIR = 'unlinkDir';
  2004. exports.EV_RAW = 'raw';
  2005. exports.EV_ERROR = 'error';
  2006. exports.STR_DATA = 'data';
  2007. exports.STR_END = 'end';
  2008. exports.STR_CLOSE = 'close';
  2009. exports.FSEVENT_CREATED = 'created';
  2010. exports.FSEVENT_MODIFIED = 'modified';
  2011. exports.FSEVENT_DELETED = 'deleted';
  2012. exports.FSEVENT_MOVED = 'moved';
  2013. exports.FSEVENT_CLONED = 'cloned';
  2014. exports.FSEVENT_UNKNOWN = 'unknown';
  2015. exports.FSEVENT_TYPE_FILE = 'file';
  2016. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  2017. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  2018. exports.KEY_LISTENERS = 'listeners';
  2019. exports.KEY_ERR = 'errHandlers';
  2020. exports.KEY_RAW = 'rawEmitters';
  2021. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  2022. exports.DOT_SLASH = `.${sep}`;
  2023. exports.BACK_SLASH_RE = /\\/g;
  2024. exports.DOUBLE_SLASH_RE = /\/\//;
  2025. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  2026. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  2027. exports.REPLACER_RE = /^\.[/\\]/;
  2028. exports.SLASH = '/';
  2029. exports.SLASH_SLASH = '//';
  2030. exports.BRACE_START = '{';
  2031. exports.BANG = '!';
  2032. exports.ONE_DOT = '.';
  2033. exports.TWO_DOTS = '..';
  2034. exports.STAR = '*';
  2035. exports.GLOBSTAR = '**';
  2036. exports.ROOT_GLOBSTAR = '/**/*';
  2037. exports.SLASH_GLOBSTAR = '/**';
  2038. exports.DIR_SUFFIX = 'Dir';
  2039. exports.ANYMATCH_OPTS = {dot: true};
  2040. exports.STRING_TYPE = 'string';
  2041. exports.FUNCTION_TYPE = 'function';
  2042. exports.EMPTY_STR = '';
  2043. exports.EMPTY_FN = () => {};
  2044. exports.IDENTITY_FN = val => val;
  2045. exports.isWindows = platform === 'win32';
  2046. exports.isMacos = platform === 'darwin';
  2047. exports.isLinux = platform === 'linux';
  2048. exports.isIBMi = os.type() === 'OS400';
  2049. } (constants));
  2050. const fs$2 = require$$0$1;
  2051. const sysPath$2 = require$$0$2;
  2052. const { promisify: promisify$2 } = require$$2;
  2053. const isBinaryPath = isBinaryPath$1;
  2054. const {
  2055. isWindows: isWindows$1,
  2056. isLinux,
  2057. EMPTY_FN: EMPTY_FN$2,
  2058. EMPTY_STR: EMPTY_STR$1,
  2059. KEY_LISTENERS,
  2060. KEY_ERR,
  2061. KEY_RAW,
  2062. HANDLER_KEYS,
  2063. EV_CHANGE: EV_CHANGE$2,
  2064. EV_ADD: EV_ADD$2,
  2065. EV_ADD_DIR: EV_ADD_DIR$2,
  2066. EV_ERROR: EV_ERROR$2,
  2067. STR_DATA: STR_DATA$1,
  2068. STR_END: STR_END$2,
  2069. BRACE_START: BRACE_START$1,
  2070. STAR
  2071. } = constants;
  2072. const THROTTLE_MODE_WATCH = 'watch';
  2073. const open = promisify$2(fs$2.open);
  2074. const stat$2 = promisify$2(fs$2.stat);
  2075. const lstat$1 = promisify$2(fs$2.lstat);
  2076. const close = promisify$2(fs$2.close);
  2077. const fsrealpath = promisify$2(fs$2.realpath);
  2078. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  2079. // TODO: emit errors properly. Example: EMFILE on Macos.
  2080. const foreach = (val, fn) => {
  2081. if (val instanceof Set) {
  2082. val.forEach(fn);
  2083. } else {
  2084. fn(val);
  2085. }
  2086. };
  2087. const addAndConvert = (main, prop, item) => {
  2088. let container = main[prop];
  2089. if (!(container instanceof Set)) {
  2090. main[prop] = container = new Set([container]);
  2091. }
  2092. container.add(item);
  2093. };
  2094. const clearItem = cont => key => {
  2095. const set = cont[key];
  2096. if (set instanceof Set) {
  2097. set.clear();
  2098. } else {
  2099. delete cont[key];
  2100. }
  2101. };
  2102. const delFromSet = (main, prop, item) => {
  2103. const container = main[prop];
  2104. if (container instanceof Set) {
  2105. container.delete(item);
  2106. } else if (container === item) {
  2107. delete main[prop];
  2108. }
  2109. };
  2110. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  2111. /**
  2112. * @typedef {String} Path
  2113. */
  2114. // fs_watch helpers
  2115. // object to hold per-process fs_watch instances
  2116. // (may be shared across chokidar FSWatcher instances)
  2117. /**
  2118. * @typedef {Object} FsWatchContainer
  2119. * @property {Set} listeners
  2120. * @property {Set} errHandlers
  2121. * @property {Set} rawEmitters
  2122. * @property {fs.FSWatcher=} watcher
  2123. * @property {Boolean=} watcherUnusable
  2124. */
  2125. /**
  2126. * @type {Map<String,FsWatchContainer>}
  2127. */
  2128. const FsWatchInstances = new Map();
  2129. /**
  2130. * Instantiates the fs_watch interface
  2131. * @param {String} path to be watched
  2132. * @param {Object} options to be passed to fs_watch
  2133. * @param {Function} listener main event handler
  2134. * @param {Function} errHandler emits info about errors
  2135. * @param {Function} emitRaw emits raw event data
  2136. * @returns {fs.FSWatcher} new fsevents instance
  2137. */
  2138. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  2139. const handleEvent = (rawEvent, evPath) => {
  2140. listener(path);
  2141. emitRaw(rawEvent, evPath, {watchedPath: path});
  2142. // emit based on events occurring for files from a directory's watcher in
  2143. // case the file's watcher misses it (and rely on throttling to de-dupe)
  2144. if (evPath && path !== evPath) {
  2145. fsWatchBroadcast(
  2146. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  2147. );
  2148. }
  2149. };
  2150. try {
  2151. return fs$2.watch(path, options, handleEvent);
  2152. } catch (error) {
  2153. errHandler(error);
  2154. }
  2155. }
  2156. /**
  2157. * Helper for passing fs_watch event data to a collection of listeners
  2158. * @param {Path} fullPath absolute path bound to fs_watch instance
  2159. * @param {String} type listener type
  2160. * @param {*=} val1 arguments to be passed to listeners
  2161. * @param {*=} val2
  2162. * @param {*=} val3
  2163. */
  2164. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  2165. const cont = FsWatchInstances.get(fullPath);
  2166. if (!cont) return;
  2167. foreach(cont[type], (listener) => {
  2168. listener(val1, val2, val3);
  2169. });
  2170. };
  2171. /**
  2172. * Instantiates the fs_watch interface or binds listeners
  2173. * to an existing one covering the same file system entry
  2174. * @param {String} path
  2175. * @param {String} fullPath absolute path
  2176. * @param {Object} options to be passed to fs_watch
  2177. * @param {Object} handlers container for event listener functions
  2178. */
  2179. const setFsWatchListener = (path, fullPath, options, handlers) => {
  2180. const {listener, errHandler, rawEmitter} = handlers;
  2181. let cont = FsWatchInstances.get(fullPath);
  2182. /** @type {fs.FSWatcher=} */
  2183. let watcher;
  2184. if (!options.persistent) {
  2185. watcher = createFsWatchInstance(
  2186. path, options, listener, errHandler, rawEmitter
  2187. );
  2188. return watcher.close.bind(watcher);
  2189. }
  2190. if (cont) {
  2191. addAndConvert(cont, KEY_LISTENERS, listener);
  2192. addAndConvert(cont, KEY_ERR, errHandler);
  2193. addAndConvert(cont, KEY_RAW, rawEmitter);
  2194. } else {
  2195. watcher = createFsWatchInstance(
  2196. path,
  2197. options,
  2198. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  2199. errHandler, // no need to use broadcast here
  2200. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  2201. );
  2202. if (!watcher) return;
  2203. watcher.on(EV_ERROR$2, async (error) => {
  2204. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  2205. cont.watcherUnusable = true; // documented since Node 10.4.1
  2206. // Workaround for https://github.com/joyent/node/issues/4337
  2207. if (isWindows$1 && error.code === 'EPERM') {
  2208. try {
  2209. const fd = await open(path, 'r');
  2210. await close(fd);
  2211. broadcastErr(error);
  2212. } catch (err) {}
  2213. } else {
  2214. broadcastErr(error);
  2215. }
  2216. });
  2217. cont = {
  2218. listeners: listener,
  2219. errHandlers: errHandler,
  2220. rawEmitters: rawEmitter,
  2221. watcher
  2222. };
  2223. FsWatchInstances.set(fullPath, cont);
  2224. }
  2225. // const index = cont.listeners.indexOf(listener);
  2226. // removes this instance's listeners and closes the underlying fs_watch
  2227. // instance if there are no more listeners left
  2228. return () => {
  2229. delFromSet(cont, KEY_LISTENERS, listener);
  2230. delFromSet(cont, KEY_ERR, errHandler);
  2231. delFromSet(cont, KEY_RAW, rawEmitter);
  2232. if (isEmptySet(cont.listeners)) {
  2233. // Check to protect against issue gh-730.
  2234. // if (cont.watcherUnusable) {
  2235. cont.watcher.close();
  2236. // }
  2237. FsWatchInstances.delete(fullPath);
  2238. HANDLER_KEYS.forEach(clearItem(cont));
  2239. cont.watcher = undefined;
  2240. Object.freeze(cont);
  2241. }
  2242. };
  2243. };
  2244. // fs_watchFile helpers
  2245. // object to hold per-process fs_watchFile instances
  2246. // (may be shared across chokidar FSWatcher instances)
  2247. const FsWatchFileInstances = new Map();
  2248. /**
  2249. * Instantiates the fs_watchFile interface or binds listeners
  2250. * to an existing one covering the same file system entry
  2251. * @param {String} path to be watched
  2252. * @param {String} fullPath absolute path
  2253. * @param {Object} options options to be passed to fs_watchFile
  2254. * @param {Object} handlers container for event listener functions
  2255. * @returns {Function} closer
  2256. */
  2257. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  2258. const {listener, rawEmitter} = handlers;
  2259. let cont = FsWatchFileInstances.get(fullPath);
  2260. const copts = cont && cont.options;
  2261. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  2262. fs$2.unwatchFile(fullPath);
  2263. cont = undefined;
  2264. }
  2265. /* eslint-enable no-unused-vars, prefer-destructuring */
  2266. if (cont) {
  2267. addAndConvert(cont, KEY_LISTENERS, listener);
  2268. addAndConvert(cont, KEY_RAW, rawEmitter);
  2269. } else {
  2270. // TODO
  2271. // listeners.add(listener);
  2272. // rawEmitters.add(rawEmitter);
  2273. cont = {
  2274. listeners: listener,
  2275. rawEmitters: rawEmitter,
  2276. options,
  2277. watcher: fs$2.watchFile(fullPath, options, (curr, prev) => {
  2278. foreach(cont.rawEmitters, (rawEmitter) => {
  2279. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  2280. });
  2281. const currmtime = curr.mtimeMs;
  2282. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  2283. foreach(cont.listeners, (listener) => listener(path, curr));
  2284. }
  2285. })
  2286. };
  2287. FsWatchFileInstances.set(fullPath, cont);
  2288. }
  2289. // const index = cont.listeners.indexOf(listener);
  2290. // Removes this instance's listeners and closes the underlying fs_watchFile
  2291. // instance if there are no more listeners left.
  2292. return () => {
  2293. delFromSet(cont, KEY_LISTENERS, listener);
  2294. delFromSet(cont, KEY_RAW, rawEmitter);
  2295. if (isEmptySet(cont.listeners)) {
  2296. FsWatchFileInstances.delete(fullPath);
  2297. fs$2.unwatchFile(fullPath);
  2298. cont.options = cont.watcher = undefined;
  2299. Object.freeze(cont);
  2300. }
  2301. };
  2302. };
  2303. /**
  2304. * @mixin
  2305. */
  2306. class NodeFsHandler$1 {
  2307. /**
  2308. * @param {import("../index").FSWatcher} fsW
  2309. */
  2310. constructor(fsW) {
  2311. this.fsw = fsW;
  2312. this._boundHandleError = (error) => fsW._handleError(error);
  2313. }
  2314. /**
  2315. * Watch file for changes with fs_watchFile or fs_watch.
  2316. * @param {String} path to file or dir
  2317. * @param {Function} listener on fs change
  2318. * @returns {Function} closer for the watcher instance
  2319. */
  2320. _watchWithNodeFs(path, listener) {
  2321. const opts = this.fsw.options;
  2322. const directory = sysPath$2.dirname(path);
  2323. const basename = sysPath$2.basename(path);
  2324. const parent = this.fsw._getWatchedDir(directory);
  2325. parent.add(basename);
  2326. const absolutePath = sysPath$2.resolve(path);
  2327. const options = {persistent: opts.persistent};
  2328. if (!listener) listener = EMPTY_FN$2;
  2329. let closer;
  2330. if (opts.usePolling) {
  2331. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  2332. opts.binaryInterval : opts.interval;
  2333. closer = setFsWatchFileListener(path, absolutePath, options, {
  2334. listener,
  2335. rawEmitter: this.fsw._emitRaw
  2336. });
  2337. } else {
  2338. closer = setFsWatchListener(path, absolutePath, options, {
  2339. listener,
  2340. errHandler: this._boundHandleError,
  2341. rawEmitter: this.fsw._emitRaw
  2342. });
  2343. }
  2344. return closer;
  2345. }
  2346. /**
  2347. * Watch a file and emit add event if warranted.
  2348. * @param {Path} file Path
  2349. * @param {fs.Stats} stats result of fs_stat
  2350. * @param {Boolean} initialAdd was the file added at watch instantiation?
  2351. * @returns {Function} closer for the watcher instance
  2352. */
  2353. _handleFile(file, stats, initialAdd) {
  2354. if (this.fsw.closed) {
  2355. return;
  2356. }
  2357. const dirname = sysPath$2.dirname(file);
  2358. const basename = sysPath$2.basename(file);
  2359. const parent = this.fsw._getWatchedDir(dirname);
  2360. // stats is always present
  2361. let prevStats = stats;
  2362. // if the file is already being watched, do nothing
  2363. if (parent.has(basename)) return;
  2364. const listener = async (path, newStats) => {
  2365. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  2366. if (!newStats || newStats.mtimeMs === 0) {
  2367. try {
  2368. const newStats = await stat$2(file);
  2369. if (this.fsw.closed) return;
  2370. // Check that change event was not fired because of changed only accessTime.
  2371. const at = newStats.atimeMs;
  2372. const mt = newStats.mtimeMs;
  2373. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  2374. this.fsw._emit(EV_CHANGE$2, file, newStats);
  2375. }
  2376. if (isLinux && prevStats.ino !== newStats.ino) {
  2377. this.fsw._closeFile(path);
  2378. prevStats = newStats;
  2379. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  2380. } else {
  2381. prevStats = newStats;
  2382. }
  2383. } catch (error) {
  2384. // Fix issues where mtime is null but file is still present
  2385. this.fsw._remove(dirname, basename);
  2386. }
  2387. // add is about to be emitted if file not already tracked in parent
  2388. } else if (parent.has(basename)) {
  2389. // Check that change event was not fired because of changed only accessTime.
  2390. const at = newStats.atimeMs;
  2391. const mt = newStats.mtimeMs;
  2392. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  2393. this.fsw._emit(EV_CHANGE$2, file, newStats);
  2394. }
  2395. prevStats = newStats;
  2396. }
  2397. };
  2398. // kick off the watcher
  2399. const closer = this._watchWithNodeFs(file, listener);
  2400. // emit an add event if we're supposed to
  2401. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  2402. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  2403. this.fsw._emit(EV_ADD$2, file, stats);
  2404. }
  2405. return closer;
  2406. }
  2407. /**
  2408. * Handle symlinks encountered while reading a dir.
  2409. * @param {Object} entry returned by readdirp
  2410. * @param {String} directory path of dir being read
  2411. * @param {String} path of this item
  2412. * @param {String} item basename of this item
  2413. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  2414. */
  2415. async _handleSymlink(entry, directory, path, item) {
  2416. if (this.fsw.closed) {
  2417. return;
  2418. }
  2419. const full = entry.fullPath;
  2420. const dir = this.fsw._getWatchedDir(directory);
  2421. if (!this.fsw.options.followSymlinks) {
  2422. // watch symlink directly (don't follow) and detect changes
  2423. this.fsw._incrReadyCount();
  2424. let linkPath;
  2425. try {
  2426. linkPath = await fsrealpath(path);
  2427. } catch (e) {
  2428. this.fsw._emitReady();
  2429. return true;
  2430. }
  2431. if (this.fsw.closed) return;
  2432. if (dir.has(item)) {
  2433. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  2434. this.fsw._symlinkPaths.set(full, linkPath);
  2435. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  2436. }
  2437. } else {
  2438. dir.add(item);
  2439. this.fsw._symlinkPaths.set(full, linkPath);
  2440. this.fsw._emit(EV_ADD$2, path, entry.stats);
  2441. }
  2442. this.fsw._emitReady();
  2443. return true;
  2444. }
  2445. // don't follow the same symlink more than once
  2446. if (this.fsw._symlinkPaths.has(full)) {
  2447. return true;
  2448. }
  2449. this.fsw._symlinkPaths.set(full, true);
  2450. }
  2451. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  2452. // Normalize the directory name on Windows
  2453. directory = sysPath$2.join(directory, EMPTY_STR$1);
  2454. if (!wh.hasGlob) {
  2455. throttler = this.fsw._throttle('readdir', directory, 1000);
  2456. if (!throttler) return;
  2457. }
  2458. const previous = this.fsw._getWatchedDir(wh.path);
  2459. const current = new Set();
  2460. let stream = this.fsw._readdirp(directory, {
  2461. fileFilter: entry => wh.filterPath(entry),
  2462. directoryFilter: entry => wh.filterDir(entry),
  2463. depth: 0
  2464. }).on(STR_DATA$1, async (entry) => {
  2465. if (this.fsw.closed) {
  2466. stream = undefined;
  2467. return;
  2468. }
  2469. const item = entry.path;
  2470. let path = sysPath$2.join(directory, item);
  2471. current.add(item);
  2472. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  2473. return;
  2474. }
  2475. if (this.fsw.closed) {
  2476. stream = undefined;
  2477. return;
  2478. }
  2479. // Files that present in current directory snapshot
  2480. // but absent in previous are added to watch list and
  2481. // emit `add` event.
  2482. if (item === target || !target && !previous.has(item)) {
  2483. this.fsw._incrReadyCount();
  2484. // ensure relativeness of path is preserved in case of watcher reuse
  2485. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  2486. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  2487. }
  2488. }).on(EV_ERROR$2, this._boundHandleError);
  2489. return new Promise(resolve =>
  2490. stream.once(STR_END$2, () => {
  2491. if (this.fsw.closed) {
  2492. stream = undefined;
  2493. return;
  2494. }
  2495. const wasThrottled = throttler ? throttler.clear() : false;
  2496. resolve();
  2497. // Files that absent in current directory snapshot
  2498. // but present in previous emit `remove` event
  2499. // and are removed from @watched[directory].
  2500. previous.getChildren().filter((item) => {
  2501. return item !== directory &&
  2502. !current.has(item) &&
  2503. // in case of intersecting globs;
  2504. // a path may have been filtered out of this readdir, but
  2505. // shouldn't be removed because it matches a different glob
  2506. (!wh.hasGlob || wh.filterPath({
  2507. fullPath: sysPath$2.resolve(directory, item)
  2508. }));
  2509. }).forEach((item) => {
  2510. this.fsw._remove(directory, item);
  2511. });
  2512. stream = undefined;
  2513. // one more time for any missed in case changes came in extremely quickly
  2514. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  2515. })
  2516. );
  2517. }
  2518. /**
  2519. * Read directory to add / remove files from `@watched` list and re-read it on change.
  2520. * @param {String} dir fs path
  2521. * @param {fs.Stats} stats
  2522. * @param {Boolean} initialAdd
  2523. * @param {Number} depth relative to user-supplied path
  2524. * @param {String} target child path targeted for watch
  2525. * @param {Object} wh Common watch helpers for this path
  2526. * @param {String} realpath
  2527. * @returns {Promise<Function>} closer for the watcher instance.
  2528. */
  2529. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  2530. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  2531. const tracked = parentDir.has(sysPath$2.basename(dir));
  2532. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  2533. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  2534. }
  2535. // ensure dir is tracked (harmless if redundant)
  2536. parentDir.add(sysPath$2.basename(dir));
  2537. this.fsw._getWatchedDir(dir);
  2538. let throttler;
  2539. let closer;
  2540. const oDepth = this.fsw.options.depth;
  2541. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  2542. if (!target) {
  2543. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  2544. if (this.fsw.closed) return;
  2545. }
  2546. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  2547. // if current directory is removed, do nothing
  2548. if (stats && stats.mtimeMs === 0) return;
  2549. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  2550. });
  2551. }
  2552. return closer;
  2553. }
  2554. /**
  2555. * Handle added file, directory, or glob pattern.
  2556. * Delegates call to _handleFile / _handleDir after checks.
  2557. * @param {String} path to file or ir
  2558. * @param {Boolean} initialAdd was the file added at watch instantiation?
  2559. * @param {Object} priorWh depth relative to user-supplied path
  2560. * @param {Number} depth Child path actually targeted for watch
  2561. * @param {String=} target Child path actually targeted for watch
  2562. * @returns {Promise}
  2563. */
  2564. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  2565. const ready = this.fsw._emitReady;
  2566. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  2567. ready();
  2568. return false;
  2569. }
  2570. const wh = this.fsw._getWatchHelpers(path, depth);
  2571. if (!wh.hasGlob && priorWh) {
  2572. wh.hasGlob = priorWh.hasGlob;
  2573. wh.globFilter = priorWh.globFilter;
  2574. wh.filterPath = entry => priorWh.filterPath(entry);
  2575. wh.filterDir = entry => priorWh.filterDir(entry);
  2576. }
  2577. // evaluate what is at the path we're being asked to watch
  2578. try {
  2579. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  2580. if (this.fsw.closed) return;
  2581. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  2582. ready();
  2583. return false;
  2584. }
  2585. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  2586. let closer;
  2587. if (stats.isDirectory()) {
  2588. const absPath = sysPath$2.resolve(path);
  2589. const targetPath = follow ? await fsrealpath(path) : path;
  2590. if (this.fsw.closed) return;
  2591. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  2592. if (this.fsw.closed) return;
  2593. // preserve this symlink's target path
  2594. if (absPath !== targetPath && targetPath !== undefined) {
  2595. this.fsw._symlinkPaths.set(absPath, targetPath);
  2596. }
  2597. } else if (stats.isSymbolicLink()) {
  2598. const targetPath = follow ? await fsrealpath(path) : path;
  2599. if (this.fsw.closed) return;
  2600. const parent = sysPath$2.dirname(wh.watchPath);
  2601. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  2602. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  2603. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  2604. if (this.fsw.closed) return;
  2605. // preserve this symlink's target path
  2606. if (targetPath !== undefined) {
  2607. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  2608. }
  2609. } else {
  2610. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  2611. }
  2612. ready();
  2613. this.fsw._addPathCloser(path, closer);
  2614. return false;
  2615. } catch (error) {
  2616. if (this.fsw._handleError(error)) {
  2617. ready();
  2618. return path;
  2619. }
  2620. }
  2621. }
  2622. }
  2623. var nodefsHandler = NodeFsHandler$1;
  2624. var fseventsHandler = {exports: {}};
  2625. const require$$3 = /*@__PURE__*/rollup.getAugmentedNamespace(rollup.fseventsImporter);
  2626. const fs$1 = require$$0$1;
  2627. const sysPath$1 = require$$0$2;
  2628. const { promisify: promisify$1 } = require$$2;
  2629. let fsevents;
  2630. try {
  2631. fsevents = require$$3.getFsEvents();
  2632. } catch (error) {
  2633. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  2634. }
  2635. if (fsevents) {
  2636. // TODO: real check
  2637. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  2638. if (mtch && mtch[1] && mtch[2]) {
  2639. const maj = Number.parseInt(mtch[1], 10);
  2640. const min = Number.parseInt(mtch[2], 10);
  2641. if (maj === 8 && min < 16) {
  2642. fsevents = undefined;
  2643. }
  2644. }
  2645. }
  2646. const {
  2647. EV_ADD: EV_ADD$1,
  2648. EV_CHANGE: EV_CHANGE$1,
  2649. EV_ADD_DIR: EV_ADD_DIR$1,
  2650. EV_UNLINK: EV_UNLINK$1,
  2651. EV_ERROR: EV_ERROR$1,
  2652. STR_DATA,
  2653. STR_END: STR_END$1,
  2654. FSEVENT_CREATED,
  2655. FSEVENT_MODIFIED,
  2656. FSEVENT_DELETED,
  2657. FSEVENT_MOVED,
  2658. // FSEVENT_CLONED,
  2659. FSEVENT_UNKNOWN,
  2660. FSEVENT_TYPE_FILE,
  2661. FSEVENT_TYPE_DIRECTORY,
  2662. FSEVENT_TYPE_SYMLINK,
  2663. ROOT_GLOBSTAR,
  2664. DIR_SUFFIX,
  2665. DOT_SLASH,
  2666. FUNCTION_TYPE: FUNCTION_TYPE$1,
  2667. EMPTY_FN: EMPTY_FN$1,
  2668. IDENTITY_FN
  2669. } = constants;
  2670. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  2671. const stat$1 = promisify$1(fs$1.stat);
  2672. const lstat = promisify$1(fs$1.lstat);
  2673. const realpath = promisify$1(fs$1.realpath);
  2674. const statMethods = { stat: stat$1, lstat };
  2675. /**
  2676. * @typedef {String} Path
  2677. */
  2678. /**
  2679. * @typedef {Object} FsEventsWatchContainer
  2680. * @property {Set<Function>} listeners
  2681. * @property {Function} rawEmitter
  2682. * @property {{stop: Function}} watcher
  2683. */
  2684. // fsevents instance helper functions
  2685. /**
  2686. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  2687. * @type {Map<Path,FsEventsWatchContainer>}
  2688. */
  2689. const FSEventsWatchers = new Map();
  2690. // Threshold of duplicate path prefixes at which to start
  2691. // consolidating going forward
  2692. const consolidateThreshhold = 10;
  2693. const wrongEventFlags = new Set([
  2694. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  2695. ]);
  2696. /**
  2697. * Instantiates the fsevents interface
  2698. * @param {Path} path path to be watched
  2699. * @param {Function} callback called when fsevents is bound and ready
  2700. * @returns {{stop: Function}} new fsevents instance
  2701. */
  2702. const createFSEventsInstance = (path, callback) => {
  2703. const stop = fsevents.watch(path, callback);
  2704. return {stop};
  2705. };
  2706. /**
  2707. * Instantiates the fsevents interface or binds listeners to an existing one covering
  2708. * the same file tree.
  2709. * @param {Path} path - to be watched
  2710. * @param {Path} realPath - real path for symlinks
  2711. * @param {Function} listener - called when fsevents emits events
  2712. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  2713. * @returns {Function} closer
  2714. */
  2715. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  2716. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  2717. const parentPath = sysPath$1.dirname(watchPath);
  2718. let cont = FSEventsWatchers.get(watchPath);
  2719. // If we've accumulated a substantial number of paths that
  2720. // could have been consolidated by watching one directory
  2721. // above the current one, create a watcher on the parent
  2722. // path instead, so that we do consolidate going forward.
  2723. if (couldConsolidate(parentPath)) {
  2724. watchPath = parentPath;
  2725. }
  2726. const resolvedPath = sysPath$1.resolve(path);
  2727. const hasSymlink = resolvedPath !== realPath;
  2728. const filteredListener = (fullPath, flags, info) => {
  2729. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  2730. if (
  2731. fullPath === resolvedPath ||
  2732. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  2733. ) listener(fullPath, flags, info);
  2734. };
  2735. // check if there is already a watcher on a parent path
  2736. // modifies `watchPath` to the parent path when it finds a match
  2737. let watchedParent = false;
  2738. for (const watchedPath of FSEventsWatchers.keys()) {
  2739. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  2740. watchPath = watchedPath;
  2741. cont = FSEventsWatchers.get(watchPath);
  2742. watchedParent = true;
  2743. break;
  2744. }
  2745. }
  2746. if (cont || watchedParent) {
  2747. cont.listeners.add(filteredListener);
  2748. } else {
  2749. cont = {
  2750. listeners: new Set([filteredListener]),
  2751. rawEmitter,
  2752. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  2753. if (!cont.listeners.size) return;
  2754. const info = fsevents.getInfo(fullPath, flags);
  2755. cont.listeners.forEach(list => {
  2756. list(fullPath, flags, info);
  2757. });
  2758. cont.rawEmitter(info.event, fullPath, info);
  2759. })
  2760. };
  2761. FSEventsWatchers.set(watchPath, cont);
  2762. }
  2763. // removes this instance's listeners and closes the underlying fsevents
  2764. // instance if there are no more listeners left
  2765. return () => {
  2766. const lst = cont.listeners;
  2767. lst.delete(filteredListener);
  2768. if (!lst.size) {
  2769. FSEventsWatchers.delete(watchPath);
  2770. if (cont.watcher) return cont.watcher.stop().then(() => {
  2771. cont.rawEmitter = cont.watcher = undefined;
  2772. Object.freeze(cont);
  2773. });
  2774. }
  2775. };
  2776. }
  2777. // Decide whether or not we should start a new higher-level
  2778. // parent watcher
  2779. const couldConsolidate = (path) => {
  2780. let count = 0;
  2781. for (const watchPath of FSEventsWatchers.keys()) {
  2782. if (watchPath.indexOf(path) === 0) {
  2783. count++;
  2784. if (count >= consolidateThreshhold) {
  2785. return true;
  2786. }
  2787. }
  2788. }
  2789. return false;
  2790. };
  2791. // returns boolean indicating whether fsevents can be used
  2792. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  2793. // determines subdirectory traversal levels from root to path
  2794. const calcDepth = (path, root) => {
  2795. let i = 0;
  2796. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  2797. return i;
  2798. };
  2799. // returns boolean indicating whether the fsevents' event info has the same type
  2800. // as the one returned by fs.stat
  2801. const sameTypes = (info, stats) => (
  2802. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  2803. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  2804. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  2805. );
  2806. /**
  2807. * @mixin
  2808. */
  2809. class FsEventsHandler$1 {
  2810. /**
  2811. * @param {import('../index').FSWatcher} fsw
  2812. */
  2813. constructor(fsw) {
  2814. this.fsw = fsw;
  2815. }
  2816. checkIgnored(path, stats) {
  2817. const ipaths = this.fsw._ignoredPaths;
  2818. if (this.fsw._isIgnored(path, stats)) {
  2819. ipaths.add(path);
  2820. if (stats && stats.isDirectory()) {
  2821. ipaths.add(path + ROOT_GLOBSTAR);
  2822. }
  2823. return true;
  2824. }
  2825. ipaths.delete(path);
  2826. ipaths.delete(path + ROOT_GLOBSTAR);
  2827. }
  2828. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  2829. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  2830. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2831. }
  2832. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  2833. try {
  2834. const stats = await stat$1(path);
  2835. if (this.fsw.closed) return;
  2836. if (sameTypes(info, stats)) {
  2837. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2838. } else {
  2839. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2840. }
  2841. } catch (error) {
  2842. if (error.code === 'EACCES') {
  2843. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2844. } else {
  2845. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2846. }
  2847. }
  2848. }
  2849. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  2850. if (this.fsw.closed || this.checkIgnored(path)) return;
  2851. if (event === EV_UNLINK$1) {
  2852. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  2853. // suppress unlink events on never before seen files
  2854. if (isDirectory || watchedDir.has(item)) {
  2855. this.fsw._remove(parent, item, isDirectory);
  2856. }
  2857. } else {
  2858. if (event === EV_ADD$1) {
  2859. // track new directories
  2860. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  2861. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  2862. // push symlinks back to the top of the stack to get handled
  2863. const curDepth = opts.depth === undefined ?
  2864. undefined : calcDepth(fullPath, realPath) + 1;
  2865. return this._addToFsEvents(path, false, true, curDepth);
  2866. }
  2867. // track new paths
  2868. // (other than symlinks being followed, which will be tracked soon)
  2869. this.fsw._getWatchedDir(parent).add(item);
  2870. }
  2871. /**
  2872. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  2873. */
  2874. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  2875. this.fsw._emit(eventName, path);
  2876. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  2877. }
  2878. }
  2879. /**
  2880. * Handle symlinks encountered during directory scan
  2881. * @param {String} watchPath - file/dir path to be watched with fsevents
  2882. * @param {String} realPath - real path (in case of symlinks)
  2883. * @param {Function} transform - path transformer
  2884. * @param {Function} globFilter - path filter in case a glob pattern was provided
  2885. * @returns {Function} closer for the watcher instance
  2886. */
  2887. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  2888. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  2889. const opts = this.fsw.options;
  2890. const watchCallback = async (fullPath, flags, info) => {
  2891. if (this.fsw.closed) return;
  2892. if (
  2893. opts.depth !== undefined &&
  2894. calcDepth(fullPath, realPath) > opts.depth
  2895. ) return;
  2896. const path = transform(sysPath$1.join(
  2897. watchPath, sysPath$1.relative(watchPath, fullPath)
  2898. ));
  2899. if (globFilter && !globFilter(path)) return;
  2900. // ensure directories are tracked
  2901. const parent = sysPath$1.dirname(path);
  2902. const item = sysPath$1.basename(path);
  2903. const watchedDir = this.fsw._getWatchedDir(
  2904. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  2905. );
  2906. // correct for wrong events emitted
  2907. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  2908. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  2909. let stats;
  2910. try {
  2911. stats = await stat$1(path);
  2912. } catch (error) {}
  2913. if (this.fsw.closed) return;
  2914. if (this.checkIgnored(path, stats)) return;
  2915. if (sameTypes(info, stats)) {
  2916. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2917. } else {
  2918. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2919. }
  2920. } else {
  2921. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2922. }
  2923. } else {
  2924. switch (info.event) {
  2925. case FSEVENT_CREATED:
  2926. case FSEVENT_MODIFIED:
  2927. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2928. case FSEVENT_DELETED:
  2929. case FSEVENT_MOVED:
  2930. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2931. }
  2932. }
  2933. };
  2934. const closer = setFSEventsListener(
  2935. watchPath,
  2936. realPath,
  2937. watchCallback,
  2938. this.fsw._emitRaw
  2939. );
  2940. this.fsw._emitReady();
  2941. return closer;
  2942. }
  2943. /**
  2944. * Handle symlinks encountered during directory scan
  2945. * @param {String} linkPath path to symlink
  2946. * @param {String} fullPath absolute path to the symlink
  2947. * @param {Function} transform pre-existing path transformer
  2948. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  2949. * @returns {Promise<void>}
  2950. */
  2951. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  2952. // don't follow the same symlink more than once
  2953. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  2954. this.fsw._symlinkPaths.set(fullPath, true);
  2955. this.fsw._incrReadyCount();
  2956. try {
  2957. const linkTarget = await realpath(linkPath);
  2958. if (this.fsw.closed) return;
  2959. if (this.fsw._isIgnored(linkTarget)) {
  2960. return this.fsw._emitReady();
  2961. }
  2962. this.fsw._incrReadyCount();
  2963. // add the linkTarget for watching with a wrapper for transform
  2964. // that causes emitted paths to incorporate the link's path
  2965. this._addToFsEvents(linkTarget || linkPath, (path) => {
  2966. let aliasedPath = linkPath;
  2967. if (linkTarget && linkTarget !== DOT_SLASH) {
  2968. aliasedPath = path.replace(linkTarget, linkPath);
  2969. } else if (path !== DOT_SLASH) {
  2970. aliasedPath = sysPath$1.join(linkPath, path);
  2971. }
  2972. return transform(aliasedPath);
  2973. }, false, curDepth);
  2974. } catch(error) {
  2975. if (this.fsw._handleError(error)) {
  2976. return this.fsw._emitReady();
  2977. }
  2978. }
  2979. }
  2980. /**
  2981. *
  2982. * @param {Path} newPath
  2983. * @param {fs.Stats} stats
  2984. */
  2985. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  2986. const pp = processPath(newPath);
  2987. const isDir = stats.isDirectory();
  2988. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  2989. const base = sysPath$1.basename(pp);
  2990. // ensure empty dirs get tracked
  2991. if (isDir) this.fsw._getWatchedDir(pp);
  2992. if (dirObj.has(base)) return;
  2993. dirObj.add(base);
  2994. if (!opts.ignoreInitial || forceAdd === true) {
  2995. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  2996. }
  2997. }
  2998. initWatch(realPath, path, wh, processPath) {
  2999. if (this.fsw.closed) return;
  3000. const closer = this._watchWithFsEvents(
  3001. wh.watchPath,
  3002. sysPath$1.resolve(realPath || wh.watchPath),
  3003. processPath,
  3004. wh.globFilter
  3005. );
  3006. this.fsw._addPathCloser(path, closer);
  3007. }
  3008. /**
  3009. * Handle added path with fsevents
  3010. * @param {String} path file/dir path or glob pattern
  3011. * @param {Function|Boolean=} transform converts working path to what the user expects
  3012. * @param {Boolean=} forceAdd ensure add is emitted
  3013. * @param {Number=} priorDepth Level of subdirectories already traversed.
  3014. * @returns {Promise<void>}
  3015. */
  3016. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  3017. if (this.fsw.closed) {
  3018. return;
  3019. }
  3020. const opts = this.fsw.options;
  3021. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  3022. const wh = this.fsw._getWatchHelpers(path);
  3023. // evaluate what is at the path we're being asked to watch
  3024. try {
  3025. const stats = await statMethods[wh.statMethod](wh.watchPath);
  3026. if (this.fsw.closed) return;
  3027. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  3028. throw null;
  3029. }
  3030. if (stats.isDirectory()) {
  3031. // emit addDir unless this is a glob parent
  3032. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  3033. // don't recurse further if it would exceed depth setting
  3034. if (priorDepth && priorDepth > opts.depth) return;
  3035. // scan the contents of the dir
  3036. this.fsw._readdirp(wh.watchPath, {
  3037. fileFilter: entry => wh.filterPath(entry),
  3038. directoryFilter: entry => wh.filterDir(entry),
  3039. ...Depth(opts.depth - (priorDepth || 0))
  3040. }).on(STR_DATA, (entry) => {
  3041. // need to check filterPath on dirs b/c filterDir is less restrictive
  3042. if (this.fsw.closed) {
  3043. return;
  3044. }
  3045. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  3046. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  3047. const {fullPath} = entry;
  3048. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  3049. // preserve the current depth here since it can't be derived from
  3050. // real paths past the symlink
  3051. const curDepth = opts.depth === undefined ?
  3052. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  3053. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  3054. } else {
  3055. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  3056. }
  3057. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  3058. this.fsw._emitReady();
  3059. });
  3060. } else {
  3061. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  3062. this.fsw._emitReady();
  3063. }
  3064. } catch (error) {
  3065. if (!error || this.fsw._handleError(error)) {
  3066. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  3067. this.fsw._emitReady();
  3068. this.fsw._emitReady();
  3069. }
  3070. }
  3071. if (opts.persistent && forceAdd !== true) {
  3072. if (typeof transform === FUNCTION_TYPE$1) {
  3073. // realpath has already been resolved
  3074. this.initWatch(undefined, path, wh, processPath);
  3075. } else {
  3076. let realPath;
  3077. try {
  3078. realPath = await realpath(wh.watchPath);
  3079. } catch (e) {}
  3080. this.initWatch(realPath, path, wh, processPath);
  3081. }
  3082. }
  3083. }
  3084. }
  3085. fseventsHandler.exports = FsEventsHandler$1;
  3086. fseventsHandler.exports.canUse = canUse;
  3087. const { EventEmitter } = require$$0$3;
  3088. const fs = require$$0$1;
  3089. const sysPath = require$$0$2;
  3090. const { promisify } = require$$2;
  3091. const readdirp = readdirp_1;
  3092. const anymatch = anymatch$2.exports.default;
  3093. const globParent = globParent$1;
  3094. const isGlob = isGlob$2;
  3095. const braces = braces_1;
  3096. const normalizePath = normalizePath$2;
  3097. const NodeFsHandler = nodefsHandler;
  3098. const FsEventsHandler = fseventsHandler.exports;
  3099. const {
  3100. EV_ALL,
  3101. EV_READY,
  3102. EV_ADD,
  3103. EV_CHANGE,
  3104. EV_UNLINK,
  3105. EV_ADD_DIR,
  3106. EV_UNLINK_DIR,
  3107. EV_RAW,
  3108. EV_ERROR,
  3109. STR_CLOSE,
  3110. STR_END,
  3111. BACK_SLASH_RE,
  3112. DOUBLE_SLASH_RE,
  3113. SLASH_OR_BACK_SLASH_RE,
  3114. DOT_RE,
  3115. REPLACER_RE,
  3116. SLASH,
  3117. SLASH_SLASH,
  3118. BRACE_START,
  3119. BANG,
  3120. ONE_DOT,
  3121. TWO_DOTS,
  3122. GLOBSTAR,
  3123. SLASH_GLOBSTAR,
  3124. ANYMATCH_OPTS,
  3125. STRING_TYPE,
  3126. FUNCTION_TYPE,
  3127. EMPTY_STR,
  3128. EMPTY_FN,
  3129. isWindows,
  3130. isMacos,
  3131. isIBMi
  3132. } = constants;
  3133. const stat = promisify(fs.stat);
  3134. const readdir = promisify(fs.readdir);
  3135. /**
  3136. * @typedef {String} Path
  3137. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  3138. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  3139. */
  3140. /**
  3141. *
  3142. * @typedef {Object} WatchHelpers
  3143. * @property {Boolean} followSymlinks
  3144. * @property {'stat'|'lstat'} statMethod
  3145. * @property {Path} path
  3146. * @property {Path} watchPath
  3147. * @property {Function} entryPath
  3148. * @property {Boolean} hasGlob
  3149. * @property {Object} globFilter
  3150. * @property {Function} filterPath
  3151. * @property {Function} filterDir
  3152. */
  3153. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  3154. const flatten = (list, result = []) => {
  3155. list.forEach(item => {
  3156. if (Array.isArray(item)) {
  3157. flatten(item, result);
  3158. } else {
  3159. result.push(item);
  3160. }
  3161. });
  3162. return result;
  3163. };
  3164. const unifyPaths = (paths_) => {
  3165. /**
  3166. * @type {Array<String>}
  3167. */
  3168. const paths = flatten(arrify(paths_));
  3169. if (!paths.every(p => typeof p === STRING_TYPE)) {
  3170. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  3171. }
  3172. return paths.map(normalizePathToUnix);
  3173. };
  3174. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  3175. // because "//StoragePC/DrivePool/Movies" is a valid network path
  3176. const toUnix = (string) => {
  3177. let str = string.replace(BACK_SLASH_RE, SLASH);
  3178. let prepend = false;
  3179. if (str.startsWith(SLASH_SLASH)) {
  3180. prepend = true;
  3181. }
  3182. while (str.match(DOUBLE_SLASH_RE)) {
  3183. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  3184. }
  3185. if (prepend) {
  3186. str = SLASH + str;
  3187. }
  3188. return str;
  3189. };
  3190. // Our version of upath.normalize
  3191. // TODO: this is not equal to path-normalize module - investigate why
  3192. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  3193. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  3194. if (typeof path !== STRING_TYPE) return path;
  3195. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  3196. };
  3197. const getAbsolutePath = (path, cwd) => {
  3198. if (sysPath.isAbsolute(path)) {
  3199. return path;
  3200. }
  3201. if (path.startsWith(BANG)) {
  3202. return BANG + sysPath.join(cwd, path.slice(1));
  3203. }
  3204. return sysPath.join(cwd, path);
  3205. };
  3206. const undef = (opts, key) => opts[key] === undefined;
  3207. /**
  3208. * Directory entry.
  3209. * @property {Path} path
  3210. * @property {Set<Path>} items
  3211. */
  3212. class DirEntry {
  3213. /**
  3214. * @param {Path} dir
  3215. * @param {Function} removeWatcher
  3216. */
  3217. constructor(dir, removeWatcher) {
  3218. this.path = dir;
  3219. this._removeWatcher = removeWatcher;
  3220. /** @type {Set<Path>} */
  3221. this.items = new Set();
  3222. }
  3223. add(item) {
  3224. const {items} = this;
  3225. if (!items) return;
  3226. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  3227. }
  3228. async remove(item) {
  3229. const {items} = this;
  3230. if (!items) return;
  3231. items.delete(item);
  3232. if (items.size > 0) return;
  3233. const dir = this.path;
  3234. try {
  3235. await readdir(dir);
  3236. } catch (err) {
  3237. if (this._removeWatcher) {
  3238. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  3239. }
  3240. }
  3241. }
  3242. has(item) {
  3243. const {items} = this;
  3244. if (!items) return;
  3245. return items.has(item);
  3246. }
  3247. /**
  3248. * @returns {Array<String>}
  3249. */
  3250. getChildren() {
  3251. const {items} = this;
  3252. if (!items) return;
  3253. return [...items.values()];
  3254. }
  3255. dispose() {
  3256. this.items.clear();
  3257. delete this.path;
  3258. delete this._removeWatcher;
  3259. delete this.items;
  3260. Object.freeze(this);
  3261. }
  3262. }
  3263. const STAT_METHOD_F = 'stat';
  3264. const STAT_METHOD_L = 'lstat';
  3265. class WatchHelper {
  3266. constructor(path, watchPath, follow, fsw) {
  3267. this.fsw = fsw;
  3268. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  3269. this.watchPath = watchPath;
  3270. this.fullWatchPath = sysPath.resolve(watchPath);
  3271. this.hasGlob = watchPath !== path;
  3272. /** @type {object|boolean} */
  3273. if (path === EMPTY_STR) this.hasGlob = false;
  3274. this.globSymlink = this.hasGlob && follow ? undefined : false;
  3275. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  3276. this.dirParts = this.getDirParts(path);
  3277. this.dirParts.forEach((parts) => {
  3278. if (parts.length > 1) parts.pop();
  3279. });
  3280. this.followSymlinks = follow;
  3281. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  3282. }
  3283. checkGlobSymlink(entry) {
  3284. // only need to resolve once
  3285. // first entry should always have entry.parentDir === EMPTY_STR
  3286. if (this.globSymlink === undefined) {
  3287. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  3288. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  3289. }
  3290. if (this.globSymlink) {
  3291. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  3292. }
  3293. return entry.fullPath;
  3294. }
  3295. entryPath(entry) {
  3296. return sysPath.join(this.watchPath,
  3297. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  3298. );
  3299. }
  3300. filterPath(entry) {
  3301. const {stats} = entry;
  3302. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  3303. const resolvedPath = this.entryPath(entry);
  3304. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  3305. this.globFilter(resolvedPath) : true;
  3306. return matchesGlob &&
  3307. this.fsw._isntIgnored(resolvedPath, stats) &&
  3308. this.fsw._hasReadPermissions(stats);
  3309. }
  3310. getDirParts(path) {
  3311. if (!this.hasGlob) return [];
  3312. const parts = [];
  3313. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  3314. expandedPath.forEach((path) => {
  3315. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  3316. });
  3317. return parts;
  3318. }
  3319. filterDir(entry) {
  3320. if (this.hasGlob) {
  3321. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  3322. let globstar = false;
  3323. this.unmatchedGlob = !this.dirParts.some((parts) => {
  3324. return parts.every((part, i) => {
  3325. if (part === GLOBSTAR) globstar = true;
  3326. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  3327. });
  3328. });
  3329. }
  3330. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  3331. }
  3332. }
  3333. /**
  3334. * Watches files & directories for changes. Emitted events:
  3335. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  3336. *
  3337. * new FSWatcher()
  3338. * .add(directories)
  3339. * .on('add', path => log('File', path, 'was added'))
  3340. */
  3341. class FSWatcher extends EventEmitter {
  3342. // Not indenting methods for history sake; for now.
  3343. constructor(_opts) {
  3344. super();
  3345. const opts = {};
  3346. if (_opts) Object.assign(opts, _opts); // for frozen objects
  3347. /** @type {Map<String, DirEntry>} */
  3348. this._watched = new Map();
  3349. /** @type {Map<String, Array>} */
  3350. this._closers = new Map();
  3351. /** @type {Set<String>} */
  3352. this._ignoredPaths = new Set();
  3353. /** @type {Map<ThrottleType, Map>} */
  3354. this._throttled = new Map();
  3355. /** @type {Map<Path, String|Boolean>} */
  3356. this._symlinkPaths = new Map();
  3357. this._streams = new Set();
  3358. this.closed = false;
  3359. // Set up default options.
  3360. if (undef(opts, 'persistent')) opts.persistent = true;
  3361. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  3362. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  3363. if (undef(opts, 'interval')) opts.interval = 100;
  3364. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  3365. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  3366. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  3367. // Enable fsevents on OS X when polling isn't explicitly enabled.
  3368. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  3369. // If we can't use fsevents, ensure the options reflect it's disabled.
  3370. const canUseFsEvents = FsEventsHandler.canUse();
  3371. if (!canUseFsEvents) opts.useFsEvents = false;
  3372. // Use polling on Mac if not using fsevents.
  3373. // Other platforms use non-polling fs_watch.
  3374. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  3375. opts.usePolling = isMacos;
  3376. }
  3377. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  3378. if(isIBMi) {
  3379. opts.usePolling = true;
  3380. }
  3381. // Global override (useful for end-developers that need to force polling for all
  3382. // instances of chokidar, regardless of usage/dependency depth)
  3383. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  3384. if (envPoll !== undefined) {
  3385. const envLower = envPoll.toLowerCase();
  3386. if (envLower === 'false' || envLower === '0') {
  3387. opts.usePolling = false;
  3388. } else if (envLower === 'true' || envLower === '1') {
  3389. opts.usePolling = true;
  3390. } else {
  3391. opts.usePolling = !!envLower;
  3392. }
  3393. }
  3394. const envInterval = process.env.CHOKIDAR_INTERVAL;
  3395. if (envInterval) {
  3396. opts.interval = Number.parseInt(envInterval, 10);
  3397. }
  3398. // Editor atomic write normalization enabled by default with fs.watch
  3399. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  3400. if (opts.atomic) this._pendingUnlinks = new Map();
  3401. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  3402. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  3403. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  3404. const awf = opts.awaitWriteFinish;
  3405. if (awf) {
  3406. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  3407. if (!awf.pollInterval) awf.pollInterval = 100;
  3408. this._pendingWrites = new Map();
  3409. }
  3410. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  3411. let readyCalls = 0;
  3412. this._emitReady = () => {
  3413. readyCalls++;
  3414. if (readyCalls >= this._readyCount) {
  3415. this._emitReady = EMPTY_FN;
  3416. this._readyEmitted = true;
  3417. // use process.nextTick to allow time for listener to be bound
  3418. process.nextTick(() => this.emit(EV_READY));
  3419. }
  3420. };
  3421. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  3422. this._readyEmitted = false;
  3423. this.options = opts;
  3424. // Initialize with proper watcher.
  3425. if (opts.useFsEvents) {
  3426. this._fsEventsHandler = new FsEventsHandler(this);
  3427. } else {
  3428. this._nodeFsHandler = new NodeFsHandler(this);
  3429. }
  3430. // You’re frozen when your heart’s not open.
  3431. Object.freeze(opts);
  3432. }
  3433. // Public methods
  3434. /**
  3435. * Adds paths to be watched on an existing FSWatcher instance
  3436. * @param {Path|Array<Path>} paths_
  3437. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  3438. * @param {Boolean=} _internal private; indicates a non-user add
  3439. * @returns {FSWatcher} for chaining
  3440. */
  3441. add(paths_, _origAdd, _internal) {
  3442. const {cwd, disableGlobbing} = this.options;
  3443. this.closed = false;
  3444. let paths = unifyPaths(paths_);
  3445. if (cwd) {
  3446. paths = paths.map((path) => {
  3447. const absPath = getAbsolutePath(path, cwd);
  3448. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  3449. if (disableGlobbing || !isGlob(path)) {
  3450. return absPath;
  3451. }
  3452. return normalizePath(absPath);
  3453. });
  3454. }
  3455. // set aside negated glob strings
  3456. paths = paths.filter((path) => {
  3457. if (path.startsWith(BANG)) {
  3458. this._ignoredPaths.add(path.slice(1));
  3459. return false;
  3460. }
  3461. // if a path is being added that was previously ignored, stop ignoring it
  3462. this._ignoredPaths.delete(path);
  3463. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  3464. // reset the cached userIgnored anymatch fn
  3465. // to make ignoredPaths changes effective
  3466. this._userIgnored = undefined;
  3467. return true;
  3468. });
  3469. if (this.options.useFsEvents && this._fsEventsHandler) {
  3470. if (!this._readyCount) this._readyCount = paths.length;
  3471. if (this.options.persistent) this._readyCount *= 2;
  3472. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  3473. } else {
  3474. if (!this._readyCount) this._readyCount = 0;
  3475. this._readyCount += paths.length;
  3476. Promise.all(
  3477. paths.map(async path => {
  3478. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  3479. if (res) this._emitReady();
  3480. return res;
  3481. })
  3482. ).then(results => {
  3483. if (this.closed) return;
  3484. results.filter(item => item).forEach(item => {
  3485. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  3486. });
  3487. });
  3488. }
  3489. return this;
  3490. }
  3491. /**
  3492. * Close watchers or start ignoring events from specified paths.
  3493. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  3494. * @returns {FSWatcher} for chaining
  3495. */
  3496. unwatch(paths_) {
  3497. if (this.closed) return this;
  3498. const paths = unifyPaths(paths_);
  3499. const {cwd} = this.options;
  3500. paths.forEach((path) => {
  3501. // convert to absolute path unless relative path already matches
  3502. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  3503. if (cwd) path = sysPath.join(cwd, path);
  3504. path = sysPath.resolve(path);
  3505. }
  3506. this._closePath(path);
  3507. this._ignoredPaths.add(path);
  3508. if (this._watched.has(path)) {
  3509. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  3510. }
  3511. // reset the cached userIgnored anymatch fn
  3512. // to make ignoredPaths changes effective
  3513. this._userIgnored = undefined;
  3514. });
  3515. return this;
  3516. }
  3517. /**
  3518. * Close watchers and remove all listeners from watched paths.
  3519. * @returns {Promise<void>}.
  3520. */
  3521. close() {
  3522. if (this.closed) return this._closePromise;
  3523. this.closed = true;
  3524. // Memory management.
  3525. this.removeAllListeners();
  3526. const closers = [];
  3527. this._closers.forEach(closerList => closerList.forEach(closer => {
  3528. const promise = closer();
  3529. if (promise instanceof Promise) closers.push(promise);
  3530. }));
  3531. this._streams.forEach(stream => stream.destroy());
  3532. this._userIgnored = undefined;
  3533. this._readyCount = 0;
  3534. this._readyEmitted = false;
  3535. this._watched.forEach(dirent => dirent.dispose());
  3536. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  3537. this[`_${key}`].clear();
  3538. });
  3539. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  3540. return this._closePromise;
  3541. }
  3542. /**
  3543. * Expose list of watched paths
  3544. * @returns {Object} for chaining
  3545. */
  3546. getWatched() {
  3547. const watchList = {};
  3548. this._watched.forEach((entry, dir) => {
  3549. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  3550. watchList[key || ONE_DOT] = entry.getChildren().sort();
  3551. });
  3552. return watchList;
  3553. }
  3554. emitWithAll(event, args) {
  3555. this.emit(...args);
  3556. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  3557. }
  3558. // Common helpers
  3559. // --------------
  3560. /**
  3561. * Normalize and emit events.
  3562. * Calling _emit DOES NOT MEAN emit() would be called!
  3563. * @param {EventName} event Type of event
  3564. * @param {Path} path File or directory path
  3565. * @param {*=} val1 arguments to be passed with event
  3566. * @param {*=} val2
  3567. * @param {*=} val3
  3568. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  3569. */
  3570. async _emit(event, path, val1, val2, val3) {
  3571. if (this.closed) return;
  3572. const opts = this.options;
  3573. if (isWindows) path = sysPath.normalize(path);
  3574. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  3575. /** @type Array<any> */
  3576. const args = [event, path];
  3577. if (val3 !== undefined) args.push(val1, val2, val3);
  3578. else if (val2 !== undefined) args.push(val1, val2);
  3579. else if (val1 !== undefined) args.push(val1);
  3580. const awf = opts.awaitWriteFinish;
  3581. let pw;
  3582. if (awf && (pw = this._pendingWrites.get(path))) {
  3583. pw.lastChange = new Date();
  3584. return this;
  3585. }
  3586. if (opts.atomic) {
  3587. if (event === EV_UNLINK) {
  3588. this._pendingUnlinks.set(path, args);
  3589. setTimeout(() => {
  3590. this._pendingUnlinks.forEach((entry, path) => {
  3591. this.emit(...entry);
  3592. this.emit(EV_ALL, ...entry);
  3593. this._pendingUnlinks.delete(path);
  3594. });
  3595. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  3596. return this;
  3597. }
  3598. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  3599. event = args[0] = EV_CHANGE;
  3600. this._pendingUnlinks.delete(path);
  3601. }
  3602. }
  3603. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  3604. const awfEmit = (err, stats) => {
  3605. if (err) {
  3606. event = args[0] = EV_ERROR;
  3607. args[1] = err;
  3608. this.emitWithAll(event, args);
  3609. } else if (stats) {
  3610. // if stats doesn't exist the file must have been deleted
  3611. if (args.length > 2) {
  3612. args[2] = stats;
  3613. } else {
  3614. args.push(stats);
  3615. }
  3616. this.emitWithAll(event, args);
  3617. }
  3618. };
  3619. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  3620. return this;
  3621. }
  3622. if (event === EV_CHANGE) {
  3623. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  3624. if (isThrottled) return this;
  3625. }
  3626. if (opts.alwaysStat && val1 === undefined &&
  3627. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  3628. ) {
  3629. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  3630. let stats;
  3631. try {
  3632. stats = await stat(fullPath);
  3633. } catch (err) {}
  3634. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  3635. if (!stats || this.closed) return;
  3636. args.push(stats);
  3637. }
  3638. this.emitWithAll(event, args);
  3639. return this;
  3640. }
  3641. /**
  3642. * Common handler for errors
  3643. * @param {Error} error
  3644. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  3645. */
  3646. _handleError(error) {
  3647. const code = error && error.code;
  3648. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  3649. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  3650. ) {
  3651. this.emit(EV_ERROR, error);
  3652. }
  3653. return error || this.closed;
  3654. }
  3655. /**
  3656. * Helper utility for throttling
  3657. * @param {ThrottleType} actionType type being throttled
  3658. * @param {Path} path being acted upon
  3659. * @param {Number} timeout duration of time to suppress duplicate actions
  3660. * @returns {Object|false} tracking object or false if action should be suppressed
  3661. */
  3662. _throttle(actionType, path, timeout) {
  3663. if (!this._throttled.has(actionType)) {
  3664. this._throttled.set(actionType, new Map());
  3665. }
  3666. /** @type {Map<Path, Object>} */
  3667. const action = this._throttled.get(actionType);
  3668. /** @type {Object} */
  3669. const actionPath = action.get(path);
  3670. if (actionPath) {
  3671. actionPath.count++;
  3672. return false;
  3673. }
  3674. let timeoutObject;
  3675. const clear = () => {
  3676. const item = action.get(path);
  3677. const count = item ? item.count : 0;
  3678. action.delete(path);
  3679. clearTimeout(timeoutObject);
  3680. if (item) clearTimeout(item.timeoutObject);
  3681. return count;
  3682. };
  3683. timeoutObject = setTimeout(clear, timeout);
  3684. const thr = {timeoutObject, clear, count: 0};
  3685. action.set(path, thr);
  3686. return thr;
  3687. }
  3688. _incrReadyCount() {
  3689. return this._readyCount++;
  3690. }
  3691. /**
  3692. * Awaits write operation to finish.
  3693. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  3694. * @param {Path} path being acted upon
  3695. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  3696. * @param {EventName} event
  3697. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  3698. */
  3699. _awaitWriteFinish(path, threshold, event, awfEmit) {
  3700. let timeoutHandler;
  3701. let fullPath = path;
  3702. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  3703. fullPath = sysPath.join(this.options.cwd, path);
  3704. }
  3705. const now = new Date();
  3706. const awaitWriteFinish = (prevStat) => {
  3707. fs.stat(fullPath, (err, curStat) => {
  3708. if (err || !this._pendingWrites.has(path)) {
  3709. if (err && err.code !== 'ENOENT') awfEmit(err);
  3710. return;
  3711. }
  3712. const now = Number(new Date());
  3713. if (prevStat && curStat.size !== prevStat.size) {
  3714. this._pendingWrites.get(path).lastChange = now;
  3715. }
  3716. const pw = this._pendingWrites.get(path);
  3717. const df = now - pw.lastChange;
  3718. if (df >= threshold) {
  3719. this._pendingWrites.delete(path);
  3720. awfEmit(undefined, curStat);
  3721. } else {
  3722. timeoutHandler = setTimeout(
  3723. awaitWriteFinish,
  3724. this.options.awaitWriteFinish.pollInterval,
  3725. curStat
  3726. );
  3727. }
  3728. });
  3729. };
  3730. if (!this._pendingWrites.has(path)) {
  3731. this._pendingWrites.set(path, {
  3732. lastChange: now,
  3733. cancelWait: () => {
  3734. this._pendingWrites.delete(path);
  3735. clearTimeout(timeoutHandler);
  3736. return event;
  3737. }
  3738. });
  3739. timeoutHandler = setTimeout(
  3740. awaitWriteFinish,
  3741. this.options.awaitWriteFinish.pollInterval
  3742. );
  3743. }
  3744. }
  3745. _getGlobIgnored() {
  3746. return [...this._ignoredPaths.values()];
  3747. }
  3748. /**
  3749. * Determines whether user has asked to ignore this path.
  3750. * @param {Path} path filepath or dir
  3751. * @param {fs.Stats=} stats result of fs.stat
  3752. * @returns {Boolean}
  3753. */
  3754. _isIgnored(path, stats) {
  3755. if (this.options.atomic && DOT_RE.test(path)) return true;
  3756. if (!this._userIgnored) {
  3757. const {cwd} = this.options;
  3758. const ign = this.options.ignored;
  3759. const ignored = ign && ign.map(normalizeIgnored(cwd));
  3760. const paths = arrify(ignored)
  3761. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  3762. .map((path) => path + SLASH_GLOBSTAR);
  3763. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  3764. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  3765. }
  3766. return this._userIgnored([path, stats]);
  3767. }
  3768. _isntIgnored(path, stat) {
  3769. return !this._isIgnored(path, stat);
  3770. }
  3771. /**
  3772. * Provides a set of common helpers and properties relating to symlink and glob handling.
  3773. * @param {Path} path file, directory, or glob pattern being watched
  3774. * @param {Number=} depth at any depth > 0, this isn't a glob
  3775. * @returns {WatchHelper} object containing helpers for this path
  3776. */
  3777. _getWatchHelpers(path, depth) {
  3778. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  3779. const follow = this.options.followSymlinks;
  3780. return new WatchHelper(path, watchPath, follow, this);
  3781. }
  3782. // Directory helpers
  3783. // -----------------
  3784. /**
  3785. * Provides directory tracking objects
  3786. * @param {String} directory path of the directory
  3787. * @returns {DirEntry} the directory's tracking object
  3788. */
  3789. _getWatchedDir(directory) {
  3790. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  3791. const dir = sysPath.resolve(directory);
  3792. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  3793. return this._watched.get(dir);
  3794. }
  3795. // File helpers
  3796. // ------------
  3797. /**
  3798. * Check for read permissions.
  3799. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  3800. * @param {fs.Stats} stats - object, result of fs_stat
  3801. * @returns {Boolean} indicates whether the file can be read
  3802. */
  3803. _hasReadPermissions(stats) {
  3804. if (this.options.ignorePermissionErrors) return true;
  3805. // stats.mode may be bigint
  3806. const md = stats && Number.parseInt(stats.mode, 10);
  3807. const st = md & 0o777;
  3808. const it = Number.parseInt(st.toString(8)[0], 10);
  3809. return Boolean(4 & it);
  3810. }
  3811. /**
  3812. * Handles emitting unlink events for
  3813. * files and directories, and via recursion, for
  3814. * files and directories within directories that are unlinked
  3815. * @param {String} directory within which the following item is located
  3816. * @param {String} item base path of item/directory
  3817. * @returns {void}
  3818. */
  3819. _remove(directory, item, isDirectory) {
  3820. // if what is being deleted is a directory, get that directory's paths
  3821. // for recursive deleting and cleaning of watched object
  3822. // if it is not a directory, nestedDirectoryChildren will be empty array
  3823. const path = sysPath.join(directory, item);
  3824. const fullPath = sysPath.resolve(path);
  3825. isDirectory = isDirectory != null
  3826. ? isDirectory
  3827. : this._watched.has(path) || this._watched.has(fullPath);
  3828. // prevent duplicate handling in case of arriving here nearly simultaneously
  3829. // via multiple paths (such as _handleFile and _handleDir)
  3830. if (!this._throttle('remove', path, 100)) return;
  3831. // if the only watched file is removed, watch for its return
  3832. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  3833. this.add(directory, item, true);
  3834. }
  3835. // This will create a new entry in the watched object in either case
  3836. // so we got to do the directory check beforehand
  3837. const wp = this._getWatchedDir(path);
  3838. const nestedDirectoryChildren = wp.getChildren();
  3839. // Recursively remove children directories / files.
  3840. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  3841. // Check if item was on the watched list and remove it
  3842. const parent = this._getWatchedDir(directory);
  3843. const wasTracked = parent.has(item);
  3844. parent.remove(item);
  3845. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  3846. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  3847. // but never removed from the map in case the path was deleted.
  3848. // This leads to an incorrect state if the path was recreated:
  3849. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  3850. if (this._symlinkPaths.has(fullPath)) {
  3851. this._symlinkPaths.delete(fullPath);
  3852. }
  3853. // If we wait for this file to be fully written, cancel the wait.
  3854. let relPath = path;
  3855. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  3856. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  3857. const event = this._pendingWrites.get(relPath).cancelWait();
  3858. if (event === EV_ADD) return;
  3859. }
  3860. // The Entry will either be a directory that just got removed
  3861. // or a bogus entry to a file, in either case we have to remove it
  3862. this._watched.delete(path);
  3863. this._watched.delete(fullPath);
  3864. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  3865. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  3866. // Avoid conflicts if we later create another file with the same name
  3867. if (!this.options.useFsEvents) {
  3868. this._closePath(path);
  3869. }
  3870. }
  3871. /**
  3872. * Closes all watchers for a path
  3873. * @param {Path} path
  3874. */
  3875. _closePath(path) {
  3876. this._closeFile(path);
  3877. const dir = sysPath.dirname(path);
  3878. this._getWatchedDir(dir).remove(sysPath.basename(path));
  3879. }
  3880. /**
  3881. * Closes only file-specific watchers
  3882. * @param {Path} path
  3883. */
  3884. _closeFile(path) {
  3885. const closers = this._closers.get(path);
  3886. if (!closers) return;
  3887. closers.forEach(closer => closer());
  3888. this._closers.delete(path);
  3889. }
  3890. /**
  3891. *
  3892. * @param {Path} path
  3893. * @param {Function} closer
  3894. */
  3895. _addPathCloser(path, closer) {
  3896. if (!closer) return;
  3897. let list = this._closers.get(path);
  3898. if (!list) {
  3899. list = [];
  3900. this._closers.set(path, list);
  3901. }
  3902. list.push(closer);
  3903. }
  3904. _readdirp(root, opts) {
  3905. if (this.closed) return;
  3906. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  3907. let stream = readdirp(root, options);
  3908. this._streams.add(stream);
  3909. stream.once(STR_CLOSE, () => {
  3910. stream = undefined;
  3911. });
  3912. stream.once(STR_END, () => {
  3913. if (stream) {
  3914. this._streams.delete(stream);
  3915. stream = undefined;
  3916. }
  3917. });
  3918. return stream;
  3919. }
  3920. }
  3921. // Export FSWatcher class
  3922. chokidar.FSWatcher = FSWatcher;
  3923. /**
  3924. * Instantiates watcher with paths to be tracked.
  3925. * @param {String|Array<String>} paths file/directory paths and/or globs
  3926. * @param {Object=} options chokidar opts
  3927. * @returns an instance of FSWatcher for chaining.
  3928. */
  3929. const watch = (paths, options) => {
  3930. const watcher = new FSWatcher(options);
  3931. watcher.add(paths);
  3932. return watcher;
  3933. };
  3934. chokidar.watch = watch;
  3935. exports.chokidar = chokidar;
  3936. //# sourceMappingURL=index.js.map