watch.js 128 KB

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