b04600e84071c646c76e10dfb9a3ac4630ef83f2c889b0deb28f9e665b683105960beee0e373eb3ea50102f70ce62af634663b11fe2fc4352dd90f8e4fc166 128 KB

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