watch.js 128 KB

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