watch.js 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331
  1. /*
  2. @license
  3. Rollup.js v2.33.1
  4. Mon, 02 Nov 2020 06:50:50 GMT - commit d861c91c068bc4e64d84db3b84232d3fb7f1d073
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { createCommonjsModule, defaultOnWarn, ensureArray as ensureArray$1, warnUnknownOptions, getAugmentedNamespace, fseventsImporter, rollupInternal } from './rollup.js';
  9. import sysPath, { sep, resolve } from 'path';
  10. import 'crypto';
  11. import fs from 'fs';
  12. import require$$0$2 from 'events';
  13. import util from 'util';
  14. import require$$0$1 from 'stream';
  15. import require$$1$1, { platform } from 'os';
  16. var utils = createCommonjsModule(function (module, exports) {
  17. exports.isInteger = num => {
  18. if (typeof num === 'number') {
  19. return Number.isInteger(num);
  20. }
  21. if (typeof num === 'string' && num.trim() !== '') {
  22. return Number.isInteger(Number(num));
  23. }
  24. return false;
  25. };
  26. /**
  27. * Find a node of the given type
  28. */
  29. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  30. /**
  31. * Find a node of the given type
  32. */
  33. exports.exceedsLimit = (min, max, step = 1, limit) => {
  34. if (limit === false) return false;
  35. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  36. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  37. };
  38. /**
  39. * Escape the given node with '\\' before node.value
  40. */
  41. exports.escapeNode = (block, n = 0, type) => {
  42. let node = block.nodes[n];
  43. if (!node) return;
  44. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  45. if (node.escaped !== true) {
  46. node.value = '\\' + node.value;
  47. node.escaped = true;
  48. }
  49. }
  50. };
  51. /**
  52. * Returns true if the given brace node should be enclosed in literal braces
  53. */
  54. exports.encloseBrace = node => {
  55. if (node.type !== 'brace') return false;
  56. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  57. node.invalid = true;
  58. return true;
  59. }
  60. return false;
  61. };
  62. /**
  63. * Returns true if a brace node is invalid.
  64. */
  65. exports.isInvalidBrace = block => {
  66. if (block.type !== 'brace') return false;
  67. if (block.invalid === true || block.dollar) return true;
  68. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  69. block.invalid = true;
  70. return true;
  71. }
  72. if (block.open !== true || block.close !== true) {
  73. block.invalid = true;
  74. return true;
  75. }
  76. return false;
  77. };
  78. /**
  79. * Returns true if a node is an open or close node
  80. */
  81. exports.isOpenOrClose = node => {
  82. if (node.type === 'open' || node.type === 'close') {
  83. return true;
  84. }
  85. return node.open === true || node.close === true;
  86. };
  87. /**
  88. * Reduce an array of text nodes.
  89. */
  90. exports.reduce = nodes => nodes.reduce((acc, node) => {
  91. if (node.type === 'text') acc.push(node.value);
  92. if (node.type === 'range') node.type = 'text';
  93. return acc;
  94. }, []);
  95. /**
  96. * Flatten an array
  97. */
  98. exports.flatten = (...args) => {
  99. const result = [];
  100. const flat = arr => {
  101. for (let i = 0; i < arr.length; i++) {
  102. let ele = arr[i];
  103. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  104. }
  105. return result;
  106. };
  107. flat(args);
  108. return result;
  109. };
  110. });
  111. var stringify = (ast, options = {}) => {
  112. let stringify = (node, parent = {}) => {
  113. let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
  114. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  115. let output = '';
  116. if (node.value) {
  117. if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
  118. return '\\' + node.value;
  119. }
  120. return node.value;
  121. }
  122. if (node.value) {
  123. return node.value;
  124. }
  125. if (node.nodes) {
  126. for (let child of node.nodes) {
  127. output += stringify(child);
  128. }
  129. }
  130. return output;
  131. };
  132. return stringify(ast);
  133. };
  134. /*!
  135. * is-number <https://github.com/jonschlinkert/is-number>
  136. *
  137. * Copyright (c) 2014-present, Jon Schlinkert.
  138. * Released under the MIT License.
  139. */
  140. var isNumber = function(num) {
  141. if (typeof num === 'number') {
  142. return num - num === 0;
  143. }
  144. if (typeof num === 'string' && num.trim() !== '') {
  145. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  146. }
  147. return false;
  148. };
  149. const toRegexRange = (min, max, options) => {
  150. if (isNumber(min) === false) {
  151. throw new TypeError('toRegexRange: expected the first argument to be a number');
  152. }
  153. if (max === void 0 || min === max) {
  154. return String(min);
  155. }
  156. if (isNumber(max) === false) {
  157. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  158. }
  159. let opts = { relaxZeros: true, ...options };
  160. if (typeof opts.strictZeros === 'boolean') {
  161. opts.relaxZeros = opts.strictZeros === false;
  162. }
  163. let relax = String(opts.relaxZeros);
  164. let shorthand = String(opts.shorthand);
  165. let capture = String(opts.capture);
  166. let wrap = String(opts.wrap);
  167. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  168. if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
  169. return toRegexRange.cache[cacheKey].result;
  170. }
  171. let a = Math.min(min, max);
  172. let b = Math.max(min, max);
  173. if (Math.abs(a - b) === 1) {
  174. let result = min + '|' + max;
  175. if (opts.capture) {
  176. return `(${result})`;
  177. }
  178. if (opts.wrap === false) {
  179. return result;
  180. }
  181. return `(?:${result})`;
  182. }
  183. let isPadded = hasPadding(min) || hasPadding(max);
  184. let state = { min, max, a, b };
  185. let positives = [];
  186. let negatives = [];
  187. if (isPadded) {
  188. state.isPadded = isPadded;
  189. state.maxLen = String(state.max).length;
  190. }
  191. if (a < 0) {
  192. let newMin = b < 0 ? Math.abs(b) : 1;
  193. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  194. a = state.a = 0;
  195. }
  196. if (b >= 0) {
  197. positives = splitToPatterns(a, b, state, opts);
  198. }
  199. state.negatives = negatives;
  200. state.positives = positives;
  201. state.result = collatePatterns(negatives, positives);
  202. if (opts.capture === true) {
  203. state.result = `(${state.result})`;
  204. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  205. state.result = `(?:${state.result})`;
  206. }
  207. toRegexRange.cache[cacheKey] = state;
  208. return state.result;
  209. };
  210. function collatePatterns(neg, pos, options) {
  211. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  212. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  213. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  214. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  215. return subpatterns.join('|');
  216. }
  217. function splitToRanges(min, max) {
  218. let nines = 1;
  219. let zeros = 1;
  220. let stop = countNines(min, nines);
  221. let stops = new Set([max]);
  222. while (min <= stop && stop <= max) {
  223. stops.add(stop);
  224. nines += 1;
  225. stop = countNines(min, nines);
  226. }
  227. stop = countZeros(max + 1, zeros) - 1;
  228. while (min < stop && stop <= max) {
  229. stops.add(stop);
  230. zeros += 1;
  231. stop = countZeros(max + 1, zeros) - 1;
  232. }
  233. stops = [...stops];
  234. stops.sort(compare);
  235. return stops;
  236. }
  237. /**
  238. * Convert a range to a regex pattern
  239. * @param {Number} `start`
  240. * @param {Number} `stop`
  241. * @return {String}
  242. */
  243. function rangeToPattern(start, stop, options) {
  244. if (start === stop) {
  245. return { pattern: start, count: [], digits: 0 };
  246. }
  247. let zipped = zip(start, stop);
  248. let digits = zipped.length;
  249. let pattern = '';
  250. let count = 0;
  251. for (let i = 0; i < digits; i++) {
  252. let [startDigit, stopDigit] = zipped[i];
  253. if (startDigit === stopDigit) {
  254. pattern += startDigit;
  255. } else if (startDigit !== '0' || stopDigit !== '9') {
  256. pattern += toCharacterClass(startDigit, stopDigit);
  257. } else {
  258. count++;
  259. }
  260. }
  261. if (count) {
  262. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  263. }
  264. return { pattern, count: [count], digits };
  265. }
  266. function splitToPatterns(min, max, tok, options) {
  267. let ranges = splitToRanges(min, max);
  268. let tokens = [];
  269. let start = min;
  270. let prev;
  271. for (let i = 0; i < ranges.length; i++) {
  272. let max = ranges[i];
  273. let obj = rangeToPattern(String(start), String(max), options);
  274. let zeros = '';
  275. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  276. if (prev.count.length > 1) {
  277. prev.count.pop();
  278. }
  279. prev.count.push(obj.count[0]);
  280. prev.string = prev.pattern + toQuantifier(prev.count);
  281. start = max + 1;
  282. continue;
  283. }
  284. if (tok.isPadded) {
  285. zeros = padZeros(max, tok, options);
  286. }
  287. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  288. tokens.push(obj);
  289. start = max + 1;
  290. prev = obj;
  291. }
  292. return tokens;
  293. }
  294. function filterPatterns(arr, comparison, prefix, intersection, options) {
  295. let result = [];
  296. for (let ele of arr) {
  297. let { string } = ele;
  298. // only push if _both_ are negative...
  299. if (!intersection && !contains(comparison, 'string', string)) {
  300. result.push(prefix + string);
  301. }
  302. // or _both_ are positive
  303. if (intersection && contains(comparison, 'string', string)) {
  304. result.push(prefix + string);
  305. }
  306. }
  307. return result;
  308. }
  309. /**
  310. * Zip strings
  311. */
  312. function zip(a, b) {
  313. let arr = [];
  314. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  315. return arr;
  316. }
  317. function compare(a, b) {
  318. return a > b ? 1 : b > a ? -1 : 0;
  319. }
  320. function contains(arr, key, val) {
  321. return arr.some(ele => ele[key] === val);
  322. }
  323. function countNines(min, len) {
  324. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  325. }
  326. function countZeros(integer, zeros) {
  327. return integer - (integer % Math.pow(10, zeros));
  328. }
  329. function toQuantifier(digits) {
  330. let [start = 0, stop = ''] = digits;
  331. if (stop || start > 1) {
  332. return `{${start + (stop ? ',' + stop : '')}}`;
  333. }
  334. return '';
  335. }
  336. function toCharacterClass(a, b, options) {
  337. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  338. }
  339. function hasPadding(str) {
  340. return /^-?(0+)\d/.test(str);
  341. }
  342. function padZeros(value, tok, options) {
  343. if (!tok.isPadded) {
  344. return value;
  345. }
  346. let diff = Math.abs(tok.maxLen - String(value).length);
  347. let relax = options.relaxZeros !== false;
  348. switch (diff) {
  349. case 0:
  350. return '';
  351. case 1:
  352. return relax ? '0?' : '0';
  353. case 2:
  354. return relax ? '0{0,2}' : '00';
  355. default: {
  356. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  357. }
  358. }
  359. }
  360. /**
  361. * Cache
  362. */
  363. toRegexRange.cache = {};
  364. toRegexRange.clearCache = () => (toRegexRange.cache = {});
  365. /**
  366. * Expose `toRegexRange`
  367. */
  368. var toRegexRange_1 = toRegexRange;
  369. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  370. const transform = toNumber => {
  371. return value => toNumber === true ? Number(value) : String(value);
  372. };
  373. const isValidValue = value => {
  374. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  375. };
  376. const isNumber$1 = num => Number.isInteger(+num);
  377. const zeros = input => {
  378. let value = `${input}`;
  379. let index = -1;
  380. if (value[0] === '-') value = value.slice(1);
  381. if (value === '0') return false;
  382. while (value[++index] === '0');
  383. return index > 0;
  384. };
  385. const stringify$1 = (start, end, options) => {
  386. if (typeof start === 'string' || typeof end === 'string') {
  387. return true;
  388. }
  389. return options.stringify === true;
  390. };
  391. const pad = (input, maxLength, toNumber) => {
  392. if (maxLength > 0) {
  393. let dash = input[0] === '-' ? '-' : '';
  394. if (dash) input = input.slice(1);
  395. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  396. }
  397. if (toNumber === false) {
  398. return String(input);
  399. }
  400. return input;
  401. };
  402. const toMaxLen = (input, maxLength) => {
  403. let negative = input[0] === '-' ? '-' : '';
  404. if (negative) {
  405. input = input.slice(1);
  406. maxLength--;
  407. }
  408. while (input.length < maxLength) input = '0' + input;
  409. return negative ? ('-' + input) : input;
  410. };
  411. const toSequence = (parts, options) => {
  412. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  413. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  414. let prefix = options.capture ? '' : '?:';
  415. let positives = '';
  416. let negatives = '';
  417. let result;
  418. if (parts.positives.length) {
  419. positives = parts.positives.join('|');
  420. }
  421. if (parts.negatives.length) {
  422. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  423. }
  424. if (positives && negatives) {
  425. result = `${positives}|${negatives}`;
  426. } else {
  427. result = positives || negatives;
  428. }
  429. if (options.wrap) {
  430. return `(${prefix}${result})`;
  431. }
  432. return result;
  433. };
  434. const toRange = (a, b, isNumbers, options) => {
  435. if (isNumbers) {
  436. return toRegexRange_1(a, b, { wrap: false, ...options });
  437. }
  438. let start = String.fromCharCode(a);
  439. if (a === b) return start;
  440. let stop = String.fromCharCode(b);
  441. return `[${start}-${stop}]`;
  442. };
  443. const toRegex = (start, end, options) => {
  444. if (Array.isArray(start)) {
  445. let wrap = options.wrap === true;
  446. let prefix = options.capture ? '' : '?:';
  447. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  448. }
  449. return toRegexRange_1(start, end, options);
  450. };
  451. const rangeError = (...args) => {
  452. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  453. };
  454. const invalidRange = (start, end, options) => {
  455. if (options.strictRanges === true) throw rangeError([start, end]);
  456. return [];
  457. };
  458. const invalidStep = (step, options) => {
  459. if (options.strictRanges === true) {
  460. throw new TypeError(`Expected step "${step}" to be a number`);
  461. }
  462. return [];
  463. };
  464. const fillNumbers = (start, end, step = 1, options = {}) => {
  465. let a = Number(start);
  466. let b = Number(end);
  467. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  468. if (options.strictRanges === true) throw rangeError([start, end]);
  469. return [];
  470. }
  471. // fix negative zero
  472. if (a === 0) a = 0;
  473. if (b === 0) b = 0;
  474. let descending = a > b;
  475. let startString = String(start);
  476. let endString = String(end);
  477. let stepString = String(step);
  478. step = Math.max(Math.abs(step), 1);
  479. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  480. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  481. let toNumber = padded === false && stringify$1(start, end, options) === false;
  482. let format = options.transform || transform(toNumber);
  483. if (options.toRegex && step === 1) {
  484. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  485. }
  486. let parts = { negatives: [], positives: [] };
  487. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  488. let range = [];
  489. let index = 0;
  490. while (descending ? a >= b : a <= b) {
  491. if (options.toRegex === true && step > 1) {
  492. push(a);
  493. } else {
  494. range.push(pad(format(a, index), maxLen, toNumber));
  495. }
  496. a = descending ? a - step : a + step;
  497. index++;
  498. }
  499. if (options.toRegex === true) {
  500. return step > 1
  501. ? toSequence(parts, options)
  502. : toRegex(range, null, { wrap: false, ...options });
  503. }
  504. return range;
  505. };
  506. const fillLetters = (start, end, step = 1, options = {}) => {
  507. if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {
  508. return invalidRange(start, end, options);
  509. }
  510. let format = options.transform || (val => String.fromCharCode(val));
  511. let a = `${start}`.charCodeAt(0);
  512. let b = `${end}`.charCodeAt(0);
  513. let descending = a > b;
  514. let min = Math.min(a, b);
  515. let max = Math.max(a, b);
  516. if (options.toRegex && step === 1) {
  517. return toRange(min, max, false, options);
  518. }
  519. let range = [];
  520. let index = 0;
  521. while (descending ? a >= b : a <= b) {
  522. range.push(format(a, index));
  523. a = descending ? a - step : a + step;
  524. index++;
  525. }
  526. if (options.toRegex === true) {
  527. return toRegex(range, null, { wrap: false, options });
  528. }
  529. return range;
  530. };
  531. const fill = (start, end, step, options = {}) => {
  532. if (end == null && isValidValue(start)) {
  533. return [start];
  534. }
  535. if (!isValidValue(start) || !isValidValue(end)) {
  536. return invalidRange(start, end, options);
  537. }
  538. if (typeof step === 'function') {
  539. return fill(start, end, 1, { transform: step });
  540. }
  541. if (isObject(step)) {
  542. return fill(start, end, 0, step);
  543. }
  544. let opts = { ...options };
  545. if (opts.capture === true) opts.wrap = true;
  546. step = step || opts.step || 1;
  547. if (!isNumber$1(step)) {
  548. if (step != null && !isObject(step)) return invalidStep(step, opts);
  549. return fill(start, end, 1, step);
  550. }
  551. if (isNumber$1(start) && isNumber$1(end)) {
  552. return fillNumbers(start, end, step, opts);
  553. }
  554. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  555. };
  556. var fillRange = fill;
  557. const compile = (ast, options = {}) => {
  558. let walk = (node, parent = {}) => {
  559. let invalidBlock = utils.isInvalidBrace(parent);
  560. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  561. let invalid = invalidBlock === true || invalidNode === true;
  562. let prefix = options.escapeInvalid === true ? '\\' : '';
  563. let output = '';
  564. if (node.isOpen === true) {
  565. return prefix + node.value;
  566. }
  567. if (node.isClose === true) {
  568. return prefix + node.value;
  569. }
  570. if (node.type === 'open') {
  571. return invalid ? (prefix + node.value) : '(';
  572. }
  573. if (node.type === 'close') {
  574. return invalid ? (prefix + node.value) : ')';
  575. }
  576. if (node.type === 'comma') {
  577. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  578. }
  579. if (node.value) {
  580. return node.value;
  581. }
  582. if (node.nodes && node.ranges > 0) {
  583. let args = utils.reduce(node.nodes);
  584. let range = fillRange(...args, { ...options, wrap: false, toRegex: true });
  585. if (range.length !== 0) {
  586. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  587. }
  588. }
  589. if (node.nodes) {
  590. for (let child of node.nodes) {
  591. output += walk(child, node);
  592. }
  593. }
  594. return output;
  595. };
  596. return walk(ast);
  597. };
  598. var compile_1 = compile;
  599. const append = (queue = '', stash = '', enclose = false) => {
  600. let result = [];
  601. queue = [].concat(queue);
  602. stash = [].concat(stash);
  603. if (!stash.length) return queue;
  604. if (!queue.length) {
  605. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  606. }
  607. for (let item of queue) {
  608. if (Array.isArray(item)) {
  609. for (let value of item) {
  610. result.push(append(value, stash, enclose));
  611. }
  612. } else {
  613. for (let ele of stash) {
  614. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  615. result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
  616. }
  617. }
  618. }
  619. return utils.flatten(result);
  620. };
  621. const expand = (ast, options = {}) => {
  622. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  623. let walk = (node, parent = {}) => {
  624. node.queue = [];
  625. let p = parent;
  626. let q = parent.queue;
  627. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  628. p = p.parent;
  629. q = p.queue;
  630. }
  631. if (node.invalid || node.dollar) {
  632. q.push(append(q.pop(), stringify(node, options)));
  633. return;
  634. }
  635. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  636. q.push(append(q.pop(), ['{}']));
  637. return;
  638. }
  639. if (node.nodes && node.ranges > 0) {
  640. let args = utils.reduce(node.nodes);
  641. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  642. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  643. }
  644. let range = fillRange(...args, options);
  645. if (range.length === 0) {
  646. range = stringify(node, options);
  647. }
  648. q.push(append(q.pop(), range));
  649. node.nodes = [];
  650. return;
  651. }
  652. let enclose = utils.encloseBrace(node);
  653. let queue = node.queue;
  654. let block = node;
  655. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  656. block = block.parent;
  657. queue = block.queue;
  658. }
  659. for (let i = 0; i < node.nodes.length; i++) {
  660. let child = node.nodes[i];
  661. if (child.type === 'comma' && node.type === 'brace') {
  662. if (i === 1) queue.push('');
  663. queue.push('');
  664. continue;
  665. }
  666. if (child.type === 'close') {
  667. q.push(append(q.pop(), queue, enclose));
  668. continue;
  669. }
  670. if (child.value && child.type !== 'open') {
  671. queue.push(append(queue.pop(), child.value));
  672. continue;
  673. }
  674. if (child.nodes) {
  675. walk(child, node);
  676. }
  677. }
  678. return queue;
  679. };
  680. return utils.flatten(walk(ast));
  681. };
  682. var expand_1 = expand;
  683. var constants = {
  684. MAX_LENGTH: 1024 * 64,
  685. // Digits
  686. CHAR_0: '0', /* 0 */
  687. CHAR_9: '9', /* 9 */
  688. // Alphabet chars.
  689. CHAR_UPPERCASE_A: 'A', /* A */
  690. CHAR_LOWERCASE_A: 'a', /* a */
  691. CHAR_UPPERCASE_Z: 'Z', /* Z */
  692. CHAR_LOWERCASE_Z: 'z', /* z */
  693. CHAR_LEFT_PARENTHESES: '(', /* ( */
  694. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  695. CHAR_ASTERISK: '*', /* * */
  696. // Non-alphabetic chars.
  697. CHAR_AMPERSAND: '&', /* & */
  698. CHAR_AT: '@', /* @ */
  699. CHAR_BACKSLASH: '\\', /* \ */
  700. CHAR_BACKTICK: '`', /* ` */
  701. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  702. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  703. CHAR_COLON: ':', /* : */
  704. CHAR_COMMA: ',', /* , */
  705. CHAR_DOLLAR: '$', /* . */
  706. CHAR_DOT: '.', /* . */
  707. CHAR_DOUBLE_QUOTE: '"', /* " */
  708. CHAR_EQUAL: '=', /* = */
  709. CHAR_EXCLAMATION_MARK: '!', /* ! */
  710. CHAR_FORM_FEED: '\f', /* \f */
  711. CHAR_FORWARD_SLASH: '/', /* / */
  712. CHAR_HASH: '#', /* # */
  713. CHAR_HYPHEN_MINUS: '-', /* - */
  714. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  715. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  716. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  717. CHAR_LINE_FEED: '\n', /* \n */
  718. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  719. CHAR_PERCENT: '%', /* % */
  720. CHAR_PLUS: '+', /* + */
  721. CHAR_QUESTION_MARK: '?', /* ? */
  722. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  723. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  724. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  725. CHAR_SEMICOLON: ';', /* ; */
  726. CHAR_SINGLE_QUOTE: '\'', /* ' */
  727. CHAR_SPACE: ' ', /* */
  728. CHAR_TAB: '\t', /* \t */
  729. CHAR_UNDERSCORE: '_', /* _ */
  730. CHAR_VERTICAL_LINE: '|', /* | */
  731. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  732. };
  733. /**
  734. * Constants
  735. */
  736. const {
  737. MAX_LENGTH,
  738. CHAR_BACKSLASH, /* \ */
  739. CHAR_BACKTICK, /* ` */
  740. CHAR_COMMA, /* , */
  741. CHAR_DOT, /* . */
  742. CHAR_LEFT_PARENTHESES, /* ( */
  743. CHAR_RIGHT_PARENTHESES, /* ) */
  744. CHAR_LEFT_CURLY_BRACE, /* { */
  745. CHAR_RIGHT_CURLY_BRACE, /* } */
  746. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  747. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  748. CHAR_DOUBLE_QUOTE, /* " */
  749. CHAR_SINGLE_QUOTE, /* ' */
  750. CHAR_NO_BREAK_SPACE,
  751. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  752. } = constants;
  753. /**
  754. * parse
  755. */
  756. const parse = (input, options = {}) => {
  757. if (typeof input !== 'string') {
  758. throw new TypeError('Expected a string');
  759. }
  760. let opts = options || {};
  761. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  762. if (input.length > max) {
  763. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  764. }
  765. let ast = { type: 'root', input, nodes: [] };
  766. let stack = [ast];
  767. let block = ast;
  768. let prev = ast;
  769. let brackets = 0;
  770. let length = input.length;
  771. let index = 0;
  772. let depth = 0;
  773. let value;
  774. /**
  775. * Helpers
  776. */
  777. const advance = () => input[index++];
  778. const push = node => {
  779. if (node.type === 'text' && prev.type === 'dot') {
  780. prev.type = 'text';
  781. }
  782. if (prev && prev.type === 'text' && node.type === 'text') {
  783. prev.value += node.value;
  784. return;
  785. }
  786. block.nodes.push(node);
  787. node.parent = block;
  788. node.prev = prev;
  789. prev = node;
  790. return node;
  791. };
  792. push({ type: 'bos' });
  793. while (index < length) {
  794. block = stack[stack.length - 1];
  795. value = advance();
  796. /**
  797. * Invalid chars
  798. */
  799. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  800. continue;
  801. }
  802. /**
  803. * Escaped chars
  804. */
  805. if (value === CHAR_BACKSLASH) {
  806. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  807. continue;
  808. }
  809. /**
  810. * Right square bracket (literal): ']'
  811. */
  812. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  813. push({ type: 'text', value: '\\' + value });
  814. continue;
  815. }
  816. /**
  817. * Left square bracket: '['
  818. */
  819. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  820. brackets++;
  821. let next;
  822. while (index < length && (next = advance())) {
  823. value += next;
  824. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  825. brackets++;
  826. continue;
  827. }
  828. if (next === CHAR_BACKSLASH) {
  829. value += advance();
  830. continue;
  831. }
  832. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  833. brackets--;
  834. if (brackets === 0) {
  835. break;
  836. }
  837. }
  838. }
  839. push({ type: 'text', value });
  840. continue;
  841. }
  842. /**
  843. * Parentheses
  844. */
  845. if (value === CHAR_LEFT_PARENTHESES) {
  846. block = push({ type: 'paren', nodes: [] });
  847. stack.push(block);
  848. push({ type: 'text', value });
  849. continue;
  850. }
  851. if (value === CHAR_RIGHT_PARENTHESES) {
  852. if (block.type !== 'paren') {
  853. push({ type: 'text', value });
  854. continue;
  855. }
  856. block = stack.pop();
  857. push({ type: 'text', value });
  858. block = stack[stack.length - 1];
  859. continue;
  860. }
  861. /**
  862. * Quotes: '|"|`
  863. */
  864. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  865. let open = value;
  866. let next;
  867. if (options.keepQuotes !== true) {
  868. value = '';
  869. }
  870. while (index < length && (next = advance())) {
  871. if (next === CHAR_BACKSLASH) {
  872. value += next + advance();
  873. continue;
  874. }
  875. if (next === open) {
  876. if (options.keepQuotes === true) value += next;
  877. break;
  878. }
  879. value += next;
  880. }
  881. push({ type: 'text', value });
  882. continue;
  883. }
  884. /**
  885. * Left curly brace: '{'
  886. */
  887. if (value === CHAR_LEFT_CURLY_BRACE) {
  888. depth++;
  889. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  890. let brace = {
  891. type: 'brace',
  892. open: true,
  893. close: false,
  894. dollar,
  895. depth,
  896. commas: 0,
  897. ranges: 0,
  898. nodes: []
  899. };
  900. block = push(brace);
  901. stack.push(block);
  902. push({ type: 'open', value });
  903. continue;
  904. }
  905. /**
  906. * Right curly brace: '}'
  907. */
  908. if (value === CHAR_RIGHT_CURLY_BRACE) {
  909. if (block.type !== 'brace') {
  910. push({ type: 'text', value });
  911. continue;
  912. }
  913. let type = 'close';
  914. block = stack.pop();
  915. block.close = true;
  916. push({ type, value });
  917. depth--;
  918. block = stack[stack.length - 1];
  919. continue;
  920. }
  921. /**
  922. * Comma: ','
  923. */
  924. if (value === CHAR_COMMA && depth > 0) {
  925. if (block.ranges > 0) {
  926. block.ranges = 0;
  927. let open = block.nodes.shift();
  928. block.nodes = [open, { type: 'text', value: stringify(block) }];
  929. }
  930. push({ type: 'comma', value });
  931. block.commas++;
  932. continue;
  933. }
  934. /**
  935. * Dot: '.'
  936. */
  937. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  938. let siblings = block.nodes;
  939. if (depth === 0 || siblings.length === 0) {
  940. push({ type: 'text', value });
  941. continue;
  942. }
  943. if (prev.type === 'dot') {
  944. block.range = [];
  945. prev.value += value;
  946. prev.type = 'range';
  947. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  948. block.invalid = true;
  949. block.ranges = 0;
  950. prev.type = 'text';
  951. continue;
  952. }
  953. block.ranges++;
  954. block.args = [];
  955. continue;
  956. }
  957. if (prev.type === 'range') {
  958. siblings.pop();
  959. let before = siblings[siblings.length - 1];
  960. before.value += prev.value + value;
  961. prev = before;
  962. block.ranges--;
  963. continue;
  964. }
  965. push({ type: 'dot', value });
  966. continue;
  967. }
  968. /**
  969. * Text
  970. */
  971. push({ type: 'text', value });
  972. }
  973. // Mark imbalanced braces and brackets as invalid
  974. do {
  975. block = stack.pop();
  976. if (block.type !== 'root') {
  977. block.nodes.forEach(node => {
  978. if (!node.nodes) {
  979. if (node.type === 'open') node.isOpen = true;
  980. if (node.type === 'close') node.isClose = true;
  981. if (!node.nodes) node.type = 'text';
  982. node.invalid = true;
  983. }
  984. });
  985. // get the location of the block on parent.nodes (block's siblings)
  986. let parent = stack[stack.length - 1];
  987. let index = parent.nodes.indexOf(block);
  988. // replace the (invalid) block with it's nodes
  989. parent.nodes.splice(index, 1, ...block.nodes);
  990. }
  991. } while (stack.length > 0);
  992. push({ type: 'eos' });
  993. return ast;
  994. };
  995. var parse_1 = parse;
  996. /**
  997. * Expand the given pattern or create a regex-compatible string.
  998. *
  999. * ```js
  1000. * const braces = require('braces');
  1001. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  1002. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  1003. * ```
  1004. * @param {String} `str`
  1005. * @param {Object} `options`
  1006. * @return {String}
  1007. * @api public
  1008. */
  1009. const braces = (input, options = {}) => {
  1010. let output = [];
  1011. if (Array.isArray(input)) {
  1012. for (let pattern of input) {
  1013. let result = braces.create(pattern, options);
  1014. if (Array.isArray(result)) {
  1015. output.push(...result);
  1016. } else {
  1017. output.push(result);
  1018. }
  1019. }
  1020. } else {
  1021. output = [].concat(braces.create(input, options));
  1022. }
  1023. if (options && options.expand === true && options.nodupes === true) {
  1024. output = [...new Set(output)];
  1025. }
  1026. return output;
  1027. };
  1028. /**
  1029. * Parse the given `str` with the given `options`.
  1030. *
  1031. * ```js
  1032. * // braces.parse(pattern, [, options]);
  1033. * const ast = braces.parse('a/{b,c}/d');
  1034. * console.log(ast);
  1035. * ```
  1036. * @param {String} pattern Brace pattern to parse
  1037. * @param {Object} options
  1038. * @return {Object} Returns an AST
  1039. * @api public
  1040. */
  1041. braces.parse = (input, options = {}) => parse_1(input, options);
  1042. /**
  1043. * Creates a braces string from an AST, or an AST node.
  1044. *
  1045. * ```js
  1046. * const braces = require('braces');
  1047. * let ast = braces.parse('foo/{a,b}/bar');
  1048. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  1049. * ```
  1050. * @param {String} `input` Brace pattern or AST.
  1051. * @param {Object} `options`
  1052. * @return {Array} Returns an array of expanded values.
  1053. * @api public
  1054. */
  1055. braces.stringify = (input, options = {}) => {
  1056. if (typeof input === 'string') {
  1057. return stringify(braces.parse(input, options), options);
  1058. }
  1059. return stringify(input, options);
  1060. };
  1061. /**
  1062. * Compiles a brace pattern into a regex-compatible, optimized string.
  1063. * This method is called by the main [braces](#braces) function by default.
  1064. *
  1065. * ```js
  1066. * const braces = require('braces');
  1067. * console.log(braces.compile('a/{b,c}/d'));
  1068. * //=> ['a/(b|c)/d']
  1069. * ```
  1070. * @param {String} `input` Brace pattern or AST.
  1071. * @param {Object} `options`
  1072. * @return {Array} Returns an array of expanded values.
  1073. * @api public
  1074. */
  1075. braces.compile = (input, options = {}) => {
  1076. if (typeof input === 'string') {
  1077. input = braces.parse(input, options);
  1078. }
  1079. return compile_1(input, options);
  1080. };
  1081. /**
  1082. * Expands a brace pattern into an array. This method is called by the
  1083. * main [braces](#braces) function when `options.expand` is true. Before
  1084. * using this method it's recommended that you read the [performance notes](#performance))
  1085. * and advantages of using [.compile](#compile) instead.
  1086. *
  1087. * ```js
  1088. * const braces = require('braces');
  1089. * console.log(braces.expand('a/{b,c}/d'));
  1090. * //=> ['a/b/d', 'a/c/d'];
  1091. * ```
  1092. * @param {String} `pattern` Brace pattern
  1093. * @param {Object} `options`
  1094. * @return {Array} Returns an array of expanded values.
  1095. * @api public
  1096. */
  1097. braces.expand = (input, options = {}) => {
  1098. if (typeof input === 'string') {
  1099. input = braces.parse(input, options);
  1100. }
  1101. let result = expand_1(input, options);
  1102. // filter out empty strings if specified
  1103. if (options.noempty === true) {
  1104. result = result.filter(Boolean);
  1105. }
  1106. // filter out duplicates if specified
  1107. if (options.nodupes === true) {
  1108. result = [...new Set(result)];
  1109. }
  1110. return result;
  1111. };
  1112. /**
  1113. * Processes a brace pattern and returns either an expanded array
  1114. * (if `options.expand` is true), a highly optimized regex-compatible string.
  1115. * This method is called by the main [braces](#braces) function.
  1116. *
  1117. * ```js
  1118. * const braces = require('braces');
  1119. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  1120. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  1121. * ```
  1122. * @param {String} `pattern` Brace pattern
  1123. * @param {Object} `options`
  1124. * @return {Array} Returns an array of expanded values.
  1125. * @api public
  1126. */
  1127. braces.create = (input, options = {}) => {
  1128. if (input === '' || input.length < 3) {
  1129. return [input];
  1130. }
  1131. return options.expand !== true
  1132. ? braces.compile(input, options)
  1133. : braces.expand(input, options);
  1134. };
  1135. /**
  1136. * Expose "braces"
  1137. */
  1138. var braces_1 = braces;
  1139. const WIN_SLASH = '\\\\/';
  1140. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  1141. /**
  1142. * Posix glob regex
  1143. */
  1144. const DOT_LITERAL = '\\.';
  1145. const PLUS_LITERAL = '\\+';
  1146. const QMARK_LITERAL = '\\?';
  1147. const SLASH_LITERAL = '\\/';
  1148. const ONE_CHAR = '(?=.)';
  1149. const QMARK = '[^/]';
  1150. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  1151. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  1152. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  1153. const NO_DOT = `(?!${DOT_LITERAL})`;
  1154. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  1155. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  1156. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  1157. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  1158. const STAR = `${QMARK}*?`;
  1159. const POSIX_CHARS = {
  1160. DOT_LITERAL,
  1161. PLUS_LITERAL,
  1162. QMARK_LITERAL,
  1163. SLASH_LITERAL,
  1164. ONE_CHAR,
  1165. QMARK,
  1166. END_ANCHOR,
  1167. DOTS_SLASH,
  1168. NO_DOT,
  1169. NO_DOTS,
  1170. NO_DOT_SLASH,
  1171. NO_DOTS_SLASH,
  1172. QMARK_NO_DOT,
  1173. STAR,
  1174. START_ANCHOR
  1175. };
  1176. /**
  1177. * Windows glob regex
  1178. */
  1179. const WINDOWS_CHARS = {
  1180. ...POSIX_CHARS,
  1181. SLASH_LITERAL: `[${WIN_SLASH}]`,
  1182. QMARK: WIN_NO_SLASH,
  1183. STAR: `${WIN_NO_SLASH}*?`,
  1184. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  1185. NO_DOT: `(?!${DOT_LITERAL})`,
  1186. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1187. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  1188. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1189. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  1190. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  1191. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  1192. };
  1193. /**
  1194. * POSIX Bracket Regex
  1195. */
  1196. const POSIX_REGEX_SOURCE = {
  1197. alnum: 'a-zA-Z0-9',
  1198. alpha: 'a-zA-Z',
  1199. ascii: '\\x00-\\x7F',
  1200. blank: ' \\t',
  1201. cntrl: '\\x00-\\x1F\\x7F',
  1202. digit: '0-9',
  1203. graph: '\\x21-\\x7E',
  1204. lower: 'a-z',
  1205. print: '\\x20-\\x7E ',
  1206. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1207. space: ' \\t\\r\\n\\v\\f',
  1208. upper: 'A-Z',
  1209. word: 'A-Za-z0-9_',
  1210. xdigit: 'A-Fa-f0-9'
  1211. };
  1212. var constants$1 = {
  1213. MAX_LENGTH: 1024 * 64,
  1214. POSIX_REGEX_SOURCE,
  1215. // regular expressions
  1216. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1217. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1218. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1219. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1220. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1221. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1222. // Replace globs with equivalent patterns to reduce parsing time.
  1223. REPLACEMENTS: {
  1224. '***': '*',
  1225. '**/**': '**',
  1226. '**/**/**': '**'
  1227. },
  1228. // Digits
  1229. CHAR_0: 48, /* 0 */
  1230. CHAR_9: 57, /* 9 */
  1231. // Alphabet chars.
  1232. CHAR_UPPERCASE_A: 65, /* A */
  1233. CHAR_LOWERCASE_A: 97, /* a */
  1234. CHAR_UPPERCASE_Z: 90, /* Z */
  1235. CHAR_LOWERCASE_Z: 122, /* z */
  1236. CHAR_LEFT_PARENTHESES: 40, /* ( */
  1237. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  1238. CHAR_ASTERISK: 42, /* * */
  1239. // Non-alphabetic chars.
  1240. CHAR_AMPERSAND: 38, /* & */
  1241. CHAR_AT: 64, /* @ */
  1242. CHAR_BACKWARD_SLASH: 92, /* \ */
  1243. CHAR_CARRIAGE_RETURN: 13, /* \r */
  1244. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  1245. CHAR_COLON: 58, /* : */
  1246. CHAR_COMMA: 44, /* , */
  1247. CHAR_DOT: 46, /* . */
  1248. CHAR_DOUBLE_QUOTE: 34, /* " */
  1249. CHAR_EQUAL: 61, /* = */
  1250. CHAR_EXCLAMATION_MARK: 33, /* ! */
  1251. CHAR_FORM_FEED: 12, /* \f */
  1252. CHAR_FORWARD_SLASH: 47, /* / */
  1253. CHAR_GRAVE_ACCENT: 96, /* ` */
  1254. CHAR_HASH: 35, /* # */
  1255. CHAR_HYPHEN_MINUS: 45, /* - */
  1256. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  1257. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  1258. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  1259. CHAR_LINE_FEED: 10, /* \n */
  1260. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  1261. CHAR_PERCENT: 37, /* % */
  1262. CHAR_PLUS: 43, /* + */
  1263. CHAR_QUESTION_MARK: 63, /* ? */
  1264. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  1265. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  1266. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  1267. CHAR_SEMICOLON: 59, /* ; */
  1268. CHAR_SINGLE_QUOTE: 39, /* ' */
  1269. CHAR_SPACE: 32, /* */
  1270. CHAR_TAB: 9, /* \t */
  1271. CHAR_UNDERSCORE: 95, /* _ */
  1272. CHAR_VERTICAL_LINE: 124, /* | */
  1273. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  1274. SEP: sysPath.sep,
  1275. /**
  1276. * Create EXTGLOB_CHARS
  1277. */
  1278. extglobChars(chars) {
  1279. return {
  1280. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1281. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1282. '+': { type: 'plus', open: '(?:', close: ')+' },
  1283. '*': { type: 'star', open: '(?:', close: ')*' },
  1284. '@': { type: 'at', open: '(?:', close: ')' }
  1285. };
  1286. },
  1287. /**
  1288. * Create GLOB_CHARS
  1289. */
  1290. globChars(win32) {
  1291. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1292. }
  1293. };
  1294. var utils$1 = createCommonjsModule(function (module, exports) {
  1295. const win32 = process.platform === 'win32';
  1296. const {
  1297. REGEX_BACKSLASH,
  1298. REGEX_REMOVE_BACKSLASH,
  1299. REGEX_SPECIAL_CHARS,
  1300. REGEX_SPECIAL_CHARS_GLOBAL
  1301. } = constants$1;
  1302. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1303. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1304. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  1305. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1306. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  1307. exports.removeBackslashes = str => {
  1308. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1309. return match === '\\' ? '' : match;
  1310. });
  1311. };
  1312. exports.supportsLookbehinds = () => {
  1313. const segs = process.version.slice(1).split('.').map(Number);
  1314. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  1315. return true;
  1316. }
  1317. return false;
  1318. };
  1319. exports.isWindows = options => {
  1320. if (options && typeof options.windows === 'boolean') {
  1321. return options.windows;
  1322. }
  1323. return win32 === true || sysPath.sep === '\\';
  1324. };
  1325. exports.escapeLast = (input, char, lastIdx) => {
  1326. const idx = input.lastIndexOf(char, lastIdx);
  1327. if (idx === -1) return input;
  1328. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  1329. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  1330. };
  1331. exports.removePrefix = (input, state = {}) => {
  1332. let output = input;
  1333. if (output.startsWith('./')) {
  1334. output = output.slice(2);
  1335. state.prefix = './';
  1336. }
  1337. return output;
  1338. };
  1339. exports.wrapOutput = (input, state = {}, options = {}) => {
  1340. const prepend = options.contains ? '' : '^';
  1341. const append = options.contains ? '' : '$';
  1342. let output = `${prepend}(?:${input})${append}`;
  1343. if (state.negated === true) {
  1344. output = `(?:^(?!${output}).*$)`;
  1345. }
  1346. return output;
  1347. };
  1348. });
  1349. const {
  1350. CHAR_ASTERISK, /* * */
  1351. CHAR_AT, /* @ */
  1352. CHAR_BACKWARD_SLASH, /* \ */
  1353. CHAR_COMMA: CHAR_COMMA$1, /* , */
  1354. CHAR_DOT: CHAR_DOT$1, /* . */
  1355. CHAR_EXCLAMATION_MARK, /* ! */
  1356. CHAR_FORWARD_SLASH, /* / */
  1357. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */
  1358. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */
  1359. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
  1360. CHAR_PLUS, /* + */
  1361. CHAR_QUESTION_MARK, /* ? */
  1362. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */
  1363. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */
  1364. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */
  1365. } = constants$1;
  1366. const isPathSeparator = code => {
  1367. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1368. };
  1369. const depth = token => {
  1370. if (token.isPrefix !== true) {
  1371. token.depth = token.isGlobstar ? Infinity : 1;
  1372. }
  1373. };
  1374. /**
  1375. * Quickly scans a glob pattern and returns an object with a handful of
  1376. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1377. * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
  1378. *
  1379. * ```js
  1380. * const pm = require('picomatch');
  1381. * console.log(pm.scan('foo/bar/*.js'));
  1382. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1383. * ```
  1384. * @param {String} `str`
  1385. * @param {Object} `options`
  1386. * @return {Object} Returns an object with tokens and regex source string.
  1387. * @api public
  1388. */
  1389. const scan = (input, options) => {
  1390. const opts = options || {};
  1391. const length = input.length - 1;
  1392. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  1393. const slashes = [];
  1394. const tokens = [];
  1395. const parts = [];
  1396. let str = input;
  1397. let index = -1;
  1398. let start = 0;
  1399. let lastIndex = 0;
  1400. let isBrace = false;
  1401. let isBracket = false;
  1402. let isGlob = false;
  1403. let isExtglob = false;
  1404. let isGlobstar = false;
  1405. let braceEscaped = false;
  1406. let backslashes = false;
  1407. let negated = false;
  1408. let finished = false;
  1409. let braces = 0;
  1410. let prev;
  1411. let code;
  1412. let token = { value: '', depth: 0, isGlob: false };
  1413. const eos = () => index >= length;
  1414. const peek = () => str.charCodeAt(index + 1);
  1415. const advance = () => {
  1416. prev = code;
  1417. return str.charCodeAt(++index);
  1418. };
  1419. while (index < length) {
  1420. code = advance();
  1421. let next;
  1422. if (code === CHAR_BACKWARD_SLASH) {
  1423. backslashes = token.backslashes = true;
  1424. code = advance();
  1425. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  1426. braceEscaped = true;
  1427. }
  1428. continue;
  1429. }
  1430. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
  1431. braces++;
  1432. while (eos() !== true && (code = advance())) {
  1433. if (code === CHAR_BACKWARD_SLASH) {
  1434. backslashes = token.backslashes = true;
  1435. advance();
  1436. continue;
  1437. }
  1438. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  1439. braces++;
  1440. continue;
  1441. }
  1442. if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
  1443. isBrace = token.isBrace = true;
  1444. isGlob = token.isGlob = true;
  1445. finished = true;
  1446. if (scanToEnd === true) {
  1447. continue;
  1448. }
  1449. break;
  1450. }
  1451. if (braceEscaped !== true && code === CHAR_COMMA$1) {
  1452. isBrace = token.isBrace = true;
  1453. isGlob = token.isGlob = true;
  1454. finished = true;
  1455. if (scanToEnd === true) {
  1456. continue;
  1457. }
  1458. break;
  1459. }
  1460. if (code === CHAR_RIGHT_CURLY_BRACE$1) {
  1461. braces--;
  1462. if (braces === 0) {
  1463. braceEscaped = false;
  1464. isBrace = token.isBrace = true;
  1465. finished = true;
  1466. break;
  1467. }
  1468. }
  1469. }
  1470. if (scanToEnd === true) {
  1471. continue;
  1472. }
  1473. break;
  1474. }
  1475. if (code === CHAR_FORWARD_SLASH) {
  1476. slashes.push(index);
  1477. tokens.push(token);
  1478. token = { value: '', depth: 0, isGlob: false };
  1479. if (finished === true) continue;
  1480. if (prev === CHAR_DOT$1 && index === (start + 1)) {
  1481. start += 2;
  1482. continue;
  1483. }
  1484. lastIndex = index + 1;
  1485. continue;
  1486. }
  1487. if (opts.noext !== true) {
  1488. const isExtglobChar = code === CHAR_PLUS
  1489. || code === CHAR_AT
  1490. || code === CHAR_ASTERISK
  1491. || code === CHAR_QUESTION_MARK
  1492. || code === CHAR_EXCLAMATION_MARK;
  1493. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
  1494. isGlob = token.isGlob = true;
  1495. isExtglob = token.isExtglob = true;
  1496. finished = true;
  1497. if (scanToEnd === true) {
  1498. while (eos() !== true && (code = advance())) {
  1499. if (code === CHAR_BACKWARD_SLASH) {
  1500. backslashes = token.backslashes = true;
  1501. code = advance();
  1502. continue;
  1503. }
  1504. if (code === CHAR_RIGHT_PARENTHESES$1) {
  1505. isGlob = token.isGlob = true;
  1506. finished = true;
  1507. break;
  1508. }
  1509. }
  1510. continue;
  1511. }
  1512. break;
  1513. }
  1514. }
  1515. if (code === CHAR_ASTERISK) {
  1516. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  1517. isGlob = token.isGlob = true;
  1518. finished = true;
  1519. if (scanToEnd === true) {
  1520. continue;
  1521. }
  1522. break;
  1523. }
  1524. if (code === CHAR_QUESTION_MARK) {
  1525. isGlob = token.isGlob = true;
  1526. finished = true;
  1527. if (scanToEnd === true) {
  1528. continue;
  1529. }
  1530. break;
  1531. }
  1532. if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
  1533. while (eos() !== true && (next = advance())) {
  1534. if (next === CHAR_BACKWARD_SLASH) {
  1535. backslashes = token.backslashes = true;
  1536. advance();
  1537. continue;
  1538. }
  1539. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  1540. isBracket = token.isBracket = true;
  1541. isGlob = token.isGlob = true;
  1542. finished = true;
  1543. if (scanToEnd === true) {
  1544. continue;
  1545. }
  1546. break;
  1547. }
  1548. }
  1549. }
  1550. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  1551. negated = token.negated = true;
  1552. start++;
  1553. continue;
  1554. }
  1555. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
  1556. isGlob = token.isGlob = true;
  1557. if (scanToEnd === true) {
  1558. while (eos() !== true && (code = advance())) {
  1559. if (code === CHAR_LEFT_PARENTHESES$1) {
  1560. backslashes = token.backslashes = true;
  1561. code = advance();
  1562. continue;
  1563. }
  1564. if (code === CHAR_RIGHT_PARENTHESES$1) {
  1565. finished = true;
  1566. break;
  1567. }
  1568. }
  1569. continue;
  1570. }
  1571. break;
  1572. }
  1573. if (isGlob === true) {
  1574. finished = true;
  1575. if (scanToEnd === true) {
  1576. continue;
  1577. }
  1578. break;
  1579. }
  1580. }
  1581. if (opts.noext === true) {
  1582. isExtglob = false;
  1583. isGlob = false;
  1584. }
  1585. let base = str;
  1586. let prefix = '';
  1587. let glob = '';
  1588. if (start > 0) {
  1589. prefix = str.slice(0, start);
  1590. str = str.slice(start);
  1591. lastIndex -= start;
  1592. }
  1593. if (base && isGlob === true && lastIndex > 0) {
  1594. base = str.slice(0, lastIndex);
  1595. glob = str.slice(lastIndex);
  1596. } else if (isGlob === true) {
  1597. base = '';
  1598. glob = str;
  1599. } else {
  1600. base = str;
  1601. }
  1602. if (base && base !== '' && base !== '/' && base !== str) {
  1603. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  1604. base = base.slice(0, -1);
  1605. }
  1606. }
  1607. if (opts.unescape === true) {
  1608. if (glob) glob = utils$1.removeBackslashes(glob);
  1609. if (base && backslashes === true) {
  1610. base = utils$1.removeBackslashes(base);
  1611. }
  1612. }
  1613. const state = {
  1614. prefix,
  1615. input,
  1616. start,
  1617. base,
  1618. glob,
  1619. isBrace,
  1620. isBracket,
  1621. isGlob,
  1622. isExtglob,
  1623. isGlobstar,
  1624. negated
  1625. };
  1626. if (opts.tokens === true) {
  1627. state.maxDepth = 0;
  1628. if (!isPathSeparator(code)) {
  1629. tokens.push(token);
  1630. }
  1631. state.tokens = tokens;
  1632. }
  1633. if (opts.parts === true || opts.tokens === true) {
  1634. let prevIndex;
  1635. for (let idx = 0; idx < slashes.length; idx++) {
  1636. const n = prevIndex ? prevIndex + 1 : start;
  1637. const i = slashes[idx];
  1638. const value = input.slice(n, i);
  1639. if (opts.tokens) {
  1640. if (idx === 0 && start !== 0) {
  1641. tokens[idx].isPrefix = true;
  1642. tokens[idx].value = prefix;
  1643. } else {
  1644. tokens[idx].value = value;
  1645. }
  1646. depth(tokens[idx]);
  1647. state.maxDepth += tokens[idx].depth;
  1648. }
  1649. if (idx !== 0 || value !== '') {
  1650. parts.push(value);
  1651. }
  1652. prevIndex = i;
  1653. }
  1654. if (prevIndex && prevIndex + 1 < input.length) {
  1655. const value = input.slice(prevIndex + 1);
  1656. parts.push(value);
  1657. if (opts.tokens) {
  1658. tokens[tokens.length - 1].value = value;
  1659. depth(tokens[tokens.length - 1]);
  1660. state.maxDepth += tokens[tokens.length - 1].depth;
  1661. }
  1662. }
  1663. state.slashes = slashes;
  1664. state.parts = parts;
  1665. }
  1666. return state;
  1667. };
  1668. var scan_1 = scan;
  1669. /**
  1670. * Constants
  1671. */
  1672. const {
  1673. MAX_LENGTH: MAX_LENGTH$1,
  1674. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  1675. REGEX_NON_SPECIAL_CHARS,
  1676. REGEX_SPECIAL_CHARS_BACKREF,
  1677. REPLACEMENTS
  1678. } = constants$1;
  1679. /**
  1680. * Helpers
  1681. */
  1682. const expandRange = (args, options) => {
  1683. if (typeof options.expandRange === 'function') {
  1684. return options.expandRange(...args, options);
  1685. }
  1686. args.sort();
  1687. const value = `[${args.join('-')}]`;
  1688. return value;
  1689. };
  1690. /**
  1691. * Create the message for a syntax error
  1692. */
  1693. const syntaxError = (type, char) => {
  1694. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  1695. };
  1696. /**
  1697. * Parse the given input string.
  1698. * @param {String} input
  1699. * @param {Object} options
  1700. * @return {Object}
  1701. */
  1702. const parse$1 = (input, options) => {
  1703. if (typeof input !== 'string') {
  1704. throw new TypeError('Expected a string');
  1705. }
  1706. input = REPLACEMENTS[input] || input;
  1707. const opts = { ...options };
  1708. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  1709. let len = input.length;
  1710. if (len > max) {
  1711. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1712. }
  1713. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  1714. const tokens = [bos];
  1715. const capture = opts.capture ? '' : '?:';
  1716. const win32 = utils$1.isWindows(options);
  1717. // create constants based on platform, for windows or posix
  1718. const PLATFORM_CHARS = constants$1.globChars(win32);
  1719. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  1720. const {
  1721. DOT_LITERAL,
  1722. PLUS_LITERAL,
  1723. SLASH_LITERAL,
  1724. ONE_CHAR,
  1725. DOTS_SLASH,
  1726. NO_DOT,
  1727. NO_DOT_SLASH,
  1728. NO_DOTS_SLASH,
  1729. QMARK,
  1730. QMARK_NO_DOT,
  1731. STAR,
  1732. START_ANCHOR
  1733. } = PLATFORM_CHARS;
  1734. const globstar = (opts) => {
  1735. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1736. };
  1737. const nodot = opts.dot ? '' : NO_DOT;
  1738. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  1739. let star = opts.bash === true ? globstar(opts) : STAR;
  1740. if (opts.capture) {
  1741. star = `(${star})`;
  1742. }
  1743. // minimatch options support
  1744. if (typeof opts.noext === 'boolean') {
  1745. opts.noextglob = opts.noext;
  1746. }
  1747. const state = {
  1748. input,
  1749. index: -1,
  1750. start: 0,
  1751. dot: opts.dot === true,
  1752. consumed: '',
  1753. output: '',
  1754. prefix: '',
  1755. backtrack: false,
  1756. negated: false,
  1757. brackets: 0,
  1758. braces: 0,
  1759. parens: 0,
  1760. quotes: 0,
  1761. globstar: false,
  1762. tokens
  1763. };
  1764. input = utils$1.removePrefix(input, state);
  1765. len = input.length;
  1766. const extglobs = [];
  1767. const braces = [];
  1768. const stack = [];
  1769. let prev = bos;
  1770. let value;
  1771. /**
  1772. * Tokenizing helpers
  1773. */
  1774. const eos = () => state.index === len - 1;
  1775. const peek = state.peek = (n = 1) => input[state.index + n];
  1776. const advance = state.advance = () => input[++state.index];
  1777. const remaining = () => input.slice(state.index + 1);
  1778. const consume = (value = '', num = 0) => {
  1779. state.consumed += value;
  1780. state.index += num;
  1781. };
  1782. const append = token => {
  1783. state.output += token.output != null ? token.output : token.value;
  1784. consume(token.value);
  1785. };
  1786. const negate = () => {
  1787. let count = 1;
  1788. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1789. advance();
  1790. state.start++;
  1791. count++;
  1792. }
  1793. if (count % 2 === 0) {
  1794. return false;
  1795. }
  1796. state.negated = true;
  1797. state.start++;
  1798. return true;
  1799. };
  1800. const increment = type => {
  1801. state[type]++;
  1802. stack.push(type);
  1803. };
  1804. const decrement = type => {
  1805. state[type]--;
  1806. stack.pop();
  1807. };
  1808. /**
  1809. * Push tokens onto the tokens array. This helper speeds up
  1810. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1811. * and 2) helping us avoid creating extra tokens when consecutive
  1812. * characters are plain text. This improves performance and simplifies
  1813. * lookbehinds.
  1814. */
  1815. const push = tok => {
  1816. if (prev.type === 'globstar') {
  1817. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1818. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1819. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1820. state.output = state.output.slice(0, -prev.output.length);
  1821. prev.type = 'star';
  1822. prev.value = '*';
  1823. prev.output = star;
  1824. state.output += prev.output;
  1825. }
  1826. }
  1827. if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
  1828. extglobs[extglobs.length - 1].inner += tok.value;
  1829. }
  1830. if (tok.value || tok.output) append(tok);
  1831. if (prev && prev.type === 'text' && tok.type === 'text') {
  1832. prev.value += tok.value;
  1833. prev.output = (prev.output || '') + tok.value;
  1834. return;
  1835. }
  1836. tok.prev = prev;
  1837. tokens.push(tok);
  1838. prev = tok;
  1839. };
  1840. const extglobOpen = (type, value) => {
  1841. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1842. token.prev = prev;
  1843. token.parens = state.parens;
  1844. token.output = state.output;
  1845. const output = (opts.capture ? '(' : '') + token.open;
  1846. increment('parens');
  1847. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1848. push({ type: 'paren', extglob: true, value: advance(), output });
  1849. extglobs.push(token);
  1850. };
  1851. const extglobClose = token => {
  1852. let output = token.close + (opts.capture ? ')' : '');
  1853. if (token.type === 'negate') {
  1854. let extglobStar = star;
  1855. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1856. extglobStar = globstar(opts);
  1857. }
  1858. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1859. output = token.close = `)$))${extglobStar}`;
  1860. }
  1861. if (token.prev.type === 'bos' && eos()) {
  1862. state.negatedExtglob = true;
  1863. }
  1864. }
  1865. push({ type: 'paren', extglob: true, value, output });
  1866. decrement('parens');
  1867. };
  1868. /**
  1869. * Fast paths
  1870. */
  1871. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1872. let backslashes = false;
  1873. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1874. if (first === '\\') {
  1875. backslashes = true;
  1876. return m;
  1877. }
  1878. if (first === '?') {
  1879. if (esc) {
  1880. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1881. }
  1882. if (index === 0) {
  1883. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1884. }
  1885. return QMARK.repeat(chars.length);
  1886. }
  1887. if (first === '.') {
  1888. return DOT_LITERAL.repeat(chars.length);
  1889. }
  1890. if (first === '*') {
  1891. if (esc) {
  1892. return esc + first + (rest ? star : '');
  1893. }
  1894. return star;
  1895. }
  1896. return esc ? m : `\\${m}`;
  1897. });
  1898. if (backslashes === true) {
  1899. if (opts.unescape === true) {
  1900. output = output.replace(/\\/g, '');
  1901. } else {
  1902. output = output.replace(/\\+/g, m => {
  1903. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1904. });
  1905. }
  1906. }
  1907. if (output === input && opts.contains === true) {
  1908. state.output = input;
  1909. return state;
  1910. }
  1911. state.output = utils$1.wrapOutput(output, state, options);
  1912. return state;
  1913. }
  1914. /**
  1915. * Tokenize input until we reach end-of-string
  1916. */
  1917. while (!eos()) {
  1918. value = advance();
  1919. if (value === '\u0000') {
  1920. continue;
  1921. }
  1922. /**
  1923. * Escaped characters
  1924. */
  1925. if (value === '\\') {
  1926. const next = peek();
  1927. if (next === '/' && opts.bash !== true) {
  1928. continue;
  1929. }
  1930. if (next === '.' || next === ';') {
  1931. continue;
  1932. }
  1933. if (!next) {
  1934. value += '\\';
  1935. push({ type: 'text', value });
  1936. continue;
  1937. }
  1938. // collapse slashes to reduce potential for exploits
  1939. const match = /^\\+/.exec(remaining());
  1940. let slashes = 0;
  1941. if (match && match[0].length > 2) {
  1942. slashes = match[0].length;
  1943. state.index += slashes;
  1944. if (slashes % 2 !== 0) {
  1945. value += '\\';
  1946. }
  1947. }
  1948. if (opts.unescape === true) {
  1949. value = advance() || '';
  1950. } else {
  1951. value += advance() || '';
  1952. }
  1953. if (state.brackets === 0) {
  1954. push({ type: 'text', value });
  1955. continue;
  1956. }
  1957. }
  1958. /**
  1959. * If we're inside a regex character class, continue
  1960. * until we reach the closing bracket.
  1961. */
  1962. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1963. if (opts.posix !== false && value === ':') {
  1964. const inner = prev.value.slice(1);
  1965. if (inner.includes('[')) {
  1966. prev.posix = true;
  1967. if (inner.includes(':')) {
  1968. const idx = prev.value.lastIndexOf('[');
  1969. const pre = prev.value.slice(0, idx);
  1970. const rest = prev.value.slice(idx + 2);
  1971. const posix = POSIX_REGEX_SOURCE$1[rest];
  1972. if (posix) {
  1973. prev.value = pre + posix;
  1974. state.backtrack = true;
  1975. advance();
  1976. if (!bos.output && tokens.indexOf(prev) === 1) {
  1977. bos.output = ONE_CHAR;
  1978. }
  1979. continue;
  1980. }
  1981. }
  1982. }
  1983. }
  1984. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1985. value = `\\${value}`;
  1986. }
  1987. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1988. value = `\\${value}`;
  1989. }
  1990. if (opts.posix === true && value === '!' && prev.value === '[') {
  1991. value = '^';
  1992. }
  1993. prev.value += value;
  1994. append({ value });
  1995. continue;
  1996. }
  1997. /**
  1998. * If we're inside a quoted string, continue
  1999. * until we reach the closing double quote.
  2000. */
  2001. if (state.quotes === 1 && value !== '"') {
  2002. value = utils$1.escapeRegex(value);
  2003. prev.value += value;
  2004. append({ value });
  2005. continue;
  2006. }
  2007. /**
  2008. * Double quotes
  2009. */
  2010. if (value === '"') {
  2011. state.quotes = state.quotes === 1 ? 0 : 1;
  2012. if (opts.keepQuotes === true) {
  2013. push({ type: 'text', value });
  2014. }
  2015. continue;
  2016. }
  2017. /**
  2018. * Parentheses
  2019. */
  2020. if (value === '(') {
  2021. increment('parens');
  2022. push({ type: 'paren', value });
  2023. continue;
  2024. }
  2025. if (value === ')') {
  2026. if (state.parens === 0 && opts.strictBrackets === true) {
  2027. throw new SyntaxError(syntaxError('opening', '('));
  2028. }
  2029. const extglob = extglobs[extglobs.length - 1];
  2030. if (extglob && state.parens === extglob.parens + 1) {
  2031. extglobClose(extglobs.pop());
  2032. continue;
  2033. }
  2034. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  2035. decrement('parens');
  2036. continue;
  2037. }
  2038. /**
  2039. * Square brackets
  2040. */
  2041. if (value === '[') {
  2042. if (opts.nobracket === true || !remaining().includes(']')) {
  2043. if (opts.nobracket !== true && opts.strictBrackets === true) {
  2044. throw new SyntaxError(syntaxError('closing', ']'));
  2045. }
  2046. value = `\\${value}`;
  2047. } else {
  2048. increment('brackets');
  2049. }
  2050. push({ type: 'bracket', value });
  2051. continue;
  2052. }
  2053. if (value === ']') {
  2054. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  2055. push({ type: 'text', value, output: `\\${value}` });
  2056. continue;
  2057. }
  2058. if (state.brackets === 0) {
  2059. if (opts.strictBrackets === true) {
  2060. throw new SyntaxError(syntaxError('opening', '['));
  2061. }
  2062. push({ type: 'text', value, output: `\\${value}` });
  2063. continue;
  2064. }
  2065. decrement('brackets');
  2066. const prevValue = prev.value.slice(1);
  2067. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  2068. value = `/${value}`;
  2069. }
  2070. prev.value += value;
  2071. append({ value });
  2072. // when literal brackets are explicitly disabled
  2073. // assume we should match with a regex character class
  2074. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  2075. continue;
  2076. }
  2077. const escaped = utils$1.escapeRegex(prev.value);
  2078. state.output = state.output.slice(0, -prev.value.length);
  2079. // when literal brackets are explicitly enabled
  2080. // assume we should escape the brackets to match literal characters
  2081. if (opts.literalBrackets === true) {
  2082. state.output += escaped;
  2083. prev.value = escaped;
  2084. continue;
  2085. }
  2086. // when the user specifies nothing, try to match both
  2087. prev.value = `(${capture}${escaped}|${prev.value})`;
  2088. state.output += prev.value;
  2089. continue;
  2090. }
  2091. /**
  2092. * Braces
  2093. */
  2094. if (value === '{' && opts.nobrace !== true) {
  2095. increment('braces');
  2096. const open = {
  2097. type: 'brace',
  2098. value,
  2099. output: '(',
  2100. outputIndex: state.output.length,
  2101. tokensIndex: state.tokens.length
  2102. };
  2103. braces.push(open);
  2104. push(open);
  2105. continue;
  2106. }
  2107. if (value === '}') {
  2108. const brace = braces[braces.length - 1];
  2109. if (opts.nobrace === true || !brace) {
  2110. push({ type: 'text', value, output: value });
  2111. continue;
  2112. }
  2113. let output = ')';
  2114. if (brace.dots === true) {
  2115. const arr = tokens.slice();
  2116. const range = [];
  2117. for (let i = arr.length - 1; i >= 0; i--) {
  2118. tokens.pop();
  2119. if (arr[i].type === 'brace') {
  2120. break;
  2121. }
  2122. if (arr[i].type !== 'dots') {
  2123. range.unshift(arr[i].value);
  2124. }
  2125. }
  2126. output = expandRange(range, opts);
  2127. state.backtrack = true;
  2128. }
  2129. if (brace.comma !== true && brace.dots !== true) {
  2130. const out = state.output.slice(0, brace.outputIndex);
  2131. const toks = state.tokens.slice(brace.tokensIndex);
  2132. brace.value = brace.output = '\\{';
  2133. value = output = '\\}';
  2134. state.output = out;
  2135. for (const t of toks) {
  2136. state.output += (t.output || t.value);
  2137. }
  2138. }
  2139. push({ type: 'brace', value, output });
  2140. decrement('braces');
  2141. braces.pop();
  2142. continue;
  2143. }
  2144. /**
  2145. * Pipes
  2146. */
  2147. if (value === '|') {
  2148. if (extglobs.length > 0) {
  2149. extglobs[extglobs.length - 1].conditions++;
  2150. }
  2151. push({ type: 'text', value });
  2152. continue;
  2153. }
  2154. /**
  2155. * Commas
  2156. */
  2157. if (value === ',') {
  2158. let output = value;
  2159. const brace = braces[braces.length - 1];
  2160. if (brace && stack[stack.length - 1] === 'braces') {
  2161. brace.comma = true;
  2162. output = '|';
  2163. }
  2164. push({ type: 'comma', value, output });
  2165. continue;
  2166. }
  2167. /**
  2168. * Slashes
  2169. */
  2170. if (value === '/') {
  2171. // if the beginning of the glob is "./", advance the start
  2172. // to the current index, and don't add the "./" characters
  2173. // to the state. This greatly simplifies lookbehinds when
  2174. // checking for BOS characters like "!" and "." (not "./")
  2175. if (prev.type === 'dot' && state.index === state.start + 1) {
  2176. state.start = state.index + 1;
  2177. state.consumed = '';
  2178. state.output = '';
  2179. tokens.pop();
  2180. prev = bos; // reset "prev" to the first token
  2181. continue;
  2182. }
  2183. push({ type: 'slash', value, output: SLASH_LITERAL });
  2184. continue;
  2185. }
  2186. /**
  2187. * Dots
  2188. */
  2189. if (value === '.') {
  2190. if (state.braces > 0 && prev.type === 'dot') {
  2191. if (prev.value === '.') prev.output = DOT_LITERAL;
  2192. const brace = braces[braces.length - 1];
  2193. prev.type = 'dots';
  2194. prev.output += value;
  2195. prev.value += value;
  2196. brace.dots = true;
  2197. continue;
  2198. }
  2199. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2200. push({ type: 'text', value, output: DOT_LITERAL });
  2201. continue;
  2202. }
  2203. push({ type: 'dot', value, output: DOT_LITERAL });
  2204. continue;
  2205. }
  2206. /**
  2207. * Question marks
  2208. */
  2209. if (value === '?') {
  2210. const isGroup = prev && prev.value === '(';
  2211. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2212. extglobOpen('qmark', value);
  2213. continue;
  2214. }
  2215. if (prev && prev.type === 'paren') {
  2216. const next = peek();
  2217. let output = value;
  2218. if (next === '<' && !utils$1.supportsLookbehinds()) {
  2219. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  2220. }
  2221. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  2222. output = `\\${value}`;
  2223. }
  2224. push({ type: 'text', value, output });
  2225. continue;
  2226. }
  2227. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2228. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2229. continue;
  2230. }
  2231. push({ type: 'qmark', value, output: QMARK });
  2232. continue;
  2233. }
  2234. /**
  2235. * Exclamation
  2236. */
  2237. if (value === '!') {
  2238. if (opts.noextglob !== true && peek() === '(') {
  2239. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2240. extglobOpen('negate', value);
  2241. continue;
  2242. }
  2243. }
  2244. if (opts.nonegate !== true && state.index === 0) {
  2245. negate();
  2246. continue;
  2247. }
  2248. }
  2249. /**
  2250. * Plus
  2251. */
  2252. if (value === '+') {
  2253. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2254. extglobOpen('plus', value);
  2255. continue;
  2256. }
  2257. if ((prev && prev.value === '(') || opts.regex === false) {
  2258. push({ type: 'plus', value, output: PLUS_LITERAL });
  2259. continue;
  2260. }
  2261. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  2262. push({ type: 'plus', value });
  2263. continue;
  2264. }
  2265. push({ type: 'plus', value: PLUS_LITERAL });
  2266. continue;
  2267. }
  2268. /**
  2269. * Plain text
  2270. */
  2271. if (value === '@') {
  2272. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2273. push({ type: 'at', extglob: true, value, output: '' });
  2274. continue;
  2275. }
  2276. push({ type: 'text', value });
  2277. continue;
  2278. }
  2279. /**
  2280. * Plain text
  2281. */
  2282. if (value !== '*') {
  2283. if (value === '$' || value === '^') {
  2284. value = `\\${value}`;
  2285. }
  2286. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  2287. if (match) {
  2288. value += match[0];
  2289. state.index += match[0].length;
  2290. }
  2291. push({ type: 'text', value });
  2292. continue;
  2293. }
  2294. /**
  2295. * Stars
  2296. */
  2297. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2298. prev.type = 'star';
  2299. prev.star = true;
  2300. prev.value += value;
  2301. prev.output = star;
  2302. state.backtrack = true;
  2303. state.globstar = true;
  2304. consume(value);
  2305. continue;
  2306. }
  2307. let rest = remaining();
  2308. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  2309. extglobOpen('star', value);
  2310. continue;
  2311. }
  2312. if (prev.type === 'star') {
  2313. if (opts.noglobstar === true) {
  2314. consume(value);
  2315. continue;
  2316. }
  2317. const prior = prev.prev;
  2318. const before = prior.prev;
  2319. const isStart = prior.type === 'slash' || prior.type === 'bos';
  2320. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2321. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  2322. push({ type: 'star', value, output: '' });
  2323. continue;
  2324. }
  2325. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2326. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2327. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2328. push({ type: 'star', value, output: '' });
  2329. continue;
  2330. }
  2331. // strip consecutive `/**/`
  2332. while (rest.slice(0, 3) === '/**') {
  2333. const after = input[state.index + 4];
  2334. if (after && after !== '/') {
  2335. break;
  2336. }
  2337. rest = rest.slice(3);
  2338. consume('/**', 3);
  2339. }
  2340. if (prior.type === 'bos' && eos()) {
  2341. prev.type = 'globstar';
  2342. prev.value += value;
  2343. prev.output = globstar(opts);
  2344. state.output = prev.output;
  2345. state.globstar = true;
  2346. consume(value);
  2347. continue;
  2348. }
  2349. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2350. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2351. prior.output = `(?:${prior.output}`;
  2352. prev.type = 'globstar';
  2353. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  2354. prev.value += value;
  2355. state.globstar = true;
  2356. state.output += prior.output + prev.output;
  2357. consume(value);
  2358. continue;
  2359. }
  2360. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  2361. const end = rest[1] !== void 0 ? '|$' : '';
  2362. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2363. prior.output = `(?:${prior.output}`;
  2364. prev.type = 'globstar';
  2365. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2366. prev.value += value;
  2367. state.output += prior.output + prev.output;
  2368. state.globstar = true;
  2369. consume(value + advance());
  2370. push({ type: 'slash', value: '/', output: '' });
  2371. continue;
  2372. }
  2373. if (prior.type === 'bos' && rest[0] === '/') {
  2374. prev.type = 'globstar';
  2375. prev.value += value;
  2376. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2377. state.output = prev.output;
  2378. state.globstar = true;
  2379. consume(value + advance());
  2380. push({ type: 'slash', value: '/', output: '' });
  2381. continue;
  2382. }
  2383. // remove single star from output
  2384. state.output = state.output.slice(0, -prev.output.length);
  2385. // reset previous token to globstar
  2386. prev.type = 'globstar';
  2387. prev.output = globstar(opts);
  2388. prev.value += value;
  2389. // reset output with globstar
  2390. state.output += prev.output;
  2391. state.globstar = true;
  2392. consume(value);
  2393. continue;
  2394. }
  2395. const token = { type: 'star', value, output: star };
  2396. if (opts.bash === true) {
  2397. token.output = '.*?';
  2398. if (prev.type === 'bos' || prev.type === 'slash') {
  2399. token.output = nodot + token.output;
  2400. }
  2401. push(token);
  2402. continue;
  2403. }
  2404. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2405. token.output = value;
  2406. push(token);
  2407. continue;
  2408. }
  2409. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2410. if (prev.type === 'dot') {
  2411. state.output += NO_DOT_SLASH;
  2412. prev.output += NO_DOT_SLASH;
  2413. } else if (opts.dot === true) {
  2414. state.output += NO_DOTS_SLASH;
  2415. prev.output += NO_DOTS_SLASH;
  2416. } else {
  2417. state.output += nodot;
  2418. prev.output += nodot;
  2419. }
  2420. if (peek() !== '*') {
  2421. state.output += ONE_CHAR;
  2422. prev.output += ONE_CHAR;
  2423. }
  2424. }
  2425. push(token);
  2426. }
  2427. while (state.brackets > 0) {
  2428. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  2429. state.output = utils$1.escapeLast(state.output, '[');
  2430. decrement('brackets');
  2431. }
  2432. while (state.parens > 0) {
  2433. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  2434. state.output = utils$1.escapeLast(state.output, '(');
  2435. decrement('parens');
  2436. }
  2437. while (state.braces > 0) {
  2438. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  2439. state.output = utils$1.escapeLast(state.output, '{');
  2440. decrement('braces');
  2441. }
  2442. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2443. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2444. }
  2445. // rebuild the output if we had to backtrack at any point
  2446. if (state.backtrack === true) {
  2447. state.output = '';
  2448. for (const token of state.tokens) {
  2449. state.output += token.output != null ? token.output : token.value;
  2450. if (token.suffix) {
  2451. state.output += token.suffix;
  2452. }
  2453. }
  2454. }
  2455. return state;
  2456. };
  2457. /**
  2458. * Fast paths for creating regular expressions for common glob patterns.
  2459. * This can significantly speed up processing and has very little downside
  2460. * impact when none of the fast paths match.
  2461. */
  2462. parse$1.fastpaths = (input, options) => {
  2463. const opts = { ...options };
  2464. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  2465. const len = input.length;
  2466. if (len > max) {
  2467. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2468. }
  2469. input = REPLACEMENTS[input] || input;
  2470. const win32 = utils$1.isWindows(options);
  2471. // create constants based on platform, for windows or posix
  2472. const {
  2473. DOT_LITERAL,
  2474. SLASH_LITERAL,
  2475. ONE_CHAR,
  2476. DOTS_SLASH,
  2477. NO_DOT,
  2478. NO_DOTS,
  2479. NO_DOTS_SLASH,
  2480. STAR,
  2481. START_ANCHOR
  2482. } = constants$1.globChars(win32);
  2483. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  2484. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2485. const capture = opts.capture ? '' : '?:';
  2486. const state = { negated: false, prefix: '' };
  2487. let star = opts.bash === true ? '.*?' : STAR;
  2488. if (opts.capture) {
  2489. star = `(${star})`;
  2490. }
  2491. const globstar = (opts) => {
  2492. if (opts.noglobstar === true) return star;
  2493. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2494. };
  2495. const create = str => {
  2496. switch (str) {
  2497. case '*':
  2498. return `${nodot}${ONE_CHAR}${star}`;
  2499. case '.*':
  2500. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2501. case '*.*':
  2502. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2503. case '*/*':
  2504. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2505. case '**':
  2506. return nodot + globstar(opts);
  2507. case '**/*':
  2508. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2509. case '**/*.*':
  2510. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2511. case '**/.*':
  2512. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2513. default: {
  2514. const match = /^(.*?)\.(\w+)$/.exec(str);
  2515. if (!match) return;
  2516. const source = create(match[1]);
  2517. if (!source) return;
  2518. return source + DOT_LITERAL + match[2];
  2519. }
  2520. }
  2521. };
  2522. const output = utils$1.removePrefix(input, state);
  2523. let source = create(output);
  2524. if (source && opts.strictSlashes !== true) {
  2525. source += `${SLASH_LITERAL}?`;
  2526. }
  2527. return source;
  2528. };
  2529. var parse_1$1 = parse$1;
  2530. const isObject$1 = val => val && typeof val === 'object' && !Array.isArray(val);
  2531. /**
  2532. * Creates a matcher function from one or more glob patterns. The
  2533. * returned function takes a string to match as its first argument,
  2534. * and returns true if the string is a match. The returned matcher
  2535. * function also takes a boolean as the second argument that, when true,
  2536. * returns an object with additional information.
  2537. *
  2538. * ```js
  2539. * const picomatch = require('picomatch');
  2540. * // picomatch(glob[, options]);
  2541. *
  2542. * const isMatch = picomatch('*.!(*a)');
  2543. * console.log(isMatch('a.a')); //=> false
  2544. * console.log(isMatch('a.b')); //=> true
  2545. * ```
  2546. * @name picomatch
  2547. * @param {String|Array} `globs` One or more glob patterns.
  2548. * @param {Object=} `options`
  2549. * @return {Function=} Returns a matcher function.
  2550. * @api public
  2551. */
  2552. const picomatch = (glob, options, returnState = false) => {
  2553. if (Array.isArray(glob)) {
  2554. const fns = glob.map(input => picomatch(input, options, returnState));
  2555. const arrayMatcher = str => {
  2556. for (const isMatch of fns) {
  2557. const state = isMatch(str);
  2558. if (state) return state;
  2559. }
  2560. return false;
  2561. };
  2562. return arrayMatcher;
  2563. }
  2564. const isState = isObject$1(glob) && glob.tokens && glob.input;
  2565. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  2566. throw new TypeError('Expected pattern to be a non-empty string');
  2567. }
  2568. const opts = options || {};
  2569. const posix = utils$1.isWindows(options);
  2570. const regex = isState
  2571. ? picomatch.compileRe(glob, options)
  2572. : picomatch.makeRe(glob, options, false, true);
  2573. const state = regex.state;
  2574. delete regex.state;
  2575. let isIgnored = () => false;
  2576. if (opts.ignore) {
  2577. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  2578. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  2579. }
  2580. const matcher = (input, returnObject = false) => {
  2581. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  2582. const result = { glob, state, regex, posix, input, output, match, isMatch };
  2583. if (typeof opts.onResult === 'function') {
  2584. opts.onResult(result);
  2585. }
  2586. if (isMatch === false) {
  2587. result.isMatch = false;
  2588. return returnObject ? result : false;
  2589. }
  2590. if (isIgnored(input)) {
  2591. if (typeof opts.onIgnore === 'function') {
  2592. opts.onIgnore(result);
  2593. }
  2594. result.isMatch = false;
  2595. return returnObject ? result : false;
  2596. }
  2597. if (typeof opts.onMatch === 'function') {
  2598. opts.onMatch(result);
  2599. }
  2600. return returnObject ? result : true;
  2601. };
  2602. if (returnState) {
  2603. matcher.state = state;
  2604. }
  2605. return matcher;
  2606. };
  2607. /**
  2608. * Test `input` with the given `regex`. This is used by the main
  2609. * `picomatch()` function to test the input string.
  2610. *
  2611. * ```js
  2612. * const picomatch = require('picomatch');
  2613. * // picomatch.test(input, regex[, options]);
  2614. *
  2615. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  2616. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  2617. * ```
  2618. * @param {String} `input` String to test.
  2619. * @param {RegExp} `regex`
  2620. * @return {Object} Returns an object with matching info.
  2621. * @api public
  2622. */
  2623. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  2624. if (typeof input !== 'string') {
  2625. throw new TypeError('Expected input to be a string');
  2626. }
  2627. if (input === '') {
  2628. return { isMatch: false, output: '' };
  2629. }
  2630. const opts = options || {};
  2631. const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
  2632. let match = input === glob;
  2633. let output = (match && format) ? format(input) : input;
  2634. if (match === false) {
  2635. output = format ? format(input) : input;
  2636. match = output === glob;
  2637. }
  2638. if (match === false || opts.capture === true) {
  2639. if (opts.matchBase === true || opts.basename === true) {
  2640. match = picomatch.matchBase(input, regex, options, posix);
  2641. } else {
  2642. match = regex.exec(output);
  2643. }
  2644. }
  2645. return { isMatch: Boolean(match), match, output };
  2646. };
  2647. /**
  2648. * Match the basename of a filepath.
  2649. *
  2650. * ```js
  2651. * const picomatch = require('picomatch');
  2652. * // picomatch.matchBase(input, glob[, options]);
  2653. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  2654. * ```
  2655. * @param {String} `input` String to test.
  2656. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  2657. * @return {Boolean}
  2658. * @api public
  2659. */
  2660. picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => {
  2661. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  2662. return regex.test(sysPath.basename(input));
  2663. };
  2664. /**
  2665. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2666. *
  2667. * ```js
  2668. * const picomatch = require('picomatch');
  2669. * // picomatch.isMatch(string, patterns[, options]);
  2670. *
  2671. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2672. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  2673. * ```
  2674. * @param {String|Array} str The string to test.
  2675. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2676. * @param {Object} [options] See available [options](#options).
  2677. * @return {Boolean} Returns true if any patterns match `str`
  2678. * @api public
  2679. */
  2680. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  2681. /**
  2682. * Parse a glob pattern to create the source string for a regular
  2683. * expression.
  2684. *
  2685. * ```js
  2686. * const picomatch = require('picomatch');
  2687. * const result = picomatch.parse(pattern[, options]);
  2688. * ```
  2689. * @param {String} `pattern`
  2690. * @param {Object} `options`
  2691. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  2692. * @api public
  2693. */
  2694. picomatch.parse = (pattern, options) => {
  2695. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  2696. return parse_1$1(pattern, { ...options, fastpaths: false });
  2697. };
  2698. /**
  2699. * Scan a glob pattern to separate the pattern into segments.
  2700. *
  2701. * ```js
  2702. * const picomatch = require('picomatch');
  2703. * // picomatch.scan(input[, options]);
  2704. *
  2705. * const result = picomatch.scan('!./foo/*.js');
  2706. * console.log(result);
  2707. * { prefix: '!./',
  2708. * input: '!./foo/*.js',
  2709. * start: 3,
  2710. * base: 'foo',
  2711. * glob: '*.js',
  2712. * isBrace: false,
  2713. * isBracket: false,
  2714. * isGlob: true,
  2715. * isExtglob: false,
  2716. * isGlobstar: false,
  2717. * negated: true }
  2718. * ```
  2719. * @param {String} `input` Glob pattern to scan.
  2720. * @param {Object} `options`
  2721. * @return {Object} Returns an object with
  2722. * @api public
  2723. */
  2724. picomatch.scan = (input, options) => scan_1(input, options);
  2725. /**
  2726. * Create a regular expression from a parsed glob pattern.
  2727. *
  2728. * ```js
  2729. * const picomatch = require('picomatch');
  2730. * const state = picomatch.parse('*.js');
  2731. * // picomatch.compileRe(state[, options]);
  2732. *
  2733. * console.log(picomatch.compileRe(state));
  2734. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2735. * ```
  2736. * @param {String} `state` The object returned from the `.parse` method.
  2737. * @param {Object} `options`
  2738. * @return {RegExp} Returns a regex created from the given pattern.
  2739. * @api public
  2740. */
  2741. picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
  2742. if (returnOutput === true) {
  2743. return parsed.output;
  2744. }
  2745. const opts = options || {};
  2746. const prepend = opts.contains ? '' : '^';
  2747. const append = opts.contains ? '' : '$';
  2748. let source = `${prepend}(?:${parsed.output})${append}`;
  2749. if (parsed && parsed.negated === true) {
  2750. source = `^(?!${source}).*$`;
  2751. }
  2752. const regex = picomatch.toRegex(source, options);
  2753. if (returnState === true) {
  2754. regex.state = parsed;
  2755. }
  2756. return regex;
  2757. };
  2758. picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
  2759. if (!input || typeof input !== 'string') {
  2760. throw new TypeError('Expected a non-empty string');
  2761. }
  2762. const opts = options || {};
  2763. let parsed = { negated: false, fastpaths: true };
  2764. let prefix = '';
  2765. let output;
  2766. if (input.startsWith('./')) {
  2767. input = input.slice(2);
  2768. prefix = parsed.prefix = './';
  2769. }
  2770. if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2771. output = parse_1$1.fastpaths(input, options);
  2772. }
  2773. if (output === undefined) {
  2774. parsed = parse_1$1(input, options);
  2775. parsed.prefix = prefix + (parsed.prefix || '');
  2776. } else {
  2777. parsed.output = output;
  2778. }
  2779. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  2780. };
  2781. /**
  2782. * Create a regular expression from the given regex source string.
  2783. *
  2784. * ```js
  2785. * const picomatch = require('picomatch');
  2786. * // picomatch.toRegex(source[, options]);
  2787. *
  2788. * const { output } = picomatch.parse('*.js');
  2789. * console.log(picomatch.toRegex(output));
  2790. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2791. * ```
  2792. * @param {String} `source` Regular expression source string.
  2793. * @param {Object} `options`
  2794. * @return {RegExp}
  2795. * @api public
  2796. */
  2797. picomatch.toRegex = (source, options) => {
  2798. try {
  2799. const opts = options || {};
  2800. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2801. } catch (err) {
  2802. if (options && options.debug === true) throw err;
  2803. return /$^/;
  2804. }
  2805. };
  2806. /**
  2807. * Picomatch constants.
  2808. * @return {Object}
  2809. */
  2810. picomatch.constants = constants$1;
  2811. /**
  2812. * Expose "picomatch"
  2813. */
  2814. var picomatch_1 = picomatch;
  2815. var picomatch$1 = picomatch_1;
  2816. const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
  2817. /**
  2818. * Returns an array of strings that match one or more glob patterns.
  2819. *
  2820. * ```js
  2821. * const mm = require('micromatch');
  2822. * // mm(list, patterns[, options]);
  2823. *
  2824. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  2825. * //=> [ 'a.js' ]
  2826. * ```
  2827. * @param {String|Array<string>} list List of strings to match.
  2828. * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
  2829. * @param {Object} options See available [options](#options)
  2830. * @return {Array} Returns an array of matches
  2831. * @summary false
  2832. * @api public
  2833. */
  2834. const micromatch = (list, patterns, options) => {
  2835. patterns = [].concat(patterns);
  2836. list = [].concat(list);
  2837. let omit = new Set();
  2838. let keep = new Set();
  2839. let items = new Set();
  2840. let negatives = 0;
  2841. let onResult = state => {
  2842. items.add(state.output);
  2843. if (options && options.onResult) {
  2844. options.onResult(state);
  2845. }
  2846. };
  2847. for (let i = 0; i < patterns.length; i++) {
  2848. let isMatch = picomatch$1(String(patterns[i]), { ...options, onResult }, true);
  2849. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  2850. if (negated) negatives++;
  2851. for (let item of list) {
  2852. let matched = isMatch(item, true);
  2853. let match = negated ? !matched.isMatch : matched.isMatch;
  2854. if (!match) continue;
  2855. if (negated) {
  2856. omit.add(matched.output);
  2857. } else {
  2858. omit.delete(matched.output);
  2859. keep.add(matched.output);
  2860. }
  2861. }
  2862. }
  2863. let result = negatives === patterns.length ? [...items] : [...keep];
  2864. let matches = result.filter(item => !omit.has(item));
  2865. if (options && matches.length === 0) {
  2866. if (options.failglob === true) {
  2867. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  2868. }
  2869. if (options.nonull === true || options.nullglob === true) {
  2870. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  2871. }
  2872. }
  2873. return matches;
  2874. };
  2875. /**
  2876. * Backwards compatibility
  2877. */
  2878. micromatch.match = micromatch;
  2879. /**
  2880. * Returns a matcher function from the given glob `pattern` and `options`.
  2881. * The returned function takes a string to match as its only argument and returns
  2882. * true if the string is a match.
  2883. *
  2884. * ```js
  2885. * const mm = require('micromatch');
  2886. * // mm.matcher(pattern[, options]);
  2887. *
  2888. * const isMatch = mm.matcher('*.!(*a)');
  2889. * console.log(isMatch('a.a')); //=> false
  2890. * console.log(isMatch('a.b')); //=> true
  2891. * ```
  2892. * @param {String} `pattern` Glob pattern
  2893. * @param {Object} `options`
  2894. * @return {Function} Returns a matcher function.
  2895. * @api public
  2896. */
  2897. micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
  2898. /**
  2899. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2900. *
  2901. * ```js
  2902. * const mm = require('micromatch');
  2903. * // mm.isMatch(string, patterns[, options]);
  2904. *
  2905. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2906. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  2907. * ```
  2908. * @param {String} str The string to test.
  2909. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2910. * @param {Object} [options] See available [options](#options).
  2911. * @return {Boolean} Returns true if any patterns match `str`
  2912. * @api public
  2913. */
  2914. micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  2915. /**
  2916. * Backwards compatibility
  2917. */
  2918. micromatch.any = micromatch.isMatch;
  2919. /**
  2920. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  2921. *
  2922. * ```js
  2923. * const mm = require('micromatch');
  2924. * // mm.not(list, patterns[, options]);
  2925. *
  2926. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  2927. * //=> ['b.b', 'c.c']
  2928. * ```
  2929. * @param {Array} `list` Array of strings to match.
  2930. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  2931. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2932. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  2933. * @api public
  2934. */
  2935. micromatch.not = (list, patterns, options = {}) => {
  2936. patterns = [].concat(patterns).map(String);
  2937. let result = new Set();
  2938. let items = [];
  2939. let onResult = state => {
  2940. if (options.onResult) options.onResult(state);
  2941. items.push(state.output);
  2942. };
  2943. let matches = micromatch(list, patterns, { ...options, onResult });
  2944. for (let item of items) {
  2945. if (!matches.includes(item)) {
  2946. result.add(item);
  2947. }
  2948. }
  2949. return [...result];
  2950. };
  2951. /**
  2952. * Returns true if the given `string` contains the given pattern. Similar
  2953. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  2954. *
  2955. * ```js
  2956. * var mm = require('micromatch');
  2957. * // mm.contains(string, pattern[, options]);
  2958. *
  2959. * console.log(mm.contains('aa/bb/cc', '*b'));
  2960. * //=> true
  2961. * console.log(mm.contains('aa/bb/cc', '*d'));
  2962. * //=> false
  2963. * ```
  2964. * @param {String} `str` The string to match.
  2965. * @param {String|Array} `patterns` Glob pattern to use for matching.
  2966. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2967. * @return {Boolean} Returns true if the patter matches any part of `str`.
  2968. * @api public
  2969. */
  2970. micromatch.contains = (str, pattern, options) => {
  2971. if (typeof str !== 'string') {
  2972. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  2973. }
  2974. if (Array.isArray(pattern)) {
  2975. return pattern.some(p => micromatch.contains(str, p, options));
  2976. }
  2977. if (typeof pattern === 'string') {
  2978. if (isEmptyString(str) || isEmptyString(pattern)) {
  2979. return false;
  2980. }
  2981. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  2982. return true;
  2983. }
  2984. }
  2985. return micromatch.isMatch(str, pattern, { ...options, contains: true });
  2986. };
  2987. /**
  2988. * Filter the keys of the given object with the given `glob` pattern
  2989. * and `options`. Does not attempt to match nested keys. If you need this feature,
  2990. * use [glob-object][] instead.
  2991. *
  2992. * ```js
  2993. * const mm = require('micromatch');
  2994. * // mm.matchKeys(object, patterns[, options]);
  2995. *
  2996. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  2997. * console.log(mm.matchKeys(obj, '*b'));
  2998. * //=> { ab: 'b' }
  2999. * ```
  3000. * @param {Object} `object` The object with keys to filter.
  3001. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3002. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3003. * @return {Object} Returns an object with only keys that match the given patterns.
  3004. * @api public
  3005. */
  3006. micromatch.matchKeys = (obj, patterns, options) => {
  3007. if (!utils$1.isObject(obj)) {
  3008. throw new TypeError('Expected the first argument to be an object');
  3009. }
  3010. let keys = micromatch(Object.keys(obj), patterns, options);
  3011. let res = {};
  3012. for (let key of keys) res[key] = obj[key];
  3013. return res;
  3014. };
  3015. /**
  3016. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  3017. *
  3018. * ```js
  3019. * const mm = require('micromatch');
  3020. * // mm.some(list, patterns[, options]);
  3021. *
  3022. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  3023. * // true
  3024. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  3025. * // false
  3026. * ```
  3027. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  3028. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3029. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3030. * @return {Boolean} Returns true if any patterns match `str`
  3031. * @api public
  3032. */
  3033. micromatch.some = (list, patterns, options) => {
  3034. let items = [].concat(list);
  3035. for (let pattern of [].concat(patterns)) {
  3036. let isMatch = picomatch$1(String(pattern), options);
  3037. if (items.some(item => isMatch(item))) {
  3038. return true;
  3039. }
  3040. }
  3041. return false;
  3042. };
  3043. /**
  3044. * Returns true if every string in the given `list` matches
  3045. * any of the given glob `patterns`.
  3046. *
  3047. * ```js
  3048. * const mm = require('micromatch');
  3049. * // mm.every(list, patterns[, options]);
  3050. *
  3051. * console.log(mm.every('foo.js', ['foo.js']));
  3052. * // true
  3053. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  3054. * // true
  3055. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  3056. * // false
  3057. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  3058. * // false
  3059. * ```
  3060. * @param {String|Array} `list` The string or array of strings to test.
  3061. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3062. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3063. * @return {Boolean} Returns true if any patterns match `str`
  3064. * @api public
  3065. */
  3066. micromatch.every = (list, patterns, options) => {
  3067. let items = [].concat(list);
  3068. for (let pattern of [].concat(patterns)) {
  3069. let isMatch = picomatch$1(String(pattern), options);
  3070. if (!items.every(item => isMatch(item))) {
  3071. return false;
  3072. }
  3073. }
  3074. return true;
  3075. };
  3076. /**
  3077. * Returns true if **all** of the given `patterns` match
  3078. * the specified string.
  3079. *
  3080. * ```js
  3081. * const mm = require('micromatch');
  3082. * // mm.all(string, patterns[, options]);
  3083. *
  3084. * console.log(mm.all('foo.js', ['foo.js']));
  3085. * // true
  3086. *
  3087. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  3088. * // false
  3089. *
  3090. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  3091. * // true
  3092. *
  3093. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  3094. * // true
  3095. * ```
  3096. * @param {String|Array} `str` The string to test.
  3097. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3098. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3099. * @return {Boolean} Returns true if any patterns match `str`
  3100. * @api public
  3101. */
  3102. micromatch.all = (str, patterns, options) => {
  3103. if (typeof str !== 'string') {
  3104. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  3105. }
  3106. return [].concat(patterns).every(p => picomatch$1(p, options)(str));
  3107. };
  3108. /**
  3109. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  3110. *
  3111. * ```js
  3112. * const mm = require('micromatch');
  3113. * // mm.capture(pattern, string[, options]);
  3114. *
  3115. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  3116. * //=> ['foo']
  3117. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  3118. * //=> null
  3119. * ```
  3120. * @param {String} `glob` Glob pattern to use for matching.
  3121. * @param {String} `input` String to match
  3122. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3123. * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  3124. * @api public
  3125. */
  3126. micromatch.capture = (glob, input, options) => {
  3127. let posix = utils$1.isWindows(options);
  3128. let regex = picomatch$1.makeRe(String(glob), { ...options, capture: true });
  3129. let match = regex.exec(posix ? utils$1.toPosixSlashes(input) : input);
  3130. if (match) {
  3131. return match.slice(1).map(v => v === void 0 ? '' : v);
  3132. }
  3133. };
  3134. /**
  3135. * Create a regular expression from the given glob `pattern`.
  3136. *
  3137. * ```js
  3138. * const mm = require('micromatch');
  3139. * // mm.makeRe(pattern[, options]);
  3140. *
  3141. * console.log(mm.makeRe('*.js'));
  3142. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  3143. * ```
  3144. * @param {String} `pattern` A glob pattern to convert to regex.
  3145. * @param {Object} `options`
  3146. * @return {RegExp} Returns a regex created from the given pattern.
  3147. * @api public
  3148. */
  3149. micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
  3150. /**
  3151. * Scan a glob pattern to separate the pattern into segments. Used
  3152. * by the [split](#split) method.
  3153. *
  3154. * ```js
  3155. * const mm = require('micromatch');
  3156. * const state = mm.scan(pattern[, options]);
  3157. * ```
  3158. * @param {String} `pattern`
  3159. * @param {Object} `options`
  3160. * @return {Object} Returns an object with
  3161. * @api public
  3162. */
  3163. micromatch.scan = (...args) => picomatch$1.scan(...args);
  3164. /**
  3165. * Parse a glob pattern to create the source string for a regular
  3166. * expression.
  3167. *
  3168. * ```js
  3169. * const mm = require('micromatch');
  3170. * const state = mm(pattern[, options]);
  3171. * ```
  3172. * @param {String} `glob`
  3173. * @param {Object} `options`
  3174. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  3175. * @api public
  3176. */
  3177. micromatch.parse = (patterns, options) => {
  3178. let res = [];
  3179. for (let pattern of [].concat(patterns || [])) {
  3180. for (let str of braces_1(String(pattern), options)) {
  3181. res.push(picomatch$1.parse(str, options));
  3182. }
  3183. }
  3184. return res;
  3185. };
  3186. /**
  3187. * Process the given brace `pattern`.
  3188. *
  3189. * ```js
  3190. * const { braces } = require('micromatch');
  3191. * console.log(braces('foo/{a,b,c}/bar'));
  3192. * //=> [ 'foo/(a|b|c)/bar' ]
  3193. *
  3194. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  3195. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  3196. * ```
  3197. * @param {String} `pattern` String with brace pattern to process.
  3198. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  3199. * @return {Array}
  3200. * @api public
  3201. */
  3202. micromatch.braces = (pattern, options) => {
  3203. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  3204. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  3205. return [pattern];
  3206. }
  3207. return braces_1(pattern, options);
  3208. };
  3209. /**
  3210. * Expand braces
  3211. */
  3212. micromatch.braceExpand = (pattern, options) => {
  3213. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  3214. return micromatch.braces(pattern, { ...options, expand: true });
  3215. };
  3216. /**
  3217. * Expose micromatch
  3218. */
  3219. var micromatch_1 = micromatch;
  3220. function ensureArray(thing) {
  3221. if (Array.isArray(thing))
  3222. return thing;
  3223. if (thing == undefined)
  3224. return [];
  3225. return [thing];
  3226. }
  3227. function getMatcherString(id, resolutionBase) {
  3228. if (resolutionBase === false) {
  3229. return id;
  3230. }
  3231. return resolve(...(typeof resolutionBase === 'string' ? [resolutionBase, id] : [id]));
  3232. }
  3233. const createFilter = function createFilter(include, exclude, options) {
  3234. const resolutionBase = options && options.resolve;
  3235. const getMatcher = (id) => {
  3236. return id instanceof RegExp
  3237. ? id
  3238. : {
  3239. test: micromatch_1.matcher(getMatcherString(id, resolutionBase)
  3240. .split(sep)
  3241. .join('/'), { dot: true })
  3242. };
  3243. };
  3244. const includeMatchers = ensureArray(include).map(getMatcher);
  3245. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  3246. return function (id) {
  3247. if (typeof id !== 'string')
  3248. return false;
  3249. if (/\0/.test(id))
  3250. return false;
  3251. id = id.split(sep).join('/');
  3252. for (let i = 0; i < excludeMatchers.length; ++i) {
  3253. const matcher = excludeMatchers[i];
  3254. if (matcher.test(id))
  3255. return false;
  3256. }
  3257. for (let i = 0; i < includeMatchers.length; ++i) {
  3258. const matcher = includeMatchers[i];
  3259. if (matcher.test(id))
  3260. return true;
  3261. }
  3262. return !includeMatchers.length;
  3263. };
  3264. };
  3265. const commandAliases = {
  3266. c: 'config',
  3267. d: 'dir',
  3268. e: 'external',
  3269. f: 'format',
  3270. g: 'globals',
  3271. h: 'help',
  3272. i: 'input',
  3273. m: 'sourcemap',
  3274. n: 'name',
  3275. o: 'file',
  3276. p: 'plugin',
  3277. v: 'version',
  3278. w: 'watch'
  3279. };
  3280. function mergeOptions(config, rawCommandOptions = { external: [], globals: undefined }, defaultOnWarnHandler = defaultOnWarn) {
  3281. const command = getCommandOptions(rawCommandOptions);
  3282. const inputOptions = mergeInputOptions(config, command, defaultOnWarnHandler);
  3283. const warn = inputOptions.onwarn;
  3284. if (command.output) {
  3285. Object.assign(command, command.output);
  3286. }
  3287. const outputOptionsArray = ensureArray$1(config.output);
  3288. if (outputOptionsArray.length === 0)
  3289. outputOptionsArray.push({});
  3290. const outputOptions = outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, warn));
  3291. warnUnknownOptions(command, Object.keys(inputOptions).concat(Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapPathTransform'), Object.keys(commandAliases), 'config', 'environment', 'plugin', 'silent', 'failAfterWarnings', 'stdin', 'waitForBundleInput'), 'CLI flags', warn, /^_$|output$|config/);
  3292. inputOptions.output = outputOptions;
  3293. return inputOptions;
  3294. }
  3295. function getCommandOptions(rawCommandOptions) {
  3296. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  3297. ? rawCommandOptions.external.split(',')
  3298. : [];
  3299. return {
  3300. ...rawCommandOptions,
  3301. external,
  3302. globals: typeof rawCommandOptions.globals === 'string'
  3303. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  3304. const [id, variableName] = globalDefinition.split(':');
  3305. globals[id] = variableName;
  3306. if (external.indexOf(id) === -1) {
  3307. external.push(id);
  3308. }
  3309. return globals;
  3310. }, Object.create(null))
  3311. : undefined
  3312. };
  3313. }
  3314. function mergeInputOptions(config, overrides, defaultOnWarnHandler) {
  3315. const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };
  3316. const inputOptions = {
  3317. acorn: getOption('acorn'),
  3318. acornInjectPlugins: config.acornInjectPlugins,
  3319. cache: config.cache,
  3320. context: getOption('context'),
  3321. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  3322. external: getExternal(config, overrides),
  3323. inlineDynamicImports: getOption('inlineDynamicImports'),
  3324. input: getOption('input') || [],
  3325. manualChunks: getOption('manualChunks'),
  3326. moduleContext: getOption('moduleContext'),
  3327. onwarn: getOnWarn(config, defaultOnWarnHandler),
  3328. perf: getOption('perf'),
  3329. plugins: ensureArray$1(config.plugins),
  3330. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  3331. preserveModules: getOption('preserveModules'),
  3332. preserveSymlinks: getOption('preserveSymlinks'),
  3333. shimMissingExports: getOption('shimMissingExports'),
  3334. strictDeprecations: getOption('strictDeprecations'),
  3335. treeshake: getObjectOption(config, overrides, 'treeshake'),
  3336. watch: getWatch(config, overrides, 'watch')
  3337. };
  3338. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', inputOptions.onwarn, /^output$/);
  3339. return inputOptions;
  3340. }
  3341. const getExternal = (config, overrides) => {
  3342. const configExternal = config.external;
  3343. return typeof configExternal === 'function'
  3344. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.indexOf(source) !== -1
  3345. : ensureArray$1(configExternal).concat(overrides.external);
  3346. };
  3347. const getOnWarn = (config, defaultOnWarnHandler) => config.onwarn
  3348. ? warning => config.onwarn(warning, defaultOnWarnHandler)
  3349. : defaultOnWarnHandler;
  3350. const getObjectOption = (config, overrides, name) => {
  3351. const commandOption = normalizeObjectOptionValue(overrides[name]);
  3352. const configOption = normalizeObjectOptionValue(config[name]);
  3353. if (commandOption !== undefined) {
  3354. return commandOption && { ...configOption, ...commandOption };
  3355. }
  3356. return configOption;
  3357. };
  3358. const getWatch = (config, overrides, name) => config.watch !== false && getObjectOption(config, overrides, name);
  3359. const normalizeObjectOptionValue = (optionValue) => {
  3360. if (!optionValue) {
  3361. return optionValue;
  3362. }
  3363. if (Array.isArray(optionValue)) {
  3364. return optionValue.reduce((result, value) => value && result && { ...result, ...value }, {});
  3365. }
  3366. if (typeof optionValue !== 'object') {
  3367. return {};
  3368. }
  3369. return optionValue;
  3370. };
  3371. function mergeOutputOptions(config, overrides, warn) {
  3372. const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };
  3373. const outputOptions = {
  3374. amd: getObjectOption(config, overrides, 'amd'),
  3375. assetFileNames: getOption('assetFileNames'),
  3376. banner: getOption('banner'),
  3377. chunkFileNames: getOption('chunkFileNames'),
  3378. compact: getOption('compact'),
  3379. dir: getOption('dir'),
  3380. dynamicImportFunction: getOption('dynamicImportFunction'),
  3381. entryFileNames: getOption('entryFileNames'),
  3382. esModule: getOption('esModule'),
  3383. exports: getOption('exports'),
  3384. extend: getOption('extend'),
  3385. externalLiveBindings: getOption('externalLiveBindings'),
  3386. file: getOption('file'),
  3387. footer: getOption('footer'),
  3388. format: getOption('format'),
  3389. freeze: getOption('freeze'),
  3390. globals: getOption('globals'),
  3391. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  3392. indent: getOption('indent'),
  3393. inlineDynamicImports: getOption('inlineDynamicImports'),
  3394. interop: getOption('interop'),
  3395. intro: getOption('intro'),
  3396. manualChunks: getOption('manualChunks'),
  3397. minifyInternalExports: getOption('minifyInternalExports'),
  3398. name: getOption('name'),
  3399. namespaceToStringTag: getOption('namespaceToStringTag'),
  3400. noConflict: getOption('noConflict'),
  3401. outro: getOption('outro'),
  3402. paths: getOption('paths'),
  3403. plugins: ensureArray$1(config.plugins),
  3404. preferConst: getOption('preferConst'),
  3405. preserveModules: getOption('preserveModules'),
  3406. preserveModulesRoot: getOption('preserveModulesRoot'),
  3407. sourcemap: getOption('sourcemap'),
  3408. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  3409. sourcemapFile: getOption('sourcemapFile'),
  3410. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  3411. strict: getOption('strict'),
  3412. systemNullSetters: getOption('systemNullSetters')
  3413. };
  3414. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', warn);
  3415. return outputOptions;
  3416. }
  3417. const { Readable } = require$$0$1;
  3418. const { promisify } = util;
  3419. const readdir = promisify(fs.readdir);
  3420. const stat = promisify(fs.stat);
  3421. const lstat = promisify(fs.lstat);
  3422. const realpath = promisify(fs.realpath);
  3423. /**
  3424. * @typedef {Object} EntryInfo
  3425. * @property {String} path
  3426. * @property {String} fullPath
  3427. * @property {fs.Stats=} stats
  3428. * @property {fs.Dirent=} dirent
  3429. * @property {String} basename
  3430. */
  3431. const BANG = '!';
  3432. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP']);
  3433. const FILE_TYPE = 'files';
  3434. const DIR_TYPE = 'directories';
  3435. const FILE_DIR_TYPE = 'files_directories';
  3436. const EVERYTHING_TYPE = 'all';
  3437. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  3438. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  3439. const normalizeFilter = filter => {
  3440. if (filter === undefined) return;
  3441. if (typeof filter === 'function') return filter;
  3442. if (typeof filter === 'string') {
  3443. const glob = picomatch$1(filter.trim());
  3444. return entry => glob(entry.basename);
  3445. }
  3446. if (Array.isArray(filter)) {
  3447. const positive = [];
  3448. const negative = [];
  3449. for (const item of filter) {
  3450. const trimmed = item.trim();
  3451. if (trimmed.charAt(0) === BANG) {
  3452. negative.push(picomatch$1(trimmed.slice(1)));
  3453. } else {
  3454. positive.push(picomatch$1(trimmed));
  3455. }
  3456. }
  3457. if (negative.length > 0) {
  3458. if (positive.length > 0) {
  3459. return entry =>
  3460. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  3461. }
  3462. return entry => !negative.some(f => f(entry.basename));
  3463. }
  3464. return entry => positive.some(f => f(entry.basename));
  3465. }
  3466. };
  3467. class ReaddirpStream extends Readable {
  3468. static get defaultOptions() {
  3469. return {
  3470. root: '.',
  3471. /* eslint-disable no-unused-vars */
  3472. fileFilter: (path) => true,
  3473. directoryFilter: (path) => true,
  3474. /* eslint-enable no-unused-vars */
  3475. type: FILE_TYPE,
  3476. lstat: false,
  3477. depth: 2147483648,
  3478. alwaysStat: false
  3479. };
  3480. }
  3481. constructor(options = {}) {
  3482. super({
  3483. objectMode: true,
  3484. autoDestroy: true,
  3485. highWaterMark: options.highWaterMark || 4096
  3486. });
  3487. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  3488. const { root, type } = opts;
  3489. this._fileFilter = normalizeFilter(opts.fileFilter);
  3490. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  3491. const statMethod = opts.lstat ? lstat : stat;
  3492. // Use bigint stats if it's windows and stat() supports options (node 10+).
  3493. if (process.platform === 'win32' && stat.length === 3) {
  3494. this._stat = path => statMethod(path, { bigint: true });
  3495. } else {
  3496. this._stat = statMethod;
  3497. }
  3498. this._maxDepth = opts.depth;
  3499. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  3500. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  3501. this._wantsEverything = type === EVERYTHING_TYPE;
  3502. this._root = sysPath.resolve(root);
  3503. this._isDirent = ('Dirent' in fs) && !opts.alwaysStat;
  3504. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  3505. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  3506. // Launch stream with one parent, the root dir.
  3507. this.parents = [this._exploreDir(root, 1)];
  3508. this.reading = false;
  3509. this.parent = undefined;
  3510. }
  3511. async _read(batch) {
  3512. if (this.reading) return;
  3513. this.reading = true;
  3514. try {
  3515. while (!this.destroyed && batch > 0) {
  3516. const { path, depth, files = [] } = this.parent || {};
  3517. if (files.length > 0) {
  3518. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  3519. for (const entry of await Promise.all(slice)) {
  3520. if (this.destroyed) return;
  3521. const entryType = await this._getEntryType(entry);
  3522. if (entryType === 'directory' && this._directoryFilter(entry)) {
  3523. if (depth <= this._maxDepth) {
  3524. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  3525. }
  3526. if (this._wantsDir) {
  3527. this.push(entry);
  3528. batch--;
  3529. }
  3530. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  3531. if (this._wantsFile) {
  3532. this.push(entry);
  3533. batch--;
  3534. }
  3535. }
  3536. }
  3537. } else {
  3538. const parent = this.parents.pop();
  3539. if (!parent) {
  3540. this.push(null);
  3541. break;
  3542. }
  3543. this.parent = await parent;
  3544. if (this.destroyed) return;
  3545. }
  3546. }
  3547. } catch (error) {
  3548. this.destroy(error);
  3549. } finally {
  3550. this.reading = false;
  3551. }
  3552. }
  3553. async _exploreDir(path, depth) {
  3554. let files;
  3555. try {
  3556. files = await readdir(path, this._rdOptions);
  3557. } catch (error) {
  3558. this._onError(error);
  3559. }
  3560. return {files, depth, path};
  3561. }
  3562. async _formatEntry(dirent, path) {
  3563. let entry;
  3564. try {
  3565. const basename = this._isDirent ? dirent.name : dirent;
  3566. const fullPath = sysPath.resolve(sysPath.join(path, basename));
  3567. entry = {path: sysPath.relative(this._root, fullPath), fullPath, basename};
  3568. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  3569. } catch (err) {
  3570. this._onError(err);
  3571. }
  3572. return entry;
  3573. }
  3574. _onError(err) {
  3575. if (isNormalFlowError(err) && !this.destroyed) {
  3576. this.emit('warn', err);
  3577. } else {
  3578. this.destroy(err);
  3579. }
  3580. }
  3581. async _getEntryType(entry) {
  3582. // entry may be undefined, because a warning or an error were emitted
  3583. // and the statsProp is undefined
  3584. const stats = entry && entry[this._statsProp];
  3585. if (!stats) {
  3586. return;
  3587. }
  3588. if (stats.isFile()) {
  3589. return 'file';
  3590. }
  3591. if (stats.isDirectory()) {
  3592. return 'directory';
  3593. }
  3594. if (stats && stats.isSymbolicLink()) {
  3595. try {
  3596. const entryRealPath = await realpath(entry.fullPath);
  3597. const entryRealPathStats = await lstat(entryRealPath);
  3598. if (entryRealPathStats.isFile()) {
  3599. return 'file';
  3600. }
  3601. if (entryRealPathStats.isDirectory()) {
  3602. return 'directory';
  3603. }
  3604. } catch (error) {
  3605. this._onError(error);
  3606. }
  3607. }
  3608. }
  3609. _includeAsFile(entry) {
  3610. const stats = entry && entry[this._statsProp];
  3611. return stats && this._wantsEverything && !stats.isDirectory();
  3612. }
  3613. }
  3614. /**
  3615. * @typedef {Object} ReaddirpArguments
  3616. * @property {Function=} fileFilter
  3617. * @property {Function=} directoryFilter
  3618. * @property {String=} type
  3619. * @property {Number=} depth
  3620. * @property {String=} root
  3621. * @property {Boolean=} lstat
  3622. * @property {Boolean=} bigint
  3623. */
  3624. /**
  3625. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  3626. * @param {String} root Root directory
  3627. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  3628. */
  3629. const readdirp = (root, options = {}) => {
  3630. let type = options.entryType || options.type;
  3631. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  3632. if (type) options.type = type;
  3633. if (!root) {
  3634. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  3635. } else if (typeof root !== 'string') {
  3636. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  3637. } else if (type && !ALL_TYPES.includes(type)) {
  3638. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  3639. }
  3640. options.root = root;
  3641. return new ReaddirpStream(options);
  3642. };
  3643. const readdirpPromise = (root, options = {}) => {
  3644. return new Promise((resolve, reject) => {
  3645. const files = [];
  3646. readdirp(root, options)
  3647. .on('data', entry => files.push(entry))
  3648. .on('end', () => resolve(files))
  3649. .on('error', error => reject(error));
  3650. });
  3651. };
  3652. readdirp.promise = readdirpPromise;
  3653. readdirp.ReaddirpStream = ReaddirpStream;
  3654. readdirp.default = readdirp;
  3655. var readdirp_1 = readdirp;
  3656. /*!
  3657. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  3658. *
  3659. * Copyright (c) 2014-2018, Jon Schlinkert.
  3660. * Released under the MIT License.
  3661. */
  3662. var normalizePath = function(path, stripTrailing) {
  3663. if (typeof path !== 'string') {
  3664. throw new TypeError('expected path to be a string');
  3665. }
  3666. if (path === '\\' || path === '/') return '/';
  3667. var len = path.length;
  3668. if (len <= 1) return path;
  3669. // ensure that win32 namespaces has two leading slashes, so that the path is
  3670. // handled properly by the win32 version of path.parse() after being normalized
  3671. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  3672. var prefix = '';
  3673. if (len > 4 && path[3] === '\\') {
  3674. var ch = path[2];
  3675. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  3676. path = path.slice(2);
  3677. prefix = '//';
  3678. }
  3679. }
  3680. var segs = path.split(/[/\\]+/);
  3681. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  3682. segs.pop();
  3683. }
  3684. return prefix + segs.join('/');
  3685. };
  3686. var anymatch_1 = createCommonjsModule(function (module, exports) {
  3687. Object.defineProperty(exports, "__esModule", { value: true });
  3688. /**
  3689. * @typedef {(testString: string) => boolean} AnymatchFn
  3690. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  3691. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  3692. */
  3693. const BANG = '!';
  3694. const DEFAULT_OPTIONS = {returnIndex: false};
  3695. const arrify = (item) => Array.isArray(item) ? item : [item];
  3696. /**
  3697. * @param {AnymatchPattern} matcher
  3698. * @param {object} options
  3699. * @returns {AnymatchFn}
  3700. */
  3701. const createPattern = (matcher, options) => {
  3702. if (typeof matcher === 'function') {
  3703. return matcher;
  3704. }
  3705. if (typeof matcher === 'string') {
  3706. const glob = picomatch$1(matcher, options);
  3707. return (string) => matcher === string || glob(string);
  3708. }
  3709. if (matcher instanceof RegExp) {
  3710. return (string) => matcher.test(string);
  3711. }
  3712. return (string) => false;
  3713. };
  3714. /**
  3715. * @param {Array<Function>} patterns
  3716. * @param {Array<Function>} negPatterns
  3717. * @param {String|Array} args
  3718. * @param {Boolean} returnIndex
  3719. * @returns {boolean|number}
  3720. */
  3721. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  3722. const isList = Array.isArray(args);
  3723. const _path = isList ? args[0] : args;
  3724. if (!isList && typeof _path !== 'string') {
  3725. throw new TypeError('anymatch: second argument must be a string: got ' +
  3726. Object.prototype.toString.call(_path))
  3727. }
  3728. const path = normalizePath(_path);
  3729. for (let index = 0; index < negPatterns.length; index++) {
  3730. const nglob = negPatterns[index];
  3731. if (nglob(path)) {
  3732. return returnIndex ? -1 : false;
  3733. }
  3734. }
  3735. const applied = isList && [path].concat(args.slice(1));
  3736. for (let index = 0; index < patterns.length; index++) {
  3737. const pattern = patterns[index];
  3738. if (isList ? pattern(...applied) : pattern(path)) {
  3739. return returnIndex ? index : true;
  3740. }
  3741. }
  3742. return returnIndex ? -1 : false;
  3743. };
  3744. /**
  3745. * @param {AnymatchMatcher} matchers
  3746. * @param {Array|string} testString
  3747. * @param {object} options
  3748. * @returns {boolean|number|Function}
  3749. */
  3750. const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => {
  3751. if (matchers == null) {
  3752. throw new TypeError('anymatch: specify first argument');
  3753. }
  3754. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  3755. const returnIndex = opts.returnIndex || false;
  3756. // Early cache for matchers.
  3757. const mtchers = arrify(matchers);
  3758. const negatedGlobs = mtchers
  3759. .filter(item => typeof item === 'string' && item.charAt(0) === BANG)
  3760. .map(item => item.slice(1))
  3761. .map(item => picomatch$1(item, opts));
  3762. const patterns = mtchers.map(matcher => createPattern(matcher, opts));
  3763. if (testString == null) {
  3764. return (testString, ri = false) => {
  3765. const returnIndex = typeof ri === 'boolean' ? ri : false;
  3766. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  3767. }
  3768. }
  3769. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  3770. };
  3771. anymatch.default = anymatch;
  3772. module.exports = anymatch;
  3773. });
  3774. /*!
  3775. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  3776. *
  3777. * Copyright (c) 2014-2016, Jon Schlinkert.
  3778. * Licensed under the MIT License.
  3779. */
  3780. var isExtglob = function isExtglob(str) {
  3781. if (typeof str !== 'string' || str === '') {
  3782. return false;
  3783. }
  3784. var match;
  3785. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  3786. if (match[2]) return true;
  3787. str = str.slice(match.index + match[0].length);
  3788. }
  3789. return false;
  3790. };
  3791. /*!
  3792. * is-glob <https://github.com/jonschlinkert/is-glob>
  3793. *
  3794. * Copyright (c) 2014-2017, Jon Schlinkert.
  3795. * Released under the MIT License.
  3796. */
  3797. var chars = { '{': '}', '(': ')', '[': ']'};
  3798. var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
  3799. var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
  3800. var isGlob = function isGlob(str, options) {
  3801. if (typeof str !== 'string' || str === '') {
  3802. return false;
  3803. }
  3804. if (isExtglob(str)) {
  3805. return true;
  3806. }
  3807. var regex = strictRegex;
  3808. var match;
  3809. // optionally relax regex
  3810. if (options && options.strict === false) {
  3811. regex = relaxedRegex;
  3812. }
  3813. while ((match = regex.exec(str))) {
  3814. if (match[2]) return true;
  3815. var idx = match.index + match[0].length;
  3816. // if an open bracket/brace/paren is escaped,
  3817. // set the index to the next closing character
  3818. var open = match[1];
  3819. var close = open ? chars[open] : null;
  3820. if (open && close) {
  3821. var n = str.indexOf(close, idx);
  3822. if (n !== -1) {
  3823. idx = n + 1;
  3824. }
  3825. }
  3826. str = str.slice(idx);
  3827. }
  3828. return false;
  3829. };
  3830. var pathPosixDirname = sysPath.posix.dirname;
  3831. var isWin32 = require$$1$1.platform() === 'win32';
  3832. var slash = '/';
  3833. var backslash = /\\/g;
  3834. var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
  3835. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  3836. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  3837. /**
  3838. * @param {string} str
  3839. * @param {Object} opts
  3840. * @param {boolean} [opts.flipBackslashes=true]
  3841. */
  3842. var globParent = function globParent(str, opts) {
  3843. var options = Object.assign({ flipBackslashes: true }, opts);
  3844. // flip windows path separators
  3845. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  3846. str = str.replace(backslash, slash);
  3847. }
  3848. // special case for strings ending in enclosure containing path separator
  3849. if (enclosure.test(str)) {
  3850. str += slash;
  3851. }
  3852. // preserves full path in case of trailing path separator
  3853. str += 'a';
  3854. // remove path parts that are globby
  3855. do {
  3856. str = pathPosixDirname(str);
  3857. } while (isGlob(str) || globby.test(str));
  3858. // remove escape chars and return result
  3859. return str.replace(escaped, '$1');
  3860. };
  3861. var require$$0 = [
  3862. "3dm",
  3863. "3ds",
  3864. "3g2",
  3865. "3gp",
  3866. "7z",
  3867. "a",
  3868. "aac",
  3869. "adp",
  3870. "ai",
  3871. "aif",
  3872. "aiff",
  3873. "alz",
  3874. "ape",
  3875. "apk",
  3876. "appimage",
  3877. "ar",
  3878. "arj",
  3879. "asf",
  3880. "au",
  3881. "avi",
  3882. "bak",
  3883. "baml",
  3884. "bh",
  3885. "bin",
  3886. "bk",
  3887. "bmp",
  3888. "btif",
  3889. "bz2",
  3890. "bzip2",
  3891. "cab",
  3892. "caf",
  3893. "cgm",
  3894. "class",
  3895. "cmx",
  3896. "cpio",
  3897. "cr2",
  3898. "cur",
  3899. "dat",
  3900. "dcm",
  3901. "deb",
  3902. "dex",
  3903. "djvu",
  3904. "dll",
  3905. "dmg",
  3906. "dng",
  3907. "doc",
  3908. "docm",
  3909. "docx",
  3910. "dot",
  3911. "dotm",
  3912. "dra",
  3913. "DS_Store",
  3914. "dsk",
  3915. "dts",
  3916. "dtshd",
  3917. "dvb",
  3918. "dwg",
  3919. "dxf",
  3920. "ecelp4800",
  3921. "ecelp7470",
  3922. "ecelp9600",
  3923. "egg",
  3924. "eol",
  3925. "eot",
  3926. "epub",
  3927. "exe",
  3928. "f4v",
  3929. "fbs",
  3930. "fh",
  3931. "fla",
  3932. "flac",
  3933. "flatpak",
  3934. "fli",
  3935. "flv",
  3936. "fpx",
  3937. "fst",
  3938. "fvt",
  3939. "g3",
  3940. "gh",
  3941. "gif",
  3942. "graffle",
  3943. "gz",
  3944. "gzip",
  3945. "h261",
  3946. "h263",
  3947. "h264",
  3948. "icns",
  3949. "ico",
  3950. "ief",
  3951. "img",
  3952. "ipa",
  3953. "iso",
  3954. "jar",
  3955. "jpeg",
  3956. "jpg",
  3957. "jpgv",
  3958. "jpm",
  3959. "jxr",
  3960. "key",
  3961. "ktx",
  3962. "lha",
  3963. "lib",
  3964. "lvp",
  3965. "lz",
  3966. "lzh",
  3967. "lzma",
  3968. "lzo",
  3969. "m3u",
  3970. "m4a",
  3971. "m4v",
  3972. "mar",
  3973. "mdi",
  3974. "mht",
  3975. "mid",
  3976. "midi",
  3977. "mj2",
  3978. "mka",
  3979. "mkv",
  3980. "mmr",
  3981. "mng",
  3982. "mobi",
  3983. "mov",
  3984. "movie",
  3985. "mp3",
  3986. "mp4",
  3987. "mp4a",
  3988. "mpeg",
  3989. "mpg",
  3990. "mpga",
  3991. "mxu",
  3992. "nef",
  3993. "npx",
  3994. "numbers",
  3995. "nupkg",
  3996. "o",
  3997. "oga",
  3998. "ogg",
  3999. "ogv",
  4000. "otf",
  4001. "pages",
  4002. "pbm",
  4003. "pcx",
  4004. "pdb",
  4005. "pdf",
  4006. "pea",
  4007. "pgm",
  4008. "pic",
  4009. "png",
  4010. "pnm",
  4011. "pot",
  4012. "potm",
  4013. "potx",
  4014. "ppa",
  4015. "ppam",
  4016. "ppm",
  4017. "pps",
  4018. "ppsm",
  4019. "ppsx",
  4020. "ppt",
  4021. "pptm",
  4022. "pptx",
  4023. "psd",
  4024. "pya",
  4025. "pyc",
  4026. "pyo",
  4027. "pyv",
  4028. "qt",
  4029. "rar",
  4030. "ras",
  4031. "raw",
  4032. "resources",
  4033. "rgb",
  4034. "rip",
  4035. "rlc",
  4036. "rmf",
  4037. "rmvb",
  4038. "rpm",
  4039. "rtf",
  4040. "rz",
  4041. "s3m",
  4042. "s7z",
  4043. "scpt",
  4044. "sgi",
  4045. "shar",
  4046. "snap",
  4047. "sil",
  4048. "sketch",
  4049. "slk",
  4050. "smv",
  4051. "snk",
  4052. "so",
  4053. "stl",
  4054. "suo",
  4055. "sub",
  4056. "swf",
  4057. "tar",
  4058. "tbz",
  4059. "tbz2",
  4060. "tga",
  4061. "tgz",
  4062. "thmx",
  4063. "tif",
  4064. "tiff",
  4065. "tlz",
  4066. "ttc",
  4067. "ttf",
  4068. "txz",
  4069. "udf",
  4070. "uvh",
  4071. "uvi",
  4072. "uvm",
  4073. "uvp",
  4074. "uvs",
  4075. "uvu",
  4076. "viv",
  4077. "vob",
  4078. "war",
  4079. "wav",
  4080. "wax",
  4081. "wbmp",
  4082. "wdp",
  4083. "weba",
  4084. "webm",
  4085. "webp",
  4086. "whl",
  4087. "wim",
  4088. "wm",
  4089. "wma",
  4090. "wmv",
  4091. "wmx",
  4092. "woff",
  4093. "woff2",
  4094. "wrm",
  4095. "wvx",
  4096. "xbm",
  4097. "xif",
  4098. "xla",
  4099. "xlam",
  4100. "xls",
  4101. "xlsb",
  4102. "xlsm",
  4103. "xlsx",
  4104. "xlt",
  4105. "xltm",
  4106. "xltx",
  4107. "xm",
  4108. "xmind",
  4109. "xpi",
  4110. "xpm",
  4111. "xwd",
  4112. "xz",
  4113. "z",
  4114. "zip",
  4115. "zipx"
  4116. ];
  4117. var binaryExtensions = require$$0;
  4118. const extensions = new Set(binaryExtensions);
  4119. var isBinaryPath = filePath => extensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
  4120. var constants$2 = createCommonjsModule(function (module, exports) {
  4121. const {sep} = sysPath;
  4122. const {platform} = process;
  4123. exports.EV_ALL = 'all';
  4124. exports.EV_READY = 'ready';
  4125. exports.EV_ADD = 'add';
  4126. exports.EV_CHANGE = 'change';
  4127. exports.EV_ADD_DIR = 'addDir';
  4128. exports.EV_UNLINK = 'unlink';
  4129. exports.EV_UNLINK_DIR = 'unlinkDir';
  4130. exports.EV_RAW = 'raw';
  4131. exports.EV_ERROR = 'error';
  4132. exports.STR_DATA = 'data';
  4133. exports.STR_END = 'end';
  4134. exports.STR_CLOSE = 'close';
  4135. exports.FSEVENT_CREATED = 'created';
  4136. exports.FSEVENT_MODIFIED = 'modified';
  4137. exports.FSEVENT_DELETED = 'deleted';
  4138. exports.FSEVENT_MOVED = 'moved';
  4139. exports.FSEVENT_CLONED = 'cloned';
  4140. exports.FSEVENT_UNKNOWN = 'unknown';
  4141. exports.FSEVENT_TYPE_FILE = 'file';
  4142. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  4143. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  4144. exports.KEY_LISTENERS = 'listeners';
  4145. exports.KEY_ERR = 'errHandlers';
  4146. exports.KEY_RAW = 'rawEmitters';
  4147. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  4148. exports.DOT_SLASH = `.${sep}`;
  4149. exports.BACK_SLASH_RE = /\\/g;
  4150. exports.DOUBLE_SLASH_RE = /\/\//;
  4151. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  4152. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  4153. exports.REPLACER_RE = /^\.[/\\]/;
  4154. exports.SLASH = '/';
  4155. exports.SLASH_SLASH = '//';
  4156. exports.BRACE_START = '{';
  4157. exports.BANG = '!';
  4158. exports.ONE_DOT = '.';
  4159. exports.TWO_DOTS = '..';
  4160. exports.STAR = '*';
  4161. exports.GLOBSTAR = '**';
  4162. exports.ROOT_GLOBSTAR = '/**/*';
  4163. exports.SLASH_GLOBSTAR = '/**';
  4164. exports.DIR_SUFFIX = 'Dir';
  4165. exports.ANYMATCH_OPTS = {dot: true};
  4166. exports.STRING_TYPE = 'string';
  4167. exports.FUNCTION_TYPE = 'function';
  4168. exports.EMPTY_STR = '';
  4169. exports.EMPTY_FN = () => {};
  4170. exports.IDENTITY_FN = val => val;
  4171. exports.isWindows = platform === 'win32';
  4172. exports.isMacos = platform === 'darwin';
  4173. exports.isLinux = platform === 'linux';
  4174. });
  4175. const { promisify: promisify$1 } = util;
  4176. const {
  4177. isWindows,
  4178. isLinux,
  4179. EMPTY_FN,
  4180. EMPTY_STR,
  4181. KEY_LISTENERS,
  4182. KEY_ERR,
  4183. KEY_RAW,
  4184. HANDLER_KEYS,
  4185. EV_CHANGE,
  4186. EV_ADD,
  4187. EV_ADD_DIR,
  4188. EV_ERROR,
  4189. STR_DATA,
  4190. STR_END,
  4191. BRACE_START,
  4192. STAR: STAR$1
  4193. } = constants$2;
  4194. const THROTTLE_MODE_WATCH = 'watch';
  4195. const open = promisify$1(fs.open);
  4196. const stat$1 = promisify$1(fs.stat);
  4197. const lstat$1 = promisify$1(fs.lstat);
  4198. const close = promisify$1(fs.close);
  4199. const fsrealpath = promisify$1(fs.realpath);
  4200. const statMethods = { lstat: lstat$1, stat: stat$1 };
  4201. // TODO: emit errors properly. Example: EMFILE on Macos.
  4202. const foreach = (val, fn) => {
  4203. if (val instanceof Set) {
  4204. val.forEach(fn);
  4205. } else {
  4206. fn(val);
  4207. }
  4208. };
  4209. const addAndConvert = (main, prop, item) => {
  4210. let container = main[prop];
  4211. if (!(container instanceof Set)) {
  4212. main[prop] = container = new Set([container]);
  4213. }
  4214. container.add(item);
  4215. };
  4216. const clearItem = cont => key => {
  4217. const set = cont[key];
  4218. if (set instanceof Set) {
  4219. set.clear();
  4220. } else {
  4221. delete cont[key];
  4222. }
  4223. };
  4224. const delFromSet = (main, prop, item) => {
  4225. const container = main[prop];
  4226. if (container instanceof Set) {
  4227. container.delete(item);
  4228. } else if (container === item) {
  4229. delete main[prop];
  4230. }
  4231. };
  4232. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  4233. /**
  4234. * @typedef {String} Path
  4235. */
  4236. // fs_watch helpers
  4237. // object to hold per-process fs_watch instances
  4238. // (may be shared across chokidar FSWatcher instances)
  4239. /**
  4240. * @typedef {Object} FsWatchContainer
  4241. * @property {Set} listeners
  4242. * @property {Set} errHandlers
  4243. * @property {Set} rawEmitters
  4244. * @property {fs.FSWatcher=} watcher
  4245. * @property {Boolean=} watcherUnusable
  4246. */
  4247. /**
  4248. * @type {Map<String,FsWatchContainer>}
  4249. */
  4250. const FsWatchInstances = new Map();
  4251. /**
  4252. * Instantiates the fs_watch interface
  4253. * @param {String} path to be watched
  4254. * @param {Object} options to be passed to fs_watch
  4255. * @param {Function} listener main event handler
  4256. * @param {Function} errHandler emits info about errors
  4257. * @param {Function} emitRaw emits raw event data
  4258. * @returns {fs.FSWatcher} new fsevents instance
  4259. */
  4260. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  4261. const handleEvent = (rawEvent, evPath) => {
  4262. listener(path);
  4263. emitRaw(rawEvent, evPath, {watchedPath: path});
  4264. // emit based on events occurring for files from a directory's watcher in
  4265. // case the file's watcher misses it (and rely on throttling to de-dupe)
  4266. if (evPath && path !== evPath) {
  4267. fsWatchBroadcast(
  4268. sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)
  4269. );
  4270. }
  4271. };
  4272. try {
  4273. return fs.watch(path, options, handleEvent);
  4274. } catch (error) {
  4275. errHandler(error);
  4276. }
  4277. }
  4278. /**
  4279. * Helper for passing fs_watch event data to a collection of listeners
  4280. * @param {Path} fullPath absolute path bound to fs_watch instance
  4281. * @param {String} type listener type
  4282. * @param {*=} val1 arguments to be passed to listeners
  4283. * @param {*=} val2
  4284. * @param {*=} val3
  4285. */
  4286. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  4287. const cont = FsWatchInstances.get(fullPath);
  4288. if (!cont) return;
  4289. foreach(cont[type], (listener) => {
  4290. listener(val1, val2, val3);
  4291. });
  4292. };
  4293. /**
  4294. * Instantiates the fs_watch interface or binds listeners
  4295. * to an existing one covering the same file system entry
  4296. * @param {String} path
  4297. * @param {String} fullPath absolute path
  4298. * @param {Object} options to be passed to fs_watch
  4299. * @param {Object} handlers container for event listener functions
  4300. */
  4301. const setFsWatchListener = (path, fullPath, options, handlers) => {
  4302. const {listener, errHandler, rawEmitter} = handlers;
  4303. let cont = FsWatchInstances.get(fullPath);
  4304. /** @type {fs.FSWatcher=} */
  4305. let watcher;
  4306. if (!options.persistent) {
  4307. watcher = createFsWatchInstance(
  4308. path, options, listener, errHandler, rawEmitter
  4309. );
  4310. return watcher.close.bind(watcher);
  4311. }
  4312. if (cont) {
  4313. addAndConvert(cont, KEY_LISTENERS, listener);
  4314. addAndConvert(cont, KEY_ERR, errHandler);
  4315. addAndConvert(cont, KEY_RAW, rawEmitter);
  4316. } else {
  4317. watcher = createFsWatchInstance(
  4318. path,
  4319. options,
  4320. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  4321. errHandler, // no need to use broadcast here
  4322. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  4323. );
  4324. if (!watcher) return;
  4325. watcher.on(EV_ERROR, async (error) => {
  4326. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  4327. cont.watcherUnusable = true; // documented since Node 10.4.1
  4328. // Workaround for https://github.com/joyent/node/issues/4337
  4329. if (isWindows && error.code === 'EPERM') {
  4330. try {
  4331. const fd = await open(path, 'r');
  4332. await close(fd);
  4333. broadcastErr(error);
  4334. } catch (err) {}
  4335. } else {
  4336. broadcastErr(error);
  4337. }
  4338. });
  4339. cont = {
  4340. listeners: listener,
  4341. errHandlers: errHandler,
  4342. rawEmitters: rawEmitter,
  4343. watcher
  4344. };
  4345. FsWatchInstances.set(fullPath, cont);
  4346. }
  4347. // const index = cont.listeners.indexOf(listener);
  4348. // removes this instance's listeners and closes the underlying fs_watch
  4349. // instance if there are no more listeners left
  4350. return () => {
  4351. delFromSet(cont, KEY_LISTENERS, listener);
  4352. delFromSet(cont, KEY_ERR, errHandler);
  4353. delFromSet(cont, KEY_RAW, rawEmitter);
  4354. if (isEmptySet(cont.listeners)) {
  4355. // Check to protect against issue gh-730.
  4356. // if (cont.watcherUnusable) {
  4357. cont.watcher.close();
  4358. // }
  4359. FsWatchInstances.delete(fullPath);
  4360. HANDLER_KEYS.forEach(clearItem(cont));
  4361. cont.watcher = undefined;
  4362. Object.freeze(cont);
  4363. }
  4364. };
  4365. };
  4366. // fs_watchFile helpers
  4367. // object to hold per-process fs_watchFile instances
  4368. // (may be shared across chokidar FSWatcher instances)
  4369. const FsWatchFileInstances = new Map();
  4370. /**
  4371. * Instantiates the fs_watchFile interface or binds listeners
  4372. * to an existing one covering the same file system entry
  4373. * @param {String} path to be watched
  4374. * @param {String} fullPath absolute path
  4375. * @param {Object} options options to be passed to fs_watchFile
  4376. * @param {Object} handlers container for event listener functions
  4377. * @returns {Function} closer
  4378. */
  4379. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  4380. const {listener, rawEmitter} = handlers;
  4381. let cont = FsWatchFileInstances.get(fullPath);
  4382. const copts = cont && cont.options;
  4383. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  4384. fs.unwatchFile(fullPath);
  4385. cont = undefined;
  4386. }
  4387. /* eslint-enable no-unused-vars, prefer-destructuring */
  4388. if (cont) {
  4389. addAndConvert(cont, KEY_LISTENERS, listener);
  4390. addAndConvert(cont, KEY_RAW, rawEmitter);
  4391. } else {
  4392. // TODO
  4393. // listeners.add(listener);
  4394. // rawEmitters.add(rawEmitter);
  4395. cont = {
  4396. listeners: listener,
  4397. rawEmitters: rawEmitter,
  4398. options,
  4399. watcher: fs.watchFile(fullPath, options, (curr, prev) => {
  4400. foreach(cont.rawEmitters, (rawEmitter) => {
  4401. rawEmitter(EV_CHANGE, fullPath, {curr, prev});
  4402. });
  4403. const currmtime = curr.mtimeMs;
  4404. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  4405. foreach(cont.listeners, (listener) => listener(path, curr));
  4406. }
  4407. })
  4408. };
  4409. FsWatchFileInstances.set(fullPath, cont);
  4410. }
  4411. // const index = cont.listeners.indexOf(listener);
  4412. // Removes this instance's listeners and closes the underlying fs_watchFile
  4413. // instance if there are no more listeners left.
  4414. return () => {
  4415. delFromSet(cont, KEY_LISTENERS, listener);
  4416. delFromSet(cont, KEY_RAW, rawEmitter);
  4417. if (isEmptySet(cont.listeners)) {
  4418. FsWatchFileInstances.delete(fullPath);
  4419. fs.unwatchFile(fullPath);
  4420. cont.options = cont.watcher = undefined;
  4421. Object.freeze(cont);
  4422. }
  4423. };
  4424. };
  4425. /**
  4426. * @mixin
  4427. */
  4428. class NodeFsHandler {
  4429. /**
  4430. * @param {import("../index").FSWatcher} fsW
  4431. */
  4432. constructor(fsW) {
  4433. this.fsw = fsW;
  4434. this._boundHandleError = (error) => fsW._handleError(error);
  4435. }
  4436. /**
  4437. * Watch file for changes with fs_watchFile or fs_watch.
  4438. * @param {String} path to file or dir
  4439. * @param {Function} listener on fs change
  4440. * @returns {Function} closer for the watcher instance
  4441. */
  4442. _watchWithNodeFs(path, listener) {
  4443. const opts = this.fsw.options;
  4444. const directory = sysPath.dirname(path);
  4445. const basename = sysPath.basename(path);
  4446. const parent = this.fsw._getWatchedDir(directory);
  4447. parent.add(basename);
  4448. const absolutePath = sysPath.resolve(path);
  4449. const options = {persistent: opts.persistent};
  4450. if (!listener) listener = EMPTY_FN;
  4451. let closer;
  4452. if (opts.usePolling) {
  4453. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  4454. opts.binaryInterval : opts.interval;
  4455. closer = setFsWatchFileListener(path, absolutePath, options, {
  4456. listener,
  4457. rawEmitter: this.fsw._emitRaw
  4458. });
  4459. } else {
  4460. closer = setFsWatchListener(path, absolutePath, options, {
  4461. listener,
  4462. errHandler: this._boundHandleError,
  4463. rawEmitter: this.fsw._emitRaw
  4464. });
  4465. }
  4466. return closer;
  4467. }
  4468. /**
  4469. * Watch a file and emit add event if warranted.
  4470. * @param {Path} file Path
  4471. * @param {fs.Stats} stats result of fs_stat
  4472. * @param {Boolean} initialAdd was the file added at watch instantiation?
  4473. * @returns {Function} closer for the watcher instance
  4474. */
  4475. _handleFile(file, stats, initialAdd) {
  4476. if (this.fsw.closed) {
  4477. return;
  4478. }
  4479. const dirname = sysPath.dirname(file);
  4480. const basename = sysPath.basename(file);
  4481. const parent = this.fsw._getWatchedDir(dirname);
  4482. // stats is always present
  4483. let prevStats = stats;
  4484. // if the file is already being watched, do nothing
  4485. if (parent.has(basename)) return;
  4486. const listener = async (path, newStats) => {
  4487. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  4488. if (!newStats || newStats.mtimeMs === 0) {
  4489. try {
  4490. const newStats = await stat$1(file);
  4491. if (this.fsw.closed) return;
  4492. // Check that change event was not fired because of changed only accessTime.
  4493. const at = newStats.atimeMs;
  4494. const mt = newStats.mtimeMs;
  4495. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  4496. this.fsw._emit(EV_CHANGE, file, newStats);
  4497. }
  4498. if (isLinux && prevStats.ino !== newStats.ino) {
  4499. this.fsw._closeFile(path);
  4500. prevStats = newStats;
  4501. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  4502. } else {
  4503. prevStats = newStats;
  4504. }
  4505. } catch (error) {
  4506. // Fix issues where mtime is null but file is still present
  4507. this.fsw._remove(dirname, basename);
  4508. }
  4509. // add is about to be emitted if file not already tracked in parent
  4510. } else if (parent.has(basename)) {
  4511. // Check that change event was not fired because of changed only accessTime.
  4512. const at = newStats.atimeMs;
  4513. const mt = newStats.mtimeMs;
  4514. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  4515. this.fsw._emit(EV_CHANGE, file, newStats);
  4516. }
  4517. prevStats = newStats;
  4518. }
  4519. };
  4520. // kick off the watcher
  4521. const closer = this._watchWithNodeFs(file, listener);
  4522. // emit an add event if we're supposed to
  4523. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  4524. if (!this.fsw._throttle(EV_ADD, file, 0)) return;
  4525. this.fsw._emit(EV_ADD, file, stats);
  4526. }
  4527. return closer;
  4528. }
  4529. /**
  4530. * Handle symlinks encountered while reading a dir.
  4531. * @param {Object} entry returned by readdirp
  4532. * @param {String} directory path of dir being read
  4533. * @param {String} path of this item
  4534. * @param {String} item basename of this item
  4535. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  4536. */
  4537. async _handleSymlink(entry, directory, path, item) {
  4538. if (this.fsw.closed) {
  4539. return;
  4540. }
  4541. const full = entry.fullPath;
  4542. const dir = this.fsw._getWatchedDir(directory);
  4543. if (!this.fsw.options.followSymlinks) {
  4544. // watch symlink directly (don't follow) and detect changes
  4545. this.fsw._incrReadyCount();
  4546. const linkPath = await fsrealpath(path);
  4547. if (this.fsw.closed) return;
  4548. if (dir.has(item)) {
  4549. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  4550. this.fsw._symlinkPaths.set(full, linkPath);
  4551. this.fsw._emit(EV_CHANGE, path, entry.stats);
  4552. }
  4553. } else {
  4554. dir.add(item);
  4555. this.fsw._symlinkPaths.set(full, linkPath);
  4556. this.fsw._emit(EV_ADD, path, entry.stats);
  4557. }
  4558. this.fsw._emitReady();
  4559. return true;
  4560. }
  4561. // don't follow the same symlink more than once
  4562. if (this.fsw._symlinkPaths.has(full)) {
  4563. return true;
  4564. }
  4565. this.fsw._symlinkPaths.set(full, true);
  4566. }
  4567. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  4568. // Normalize the directory name on Windows
  4569. directory = sysPath.join(directory, EMPTY_STR);
  4570. if (!wh.hasGlob) {
  4571. throttler = this.fsw._throttle('readdir', directory, 1000);
  4572. if (!throttler) return;
  4573. }
  4574. const previous = this.fsw._getWatchedDir(wh.path);
  4575. const current = new Set();
  4576. let stream = this.fsw._readdirp(directory, {
  4577. fileFilter: entry => wh.filterPath(entry),
  4578. directoryFilter: entry => wh.filterDir(entry),
  4579. depth: 0
  4580. }).on(STR_DATA, async (entry) => {
  4581. if (this.fsw.closed) {
  4582. stream = undefined;
  4583. return;
  4584. }
  4585. const item = entry.path;
  4586. let path = sysPath.join(directory, item);
  4587. current.add(item);
  4588. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  4589. return;
  4590. }
  4591. if (this.fsw.closed) {
  4592. stream = undefined;
  4593. return;
  4594. }
  4595. // Files that present in current directory snapshot
  4596. // but absent in previous are added to watch list and
  4597. // emit `add` event.
  4598. if (item === target || !target && !previous.has(item)) {
  4599. this.fsw._incrReadyCount();
  4600. // ensure relativeness of path is preserved in case of watcher reuse
  4601. path = sysPath.join(dir, sysPath.relative(dir, path));
  4602. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  4603. }
  4604. }).on(EV_ERROR, this._boundHandleError);
  4605. return new Promise(resolve =>
  4606. stream.once(STR_END, () => {
  4607. if (this.fsw.closed) {
  4608. stream = undefined;
  4609. return;
  4610. }
  4611. const wasThrottled = throttler ? throttler.clear() : false;
  4612. resolve();
  4613. // Files that absent in current directory snapshot
  4614. // but present in previous emit `remove` event
  4615. // and are removed from @watched[directory].
  4616. previous.getChildren().filter((item) => {
  4617. return item !== directory &&
  4618. !current.has(item) &&
  4619. // in case of intersecting globs;
  4620. // a path may have been filtered out of this readdir, but
  4621. // shouldn't be removed because it matches a different glob
  4622. (!wh.hasGlob || wh.filterPath({
  4623. fullPath: sysPath.resolve(directory, item)
  4624. }));
  4625. }).forEach((item) => {
  4626. this.fsw._remove(directory, item);
  4627. });
  4628. stream = undefined;
  4629. // one more time for any missed in case changes came in extremely quickly
  4630. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  4631. })
  4632. );
  4633. }
  4634. /**
  4635. * Read directory to add / remove files from `@watched` list and re-read it on change.
  4636. * @param {String} dir fs path
  4637. * @param {fs.Stats} stats
  4638. * @param {Boolean} initialAdd
  4639. * @param {Number} depth relative to user-supplied path
  4640. * @param {String} target child path targeted for watch
  4641. * @param {Object} wh Common watch helpers for this path
  4642. * @param {String} realpath
  4643. * @returns {Promise<Function>} closer for the watcher instance.
  4644. */
  4645. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  4646. const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
  4647. const tracked = parentDir.has(sysPath.basename(dir));
  4648. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  4649. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
  4650. }
  4651. // ensure dir is tracked (harmless if redundant)
  4652. parentDir.add(sysPath.basename(dir));
  4653. this.fsw._getWatchedDir(dir);
  4654. let throttler;
  4655. let closer;
  4656. const oDepth = this.fsw.options.depth;
  4657. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  4658. if (!target) {
  4659. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  4660. if (this.fsw.closed) return;
  4661. }
  4662. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  4663. // if current directory is removed, do nothing
  4664. if (stats && stats.mtimeMs === 0) return;
  4665. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  4666. });
  4667. }
  4668. return closer;
  4669. }
  4670. /**
  4671. * Handle added file, directory, or glob pattern.
  4672. * Delegates call to _handleFile / _handleDir after checks.
  4673. * @param {String} path to file or ir
  4674. * @param {Boolean} initialAdd was the file added at watch instantiation?
  4675. * @param {Object} priorWh depth relative to user-supplied path
  4676. * @param {Number} depth Child path actually targeted for watch
  4677. * @param {String=} target Child path actually targeted for watch
  4678. * @returns {Promise}
  4679. */
  4680. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  4681. const ready = this.fsw._emitReady;
  4682. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  4683. ready();
  4684. return false;
  4685. }
  4686. const wh = this.fsw._getWatchHelpers(path, depth);
  4687. if (!wh.hasGlob && priorWh) {
  4688. wh.hasGlob = priorWh.hasGlob;
  4689. wh.globFilter = priorWh.globFilter;
  4690. wh.filterPath = entry => priorWh.filterPath(entry);
  4691. wh.filterDir = entry => priorWh.filterDir(entry);
  4692. }
  4693. // evaluate what is at the path we're being asked to watch
  4694. try {
  4695. const stats = await statMethods[wh.statMethod](wh.watchPath);
  4696. if (this.fsw.closed) return;
  4697. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  4698. ready();
  4699. return false;
  4700. }
  4701. const follow = this.fsw.options.followSymlinks && !path.includes(STAR$1) && !path.includes(BRACE_START);
  4702. let closer;
  4703. if (stats.isDirectory()) {
  4704. const targetPath = follow ? await fsrealpath(path) : path;
  4705. if (this.fsw.closed) return;
  4706. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  4707. if (this.fsw.closed) return;
  4708. // preserve this symlink's target path
  4709. if (path !== targetPath && targetPath !== undefined) {
  4710. this.fsw._symlinkPaths.set(targetPath, true);
  4711. }
  4712. } else if (stats.isSymbolicLink()) {
  4713. const targetPath = follow ? await fsrealpath(path) : path;
  4714. if (this.fsw.closed) return;
  4715. const parent = sysPath.dirname(wh.watchPath);
  4716. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  4717. this.fsw._emit(EV_ADD, wh.watchPath, stats);
  4718. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  4719. if (this.fsw.closed) return;
  4720. // preserve this symlink's target path
  4721. if (targetPath !== undefined) {
  4722. this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
  4723. }
  4724. } else {
  4725. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  4726. }
  4727. ready();
  4728. this.fsw._addPathCloser(path, closer);
  4729. return false;
  4730. } catch (error) {
  4731. if (this.fsw._handleError(error)) {
  4732. ready();
  4733. return path;
  4734. }
  4735. }
  4736. }
  4737. }
  4738. var nodefsHandler = NodeFsHandler;
  4739. var require$$1 = /*@__PURE__*/getAugmentedNamespace(fseventsImporter);
  4740. const { promisify: promisify$2 } = util;
  4741. let fsevents;
  4742. try {
  4743. fsevents = require$$1.getFsEvents();
  4744. } catch (error) {
  4745. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  4746. }
  4747. if (fsevents) {
  4748. // TODO: real check
  4749. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  4750. if (mtch && mtch[1] && mtch[2]) {
  4751. const maj = Number.parseInt(mtch[1], 10);
  4752. const min = Number.parseInt(mtch[2], 10);
  4753. if (maj === 8 && min < 16) {
  4754. fsevents = undefined;
  4755. }
  4756. }
  4757. }
  4758. const {
  4759. EV_ADD: EV_ADD$1,
  4760. EV_CHANGE: EV_CHANGE$1,
  4761. EV_ADD_DIR: EV_ADD_DIR$1,
  4762. EV_UNLINK,
  4763. EV_ERROR: EV_ERROR$1,
  4764. STR_DATA: STR_DATA$1,
  4765. STR_END: STR_END$1,
  4766. FSEVENT_CREATED,
  4767. FSEVENT_MODIFIED,
  4768. FSEVENT_DELETED,
  4769. FSEVENT_MOVED,
  4770. // FSEVENT_CLONED,
  4771. FSEVENT_UNKNOWN,
  4772. FSEVENT_TYPE_FILE,
  4773. FSEVENT_TYPE_DIRECTORY,
  4774. FSEVENT_TYPE_SYMLINK,
  4775. ROOT_GLOBSTAR,
  4776. DIR_SUFFIX,
  4777. DOT_SLASH,
  4778. FUNCTION_TYPE,
  4779. EMPTY_FN: EMPTY_FN$1,
  4780. IDENTITY_FN
  4781. } = constants$2;
  4782. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  4783. const stat$2 = promisify$2(fs.stat);
  4784. const lstat$2 = promisify$2(fs.lstat);
  4785. const realpath$1 = promisify$2(fs.realpath);
  4786. const statMethods$1 = { stat: stat$2, lstat: lstat$2 };
  4787. /**
  4788. * @typedef {String} Path
  4789. */
  4790. /**
  4791. * @typedef {Object} FsEventsWatchContainer
  4792. * @property {Set<Function>} listeners
  4793. * @property {Function} rawEmitter
  4794. * @property {{stop: Function}} watcher
  4795. */
  4796. // fsevents instance helper functions
  4797. /**
  4798. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  4799. * @type {Map<Path,FsEventsWatchContainer>}
  4800. */
  4801. const FSEventsWatchers = new Map();
  4802. // Threshold of duplicate path prefixes at which to start
  4803. // consolidating going forward
  4804. const consolidateThreshhold = 10;
  4805. const wrongEventFlags = new Set([
  4806. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  4807. ]);
  4808. /**
  4809. * Instantiates the fsevents interface
  4810. * @param {Path} path path to be watched
  4811. * @param {Function} callback called when fsevents is bound and ready
  4812. * @returns {{stop: Function}} new fsevents instance
  4813. */
  4814. const createFSEventsInstance = (path, callback) => {
  4815. const stop = fsevents.watch(path, callback);
  4816. return {stop};
  4817. };
  4818. /**
  4819. * Instantiates the fsevents interface or binds listeners to an existing one covering
  4820. * the same file tree.
  4821. * @param {Path} path - to be watched
  4822. * @param {Path} realPath - real path for symlinks
  4823. * @param {Function} listener - called when fsevents emits events
  4824. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  4825. * @returns {Function} closer
  4826. */
  4827. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  4828. let watchPath = sysPath.extname(path) ? sysPath.dirname(path) : path;
  4829. const parentPath = sysPath.dirname(watchPath);
  4830. let cont = FSEventsWatchers.get(watchPath);
  4831. // If we've accumulated a substantial number of paths that
  4832. // could have been consolidated by watching one directory
  4833. // above the current one, create a watcher on the parent
  4834. // path instead, so that we do consolidate going forward.
  4835. if (couldConsolidate(parentPath)) {
  4836. watchPath = parentPath;
  4837. }
  4838. const resolvedPath = sysPath.resolve(path);
  4839. const hasSymlink = resolvedPath !== realPath;
  4840. const filteredListener = (fullPath, flags, info) => {
  4841. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  4842. if (
  4843. fullPath === resolvedPath ||
  4844. !fullPath.indexOf(resolvedPath + sysPath.sep)
  4845. ) listener(fullPath, flags, info);
  4846. };
  4847. // check if there is already a watcher on a parent path
  4848. // modifies `watchPath` to the parent path when it finds a match
  4849. let watchedParent = false;
  4850. for (const watchedPath of FSEventsWatchers.keys()) {
  4851. if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) {
  4852. watchPath = watchedPath;
  4853. cont = FSEventsWatchers.get(watchPath);
  4854. watchedParent = true;
  4855. break;
  4856. }
  4857. }
  4858. if (cont || watchedParent) {
  4859. cont.listeners.add(filteredListener);
  4860. } else {
  4861. cont = {
  4862. listeners: new Set([filteredListener]),
  4863. rawEmitter,
  4864. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  4865. if (!cont.listeners.size) return;
  4866. const info = fsevents.getInfo(fullPath, flags);
  4867. cont.listeners.forEach(list => {
  4868. list(fullPath, flags, info);
  4869. });
  4870. cont.rawEmitter(info.event, fullPath, info);
  4871. })
  4872. };
  4873. FSEventsWatchers.set(watchPath, cont);
  4874. }
  4875. // removes this instance's listeners and closes the underlying fsevents
  4876. // instance if there are no more listeners left
  4877. return () => {
  4878. const lst = cont.listeners;
  4879. lst.delete(filteredListener);
  4880. if (!lst.size) {
  4881. FSEventsWatchers.delete(watchPath);
  4882. if (cont.watcher) return cont.watcher.stop().then(() => {
  4883. cont.rawEmitter = cont.watcher = undefined;
  4884. Object.freeze(cont);
  4885. });
  4886. }
  4887. };
  4888. }
  4889. // Decide whether or not we should start a new higher-level
  4890. // parent watcher
  4891. const couldConsolidate = (path) => {
  4892. let count = 0;
  4893. for (const watchPath of FSEventsWatchers.keys()) {
  4894. if (watchPath.indexOf(path) === 0) {
  4895. count++;
  4896. if (count >= consolidateThreshhold) {
  4897. return true;
  4898. }
  4899. }
  4900. }
  4901. return false;
  4902. };
  4903. // returns boolean indicating whether fsevents can be used
  4904. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  4905. // determines subdirectory traversal levels from root to path
  4906. const calcDepth = (path, root) => {
  4907. let i = 0;
  4908. while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++;
  4909. return i;
  4910. };
  4911. // returns boolean indicating whether the fsevents' event info has the same type
  4912. // as the one returned by fs.stat
  4913. const sameTypes = (info, stats) => (
  4914. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  4915. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  4916. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  4917. );
  4918. /**
  4919. * @mixin
  4920. */
  4921. class FsEventsHandler {
  4922. /**
  4923. * @param {import('../index').FSWatcher} fsw
  4924. */
  4925. constructor(fsw) {
  4926. this.fsw = fsw;
  4927. }
  4928. checkIgnored(path, stats) {
  4929. const ipaths = this.fsw._ignoredPaths;
  4930. if (this.fsw._isIgnored(path, stats)) {
  4931. ipaths.add(path);
  4932. if (stats && stats.isDirectory()) {
  4933. ipaths.add(path + ROOT_GLOBSTAR);
  4934. }
  4935. return true;
  4936. }
  4937. ipaths.delete(path);
  4938. ipaths.delete(path + ROOT_GLOBSTAR);
  4939. }
  4940. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  4941. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  4942. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4943. }
  4944. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  4945. try {
  4946. const stats = await stat$2(path);
  4947. if (this.fsw.closed) return;
  4948. if (sameTypes(info, stats)) {
  4949. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4950. } else {
  4951. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4952. }
  4953. } catch (error) {
  4954. if (error.code === 'EACCES') {
  4955. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4956. } else {
  4957. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4958. }
  4959. }
  4960. }
  4961. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  4962. if (this.fsw.closed || this.checkIgnored(path)) return;
  4963. if (event === EV_UNLINK) {
  4964. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  4965. // suppress unlink events on never before seen files
  4966. if (isDirectory || watchedDir.has(item)) {
  4967. this.fsw._remove(parent, item, isDirectory);
  4968. }
  4969. } else {
  4970. if (event === EV_ADD$1) {
  4971. // track new directories
  4972. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  4973. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  4974. // push symlinks back to the top of the stack to get handled
  4975. const curDepth = opts.depth === undefined ?
  4976. undefined : calcDepth(fullPath, realPath) + 1;
  4977. return this._addToFsEvents(path, false, true, curDepth);
  4978. }
  4979. // track new paths
  4980. // (other than symlinks being followed, which will be tracked soon)
  4981. this.fsw._getWatchedDir(parent).add(item);
  4982. }
  4983. /**
  4984. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  4985. */
  4986. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  4987. this.fsw._emit(eventName, path);
  4988. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  4989. }
  4990. }
  4991. /**
  4992. * Handle symlinks encountered during directory scan
  4993. * @param {String} watchPath - file/dir path to be watched with fsevents
  4994. * @param {String} realPath - real path (in case of symlinks)
  4995. * @param {Function} transform - path transformer
  4996. * @param {Function} globFilter - path filter in case a glob pattern was provided
  4997. * @returns {Function} closer for the watcher instance
  4998. */
  4999. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  5000. if (this.fsw.closed) return;
  5001. if (this.fsw._isIgnored(watchPath)) return;
  5002. const opts = this.fsw.options;
  5003. const watchCallback = async (fullPath, flags, info) => {
  5004. if (this.fsw.closed) return;
  5005. if (
  5006. opts.depth !== undefined &&
  5007. calcDepth(fullPath, realPath) > opts.depth
  5008. ) return;
  5009. const path = transform(sysPath.join(
  5010. watchPath, sysPath.relative(watchPath, fullPath)
  5011. ));
  5012. if (globFilter && !globFilter(path)) return;
  5013. // ensure directories are tracked
  5014. const parent = sysPath.dirname(path);
  5015. const item = sysPath.basename(path);
  5016. const watchedDir = this.fsw._getWatchedDir(
  5017. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  5018. );
  5019. // correct for wrong events emitted
  5020. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  5021. if (typeof opts.ignored === FUNCTION_TYPE) {
  5022. let stats;
  5023. try {
  5024. stats = await stat$2(path);
  5025. } catch (error) {}
  5026. if (this.fsw.closed) return;
  5027. if (this.checkIgnored(path, stats)) return;
  5028. if (sameTypes(info, stats)) {
  5029. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5030. } else {
  5031. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5032. }
  5033. } else {
  5034. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5035. }
  5036. } else {
  5037. switch (info.event) {
  5038. case FSEVENT_CREATED:
  5039. case FSEVENT_MODIFIED:
  5040. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5041. case FSEVENT_DELETED:
  5042. case FSEVENT_MOVED:
  5043. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5044. }
  5045. }
  5046. };
  5047. const closer = setFSEventsListener(
  5048. watchPath,
  5049. realPath,
  5050. watchCallback,
  5051. this.fsw._emitRaw
  5052. );
  5053. this.fsw._emitReady();
  5054. return closer;
  5055. }
  5056. /**
  5057. * Handle symlinks encountered during directory scan
  5058. * @param {String} linkPath path to symlink
  5059. * @param {String} fullPath absolute path to the symlink
  5060. * @param {Function} transform pre-existing path transformer
  5061. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  5062. * @returns {Promise<void>}
  5063. */
  5064. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  5065. // don't follow the same symlink more than once
  5066. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  5067. this.fsw._symlinkPaths.set(fullPath, true);
  5068. this.fsw._incrReadyCount();
  5069. try {
  5070. const linkTarget = await realpath$1(linkPath);
  5071. if (this.fsw.closed) return;
  5072. if (this.fsw._isIgnored(linkTarget)) {
  5073. return this.fsw._emitReady();
  5074. }
  5075. this.fsw._incrReadyCount();
  5076. // add the linkTarget for watching with a wrapper for transform
  5077. // that causes emitted paths to incorporate the link's path
  5078. this._addToFsEvents(linkTarget || linkPath, (path) => {
  5079. let aliasedPath = linkPath;
  5080. if (linkTarget && linkTarget !== DOT_SLASH) {
  5081. aliasedPath = path.replace(linkTarget, linkPath);
  5082. } else if (path !== DOT_SLASH) {
  5083. aliasedPath = sysPath.join(linkPath, path);
  5084. }
  5085. return transform(aliasedPath);
  5086. }, false, curDepth);
  5087. } catch(error) {
  5088. if (this.fsw._handleError(error)) {
  5089. return this.fsw._emitReady();
  5090. }
  5091. }
  5092. }
  5093. /**
  5094. *
  5095. * @param {Path} newPath
  5096. * @param {fs.Stats} stats
  5097. */
  5098. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  5099. const pp = processPath(newPath);
  5100. const isDir = stats.isDirectory();
  5101. const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp));
  5102. const base = sysPath.basename(pp);
  5103. // ensure empty dirs get tracked
  5104. if (isDir) this.fsw._getWatchedDir(pp);
  5105. if (dirObj.has(base)) return;
  5106. dirObj.add(base);
  5107. if (!opts.ignoreInitial || forceAdd === true) {
  5108. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  5109. }
  5110. }
  5111. initWatch(realPath, path, wh, processPath) {
  5112. if (this.fsw.closed) return;
  5113. const closer = this._watchWithFsEvents(
  5114. wh.watchPath,
  5115. sysPath.resolve(realPath || wh.watchPath),
  5116. processPath,
  5117. wh.globFilter
  5118. );
  5119. this.fsw._addPathCloser(path, closer);
  5120. }
  5121. /**
  5122. * Handle added path with fsevents
  5123. * @param {String} path file/dir path or glob pattern
  5124. * @param {Function|Boolean=} transform converts working path to what the user expects
  5125. * @param {Boolean=} forceAdd ensure add is emitted
  5126. * @param {Number=} priorDepth Level of subdirectories already traversed.
  5127. * @returns {Promise<void>}
  5128. */
  5129. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  5130. if (this.fsw.closed) {
  5131. return;
  5132. }
  5133. const opts = this.fsw.options;
  5134. const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN;
  5135. const wh = this.fsw._getWatchHelpers(path);
  5136. // evaluate what is at the path we're being asked to watch
  5137. try {
  5138. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  5139. if (this.fsw.closed) return;
  5140. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  5141. throw null;
  5142. }
  5143. if (stats.isDirectory()) {
  5144. // emit addDir unless this is a glob parent
  5145. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  5146. // don't recurse further if it would exceed depth setting
  5147. if (priorDepth && priorDepth > opts.depth) return;
  5148. // scan the contents of the dir
  5149. this.fsw._readdirp(wh.watchPath, {
  5150. fileFilter: entry => wh.filterPath(entry),
  5151. directoryFilter: entry => wh.filterDir(entry),
  5152. ...Depth(opts.depth - (priorDepth || 0))
  5153. }).on(STR_DATA$1, (entry) => {
  5154. // need to check filterPath on dirs b/c filterDir is less restrictive
  5155. if (this.fsw.closed) {
  5156. return;
  5157. }
  5158. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  5159. const joinedPath = sysPath.join(wh.watchPath, entry.path);
  5160. const {fullPath} = entry;
  5161. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  5162. // preserve the current depth here since it can't be derived from
  5163. // real paths past the symlink
  5164. const curDepth = opts.depth === undefined ?
  5165. undefined : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1;
  5166. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  5167. } else {
  5168. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  5169. }
  5170. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  5171. this.fsw._emitReady();
  5172. });
  5173. } else {
  5174. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  5175. this.fsw._emitReady();
  5176. }
  5177. } catch (error) {
  5178. if (!error || this.fsw._handleError(error)) {
  5179. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  5180. this.fsw._emitReady();
  5181. this.fsw._emitReady();
  5182. }
  5183. }
  5184. if (opts.persistent && forceAdd !== true) {
  5185. if (typeof transform === FUNCTION_TYPE) {
  5186. // realpath has already been resolved
  5187. this.initWatch(undefined, path, wh, processPath);
  5188. } else {
  5189. let realPath;
  5190. try {
  5191. realPath = await realpath$1(wh.watchPath);
  5192. } catch (e) {}
  5193. this.initWatch(realPath, path, wh, processPath);
  5194. }
  5195. }
  5196. }
  5197. }
  5198. var fseventsHandler = FsEventsHandler;
  5199. var canUse_1 = canUse;
  5200. fseventsHandler.canUse = canUse_1;
  5201. const { EventEmitter } = require$$0$2;
  5202. const { promisify: promisify$3 } = util;
  5203. const anymatch = anymatch_1.default;
  5204. const {
  5205. EV_ALL,
  5206. EV_READY,
  5207. EV_ADD: EV_ADD$2,
  5208. EV_CHANGE: EV_CHANGE$2,
  5209. EV_UNLINK: EV_UNLINK$1,
  5210. EV_ADD_DIR: EV_ADD_DIR$2,
  5211. EV_UNLINK_DIR,
  5212. EV_RAW,
  5213. EV_ERROR: EV_ERROR$2,
  5214. STR_CLOSE,
  5215. STR_END: STR_END$2,
  5216. BACK_SLASH_RE,
  5217. DOUBLE_SLASH_RE,
  5218. SLASH_OR_BACK_SLASH_RE,
  5219. DOT_RE,
  5220. REPLACER_RE,
  5221. SLASH,
  5222. SLASH_SLASH,
  5223. BRACE_START: BRACE_START$1,
  5224. BANG: BANG$1,
  5225. ONE_DOT,
  5226. TWO_DOTS,
  5227. GLOBSTAR,
  5228. SLASH_GLOBSTAR,
  5229. ANYMATCH_OPTS,
  5230. STRING_TYPE,
  5231. FUNCTION_TYPE: FUNCTION_TYPE$1,
  5232. EMPTY_STR: EMPTY_STR$1,
  5233. EMPTY_FN: EMPTY_FN$2,
  5234. isWindows: isWindows$1,
  5235. isMacos
  5236. } = constants$2;
  5237. const stat$3 = promisify$3(fs.stat);
  5238. const readdir$1 = promisify$3(fs.readdir);
  5239. /**
  5240. * @typedef {String} Path
  5241. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  5242. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  5243. */
  5244. /**
  5245. *
  5246. * @typedef {Object} WatchHelpers
  5247. * @property {Boolean} followSymlinks
  5248. * @property {'stat'|'lstat'} statMethod
  5249. * @property {Path} path
  5250. * @property {Path} watchPath
  5251. * @property {Function} entryPath
  5252. * @property {Boolean} hasGlob
  5253. * @property {Object} globFilter
  5254. * @property {Function} filterPath
  5255. * @property {Function} filterDir
  5256. */
  5257. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  5258. const flatten = (list, result = []) => {
  5259. list.forEach(item => {
  5260. if (Array.isArray(item)) {
  5261. flatten(item, result);
  5262. } else {
  5263. result.push(item);
  5264. }
  5265. });
  5266. return result;
  5267. };
  5268. const unifyPaths = (paths_) => {
  5269. /**
  5270. * @type {Array<String>}
  5271. */
  5272. const paths = flatten(arrify(paths_));
  5273. if (!paths.every(p => typeof p === STRING_TYPE)) {
  5274. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  5275. }
  5276. return paths.map(normalizePathToUnix);
  5277. };
  5278. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  5279. // because "//StoragePC/DrivePool/Movies" is a valid network path
  5280. const toUnix = (string) => {
  5281. let str = string.replace(BACK_SLASH_RE, SLASH);
  5282. let prepend = false;
  5283. if (str.startsWith(SLASH_SLASH)) {
  5284. prepend = true;
  5285. }
  5286. while (str.match(DOUBLE_SLASH_RE)) {
  5287. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  5288. }
  5289. if (prepend) {
  5290. str = SLASH + str;
  5291. }
  5292. return str;
  5293. };
  5294. // Our version of upath.normalize
  5295. // TODO: this is not equal to path-normalize module - investigate why
  5296. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  5297. const normalizeIgnored = (cwd = EMPTY_STR$1) => (path) => {
  5298. if (typeof path !== STRING_TYPE) return path;
  5299. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  5300. };
  5301. const getAbsolutePath = (path, cwd) => {
  5302. if (sysPath.isAbsolute(path)) {
  5303. return path;
  5304. }
  5305. if (path.startsWith(BANG$1)) {
  5306. return BANG$1 + sysPath.join(cwd, path.slice(1));
  5307. }
  5308. return sysPath.join(cwd, path);
  5309. };
  5310. const undef = (opts, key) => opts[key] === undefined;
  5311. /**
  5312. * Directory entry.
  5313. * @property {Path} path
  5314. * @property {Set<Path>} items
  5315. */
  5316. class DirEntry {
  5317. /**
  5318. * @param {Path} dir
  5319. * @param {Function} removeWatcher
  5320. */
  5321. constructor(dir, removeWatcher) {
  5322. this.path = dir;
  5323. this._removeWatcher = removeWatcher;
  5324. /** @type {Set<Path>} */
  5325. this.items = new Set();
  5326. }
  5327. add(item) {
  5328. const {items} = this;
  5329. if (!items) return;
  5330. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  5331. }
  5332. async remove(item) {
  5333. const {items} = this;
  5334. if (!items) return;
  5335. items.delete(item);
  5336. if (items.size > 0) return;
  5337. const dir = this.path;
  5338. try {
  5339. await readdir$1(dir);
  5340. } catch (err) {
  5341. if (this._removeWatcher) {
  5342. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  5343. }
  5344. }
  5345. }
  5346. has(item) {
  5347. const {items} = this;
  5348. if (!items) return;
  5349. return items.has(item);
  5350. }
  5351. /**
  5352. * @returns {Array<String>}
  5353. */
  5354. getChildren() {
  5355. const {items} = this;
  5356. if (!items) return;
  5357. return [...items.values()];
  5358. }
  5359. dispose() {
  5360. this.items.clear();
  5361. delete this.path;
  5362. delete this._removeWatcher;
  5363. delete this.items;
  5364. Object.freeze(this);
  5365. }
  5366. }
  5367. const STAT_METHOD_F = 'stat';
  5368. const STAT_METHOD_L = 'lstat';
  5369. class WatchHelper {
  5370. constructor(path, watchPath, follow, fsw) {
  5371. this.fsw = fsw;
  5372. this.path = path = path.replace(REPLACER_RE, EMPTY_STR$1);
  5373. this.watchPath = watchPath;
  5374. this.fullWatchPath = sysPath.resolve(watchPath);
  5375. this.hasGlob = watchPath !== path;
  5376. /** @type {object|boolean} */
  5377. if (path === EMPTY_STR$1) this.hasGlob = false;
  5378. this.globSymlink = this.hasGlob && follow ? undefined : false;
  5379. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  5380. this.dirParts = this.getDirParts(path);
  5381. this.dirParts.forEach((parts) => {
  5382. if (parts.length > 1) parts.pop();
  5383. });
  5384. this.followSymlinks = follow;
  5385. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  5386. }
  5387. checkGlobSymlink(entry) {
  5388. // only need to resolve once
  5389. // first entry should always have entry.parentDir === EMPTY_STR
  5390. if (this.globSymlink === undefined) {
  5391. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  5392. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  5393. }
  5394. if (this.globSymlink) {
  5395. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  5396. }
  5397. return entry.fullPath;
  5398. }
  5399. entryPath(entry) {
  5400. return sysPath.join(this.watchPath,
  5401. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  5402. );
  5403. }
  5404. filterPath(entry) {
  5405. const {stats} = entry;
  5406. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  5407. const resolvedPath = this.entryPath(entry);
  5408. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE$1 ?
  5409. this.globFilter(resolvedPath) : true;
  5410. return matchesGlob &&
  5411. this.fsw._isntIgnored(resolvedPath, stats) &&
  5412. this.fsw._hasReadPermissions(stats);
  5413. }
  5414. getDirParts(path) {
  5415. if (!this.hasGlob) return [];
  5416. const parts = [];
  5417. const expandedPath = path.includes(BRACE_START$1) ? braces_1.expand(path) : [path];
  5418. expandedPath.forEach((path) => {
  5419. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  5420. });
  5421. return parts;
  5422. }
  5423. filterDir(entry) {
  5424. if (this.hasGlob) {
  5425. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  5426. let globstar = false;
  5427. this.unmatchedGlob = !this.dirParts.some((parts) => {
  5428. return parts.every((part, i) => {
  5429. if (part === GLOBSTAR) globstar = true;
  5430. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  5431. });
  5432. });
  5433. }
  5434. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  5435. }
  5436. }
  5437. /**
  5438. * Watches files & directories for changes. Emitted events:
  5439. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  5440. *
  5441. * new FSWatcher()
  5442. * .add(directories)
  5443. * .on('add', path => log('File', path, 'was added'))
  5444. */
  5445. class FSWatcher extends EventEmitter {
  5446. // Not indenting methods for history sake; for now.
  5447. constructor(_opts) {
  5448. super();
  5449. const opts = {};
  5450. if (_opts) Object.assign(opts, _opts); // for frozen objects
  5451. /** @type {Map<String, DirEntry>} */
  5452. this._watched = new Map();
  5453. /** @type {Map<String, Array>} */
  5454. this._closers = new Map();
  5455. /** @type {Set<String>} */
  5456. this._ignoredPaths = new Set();
  5457. /** @type {Map<ThrottleType, Map>} */
  5458. this._throttled = new Map();
  5459. /** @type {Map<Path, String|Boolean>} */
  5460. this._symlinkPaths = new Map();
  5461. this._streams = new Set();
  5462. this.closed = false;
  5463. // Set up default options.
  5464. if (undef(opts, 'persistent')) opts.persistent = true;
  5465. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  5466. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  5467. if (undef(opts, 'interval')) opts.interval = 100;
  5468. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  5469. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  5470. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  5471. // Enable fsevents on OS X when polling isn't explicitly enabled.
  5472. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  5473. // If we can't use fsevents, ensure the options reflect it's disabled.
  5474. const canUseFsEvents = fseventsHandler.canUse();
  5475. if (!canUseFsEvents) opts.useFsEvents = false;
  5476. // Use polling on Mac if not using fsevents.
  5477. // Other platforms use non-polling fs_watch.
  5478. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  5479. opts.usePolling = isMacos;
  5480. }
  5481. // Global override (useful for end-developers that need to force polling for all
  5482. // instances of chokidar, regardless of usage/dependency depth)
  5483. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  5484. if (envPoll !== undefined) {
  5485. const envLower = envPoll.toLowerCase();
  5486. if (envLower === 'false' || envLower === '0') {
  5487. opts.usePolling = false;
  5488. } else if (envLower === 'true' || envLower === '1') {
  5489. opts.usePolling = true;
  5490. } else {
  5491. opts.usePolling = !!envLower;
  5492. }
  5493. }
  5494. const envInterval = process.env.CHOKIDAR_INTERVAL;
  5495. if (envInterval) {
  5496. opts.interval = Number.parseInt(envInterval, 10);
  5497. }
  5498. // Editor atomic write normalization enabled by default with fs.watch
  5499. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  5500. if (opts.atomic) this._pendingUnlinks = new Map();
  5501. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  5502. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  5503. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  5504. const awf = opts.awaitWriteFinish;
  5505. if (awf) {
  5506. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  5507. if (!awf.pollInterval) awf.pollInterval = 100;
  5508. this._pendingWrites = new Map();
  5509. }
  5510. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  5511. let readyCalls = 0;
  5512. this._emitReady = () => {
  5513. readyCalls++;
  5514. if (readyCalls >= this._readyCount) {
  5515. this._emitReady = EMPTY_FN$2;
  5516. this._readyEmitted = true;
  5517. // use process.nextTick to allow time for listener to be bound
  5518. process.nextTick(() => this.emit(EV_READY));
  5519. }
  5520. };
  5521. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  5522. this._readyEmitted = false;
  5523. this.options = opts;
  5524. // Initialize with proper watcher.
  5525. if (opts.useFsEvents) {
  5526. this._fsEventsHandler = new fseventsHandler(this);
  5527. } else {
  5528. this._nodeFsHandler = new nodefsHandler(this);
  5529. }
  5530. // You’re frozen when your heart’s not open.
  5531. Object.freeze(opts);
  5532. }
  5533. // Public methods
  5534. /**
  5535. * Adds paths to be watched on an existing FSWatcher instance
  5536. * @param {Path|Array<Path>} paths_
  5537. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  5538. * @param {Boolean=} _internal private; indicates a non-user add
  5539. * @returns {FSWatcher} for chaining
  5540. */
  5541. add(paths_, _origAdd, _internal) {
  5542. const {cwd, disableGlobbing} = this.options;
  5543. this.closed = false;
  5544. let paths = unifyPaths(paths_);
  5545. if (cwd) {
  5546. paths = paths.map((path) => {
  5547. const absPath = getAbsolutePath(path, cwd);
  5548. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  5549. if (disableGlobbing || !isGlob(path)) {
  5550. return absPath;
  5551. }
  5552. return normalizePath(absPath);
  5553. });
  5554. }
  5555. // set aside negated glob strings
  5556. paths = paths.filter((path) => {
  5557. if (path.startsWith(BANG$1)) {
  5558. this._ignoredPaths.add(path.slice(1));
  5559. return false;
  5560. }
  5561. // if a path is being added that was previously ignored, stop ignoring it
  5562. this._ignoredPaths.delete(path);
  5563. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  5564. // reset the cached userIgnored anymatch fn
  5565. // to make ignoredPaths changes effective
  5566. this._userIgnored = undefined;
  5567. return true;
  5568. });
  5569. if (this.options.useFsEvents && this._fsEventsHandler) {
  5570. if (!this._readyCount) this._readyCount = paths.length;
  5571. if (this.options.persistent) this._readyCount *= 2;
  5572. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  5573. } else {
  5574. if (!this._readyCount) this._readyCount = 0;
  5575. this._readyCount += paths.length;
  5576. Promise.all(
  5577. paths.map(async path => {
  5578. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  5579. if (res) this._emitReady();
  5580. return res;
  5581. })
  5582. ).then(results => {
  5583. if (this.closed) return;
  5584. results.filter(item => item).forEach(item => {
  5585. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  5586. });
  5587. });
  5588. }
  5589. return this;
  5590. }
  5591. /**
  5592. * Close watchers or start ignoring events from specified paths.
  5593. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  5594. * @returns {FSWatcher} for chaining
  5595. */
  5596. unwatch(paths_) {
  5597. if (this.closed) return this;
  5598. const paths = unifyPaths(paths_);
  5599. const {cwd} = this.options;
  5600. paths.forEach((path) => {
  5601. // convert to absolute path unless relative path already matches
  5602. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  5603. if (cwd) path = sysPath.join(cwd, path);
  5604. path = sysPath.resolve(path);
  5605. }
  5606. this._closePath(path);
  5607. this._ignoredPaths.add(path);
  5608. if (this._watched.has(path)) {
  5609. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  5610. }
  5611. // reset the cached userIgnored anymatch fn
  5612. // to make ignoredPaths changes effective
  5613. this._userIgnored = undefined;
  5614. });
  5615. return this;
  5616. }
  5617. /**
  5618. * Close watchers and remove all listeners from watched paths.
  5619. * @returns {Promise<void>}.
  5620. */
  5621. close() {
  5622. if (this.closed) return this._closePromise;
  5623. this.closed = true;
  5624. // Memory management.
  5625. this.removeAllListeners();
  5626. const closers = [];
  5627. this._closers.forEach(closerList => closerList.forEach(closer => {
  5628. const promise = closer();
  5629. if (promise instanceof Promise) closers.push(promise);
  5630. }));
  5631. this._streams.forEach(stream => stream.destroy());
  5632. this._userIgnored = undefined;
  5633. this._readyCount = 0;
  5634. this._readyEmitted = false;
  5635. this._watched.forEach(dirent => dirent.dispose());
  5636. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  5637. this[`_${key}`].clear();
  5638. });
  5639. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  5640. return this._closePromise;
  5641. }
  5642. /**
  5643. * Expose list of watched paths
  5644. * @returns {Object} for chaining
  5645. */
  5646. getWatched() {
  5647. const watchList = {};
  5648. this._watched.forEach((entry, dir) => {
  5649. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  5650. watchList[key || ONE_DOT] = entry.getChildren().sort();
  5651. });
  5652. return watchList;
  5653. }
  5654. emitWithAll(event, args) {
  5655. this.emit(...args);
  5656. if (event !== EV_ERROR$2) this.emit(EV_ALL, ...args);
  5657. }
  5658. // Common helpers
  5659. // --------------
  5660. /**
  5661. * Normalize and emit events.
  5662. * Calling _emit DOES NOT MEAN emit() would be called!
  5663. * @param {EventName} event Type of event
  5664. * @param {Path} path File or directory path
  5665. * @param {*=} val1 arguments to be passed with event
  5666. * @param {*=} val2
  5667. * @param {*=} val3
  5668. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  5669. */
  5670. async _emit(event, path, val1, val2, val3) {
  5671. if (this.closed) return;
  5672. const opts = this.options;
  5673. if (isWindows$1) path = sysPath.normalize(path);
  5674. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  5675. /** @type Array<any> */
  5676. const args = [event, path];
  5677. if (val3 !== undefined) args.push(val1, val2, val3);
  5678. else if (val2 !== undefined) args.push(val1, val2);
  5679. else if (val1 !== undefined) args.push(val1);
  5680. const awf = opts.awaitWriteFinish;
  5681. let pw;
  5682. if (awf && (pw = this._pendingWrites.get(path))) {
  5683. pw.lastChange = new Date();
  5684. return this;
  5685. }
  5686. if (opts.atomic) {
  5687. if (event === EV_UNLINK$1) {
  5688. this._pendingUnlinks.set(path, args);
  5689. setTimeout(() => {
  5690. this._pendingUnlinks.forEach((entry, path) => {
  5691. this.emit(...entry);
  5692. this.emit(EV_ALL, ...entry);
  5693. this._pendingUnlinks.delete(path);
  5694. });
  5695. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  5696. return this;
  5697. }
  5698. if (event === EV_ADD$2 && this._pendingUnlinks.has(path)) {
  5699. event = args[0] = EV_CHANGE$2;
  5700. this._pendingUnlinks.delete(path);
  5701. }
  5702. }
  5703. if (awf && (event === EV_ADD$2 || event === EV_CHANGE$2) && this._readyEmitted) {
  5704. const awfEmit = (err, stats) => {
  5705. if (err) {
  5706. event = args[0] = EV_ERROR$2;
  5707. args[1] = err;
  5708. this.emitWithAll(event, args);
  5709. } else if (stats) {
  5710. // if stats doesn't exist the file must have been deleted
  5711. if (args.length > 2) {
  5712. args[2] = stats;
  5713. } else {
  5714. args.push(stats);
  5715. }
  5716. this.emitWithAll(event, args);
  5717. }
  5718. };
  5719. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  5720. return this;
  5721. }
  5722. if (event === EV_CHANGE$2) {
  5723. const isThrottled = !this._throttle(EV_CHANGE$2, path, 50);
  5724. if (isThrottled) return this;
  5725. }
  5726. if (opts.alwaysStat && val1 === undefined &&
  5727. (event === EV_ADD$2 || event === EV_ADD_DIR$2 || event === EV_CHANGE$2)
  5728. ) {
  5729. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  5730. let stats;
  5731. try {
  5732. stats = await stat$3(fullPath);
  5733. } catch (err) {}
  5734. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  5735. if (!stats || this.closed) return;
  5736. args.push(stats);
  5737. }
  5738. this.emitWithAll(event, args);
  5739. return this;
  5740. }
  5741. /**
  5742. * Common handler for errors
  5743. * @param {Error} error
  5744. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  5745. */
  5746. _handleError(error) {
  5747. const code = error && error.code;
  5748. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  5749. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  5750. ) {
  5751. this.emit(EV_ERROR$2, error);
  5752. }
  5753. return error || this.closed;
  5754. }
  5755. /**
  5756. * Helper utility for throttling
  5757. * @param {ThrottleType} actionType type being throttled
  5758. * @param {Path} path being acted upon
  5759. * @param {Number} timeout duration of time to suppress duplicate actions
  5760. * @returns {Object|false} tracking object or false if action should be suppressed
  5761. */
  5762. _throttle(actionType, path, timeout) {
  5763. if (!this._throttled.has(actionType)) {
  5764. this._throttled.set(actionType, new Map());
  5765. }
  5766. /** @type {Map<Path, Object>} */
  5767. const action = this._throttled.get(actionType);
  5768. /** @type {Object} */
  5769. const actionPath = action.get(path);
  5770. if (actionPath) {
  5771. actionPath.count++;
  5772. return false;
  5773. }
  5774. let timeoutObject;
  5775. const clear = () => {
  5776. const item = action.get(path);
  5777. const count = item ? item.count : 0;
  5778. action.delete(path);
  5779. clearTimeout(timeoutObject);
  5780. if (item) clearTimeout(item.timeoutObject);
  5781. return count;
  5782. };
  5783. timeoutObject = setTimeout(clear, timeout);
  5784. const thr = {timeoutObject, clear, count: 0};
  5785. action.set(path, thr);
  5786. return thr;
  5787. }
  5788. _incrReadyCount() {
  5789. return this._readyCount++;
  5790. }
  5791. /**
  5792. * Awaits write operation to finish.
  5793. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  5794. * @param {Path} path being acted upon
  5795. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  5796. * @param {EventName} event
  5797. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  5798. */
  5799. _awaitWriteFinish(path, threshold, event, awfEmit) {
  5800. let timeoutHandler;
  5801. let fullPath = path;
  5802. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  5803. fullPath = sysPath.join(this.options.cwd, path);
  5804. }
  5805. const now = new Date();
  5806. const awaitWriteFinish = (prevStat) => {
  5807. fs.stat(fullPath, (err, curStat) => {
  5808. if (err || !this._pendingWrites.has(path)) {
  5809. if (err && err.code !== 'ENOENT') awfEmit(err);
  5810. return;
  5811. }
  5812. const now = Number(new Date());
  5813. if (prevStat && curStat.size !== prevStat.size) {
  5814. this._pendingWrites.get(path).lastChange = now;
  5815. }
  5816. const pw = this._pendingWrites.get(path);
  5817. const df = now - pw.lastChange;
  5818. if (df >= threshold) {
  5819. this._pendingWrites.delete(path);
  5820. awfEmit(undefined, curStat);
  5821. } else {
  5822. timeoutHandler = setTimeout(
  5823. awaitWriteFinish,
  5824. this.options.awaitWriteFinish.pollInterval,
  5825. curStat
  5826. );
  5827. }
  5828. });
  5829. };
  5830. if (!this._pendingWrites.has(path)) {
  5831. this._pendingWrites.set(path, {
  5832. lastChange: now,
  5833. cancelWait: () => {
  5834. this._pendingWrites.delete(path);
  5835. clearTimeout(timeoutHandler);
  5836. return event;
  5837. }
  5838. });
  5839. timeoutHandler = setTimeout(
  5840. awaitWriteFinish,
  5841. this.options.awaitWriteFinish.pollInterval
  5842. );
  5843. }
  5844. }
  5845. _getGlobIgnored() {
  5846. return [...this._ignoredPaths.values()];
  5847. }
  5848. /**
  5849. * Determines whether user has asked to ignore this path.
  5850. * @param {Path} path filepath or dir
  5851. * @param {fs.Stats=} stats result of fs.stat
  5852. * @returns {Boolean}
  5853. */
  5854. _isIgnored(path, stats) {
  5855. if (this.options.atomic && DOT_RE.test(path)) return true;
  5856. if (!this._userIgnored) {
  5857. const {cwd} = this.options;
  5858. const ign = this.options.ignored;
  5859. const ignored = ign && ign.map(normalizeIgnored(cwd));
  5860. const paths = arrify(ignored)
  5861. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  5862. .map((path) => path + SLASH_GLOBSTAR);
  5863. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  5864. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  5865. }
  5866. return this._userIgnored([path, stats]);
  5867. }
  5868. _isntIgnored(path, stat) {
  5869. return !this._isIgnored(path, stat);
  5870. }
  5871. /**
  5872. * Provides a set of common helpers and properties relating to symlink and glob handling.
  5873. * @param {Path} path file, directory, or glob pattern being watched
  5874. * @param {Number=} depth at any depth > 0, this isn't a glob
  5875. * @returns {WatchHelper} object containing helpers for this path
  5876. */
  5877. _getWatchHelpers(path, depth) {
  5878. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  5879. const follow = this.options.followSymlinks;
  5880. return new WatchHelper(path, watchPath, follow, this);
  5881. }
  5882. // Directory helpers
  5883. // -----------------
  5884. /**
  5885. * Provides directory tracking objects
  5886. * @param {String} directory path of the directory
  5887. * @returns {DirEntry} the directory's tracking object
  5888. */
  5889. _getWatchedDir(directory) {
  5890. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  5891. const dir = sysPath.resolve(directory);
  5892. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  5893. return this._watched.get(dir);
  5894. }
  5895. // File helpers
  5896. // ------------
  5897. /**
  5898. * Check for read permissions.
  5899. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  5900. * @param {fs.Stats} stats - object, result of fs_stat
  5901. * @returns {Boolean} indicates whether the file can be read
  5902. */
  5903. _hasReadPermissions(stats) {
  5904. if (this.options.ignorePermissionErrors) return true;
  5905. // stats.mode may be bigint
  5906. const md = stats && Number.parseInt(stats.mode, 10);
  5907. const st = md & 0o777;
  5908. const it = Number.parseInt(st.toString(8)[0], 10);
  5909. return Boolean(4 & it);
  5910. }
  5911. /**
  5912. * Handles emitting unlink events for
  5913. * files and directories, and via recursion, for
  5914. * files and directories within directories that are unlinked
  5915. * @param {String} directory within which the following item is located
  5916. * @param {String} item base path of item/directory
  5917. * @returns {void}
  5918. */
  5919. _remove(directory, item, isDirectory) {
  5920. // if what is being deleted is a directory, get that directory's paths
  5921. // for recursive deleting and cleaning of watched object
  5922. // if it is not a directory, nestedDirectoryChildren will be empty array
  5923. const path = sysPath.join(directory, item);
  5924. const fullPath = sysPath.resolve(path);
  5925. isDirectory = isDirectory != null
  5926. ? isDirectory
  5927. : this._watched.has(path) || this._watched.has(fullPath);
  5928. // prevent duplicate handling in case of arriving here nearly simultaneously
  5929. // via multiple paths (such as _handleFile and _handleDir)
  5930. if (!this._throttle('remove', path, 100)) return;
  5931. // if the only watched file is removed, watch for its return
  5932. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  5933. this.add(directory, item, true);
  5934. }
  5935. // This will create a new entry in the watched object in either case
  5936. // so we got to do the directory check beforehand
  5937. const wp = this._getWatchedDir(path);
  5938. const nestedDirectoryChildren = wp.getChildren();
  5939. // Recursively remove children directories / files.
  5940. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  5941. // Check if item was on the watched list and remove it
  5942. const parent = this._getWatchedDir(directory);
  5943. const wasTracked = parent.has(item);
  5944. parent.remove(item);
  5945. // If we wait for this file to be fully written, cancel the wait.
  5946. let relPath = path;
  5947. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  5948. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  5949. const event = this._pendingWrites.get(relPath).cancelWait();
  5950. if (event === EV_ADD$2) return;
  5951. }
  5952. // The Entry will either be a directory that just got removed
  5953. // or a bogus entry to a file, in either case we have to remove it
  5954. this._watched.delete(path);
  5955. this._watched.delete(fullPath);
  5956. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK$1;
  5957. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  5958. // Avoid conflicts if we later create another file with the same name
  5959. if (!this.options.useFsEvents) {
  5960. this._closePath(path);
  5961. }
  5962. }
  5963. /**
  5964. * Closes all watchers for a path
  5965. * @param {Path} path
  5966. */
  5967. _closePath(path) {
  5968. this._closeFile(path);
  5969. const dir = sysPath.dirname(path);
  5970. this._getWatchedDir(dir).remove(sysPath.basename(path));
  5971. }
  5972. /**
  5973. * Closes only file-specific watchers
  5974. * @param {Path} path
  5975. */
  5976. _closeFile(path) {
  5977. const closers = this._closers.get(path);
  5978. if (!closers) return;
  5979. closers.forEach(closer => closer());
  5980. this._closers.delete(path);
  5981. }
  5982. /**
  5983. *
  5984. * @param {Path} path
  5985. * @param {Function} closer
  5986. */
  5987. _addPathCloser(path, closer) {
  5988. if (!closer) return;
  5989. let list = this._closers.get(path);
  5990. if (!list) {
  5991. list = [];
  5992. this._closers.set(path, list);
  5993. }
  5994. list.push(closer);
  5995. }
  5996. _readdirp(root, opts) {
  5997. if (this.closed) return;
  5998. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  5999. let stream = readdirp_1(root, options);
  6000. this._streams.add(stream);
  6001. stream.once(STR_CLOSE, () => {
  6002. stream = undefined;
  6003. });
  6004. stream.once(STR_END$2, () => {
  6005. if (stream) {
  6006. this._streams.delete(stream);
  6007. stream = undefined;
  6008. }
  6009. });
  6010. return stream;
  6011. }
  6012. }
  6013. // Export FSWatcher class
  6014. var FSWatcher_1 = FSWatcher;
  6015. /**
  6016. * Instantiates watcher with paths to be tracked.
  6017. * @param {String|Array<String>} paths file/directory paths and/or globs
  6018. * @param {Object=} options chokidar opts
  6019. * @returns an instance of FSWatcher for chaining.
  6020. */
  6021. const watch = (paths, options) => {
  6022. const watcher = new FSWatcher(options);
  6023. watcher.add(paths);
  6024. return watcher;
  6025. };
  6026. var watch_1 = watch;
  6027. var chokidar = {
  6028. FSWatcher: FSWatcher_1,
  6029. watch: watch_1
  6030. };
  6031. class FileWatcher {
  6032. constructor(task, chokidarOptions) {
  6033. this.transformWatchers = new Map();
  6034. this.chokidarOptions = chokidarOptions;
  6035. this.task = task;
  6036. this.watcher = this.createWatcher(null);
  6037. }
  6038. close() {
  6039. this.watcher.close();
  6040. for (const watcher of this.transformWatchers.values()) {
  6041. watcher.close();
  6042. }
  6043. }
  6044. unwatch(id) {
  6045. this.watcher.unwatch(id);
  6046. const transformWatcher = this.transformWatchers.get(id);
  6047. if (transformWatcher) {
  6048. this.transformWatchers.delete(id);
  6049. transformWatcher.close();
  6050. }
  6051. }
  6052. watch(id, isTransformDependency) {
  6053. if (isTransformDependency) {
  6054. const watcher = this.transformWatchers.get(id) || this.createWatcher(id);
  6055. watcher.add(id);
  6056. this.transformWatchers.set(id, watcher);
  6057. }
  6058. else {
  6059. this.watcher.add(id);
  6060. }
  6061. }
  6062. createWatcher(transformWatcherId) {
  6063. const task = this.task;
  6064. const isLinux = platform() === 'linux';
  6065. const isTransformDependency = transformWatcherId !== null;
  6066. const handleChange = (id, event) => {
  6067. const changedId = transformWatcherId || id;
  6068. if (isLinux) {
  6069. // unwatching and watching fixes an issue with chokidar where on certain systems,
  6070. // a file that was unlinked and immediately recreated would create a change event
  6071. // but then no longer any further events
  6072. watcher.unwatch(changedId);
  6073. watcher.add(changedId);
  6074. }
  6075. task.invalidate(changedId, { isTransformDependency, event });
  6076. };
  6077. const watcher = chokidar
  6078. .watch([], this.chokidarOptions)
  6079. .on('add', id => handleChange(id, 'create'))
  6080. .on('change', id => handleChange(id, 'update'))
  6081. .on('unlink', id => handleChange(id, 'delete'));
  6082. return watcher;
  6083. }
  6084. }
  6085. const eventsRewrites = {
  6086. create: {
  6087. create: 'buggy',
  6088. delete: null,
  6089. update: 'create',
  6090. },
  6091. delete: {
  6092. create: 'update',
  6093. delete: 'buggy',
  6094. update: 'buggy',
  6095. },
  6096. update: {
  6097. create: 'buggy',
  6098. delete: 'delete',
  6099. update: 'update',
  6100. }
  6101. };
  6102. class Watcher {
  6103. constructor(configs, emitter) {
  6104. this.buildDelay = 0;
  6105. this.buildTimeout = null;
  6106. this.invalidatedIds = new Map();
  6107. this.rerun = false;
  6108. this.emitter = emitter;
  6109. emitter.close = this.close.bind(this);
  6110. this.tasks = configs.map(config => new Task(this, config));
  6111. this.buildDelay = configs.reduce((buildDelay, { watch }) => watch && typeof watch.buildDelay === 'number'
  6112. ? Math.max(buildDelay, watch.buildDelay)
  6113. : buildDelay, this.buildDelay);
  6114. this.running = true;
  6115. process.nextTick(() => this.run());
  6116. }
  6117. close() {
  6118. if (this.buildTimeout)
  6119. clearTimeout(this.buildTimeout);
  6120. for (const task of this.tasks) {
  6121. task.close();
  6122. }
  6123. this.emitter.emit('close');
  6124. this.emitter.removeAllListeners();
  6125. }
  6126. invalidate(file) {
  6127. if (file) {
  6128. const prevEvent = this.invalidatedIds.get(file.id);
  6129. const event = prevEvent
  6130. ? eventsRewrites[prevEvent][file.event]
  6131. : file.event;
  6132. if (event === 'buggy') {
  6133. //TODO: throws or warn? Currently just ignore, uses new event
  6134. this.invalidatedIds.set(file.id, file.event);
  6135. }
  6136. else if (event === null) {
  6137. this.invalidatedIds.delete(file.id);
  6138. }
  6139. else {
  6140. this.invalidatedIds.set(file.id, event);
  6141. }
  6142. }
  6143. if (this.running) {
  6144. this.rerun = true;
  6145. return;
  6146. }
  6147. if (this.buildTimeout)
  6148. clearTimeout(this.buildTimeout);
  6149. this.buildTimeout = setTimeout(() => {
  6150. this.buildTimeout = null;
  6151. for (const [id, event] of this.invalidatedIds.entries()) {
  6152. this.emitter.emit('change', id, { event });
  6153. }
  6154. this.invalidatedIds.clear();
  6155. this.emitter.emit('restart');
  6156. this.run();
  6157. }, this.buildDelay);
  6158. }
  6159. async run() {
  6160. this.running = true;
  6161. this.emitter.emit('event', {
  6162. code: 'START'
  6163. });
  6164. try {
  6165. for (const task of this.tasks) {
  6166. await task.run();
  6167. }
  6168. this.running = false;
  6169. this.emitter.emit('event', {
  6170. code: 'END'
  6171. });
  6172. }
  6173. catch (error) {
  6174. this.running = false;
  6175. this.emitter.emit('event', {
  6176. code: 'ERROR',
  6177. error
  6178. });
  6179. }
  6180. if (this.rerun) {
  6181. this.rerun = false;
  6182. this.invalidate();
  6183. }
  6184. }
  6185. }
  6186. class Task {
  6187. constructor(watcher, config) {
  6188. this.cache = { modules: [] };
  6189. this.watchFiles = [];
  6190. this.invalidated = true;
  6191. this.watcher = watcher;
  6192. this.closed = false;
  6193. this.watched = new Set();
  6194. this.skipWrite = config.watch && !!config.watch.skipWrite;
  6195. this.options = mergeOptions(config);
  6196. this.outputs = this.options.output;
  6197. this.outputFiles = this.outputs.map(output => {
  6198. if (output.file || output.dir)
  6199. return resolve(output.file || output.dir);
  6200. return undefined;
  6201. });
  6202. const watchOptions = this.options.watch || {};
  6203. this.filter = createFilter(watchOptions.include, watchOptions.exclude);
  6204. this.fileWatcher = new FileWatcher(this, {
  6205. ...watchOptions.chokidar,
  6206. disableGlobbing: true,
  6207. ignoreInitial: true
  6208. });
  6209. }
  6210. close() {
  6211. this.closed = true;
  6212. this.fileWatcher.close();
  6213. }
  6214. invalidate(id, details) {
  6215. this.invalidated = true;
  6216. if (details.isTransformDependency) {
  6217. for (const module of this.cache.modules) {
  6218. if (module.transformDependencies.indexOf(id) === -1)
  6219. continue;
  6220. // effective invalidation
  6221. module.originalCode = null;
  6222. }
  6223. }
  6224. this.watcher.invalidate({ id, event: details.event });
  6225. }
  6226. async run() {
  6227. if (!this.invalidated)
  6228. return;
  6229. this.invalidated = false;
  6230. const options = {
  6231. ...this.options,
  6232. cache: this.cache
  6233. };
  6234. const start = Date.now();
  6235. this.watcher.emitter.emit('event', {
  6236. code: 'BUNDLE_START',
  6237. input: this.options.input,
  6238. output: this.outputFiles
  6239. });
  6240. try {
  6241. const result = await rollupInternal(options, this.watcher.emitter);
  6242. if (this.closed) {
  6243. return;
  6244. }
  6245. this.updateWatchedFiles(result);
  6246. this.skipWrite || (await Promise.all(this.outputs.map(output => result.write(output))));
  6247. this.watcher.emitter.emit('event', {
  6248. code: 'BUNDLE_END',
  6249. duration: Date.now() - start,
  6250. input: this.options.input,
  6251. output: this.outputFiles,
  6252. result
  6253. });
  6254. }
  6255. catch (error) {
  6256. if (this.closed) {
  6257. return;
  6258. }
  6259. if (Array.isArray(error.watchFiles)) {
  6260. for (const id of error.watchFiles) {
  6261. this.watchFile(id);
  6262. }
  6263. }
  6264. if (error.id) {
  6265. this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);
  6266. }
  6267. throw error;
  6268. }
  6269. }
  6270. updateWatchedFiles(result) {
  6271. const previouslyWatched = this.watched;
  6272. this.watched = new Set();
  6273. this.watchFiles = result.watchFiles;
  6274. this.cache = result.cache;
  6275. for (const id of this.watchFiles) {
  6276. this.watchFile(id);
  6277. }
  6278. for (const module of this.cache.modules) {
  6279. for (const depId of module.transformDependencies) {
  6280. this.watchFile(depId, true);
  6281. }
  6282. }
  6283. for (const id of previouslyWatched) {
  6284. if (!this.watched.has(id)) {
  6285. this.fileWatcher.unwatch(id);
  6286. }
  6287. }
  6288. }
  6289. watchFile(id, isTransformDependency = false) {
  6290. if (!this.filter(id))
  6291. return;
  6292. this.watched.add(id);
  6293. if (this.outputFiles.some(file => file === id)) {
  6294. throw new Error('Cannot import the generated bundle');
  6295. }
  6296. // this is necessary to ensure that any 'renamed' files
  6297. // continue to be watched following an error
  6298. this.fileWatcher.watch(id, isTransformDependency);
  6299. }
  6300. }
  6301. export { Task, Watcher };