watch.js 258 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909
  1. /*
  2. @license
  3. Rollup.js v4.60.1
  4. Mon, 30 Mar 2026 04:32:12 GMT - commit ae871d762f6bbeb4320d28fe179211168f27a434
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { getAugmentedNamespace, fseventsImporter, getDefaultExportFromCjs, createFilter, rollupInternal } from './node-entry.js';
  9. import path from 'node:path';
  10. import process$1 from 'node:process';
  11. import require$$0$1 from 'path';
  12. import require$$0$2 from 'fs';
  13. import require$$2 from 'util';
  14. import require$$1 from 'stream';
  15. import require$$2$1 from 'os';
  16. import require$$0$3 from 'events';
  17. import { platform } from 'node:os';
  18. import './parseAst.js';
  19. import '../../native.js';
  20. import 'node:perf_hooks';
  21. import 'node:fs/promises';
  22. var chokidar$1 = {};
  23. var utils$2 = {};
  24. var constants$3;
  25. var hasRequiredConstants$3;
  26. function requireConstants$3 () {
  27. if (hasRequiredConstants$3) return constants$3;
  28. hasRequiredConstants$3 = 1;
  29. const path = require$$0$1;
  30. const WIN_SLASH = '\\\\/';
  31. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  32. const DEFAULT_MAX_EXTGLOB_RECURSION = 0;
  33. /**
  34. * Posix glob regex
  35. */
  36. const DOT_LITERAL = '\\.';
  37. const PLUS_LITERAL = '\\+';
  38. const QMARK_LITERAL = '\\?';
  39. const SLASH_LITERAL = '\\/';
  40. const ONE_CHAR = '(?=.)';
  41. const QMARK = '[^/]';
  42. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  43. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  44. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  45. const NO_DOT = `(?!${DOT_LITERAL})`;
  46. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  47. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  48. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  49. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  50. const STAR = `${QMARK}*?`;
  51. const POSIX_CHARS = {
  52. DOT_LITERAL,
  53. PLUS_LITERAL,
  54. QMARK_LITERAL,
  55. SLASH_LITERAL,
  56. ONE_CHAR,
  57. QMARK,
  58. END_ANCHOR,
  59. DOTS_SLASH,
  60. NO_DOT,
  61. NO_DOTS,
  62. NO_DOT_SLASH,
  63. NO_DOTS_SLASH,
  64. QMARK_NO_DOT,
  65. STAR,
  66. START_ANCHOR
  67. };
  68. /**
  69. * Windows glob regex
  70. */
  71. const WINDOWS_CHARS = {
  72. ...POSIX_CHARS,
  73. SLASH_LITERAL: `[${WIN_SLASH}]`,
  74. QMARK: WIN_NO_SLASH,
  75. STAR: `${WIN_NO_SLASH}*?`,
  76. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  77. NO_DOT: `(?!${DOT_LITERAL})`,
  78. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  79. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  80. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  81. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  82. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  83. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  84. };
  85. /**
  86. * POSIX Bracket Regex
  87. */
  88. const POSIX_REGEX_SOURCE = {
  89. __proto__: null,
  90. alnum: 'a-zA-Z0-9',
  91. alpha: 'a-zA-Z',
  92. ascii: '\\x00-\\x7F',
  93. blank: ' \\t',
  94. cntrl: '\\x00-\\x1F\\x7F',
  95. digit: '0-9',
  96. graph: '\\x21-\\x7E',
  97. lower: 'a-z',
  98. print: '\\x20-\\x7E ',
  99. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  100. space: ' \\t\\r\\n\\v\\f',
  101. upper: 'A-Z',
  102. word: 'A-Za-z0-9_',
  103. xdigit: 'A-Fa-f0-9'
  104. };
  105. constants$3 = {
  106. DEFAULT_MAX_EXTGLOB_RECURSION,
  107. MAX_LENGTH: 1024 * 64,
  108. POSIX_REGEX_SOURCE,
  109. // regular expressions
  110. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  111. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  112. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  113. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  114. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  115. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  116. // Replace globs with equivalent patterns to reduce parsing time.
  117. REPLACEMENTS: {
  118. __proto__: null,
  119. '***': '*',
  120. '**/**': '**',
  121. '**/**/**': '**'
  122. },
  123. // Digits
  124. CHAR_0: 48, /* 0 */
  125. CHAR_9: 57, /* 9 */
  126. // Alphabet chars.
  127. CHAR_UPPERCASE_A: 65, /* A */
  128. CHAR_LOWERCASE_A: 97, /* a */
  129. CHAR_UPPERCASE_Z: 90, /* Z */
  130. CHAR_LOWERCASE_Z: 122, /* z */
  131. CHAR_LEFT_PARENTHESES: 40, /* ( */
  132. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  133. CHAR_ASTERISK: 42, /* * */
  134. // Non-alphabetic chars.
  135. CHAR_AMPERSAND: 38, /* & */
  136. CHAR_AT: 64, /* @ */
  137. CHAR_BACKWARD_SLASH: 92, /* \ */
  138. CHAR_CARRIAGE_RETURN: 13, /* \r */
  139. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  140. CHAR_COLON: 58, /* : */
  141. CHAR_COMMA: 44, /* , */
  142. CHAR_DOT: 46, /* . */
  143. CHAR_DOUBLE_QUOTE: 34, /* " */
  144. CHAR_EQUAL: 61, /* = */
  145. CHAR_EXCLAMATION_MARK: 33, /* ! */
  146. CHAR_FORM_FEED: 12, /* \f */
  147. CHAR_FORWARD_SLASH: 47, /* / */
  148. CHAR_GRAVE_ACCENT: 96, /* ` */
  149. CHAR_HASH: 35, /* # */
  150. CHAR_HYPHEN_MINUS: 45, /* - */
  151. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  152. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  153. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  154. CHAR_LINE_FEED: 10, /* \n */
  155. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  156. CHAR_PERCENT: 37, /* % */
  157. CHAR_PLUS: 43, /* + */
  158. CHAR_QUESTION_MARK: 63, /* ? */
  159. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  160. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  161. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  162. CHAR_SEMICOLON: 59, /* ; */
  163. CHAR_SINGLE_QUOTE: 39, /* ' */
  164. CHAR_SPACE: 32, /* */
  165. CHAR_TAB: 9, /* \t */
  166. CHAR_UNDERSCORE: 95, /* _ */
  167. CHAR_VERTICAL_LINE: 124, /* | */
  168. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  169. SEP: path.sep,
  170. /**
  171. * Create EXTGLOB_CHARS
  172. */
  173. extglobChars(chars) {
  174. return {
  175. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  176. '?': { type: 'qmark', open: '(?:', close: ')?' },
  177. '+': { type: 'plus', open: '(?:', close: ')+' },
  178. '*': { type: 'star', open: '(?:', close: ')*' },
  179. '@': { type: 'at', open: '(?:', close: ')' }
  180. };
  181. },
  182. /**
  183. * Create GLOB_CHARS
  184. */
  185. globChars(win32) {
  186. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  187. }
  188. };
  189. return constants$3;
  190. }
  191. var hasRequiredUtils$2;
  192. function requireUtils$2 () {
  193. if (hasRequiredUtils$2) return utils$2;
  194. hasRequiredUtils$2 = 1;
  195. (function (exports$1) {
  196. const path = require$$0$1;
  197. const win32 = process.platform === 'win32';
  198. const {
  199. REGEX_BACKSLASH,
  200. REGEX_REMOVE_BACKSLASH,
  201. REGEX_SPECIAL_CHARS,
  202. REGEX_SPECIAL_CHARS_GLOBAL
  203. } = /*@__PURE__*/ requireConstants$3();
  204. exports$1.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  205. exports$1.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  206. exports$1.isRegexChar = str => str.length === 1 && exports$1.hasRegexChars(str);
  207. exports$1.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  208. exports$1.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  209. exports$1.removeBackslashes = str => {
  210. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  211. return match === '\\' ? '' : match;
  212. });
  213. };
  214. exports$1.supportsLookbehinds = () => {
  215. const segs = process.version.slice(1).split('.').map(Number);
  216. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  217. return true;
  218. }
  219. return false;
  220. };
  221. exports$1.isWindows = options => {
  222. if (options && typeof options.windows === 'boolean') {
  223. return options.windows;
  224. }
  225. return win32 === true || path.sep === '\\';
  226. };
  227. exports$1.escapeLast = (input, char, lastIdx) => {
  228. const idx = input.lastIndexOf(char, lastIdx);
  229. if (idx === -1) return input;
  230. if (input[idx - 1] === '\\') return exports$1.escapeLast(input, char, idx - 1);
  231. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  232. };
  233. exports$1.removePrefix = (input, state = {}) => {
  234. let output = input;
  235. if (output.startsWith('./')) {
  236. output = output.slice(2);
  237. state.prefix = './';
  238. }
  239. return output;
  240. };
  241. exports$1.wrapOutput = (input, state = {}, options = {}) => {
  242. const prepend = options.contains ? '' : '^';
  243. const append = options.contains ? '' : '$';
  244. let output = `${prepend}(?:${input})${append}`;
  245. if (state.negated === true) {
  246. output = `(?:^(?!${output}).*$)`;
  247. }
  248. return output;
  249. };
  250. } (utils$2));
  251. return utils$2;
  252. }
  253. var scan_1$1;
  254. var hasRequiredScan$1;
  255. function requireScan$1 () {
  256. if (hasRequiredScan$1) return scan_1$1;
  257. hasRequiredScan$1 = 1;
  258. const utils = /*@__PURE__*/ requireUtils$2();
  259. const {
  260. CHAR_ASTERISK, /* * */
  261. CHAR_AT, /* @ */
  262. CHAR_BACKWARD_SLASH, /* \ */
  263. CHAR_COMMA, /* , */
  264. CHAR_DOT, /* . */
  265. CHAR_EXCLAMATION_MARK, /* ! */
  266. CHAR_FORWARD_SLASH, /* / */
  267. CHAR_LEFT_CURLY_BRACE, /* { */
  268. CHAR_LEFT_PARENTHESES, /* ( */
  269. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  270. CHAR_PLUS, /* + */
  271. CHAR_QUESTION_MARK, /* ? */
  272. CHAR_RIGHT_CURLY_BRACE, /* } */
  273. CHAR_RIGHT_PARENTHESES, /* ) */
  274. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  275. } = /*@__PURE__*/ requireConstants$3();
  276. const isPathSeparator = code => {
  277. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  278. };
  279. const depth = token => {
  280. if (token.isPrefix !== true) {
  281. token.depth = token.isGlobstar ? Infinity : 1;
  282. }
  283. };
  284. /**
  285. * Quickly scans a glob pattern and returns an object with a handful of
  286. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  287. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  288. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  289. *
  290. * ```js
  291. * const pm = require('picomatch');
  292. * console.log(pm.scan('foo/bar/*.js'));
  293. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  294. * ```
  295. * @param {String} `str`
  296. * @param {Object} `options`
  297. * @return {Object} Returns an object with tokens and regex source string.
  298. * @api public
  299. */
  300. const scan = (input, options) => {
  301. const opts = options || {};
  302. const length = input.length - 1;
  303. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  304. const slashes = [];
  305. const tokens = [];
  306. const parts = [];
  307. let str = input;
  308. let index = -1;
  309. let start = 0;
  310. let lastIndex = 0;
  311. let isBrace = false;
  312. let isBracket = false;
  313. let isGlob = false;
  314. let isExtglob = false;
  315. let isGlobstar = false;
  316. let braceEscaped = false;
  317. let backslashes = false;
  318. let negated = false;
  319. let negatedExtglob = false;
  320. let finished = false;
  321. let braces = 0;
  322. let prev;
  323. let code;
  324. let token = { value: '', depth: 0, isGlob: false };
  325. const eos = () => index >= length;
  326. const peek = () => str.charCodeAt(index + 1);
  327. const advance = () => {
  328. prev = code;
  329. return str.charCodeAt(++index);
  330. };
  331. while (index < length) {
  332. code = advance();
  333. let next;
  334. if (code === CHAR_BACKWARD_SLASH) {
  335. backslashes = token.backslashes = true;
  336. code = advance();
  337. if (code === CHAR_LEFT_CURLY_BRACE) {
  338. braceEscaped = true;
  339. }
  340. continue;
  341. }
  342. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  343. braces++;
  344. while (eos() !== true && (code = advance())) {
  345. if (code === CHAR_BACKWARD_SLASH) {
  346. backslashes = token.backslashes = true;
  347. advance();
  348. continue;
  349. }
  350. if (code === CHAR_LEFT_CURLY_BRACE) {
  351. braces++;
  352. continue;
  353. }
  354. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  355. isBrace = token.isBrace = true;
  356. isGlob = token.isGlob = true;
  357. finished = true;
  358. if (scanToEnd === true) {
  359. continue;
  360. }
  361. break;
  362. }
  363. if (braceEscaped !== true && code === CHAR_COMMA) {
  364. isBrace = token.isBrace = true;
  365. isGlob = token.isGlob = true;
  366. finished = true;
  367. if (scanToEnd === true) {
  368. continue;
  369. }
  370. break;
  371. }
  372. if (code === CHAR_RIGHT_CURLY_BRACE) {
  373. braces--;
  374. if (braces === 0) {
  375. braceEscaped = false;
  376. isBrace = token.isBrace = true;
  377. finished = true;
  378. break;
  379. }
  380. }
  381. }
  382. if (scanToEnd === true) {
  383. continue;
  384. }
  385. break;
  386. }
  387. if (code === CHAR_FORWARD_SLASH) {
  388. slashes.push(index);
  389. tokens.push(token);
  390. token = { value: '', depth: 0, isGlob: false };
  391. if (finished === true) continue;
  392. if (prev === CHAR_DOT && index === (start + 1)) {
  393. start += 2;
  394. continue;
  395. }
  396. lastIndex = index + 1;
  397. continue;
  398. }
  399. if (opts.noext !== true) {
  400. const isExtglobChar = code === CHAR_PLUS
  401. || code === CHAR_AT
  402. || code === CHAR_ASTERISK
  403. || code === CHAR_QUESTION_MARK
  404. || code === CHAR_EXCLAMATION_MARK;
  405. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  406. isGlob = token.isGlob = true;
  407. isExtglob = token.isExtglob = true;
  408. finished = true;
  409. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  410. negatedExtglob = true;
  411. }
  412. if (scanToEnd === true) {
  413. while (eos() !== true && (code = advance())) {
  414. if (code === CHAR_BACKWARD_SLASH) {
  415. backslashes = token.backslashes = true;
  416. code = advance();
  417. continue;
  418. }
  419. if (code === CHAR_RIGHT_PARENTHESES) {
  420. isGlob = token.isGlob = true;
  421. finished = true;
  422. break;
  423. }
  424. }
  425. continue;
  426. }
  427. break;
  428. }
  429. }
  430. if (code === CHAR_ASTERISK) {
  431. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  432. isGlob = token.isGlob = true;
  433. finished = true;
  434. if (scanToEnd === true) {
  435. continue;
  436. }
  437. break;
  438. }
  439. if (code === CHAR_QUESTION_MARK) {
  440. isGlob = token.isGlob = true;
  441. finished = true;
  442. if (scanToEnd === true) {
  443. continue;
  444. }
  445. break;
  446. }
  447. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  448. while (eos() !== true && (next = advance())) {
  449. if (next === CHAR_BACKWARD_SLASH) {
  450. backslashes = token.backslashes = true;
  451. advance();
  452. continue;
  453. }
  454. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  455. isBracket = token.isBracket = true;
  456. isGlob = token.isGlob = true;
  457. finished = true;
  458. break;
  459. }
  460. }
  461. if (scanToEnd === true) {
  462. continue;
  463. }
  464. break;
  465. }
  466. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  467. negated = token.negated = true;
  468. start++;
  469. continue;
  470. }
  471. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  472. isGlob = token.isGlob = true;
  473. if (scanToEnd === true) {
  474. while (eos() !== true && (code = advance())) {
  475. if (code === CHAR_LEFT_PARENTHESES) {
  476. backslashes = token.backslashes = true;
  477. code = advance();
  478. continue;
  479. }
  480. if (code === CHAR_RIGHT_PARENTHESES) {
  481. finished = true;
  482. break;
  483. }
  484. }
  485. continue;
  486. }
  487. break;
  488. }
  489. if (isGlob === true) {
  490. finished = true;
  491. if (scanToEnd === true) {
  492. continue;
  493. }
  494. break;
  495. }
  496. }
  497. if (opts.noext === true) {
  498. isExtglob = false;
  499. isGlob = false;
  500. }
  501. let base = str;
  502. let prefix = '';
  503. let glob = '';
  504. if (start > 0) {
  505. prefix = str.slice(0, start);
  506. str = str.slice(start);
  507. lastIndex -= start;
  508. }
  509. if (base && isGlob === true && lastIndex > 0) {
  510. base = str.slice(0, lastIndex);
  511. glob = str.slice(lastIndex);
  512. } else if (isGlob === true) {
  513. base = '';
  514. glob = str;
  515. } else {
  516. base = str;
  517. }
  518. if (base && base !== '' && base !== '/' && base !== str) {
  519. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  520. base = base.slice(0, -1);
  521. }
  522. }
  523. if (opts.unescape === true) {
  524. if (glob) glob = utils.removeBackslashes(glob);
  525. if (base && backslashes === true) {
  526. base = utils.removeBackslashes(base);
  527. }
  528. }
  529. const state = {
  530. prefix,
  531. input,
  532. start,
  533. base,
  534. glob,
  535. isBrace,
  536. isBracket,
  537. isGlob,
  538. isExtglob,
  539. isGlobstar,
  540. negated,
  541. negatedExtglob
  542. };
  543. if (opts.tokens === true) {
  544. state.maxDepth = 0;
  545. if (!isPathSeparator(code)) {
  546. tokens.push(token);
  547. }
  548. state.tokens = tokens;
  549. }
  550. if (opts.parts === true || opts.tokens === true) {
  551. let prevIndex;
  552. for (let idx = 0; idx < slashes.length; idx++) {
  553. const n = prevIndex ? prevIndex + 1 : start;
  554. const i = slashes[idx];
  555. const value = input.slice(n, i);
  556. if (opts.tokens) {
  557. if (idx === 0 && start !== 0) {
  558. tokens[idx].isPrefix = true;
  559. tokens[idx].value = prefix;
  560. } else {
  561. tokens[idx].value = value;
  562. }
  563. depth(tokens[idx]);
  564. state.maxDepth += tokens[idx].depth;
  565. }
  566. if (idx !== 0 || value !== '') {
  567. parts.push(value);
  568. }
  569. prevIndex = i;
  570. }
  571. if (prevIndex && prevIndex + 1 < input.length) {
  572. const value = input.slice(prevIndex + 1);
  573. parts.push(value);
  574. if (opts.tokens) {
  575. tokens[tokens.length - 1].value = value;
  576. depth(tokens[tokens.length - 1]);
  577. state.maxDepth += tokens[tokens.length - 1].depth;
  578. }
  579. }
  580. state.slashes = slashes;
  581. state.parts = parts;
  582. }
  583. return state;
  584. };
  585. scan_1$1 = scan;
  586. return scan_1$1;
  587. }
  588. var parse_1$2;
  589. var hasRequiredParse$2;
  590. function requireParse$2 () {
  591. if (hasRequiredParse$2) return parse_1$2;
  592. hasRequiredParse$2 = 1;
  593. const constants = /*@__PURE__*/ requireConstants$3();
  594. const utils = /*@__PURE__*/ requireUtils$2();
  595. /**
  596. * Constants
  597. */
  598. const {
  599. MAX_LENGTH,
  600. POSIX_REGEX_SOURCE,
  601. REGEX_NON_SPECIAL_CHARS,
  602. REGEX_SPECIAL_CHARS_BACKREF,
  603. REPLACEMENTS
  604. } = constants;
  605. /**
  606. * Helpers
  607. */
  608. const expandRange = (args, options) => {
  609. if (typeof options.expandRange === 'function') {
  610. return options.expandRange(...args, options);
  611. }
  612. args.sort();
  613. const value = `[${args.join('-')}]`;
  614. return value;
  615. };
  616. /**
  617. * Create the message for a syntax error
  618. */
  619. const syntaxError = (type, char) => {
  620. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  621. };
  622. const splitTopLevel = input => {
  623. const parts = [];
  624. let bracket = 0;
  625. let paren = 0;
  626. let quote = 0;
  627. let value = '';
  628. let escaped = false;
  629. for (const ch of input) {
  630. if (escaped === true) {
  631. value += ch;
  632. escaped = false;
  633. continue;
  634. }
  635. if (ch === '\\') {
  636. value += ch;
  637. escaped = true;
  638. continue;
  639. }
  640. if (ch === '"') {
  641. quote = quote === 1 ? 0 : 1;
  642. value += ch;
  643. continue;
  644. }
  645. if (quote === 0) {
  646. if (ch === '[') {
  647. bracket++;
  648. } else if (ch === ']' && bracket > 0) {
  649. bracket--;
  650. } else if (bracket === 0) {
  651. if (ch === '(') {
  652. paren++;
  653. } else if (ch === ')' && paren > 0) {
  654. paren--;
  655. } else if (ch === '|' && paren === 0) {
  656. parts.push(value);
  657. value = '';
  658. continue;
  659. }
  660. }
  661. }
  662. value += ch;
  663. }
  664. parts.push(value);
  665. return parts;
  666. };
  667. const isPlainBranch = branch => {
  668. let escaped = false;
  669. for (const ch of branch) {
  670. if (escaped === true) {
  671. escaped = false;
  672. continue;
  673. }
  674. if (ch === '\\') {
  675. escaped = true;
  676. continue;
  677. }
  678. if (/[?*+@!()[\]{}]/.test(ch)) {
  679. return false;
  680. }
  681. }
  682. return true;
  683. };
  684. const normalizeSimpleBranch = branch => {
  685. let value = branch.trim();
  686. let changed = true;
  687. while (changed === true) {
  688. changed = false;
  689. if (/^@\([^\\()[\]{}|]+\)$/.test(value)) {
  690. value = value.slice(2, -1);
  691. changed = true;
  692. }
  693. }
  694. if (!isPlainBranch(value)) {
  695. return;
  696. }
  697. return value.replace(/\\(.)/g, '$1');
  698. };
  699. const hasRepeatedCharPrefixOverlap = branches => {
  700. const values = branches.map(normalizeSimpleBranch).filter(Boolean);
  701. for (let i = 0; i < values.length; i++) {
  702. for (let j = i + 1; j < values.length; j++) {
  703. const a = values[i];
  704. const b = values[j];
  705. const char = a[0];
  706. if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) {
  707. continue;
  708. }
  709. if (a === b || a.startsWith(b) || b.startsWith(a)) {
  710. return true;
  711. }
  712. }
  713. }
  714. return false;
  715. };
  716. const parseRepeatedExtglob = (pattern, requireEnd = true) => {
  717. if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') {
  718. return;
  719. }
  720. let bracket = 0;
  721. let paren = 0;
  722. let quote = 0;
  723. let escaped = false;
  724. for (let i = 1; i < pattern.length; i++) {
  725. const ch = pattern[i];
  726. if (escaped === true) {
  727. escaped = false;
  728. continue;
  729. }
  730. if (ch === '\\') {
  731. escaped = true;
  732. continue;
  733. }
  734. if (ch === '"') {
  735. quote = quote === 1 ? 0 : 1;
  736. continue;
  737. }
  738. if (quote === 1) {
  739. continue;
  740. }
  741. if (ch === '[') {
  742. bracket++;
  743. continue;
  744. }
  745. if (ch === ']' && bracket > 0) {
  746. bracket--;
  747. continue;
  748. }
  749. if (bracket > 0) {
  750. continue;
  751. }
  752. if (ch === '(') {
  753. paren++;
  754. continue;
  755. }
  756. if (ch === ')') {
  757. paren--;
  758. if (paren === 0) {
  759. if (requireEnd === true && i !== pattern.length - 1) {
  760. return;
  761. }
  762. return {
  763. type: pattern[0],
  764. body: pattern.slice(2, i),
  765. end: i
  766. };
  767. }
  768. }
  769. }
  770. };
  771. const getStarExtglobSequenceOutput = pattern => {
  772. let index = 0;
  773. const chars = [];
  774. while (index < pattern.length) {
  775. const match = parseRepeatedExtglob(pattern.slice(index), false);
  776. if (!match || match.type !== '*') {
  777. return;
  778. }
  779. const branches = splitTopLevel(match.body).map(branch => branch.trim());
  780. if (branches.length !== 1) {
  781. return;
  782. }
  783. const branch = normalizeSimpleBranch(branches[0]);
  784. if (!branch || branch.length !== 1) {
  785. return;
  786. }
  787. chars.push(branch);
  788. index += match.end + 1;
  789. }
  790. if (chars.length < 1) {
  791. return;
  792. }
  793. const source = chars.length === 1
  794. ? utils.escapeRegex(chars[0])
  795. : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`;
  796. return `${source}*`;
  797. };
  798. const repeatedExtglobRecursion = pattern => {
  799. let depth = 0;
  800. let value = pattern.trim();
  801. let match = parseRepeatedExtglob(value);
  802. while (match) {
  803. depth++;
  804. value = match.body.trim();
  805. match = parseRepeatedExtglob(value);
  806. }
  807. return depth;
  808. };
  809. const analyzeRepeatedExtglob = (body, options) => {
  810. if (options.maxExtglobRecursion === false) {
  811. return { risky: false };
  812. }
  813. const max =
  814. typeof options.maxExtglobRecursion === 'number'
  815. ? options.maxExtglobRecursion
  816. : constants.DEFAULT_MAX_EXTGLOB_RECURSION;
  817. const branches = splitTopLevel(body).map(branch => branch.trim());
  818. if (branches.length > 1) {
  819. if (
  820. branches.some(branch => branch === '') ||
  821. branches.some(branch => /^[*?]+$/.test(branch)) ||
  822. hasRepeatedCharPrefixOverlap(branches)
  823. ) {
  824. return { risky: true };
  825. }
  826. }
  827. for (const branch of branches) {
  828. const safeOutput = getStarExtglobSequenceOutput(branch);
  829. if (safeOutput) {
  830. return { risky: true, safeOutput };
  831. }
  832. if (repeatedExtglobRecursion(branch) > max) {
  833. return { risky: true };
  834. }
  835. }
  836. return { risky: false };
  837. };
  838. /**
  839. * Parse the given input string.
  840. * @param {String} input
  841. * @param {Object} options
  842. * @return {Object}
  843. */
  844. const parse = (input, options) => {
  845. if (typeof input !== 'string') {
  846. throw new TypeError('Expected a string');
  847. }
  848. input = REPLACEMENTS[input] || input;
  849. const opts = { ...options };
  850. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  851. let len = input.length;
  852. if (len > max) {
  853. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  854. }
  855. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  856. const tokens = [bos];
  857. const capture = opts.capture ? '' : '?:';
  858. const win32 = utils.isWindows(options);
  859. // create constants based on platform, for windows or posix
  860. const PLATFORM_CHARS = constants.globChars(win32);
  861. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  862. const {
  863. DOT_LITERAL,
  864. PLUS_LITERAL,
  865. SLASH_LITERAL,
  866. ONE_CHAR,
  867. DOTS_SLASH,
  868. NO_DOT,
  869. NO_DOT_SLASH,
  870. NO_DOTS_SLASH,
  871. QMARK,
  872. QMARK_NO_DOT,
  873. STAR,
  874. START_ANCHOR
  875. } = PLATFORM_CHARS;
  876. const globstar = opts => {
  877. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  878. };
  879. const nodot = opts.dot ? '' : NO_DOT;
  880. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  881. let star = opts.bash === true ? globstar(opts) : STAR;
  882. if (opts.capture) {
  883. star = `(${star})`;
  884. }
  885. // minimatch options support
  886. if (typeof opts.noext === 'boolean') {
  887. opts.noextglob = opts.noext;
  888. }
  889. const state = {
  890. input,
  891. index: -1,
  892. start: 0,
  893. dot: opts.dot === true,
  894. consumed: '',
  895. output: '',
  896. prefix: '',
  897. backtrack: false,
  898. negated: false,
  899. brackets: 0,
  900. braces: 0,
  901. parens: 0,
  902. quotes: 0,
  903. globstar: false,
  904. tokens
  905. };
  906. input = utils.removePrefix(input, state);
  907. len = input.length;
  908. const extglobs = [];
  909. const braces = [];
  910. const stack = [];
  911. let prev = bos;
  912. let value;
  913. /**
  914. * Tokenizing helpers
  915. */
  916. const eos = () => state.index === len - 1;
  917. const peek = state.peek = (n = 1) => input[state.index + n];
  918. const advance = state.advance = () => input[++state.index] || '';
  919. const remaining = () => input.slice(state.index + 1);
  920. const consume = (value = '', num = 0) => {
  921. state.consumed += value;
  922. state.index += num;
  923. };
  924. const append = token => {
  925. state.output += token.output != null ? token.output : token.value;
  926. consume(token.value);
  927. };
  928. const negate = () => {
  929. let count = 1;
  930. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  931. advance();
  932. state.start++;
  933. count++;
  934. }
  935. if (count % 2 === 0) {
  936. return false;
  937. }
  938. state.negated = true;
  939. state.start++;
  940. return true;
  941. };
  942. const increment = type => {
  943. state[type]++;
  944. stack.push(type);
  945. };
  946. const decrement = type => {
  947. state[type]--;
  948. stack.pop();
  949. };
  950. /**
  951. * Push tokens onto the tokens array. This helper speeds up
  952. * tokenizing by 1) helping us avoid backtracking as much as possible,
  953. * and 2) helping us avoid creating extra tokens when consecutive
  954. * characters are plain text. This improves performance and simplifies
  955. * lookbehinds.
  956. */
  957. const push = tok => {
  958. if (prev.type === 'globstar') {
  959. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  960. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  961. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  962. state.output = state.output.slice(0, -prev.output.length);
  963. prev.type = 'star';
  964. prev.value = '*';
  965. prev.output = star;
  966. state.output += prev.output;
  967. }
  968. }
  969. if (extglobs.length && tok.type !== 'paren') {
  970. extglobs[extglobs.length - 1].inner += tok.value;
  971. }
  972. if (tok.value || tok.output) append(tok);
  973. if (prev && prev.type === 'text' && tok.type === 'text') {
  974. prev.value += tok.value;
  975. prev.output = (prev.output || '') + tok.value;
  976. return;
  977. }
  978. tok.prev = prev;
  979. tokens.push(tok);
  980. prev = tok;
  981. };
  982. const extglobOpen = (type, value) => {
  983. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  984. token.prev = prev;
  985. token.parens = state.parens;
  986. token.output = state.output;
  987. token.startIndex = state.index;
  988. token.tokensIndex = tokens.length;
  989. const output = (opts.capture ? '(' : '') + token.open;
  990. increment('parens');
  991. push({ type, value, output: state.output ? '' : ONE_CHAR });
  992. push({ type: 'paren', extglob: true, value: advance(), output });
  993. extglobs.push(token);
  994. };
  995. const extglobClose = token => {
  996. const literal = input.slice(token.startIndex, state.index + 1);
  997. const body = input.slice(token.startIndex + 2, state.index);
  998. const analysis = analyzeRepeatedExtglob(body, opts);
  999. if ((token.type === 'plus' || token.type === 'star') && analysis.risky) {
  1000. const safeOutput = analysis.safeOutput
  1001. ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput)
  1002. : undefined;
  1003. const open = tokens[token.tokensIndex];
  1004. open.type = 'text';
  1005. open.value = literal;
  1006. open.output = safeOutput || utils.escapeRegex(literal);
  1007. for (let i = token.tokensIndex + 1; i < tokens.length; i++) {
  1008. tokens[i].value = '';
  1009. tokens[i].output = '';
  1010. delete tokens[i].suffix;
  1011. }
  1012. state.output = token.output + open.output;
  1013. state.backtrack = true;
  1014. push({ type: 'paren', extglob: true, value, output: '' });
  1015. decrement('parens');
  1016. return;
  1017. }
  1018. let output = token.close + (opts.capture ? ')' : '');
  1019. let rest;
  1020. if (token.type === 'negate') {
  1021. let extglobStar = star;
  1022. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1023. extglobStar = globstar(opts);
  1024. }
  1025. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1026. output = token.close = `)$))${extglobStar}`;
  1027. }
  1028. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1029. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1030. // In this case, we need to parse the string and use it in the output of the original pattern.
  1031. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1032. //
  1033. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1034. const expression = parse(rest, { ...options, fastpaths: false }).output;
  1035. output = token.close = `)${expression})${extglobStar})`;
  1036. }
  1037. if (token.prev.type === 'bos') {
  1038. state.negatedExtglob = true;
  1039. }
  1040. }
  1041. push({ type: 'paren', extglob: true, value, output });
  1042. decrement('parens');
  1043. };
  1044. /**
  1045. * Fast paths
  1046. */
  1047. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1048. let backslashes = false;
  1049. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1050. if (first === '\\') {
  1051. backslashes = true;
  1052. return m;
  1053. }
  1054. if (first === '?') {
  1055. if (esc) {
  1056. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1057. }
  1058. if (index === 0) {
  1059. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1060. }
  1061. return QMARK.repeat(chars.length);
  1062. }
  1063. if (first === '.') {
  1064. return DOT_LITERAL.repeat(chars.length);
  1065. }
  1066. if (first === '*') {
  1067. if (esc) {
  1068. return esc + first + (rest ? star : '');
  1069. }
  1070. return star;
  1071. }
  1072. return esc ? m : `\\${m}`;
  1073. });
  1074. if (backslashes === true) {
  1075. if (opts.unescape === true) {
  1076. output = output.replace(/\\/g, '');
  1077. } else {
  1078. output = output.replace(/\\+/g, m => {
  1079. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1080. });
  1081. }
  1082. }
  1083. if (output === input && opts.contains === true) {
  1084. state.output = input;
  1085. return state;
  1086. }
  1087. state.output = utils.wrapOutput(output, state, options);
  1088. return state;
  1089. }
  1090. /**
  1091. * Tokenize input until we reach end-of-string
  1092. */
  1093. while (!eos()) {
  1094. value = advance();
  1095. if (value === '\u0000') {
  1096. continue;
  1097. }
  1098. /**
  1099. * Escaped characters
  1100. */
  1101. if (value === '\\') {
  1102. const next = peek();
  1103. if (next === '/' && opts.bash !== true) {
  1104. continue;
  1105. }
  1106. if (next === '.' || next === ';') {
  1107. continue;
  1108. }
  1109. if (!next) {
  1110. value += '\\';
  1111. push({ type: 'text', value });
  1112. continue;
  1113. }
  1114. // collapse slashes to reduce potential for exploits
  1115. const match = /^\\+/.exec(remaining());
  1116. let slashes = 0;
  1117. if (match && match[0].length > 2) {
  1118. slashes = match[0].length;
  1119. state.index += slashes;
  1120. if (slashes % 2 !== 0) {
  1121. value += '\\';
  1122. }
  1123. }
  1124. if (opts.unescape === true) {
  1125. value = advance();
  1126. } else {
  1127. value += advance();
  1128. }
  1129. if (state.brackets === 0) {
  1130. push({ type: 'text', value });
  1131. continue;
  1132. }
  1133. }
  1134. /**
  1135. * If we're inside a regex character class, continue
  1136. * until we reach the closing bracket.
  1137. */
  1138. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1139. if (opts.posix !== false && value === ':') {
  1140. const inner = prev.value.slice(1);
  1141. if (inner.includes('[')) {
  1142. prev.posix = true;
  1143. if (inner.includes(':')) {
  1144. const idx = prev.value.lastIndexOf('[');
  1145. const pre = prev.value.slice(0, idx);
  1146. const rest = prev.value.slice(idx + 2);
  1147. const posix = POSIX_REGEX_SOURCE[rest];
  1148. if (posix) {
  1149. prev.value = pre + posix;
  1150. state.backtrack = true;
  1151. advance();
  1152. if (!bos.output && tokens.indexOf(prev) === 1) {
  1153. bos.output = ONE_CHAR;
  1154. }
  1155. continue;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1161. value = `\\${value}`;
  1162. }
  1163. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1164. value = `\\${value}`;
  1165. }
  1166. if (opts.posix === true && value === '!' && prev.value === '[') {
  1167. value = '^';
  1168. }
  1169. prev.value += value;
  1170. append({ value });
  1171. continue;
  1172. }
  1173. /**
  1174. * If we're inside a quoted string, continue
  1175. * until we reach the closing double quote.
  1176. */
  1177. if (state.quotes === 1 && value !== '"') {
  1178. value = utils.escapeRegex(value);
  1179. prev.value += value;
  1180. append({ value });
  1181. continue;
  1182. }
  1183. /**
  1184. * Double quotes
  1185. */
  1186. if (value === '"') {
  1187. state.quotes = state.quotes === 1 ? 0 : 1;
  1188. if (opts.keepQuotes === true) {
  1189. push({ type: 'text', value });
  1190. }
  1191. continue;
  1192. }
  1193. /**
  1194. * Parentheses
  1195. */
  1196. if (value === '(') {
  1197. increment('parens');
  1198. push({ type: 'paren', value });
  1199. continue;
  1200. }
  1201. if (value === ')') {
  1202. if (state.parens === 0 && opts.strictBrackets === true) {
  1203. throw new SyntaxError(syntaxError('opening', '('));
  1204. }
  1205. const extglob = extglobs[extglobs.length - 1];
  1206. if (extglob && state.parens === extglob.parens + 1) {
  1207. extglobClose(extglobs.pop());
  1208. continue;
  1209. }
  1210. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1211. decrement('parens');
  1212. continue;
  1213. }
  1214. /**
  1215. * Square brackets
  1216. */
  1217. if (value === '[') {
  1218. if (opts.nobracket === true || !remaining().includes(']')) {
  1219. if (opts.nobracket !== true && opts.strictBrackets === true) {
  1220. throw new SyntaxError(syntaxError('closing', ']'));
  1221. }
  1222. value = `\\${value}`;
  1223. } else {
  1224. increment('brackets');
  1225. }
  1226. push({ type: 'bracket', value });
  1227. continue;
  1228. }
  1229. if (value === ']') {
  1230. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  1231. push({ type: 'text', value, output: `\\${value}` });
  1232. continue;
  1233. }
  1234. if (state.brackets === 0) {
  1235. if (opts.strictBrackets === true) {
  1236. throw new SyntaxError(syntaxError('opening', '['));
  1237. }
  1238. push({ type: 'text', value, output: `\\${value}` });
  1239. continue;
  1240. }
  1241. decrement('brackets');
  1242. const prevValue = prev.value.slice(1);
  1243. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  1244. value = `/${value}`;
  1245. }
  1246. prev.value += value;
  1247. append({ value });
  1248. // when literal brackets are explicitly disabled
  1249. // assume we should match with a regex character class
  1250. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  1251. continue;
  1252. }
  1253. const escaped = utils.escapeRegex(prev.value);
  1254. state.output = state.output.slice(0, -prev.value.length);
  1255. // when literal brackets are explicitly enabled
  1256. // assume we should escape the brackets to match literal characters
  1257. if (opts.literalBrackets === true) {
  1258. state.output += escaped;
  1259. prev.value = escaped;
  1260. continue;
  1261. }
  1262. // when the user specifies nothing, try to match both
  1263. prev.value = `(${capture}${escaped}|${prev.value})`;
  1264. state.output += prev.value;
  1265. continue;
  1266. }
  1267. /**
  1268. * Braces
  1269. */
  1270. if (value === '{' && opts.nobrace !== true) {
  1271. increment('braces');
  1272. const open = {
  1273. type: 'brace',
  1274. value,
  1275. output: '(',
  1276. outputIndex: state.output.length,
  1277. tokensIndex: state.tokens.length
  1278. };
  1279. braces.push(open);
  1280. push(open);
  1281. continue;
  1282. }
  1283. if (value === '}') {
  1284. const brace = braces[braces.length - 1];
  1285. if (opts.nobrace === true || !brace) {
  1286. push({ type: 'text', value, output: value });
  1287. continue;
  1288. }
  1289. let output = ')';
  1290. if (brace.dots === true) {
  1291. const arr = tokens.slice();
  1292. const range = [];
  1293. for (let i = arr.length - 1; i >= 0; i--) {
  1294. tokens.pop();
  1295. if (arr[i].type === 'brace') {
  1296. break;
  1297. }
  1298. if (arr[i].type !== 'dots') {
  1299. range.unshift(arr[i].value);
  1300. }
  1301. }
  1302. output = expandRange(range, opts);
  1303. state.backtrack = true;
  1304. }
  1305. if (brace.comma !== true && brace.dots !== true) {
  1306. const out = state.output.slice(0, brace.outputIndex);
  1307. const toks = state.tokens.slice(brace.tokensIndex);
  1308. brace.value = brace.output = '\\{';
  1309. value = output = '\\}';
  1310. state.output = out;
  1311. for (const t of toks) {
  1312. state.output += (t.output || t.value);
  1313. }
  1314. }
  1315. push({ type: 'brace', value, output });
  1316. decrement('braces');
  1317. braces.pop();
  1318. continue;
  1319. }
  1320. /**
  1321. * Pipes
  1322. */
  1323. if (value === '|') {
  1324. if (extglobs.length > 0) {
  1325. extglobs[extglobs.length - 1].conditions++;
  1326. }
  1327. push({ type: 'text', value });
  1328. continue;
  1329. }
  1330. /**
  1331. * Commas
  1332. */
  1333. if (value === ',') {
  1334. let output = value;
  1335. const brace = braces[braces.length - 1];
  1336. if (brace && stack[stack.length - 1] === 'braces') {
  1337. brace.comma = true;
  1338. output = '|';
  1339. }
  1340. push({ type: 'comma', value, output });
  1341. continue;
  1342. }
  1343. /**
  1344. * Slashes
  1345. */
  1346. if (value === '/') {
  1347. // if the beginning of the glob is "./", advance the start
  1348. // to the current index, and don't add the "./" characters
  1349. // to the state. This greatly simplifies lookbehinds when
  1350. // checking for BOS characters like "!" and "." (not "./")
  1351. if (prev.type === 'dot' && state.index === state.start + 1) {
  1352. state.start = state.index + 1;
  1353. state.consumed = '';
  1354. state.output = '';
  1355. tokens.pop();
  1356. prev = bos; // reset "prev" to the first token
  1357. continue;
  1358. }
  1359. push({ type: 'slash', value, output: SLASH_LITERAL });
  1360. continue;
  1361. }
  1362. /**
  1363. * Dots
  1364. */
  1365. if (value === '.') {
  1366. if (state.braces > 0 && prev.type === 'dot') {
  1367. if (prev.value === '.') prev.output = DOT_LITERAL;
  1368. const brace = braces[braces.length - 1];
  1369. prev.type = 'dots';
  1370. prev.output += value;
  1371. prev.value += value;
  1372. brace.dots = true;
  1373. continue;
  1374. }
  1375. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  1376. push({ type: 'text', value, output: DOT_LITERAL });
  1377. continue;
  1378. }
  1379. push({ type: 'dot', value, output: DOT_LITERAL });
  1380. continue;
  1381. }
  1382. /**
  1383. * Question marks
  1384. */
  1385. if (value === '?') {
  1386. const isGroup = prev && prev.value === '(';
  1387. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1388. extglobOpen('qmark', value);
  1389. continue;
  1390. }
  1391. if (prev && prev.type === 'paren') {
  1392. const next = peek();
  1393. let output = value;
  1394. if (next === '<' && !utils.supportsLookbehinds()) {
  1395. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  1396. }
  1397. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  1398. output = `\\${value}`;
  1399. }
  1400. push({ type: 'text', value, output });
  1401. continue;
  1402. }
  1403. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  1404. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  1405. continue;
  1406. }
  1407. push({ type: 'qmark', value, output: QMARK });
  1408. continue;
  1409. }
  1410. /**
  1411. * Exclamation
  1412. */
  1413. if (value === '!') {
  1414. if (opts.noextglob !== true && peek() === '(') {
  1415. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  1416. extglobOpen('negate', value);
  1417. continue;
  1418. }
  1419. }
  1420. if (opts.nonegate !== true && state.index === 0) {
  1421. negate();
  1422. continue;
  1423. }
  1424. }
  1425. /**
  1426. * Plus
  1427. */
  1428. if (value === '+') {
  1429. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1430. extglobOpen('plus', value);
  1431. continue;
  1432. }
  1433. if ((prev && prev.value === '(') || opts.regex === false) {
  1434. push({ type: 'plus', value, output: PLUS_LITERAL });
  1435. continue;
  1436. }
  1437. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  1438. push({ type: 'plus', value });
  1439. continue;
  1440. }
  1441. push({ type: 'plus', value: PLUS_LITERAL });
  1442. continue;
  1443. }
  1444. /**
  1445. * Plain text
  1446. */
  1447. if (value === '@') {
  1448. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1449. push({ type: 'at', extglob: true, value, output: '' });
  1450. continue;
  1451. }
  1452. push({ type: 'text', value });
  1453. continue;
  1454. }
  1455. /**
  1456. * Plain text
  1457. */
  1458. if (value !== '*') {
  1459. if (value === '$' || value === '^') {
  1460. value = `\\${value}`;
  1461. }
  1462. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  1463. if (match) {
  1464. value += match[0];
  1465. state.index += match[0].length;
  1466. }
  1467. push({ type: 'text', value });
  1468. continue;
  1469. }
  1470. /**
  1471. * Stars
  1472. */
  1473. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  1474. prev.type = 'star';
  1475. prev.star = true;
  1476. prev.value += value;
  1477. prev.output = star;
  1478. state.backtrack = true;
  1479. state.globstar = true;
  1480. consume(value);
  1481. continue;
  1482. }
  1483. let rest = remaining();
  1484. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  1485. extglobOpen('star', value);
  1486. continue;
  1487. }
  1488. if (prev.type === 'star') {
  1489. if (opts.noglobstar === true) {
  1490. consume(value);
  1491. continue;
  1492. }
  1493. const prior = prev.prev;
  1494. const before = prior.prev;
  1495. const isStart = prior.type === 'slash' || prior.type === 'bos';
  1496. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  1497. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  1498. push({ type: 'star', value, output: '' });
  1499. continue;
  1500. }
  1501. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  1502. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  1503. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  1504. push({ type: 'star', value, output: '' });
  1505. continue;
  1506. }
  1507. // strip consecutive `/**/`
  1508. while (rest.slice(0, 3) === '/**') {
  1509. const after = input[state.index + 4];
  1510. if (after && after !== '/') {
  1511. break;
  1512. }
  1513. rest = rest.slice(3);
  1514. consume('/**', 3);
  1515. }
  1516. if (prior.type === 'bos' && eos()) {
  1517. prev.type = 'globstar';
  1518. prev.value += value;
  1519. prev.output = globstar(opts);
  1520. state.output = prev.output;
  1521. state.globstar = true;
  1522. consume(value);
  1523. continue;
  1524. }
  1525. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  1526. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1527. prior.output = `(?:${prior.output}`;
  1528. prev.type = 'globstar';
  1529. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  1530. prev.value += value;
  1531. state.globstar = true;
  1532. state.output += prior.output + prev.output;
  1533. consume(value);
  1534. continue;
  1535. }
  1536. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  1537. const end = rest[1] !== void 0 ? '|$' : '';
  1538. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1539. prior.output = `(?:${prior.output}`;
  1540. prev.type = 'globstar';
  1541. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  1542. prev.value += value;
  1543. state.output += prior.output + prev.output;
  1544. state.globstar = true;
  1545. consume(value + advance());
  1546. push({ type: 'slash', value: '/', output: '' });
  1547. continue;
  1548. }
  1549. if (prior.type === 'bos' && rest[0] === '/') {
  1550. prev.type = 'globstar';
  1551. prev.value += value;
  1552. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  1553. state.output = prev.output;
  1554. state.globstar = true;
  1555. consume(value + advance());
  1556. push({ type: 'slash', value: '/', output: '' });
  1557. continue;
  1558. }
  1559. // remove single star from output
  1560. state.output = state.output.slice(0, -prev.output.length);
  1561. // reset previous token to globstar
  1562. prev.type = 'globstar';
  1563. prev.output = globstar(opts);
  1564. prev.value += value;
  1565. // reset output with globstar
  1566. state.output += prev.output;
  1567. state.globstar = true;
  1568. consume(value);
  1569. continue;
  1570. }
  1571. const token = { type: 'star', value, output: star };
  1572. if (opts.bash === true) {
  1573. token.output = '.*?';
  1574. if (prev.type === 'bos' || prev.type === 'slash') {
  1575. token.output = nodot + token.output;
  1576. }
  1577. push(token);
  1578. continue;
  1579. }
  1580. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  1581. token.output = value;
  1582. push(token);
  1583. continue;
  1584. }
  1585. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  1586. if (prev.type === 'dot') {
  1587. state.output += NO_DOT_SLASH;
  1588. prev.output += NO_DOT_SLASH;
  1589. } else if (opts.dot === true) {
  1590. state.output += NO_DOTS_SLASH;
  1591. prev.output += NO_DOTS_SLASH;
  1592. } else {
  1593. state.output += nodot;
  1594. prev.output += nodot;
  1595. }
  1596. if (peek() !== '*') {
  1597. state.output += ONE_CHAR;
  1598. prev.output += ONE_CHAR;
  1599. }
  1600. }
  1601. push(token);
  1602. }
  1603. while (state.brackets > 0) {
  1604. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  1605. state.output = utils.escapeLast(state.output, '[');
  1606. decrement('brackets');
  1607. }
  1608. while (state.parens > 0) {
  1609. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  1610. state.output = utils.escapeLast(state.output, '(');
  1611. decrement('parens');
  1612. }
  1613. while (state.braces > 0) {
  1614. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  1615. state.output = utils.escapeLast(state.output, '{');
  1616. decrement('braces');
  1617. }
  1618. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  1619. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  1620. }
  1621. // rebuild the output if we had to backtrack at any point
  1622. if (state.backtrack === true) {
  1623. state.output = '';
  1624. for (const token of state.tokens) {
  1625. state.output += token.output != null ? token.output : token.value;
  1626. if (token.suffix) {
  1627. state.output += token.suffix;
  1628. }
  1629. }
  1630. }
  1631. return state;
  1632. };
  1633. /**
  1634. * Fast paths for creating regular expressions for common glob patterns.
  1635. * This can significantly speed up processing and has very little downside
  1636. * impact when none of the fast paths match.
  1637. */
  1638. parse.fastpaths = (input, options) => {
  1639. const opts = { ...options };
  1640. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1641. const len = input.length;
  1642. if (len > max) {
  1643. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1644. }
  1645. input = REPLACEMENTS[input] || input;
  1646. const win32 = utils.isWindows(options);
  1647. // create constants based on platform, for windows or posix
  1648. const {
  1649. DOT_LITERAL,
  1650. SLASH_LITERAL,
  1651. ONE_CHAR,
  1652. DOTS_SLASH,
  1653. NO_DOT,
  1654. NO_DOTS,
  1655. NO_DOTS_SLASH,
  1656. STAR,
  1657. START_ANCHOR
  1658. } = constants.globChars(win32);
  1659. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  1660. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  1661. const capture = opts.capture ? '' : '?:';
  1662. const state = { negated: false, prefix: '' };
  1663. let star = opts.bash === true ? '.*?' : STAR;
  1664. if (opts.capture) {
  1665. star = `(${star})`;
  1666. }
  1667. const globstar = opts => {
  1668. if (opts.noglobstar === true) return star;
  1669. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1670. };
  1671. const create = str => {
  1672. switch (str) {
  1673. case '*':
  1674. return `${nodot}${ONE_CHAR}${star}`;
  1675. case '.*':
  1676. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  1677. case '*.*':
  1678. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1679. case '*/*':
  1680. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  1681. case '**':
  1682. return nodot + globstar(opts);
  1683. case '**/*':
  1684. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  1685. case '**/*.*':
  1686. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1687. case '**/.*':
  1688. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  1689. default: {
  1690. const match = /^(.*?)\.(\w+)$/.exec(str);
  1691. if (!match) return;
  1692. const source = create(match[1]);
  1693. if (!source) return;
  1694. return source + DOT_LITERAL + match[2];
  1695. }
  1696. }
  1697. };
  1698. const output = utils.removePrefix(input, state);
  1699. let source = create(output);
  1700. if (source && opts.strictSlashes !== true) {
  1701. source += `${SLASH_LITERAL}?`;
  1702. }
  1703. return source;
  1704. };
  1705. parse_1$2 = parse;
  1706. return parse_1$2;
  1707. }
  1708. var picomatch_1$1;
  1709. var hasRequiredPicomatch$3;
  1710. function requirePicomatch$3 () {
  1711. if (hasRequiredPicomatch$3) return picomatch_1$1;
  1712. hasRequiredPicomatch$3 = 1;
  1713. const path = require$$0$1;
  1714. const scan = /*@__PURE__*/ requireScan$1();
  1715. const parse = /*@__PURE__*/ requireParse$2();
  1716. const utils = /*@__PURE__*/ requireUtils$2();
  1717. const constants = /*@__PURE__*/ requireConstants$3();
  1718. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  1719. /**
  1720. * Creates a matcher function from one or more glob patterns. The
  1721. * returned function takes a string to match as its first argument,
  1722. * and returns true if the string is a match. The returned matcher
  1723. * function also takes a boolean as the second argument that, when true,
  1724. * returns an object with additional information.
  1725. *
  1726. * ```js
  1727. * const picomatch = require('picomatch');
  1728. * // picomatch(glob[, options]);
  1729. *
  1730. * const isMatch = picomatch('*.!(*a)');
  1731. * console.log(isMatch('a.a')); //=> false
  1732. * console.log(isMatch('a.b')); //=> true
  1733. * ```
  1734. * @name picomatch
  1735. * @param {String|Array} `globs` One or more glob patterns.
  1736. * @param {Object=} `options`
  1737. * @return {Function=} Returns a matcher function.
  1738. * @api public
  1739. */
  1740. const picomatch = (glob, options, returnState = false) => {
  1741. if (Array.isArray(glob)) {
  1742. const fns = glob.map(input => picomatch(input, options, returnState));
  1743. const arrayMatcher = str => {
  1744. for (const isMatch of fns) {
  1745. const state = isMatch(str);
  1746. if (state) return state;
  1747. }
  1748. return false;
  1749. };
  1750. return arrayMatcher;
  1751. }
  1752. const isState = isObject(glob) && glob.tokens && glob.input;
  1753. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  1754. throw new TypeError('Expected pattern to be a non-empty string');
  1755. }
  1756. const opts = options || {};
  1757. const posix = utils.isWindows(options);
  1758. const regex = isState
  1759. ? picomatch.compileRe(glob, options)
  1760. : picomatch.makeRe(glob, options, false, true);
  1761. const state = regex.state;
  1762. delete regex.state;
  1763. let isIgnored = () => false;
  1764. if (opts.ignore) {
  1765. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  1766. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  1767. }
  1768. const matcher = (input, returnObject = false) => {
  1769. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  1770. const result = { glob, state, regex, posix, input, output, match, isMatch };
  1771. if (typeof opts.onResult === 'function') {
  1772. opts.onResult(result);
  1773. }
  1774. if (isMatch === false) {
  1775. result.isMatch = false;
  1776. return returnObject ? result : false;
  1777. }
  1778. if (isIgnored(input)) {
  1779. if (typeof opts.onIgnore === 'function') {
  1780. opts.onIgnore(result);
  1781. }
  1782. result.isMatch = false;
  1783. return returnObject ? result : false;
  1784. }
  1785. if (typeof opts.onMatch === 'function') {
  1786. opts.onMatch(result);
  1787. }
  1788. return returnObject ? result : true;
  1789. };
  1790. if (returnState) {
  1791. matcher.state = state;
  1792. }
  1793. return matcher;
  1794. };
  1795. /**
  1796. * Test `input` with the given `regex`. This is used by the main
  1797. * `picomatch()` function to test the input string.
  1798. *
  1799. * ```js
  1800. * const picomatch = require('picomatch');
  1801. * // picomatch.test(input, regex[, options]);
  1802. *
  1803. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  1804. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  1805. * ```
  1806. * @param {String} `input` String to test.
  1807. * @param {RegExp} `regex`
  1808. * @return {Object} Returns an object with matching info.
  1809. * @api public
  1810. */
  1811. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  1812. if (typeof input !== 'string') {
  1813. throw new TypeError('Expected input to be a string');
  1814. }
  1815. if (input === '') {
  1816. return { isMatch: false, output: '' };
  1817. }
  1818. const opts = options || {};
  1819. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  1820. let match = input === glob;
  1821. let output = (match && format) ? format(input) : input;
  1822. if (match === false) {
  1823. output = format ? format(input) : input;
  1824. match = output === glob;
  1825. }
  1826. if (match === false || opts.capture === true) {
  1827. if (opts.matchBase === true || opts.basename === true) {
  1828. match = picomatch.matchBase(input, regex, options, posix);
  1829. } else {
  1830. match = regex.exec(output);
  1831. }
  1832. }
  1833. return { isMatch: Boolean(match), match, output };
  1834. };
  1835. /**
  1836. * Match the basename of a filepath.
  1837. *
  1838. * ```js
  1839. * const picomatch = require('picomatch');
  1840. * // picomatch.matchBase(input, glob[, options]);
  1841. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  1842. * ```
  1843. * @param {String} `input` String to test.
  1844. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  1845. * @return {Boolean}
  1846. * @api public
  1847. */
  1848. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  1849. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  1850. return regex.test(path.basename(input));
  1851. };
  1852. /**
  1853. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  1854. *
  1855. * ```js
  1856. * const picomatch = require('picomatch');
  1857. * // picomatch.isMatch(string, patterns[, options]);
  1858. *
  1859. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  1860. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  1861. * ```
  1862. * @param {String|Array} str The string to test.
  1863. * @param {String|Array} patterns One or more glob patterns to use for matching.
  1864. * @param {Object} [options] See available [options](#options).
  1865. * @return {Boolean} Returns true if any patterns match `str`
  1866. * @api public
  1867. */
  1868. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  1869. /**
  1870. * Parse a glob pattern to create the source string for a regular
  1871. * expression.
  1872. *
  1873. * ```js
  1874. * const picomatch = require('picomatch');
  1875. * const result = picomatch.parse(pattern[, options]);
  1876. * ```
  1877. * @param {String} `pattern`
  1878. * @param {Object} `options`
  1879. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  1880. * @api public
  1881. */
  1882. picomatch.parse = (pattern, options) => {
  1883. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  1884. return parse(pattern, { ...options, fastpaths: false });
  1885. };
  1886. /**
  1887. * Scan a glob pattern to separate the pattern into segments.
  1888. *
  1889. * ```js
  1890. * const picomatch = require('picomatch');
  1891. * // picomatch.scan(input[, options]);
  1892. *
  1893. * const result = picomatch.scan('!./foo/*.js');
  1894. * console.log(result);
  1895. * { prefix: '!./',
  1896. * input: '!./foo/*.js',
  1897. * start: 3,
  1898. * base: 'foo',
  1899. * glob: '*.js',
  1900. * isBrace: false,
  1901. * isBracket: false,
  1902. * isGlob: true,
  1903. * isExtglob: false,
  1904. * isGlobstar: false,
  1905. * negated: true }
  1906. * ```
  1907. * @param {String} `input` Glob pattern to scan.
  1908. * @param {Object} `options`
  1909. * @return {Object} Returns an object with
  1910. * @api public
  1911. */
  1912. picomatch.scan = (input, options) => scan(input, options);
  1913. /**
  1914. * Compile a regular expression from the `state` object returned by the
  1915. * [parse()](#parse) method.
  1916. *
  1917. * @param {Object} `state`
  1918. * @param {Object} `options`
  1919. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  1920. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  1921. * @return {RegExp}
  1922. * @api public
  1923. */
  1924. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  1925. if (returnOutput === true) {
  1926. return state.output;
  1927. }
  1928. const opts = options || {};
  1929. const prepend = opts.contains ? '' : '^';
  1930. const append = opts.contains ? '' : '$';
  1931. let source = `${prepend}(?:${state.output})${append}`;
  1932. if (state && state.negated === true) {
  1933. source = `^(?!${source}).*$`;
  1934. }
  1935. const regex = picomatch.toRegex(source, options);
  1936. if (returnState === true) {
  1937. regex.state = state;
  1938. }
  1939. return regex;
  1940. };
  1941. /**
  1942. * Create a regular expression from a parsed glob pattern.
  1943. *
  1944. * ```js
  1945. * const picomatch = require('picomatch');
  1946. * const state = picomatch.parse('*.js');
  1947. * // picomatch.compileRe(state[, options]);
  1948. *
  1949. * console.log(picomatch.compileRe(state));
  1950. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  1951. * ```
  1952. * @param {String} `state` The object returned from the `.parse` method.
  1953. * @param {Object} `options`
  1954. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  1955. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  1956. * @return {RegExp} Returns a regex created from the given pattern.
  1957. * @api public
  1958. */
  1959. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  1960. if (!input || typeof input !== 'string') {
  1961. throw new TypeError('Expected a non-empty string');
  1962. }
  1963. let parsed = { negated: false, fastpaths: true };
  1964. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  1965. parsed.output = parse.fastpaths(input, options);
  1966. }
  1967. if (!parsed.output) {
  1968. parsed = parse(input, options);
  1969. }
  1970. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  1971. };
  1972. /**
  1973. * Create a regular expression from the given regex source string.
  1974. *
  1975. * ```js
  1976. * const picomatch = require('picomatch');
  1977. * // picomatch.toRegex(source[, options]);
  1978. *
  1979. * const { output } = picomatch.parse('*.js');
  1980. * console.log(picomatch.toRegex(output));
  1981. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  1982. * ```
  1983. * @param {String} `source` Regular expression source string.
  1984. * @param {Object} `options`
  1985. * @return {RegExp}
  1986. * @api public
  1987. */
  1988. picomatch.toRegex = (source, options) => {
  1989. try {
  1990. const opts = options || {};
  1991. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  1992. } catch (err) {
  1993. if (options && options.debug === true) throw err;
  1994. return /$^/;
  1995. }
  1996. };
  1997. /**
  1998. * Picomatch constants.
  1999. * @return {Object}
  2000. */
  2001. picomatch.constants = constants;
  2002. /**
  2003. * Expose "picomatch"
  2004. */
  2005. picomatch_1$1 = picomatch;
  2006. return picomatch_1$1;
  2007. }
  2008. var picomatch$1;
  2009. var hasRequiredPicomatch$2;
  2010. function requirePicomatch$2 () {
  2011. if (hasRequiredPicomatch$2) return picomatch$1;
  2012. hasRequiredPicomatch$2 = 1;
  2013. picomatch$1 = /*@__PURE__*/ requirePicomatch$3();
  2014. return picomatch$1;
  2015. }
  2016. var readdirp_1;
  2017. var hasRequiredReaddirp;
  2018. function requireReaddirp () {
  2019. if (hasRequiredReaddirp) return readdirp_1;
  2020. hasRequiredReaddirp = 1;
  2021. const fs = require$$0$2;
  2022. const { Readable } = require$$1;
  2023. const sysPath = require$$0$1;
  2024. const { promisify } = require$$2;
  2025. const picomatch = /*@__PURE__*/ requirePicomatch$2();
  2026. const readdir = promisify(fs.readdir);
  2027. const stat = promisify(fs.stat);
  2028. const lstat = promisify(fs.lstat);
  2029. const realpath = promisify(fs.realpath);
  2030. /**
  2031. * @typedef {Object} EntryInfo
  2032. * @property {String} path
  2033. * @property {String} fullPath
  2034. * @property {fs.Stats=} stats
  2035. * @property {fs.Dirent=} dirent
  2036. * @property {String} basename
  2037. */
  2038. const BANG = '!';
  2039. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  2040. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  2041. const FILE_TYPE = 'files';
  2042. const DIR_TYPE = 'directories';
  2043. const FILE_DIR_TYPE = 'files_directories';
  2044. const EVERYTHING_TYPE = 'all';
  2045. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  2046. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  2047. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  2048. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  2049. const normalizeFilter = filter => {
  2050. if (filter === undefined) return;
  2051. if (typeof filter === 'function') return filter;
  2052. if (typeof filter === 'string') {
  2053. const glob = picomatch(filter.trim());
  2054. return entry => glob(entry.basename);
  2055. }
  2056. if (Array.isArray(filter)) {
  2057. const positive = [];
  2058. const negative = [];
  2059. for (const item of filter) {
  2060. const trimmed = item.trim();
  2061. if (trimmed.charAt(0) === BANG) {
  2062. negative.push(picomatch(trimmed.slice(1)));
  2063. } else {
  2064. positive.push(picomatch(trimmed));
  2065. }
  2066. }
  2067. if (negative.length > 0) {
  2068. if (positive.length > 0) {
  2069. return entry =>
  2070. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  2071. }
  2072. return entry => !negative.some(f => f(entry.basename));
  2073. }
  2074. return entry => positive.some(f => f(entry.basename));
  2075. }
  2076. };
  2077. class ReaddirpStream extends Readable {
  2078. static get defaultOptions() {
  2079. return {
  2080. root: '.',
  2081. /* eslint-disable no-unused-vars */
  2082. fileFilter: (path) => true,
  2083. directoryFilter: (path) => true,
  2084. /* eslint-enable no-unused-vars */
  2085. type: FILE_TYPE,
  2086. lstat: false,
  2087. depth: 2147483648,
  2088. alwaysStat: false
  2089. };
  2090. }
  2091. constructor(options = {}) {
  2092. super({
  2093. objectMode: true,
  2094. autoDestroy: true,
  2095. highWaterMark: options.highWaterMark || 4096
  2096. });
  2097. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  2098. const { root, type } = opts;
  2099. this._fileFilter = normalizeFilter(opts.fileFilter);
  2100. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  2101. const statMethod = opts.lstat ? lstat : stat;
  2102. // Use bigint stats if it's windows and stat() supports options (node 10+).
  2103. if (wantBigintFsStats) {
  2104. this._stat = path => statMethod(path, { bigint: true });
  2105. } else {
  2106. this._stat = statMethod;
  2107. }
  2108. this._maxDepth = opts.depth;
  2109. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  2110. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  2111. this._wantsEverything = type === EVERYTHING_TYPE;
  2112. this._root = sysPath.resolve(root);
  2113. this._isDirent = ('Dirent' in fs) && !opts.alwaysStat;
  2114. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  2115. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  2116. // Launch stream with one parent, the root dir.
  2117. this.parents = [this._exploreDir(root, 1)];
  2118. this.reading = false;
  2119. this.parent = undefined;
  2120. }
  2121. async _read(batch) {
  2122. if (this.reading) return;
  2123. this.reading = true;
  2124. try {
  2125. while (!this.destroyed && batch > 0) {
  2126. const { path, depth, files = [] } = this.parent || {};
  2127. if (files.length > 0) {
  2128. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  2129. for (const entry of await Promise.all(slice)) {
  2130. if (this.destroyed) return;
  2131. const entryType = await this._getEntryType(entry);
  2132. if (entryType === 'directory' && this._directoryFilter(entry)) {
  2133. if (depth <= this._maxDepth) {
  2134. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  2135. }
  2136. if (this._wantsDir) {
  2137. this.push(entry);
  2138. batch--;
  2139. }
  2140. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  2141. if (this._wantsFile) {
  2142. this.push(entry);
  2143. batch--;
  2144. }
  2145. }
  2146. }
  2147. } else {
  2148. const parent = this.parents.pop();
  2149. if (!parent) {
  2150. this.push(null);
  2151. break;
  2152. }
  2153. this.parent = await parent;
  2154. if (this.destroyed) return;
  2155. }
  2156. }
  2157. } catch (error) {
  2158. this.destroy(error);
  2159. } finally {
  2160. this.reading = false;
  2161. }
  2162. }
  2163. async _exploreDir(path, depth) {
  2164. let files;
  2165. try {
  2166. files = await readdir(path, this._rdOptions);
  2167. } catch (error) {
  2168. this._onError(error);
  2169. }
  2170. return { files, depth, path };
  2171. }
  2172. async _formatEntry(dirent, path) {
  2173. let entry;
  2174. try {
  2175. const basename = this._isDirent ? dirent.name : dirent;
  2176. const fullPath = sysPath.resolve(sysPath.join(path, basename));
  2177. entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename };
  2178. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  2179. } catch (err) {
  2180. this._onError(err);
  2181. }
  2182. return entry;
  2183. }
  2184. _onError(err) {
  2185. if (isNormalFlowError(err) && !this.destroyed) {
  2186. this.emit('warn', err);
  2187. } else {
  2188. this.destroy(err);
  2189. }
  2190. }
  2191. async _getEntryType(entry) {
  2192. // entry may be undefined, because a warning or an error were emitted
  2193. // and the statsProp is undefined
  2194. const stats = entry && entry[this._statsProp];
  2195. if (!stats) {
  2196. return;
  2197. }
  2198. if (stats.isFile()) {
  2199. return 'file';
  2200. }
  2201. if (stats.isDirectory()) {
  2202. return 'directory';
  2203. }
  2204. if (stats && stats.isSymbolicLink()) {
  2205. const full = entry.fullPath;
  2206. try {
  2207. const entryRealPath = await realpath(full);
  2208. const entryRealPathStats = await lstat(entryRealPath);
  2209. if (entryRealPathStats.isFile()) {
  2210. return 'file';
  2211. }
  2212. if (entryRealPathStats.isDirectory()) {
  2213. const len = entryRealPath.length;
  2214. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) {
  2215. const recursiveError = new Error(
  2216. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  2217. );
  2218. recursiveError.code = RECURSIVE_ERROR_CODE;
  2219. return this._onError(recursiveError);
  2220. }
  2221. return 'directory';
  2222. }
  2223. } catch (error) {
  2224. this._onError(error);
  2225. }
  2226. }
  2227. }
  2228. _includeAsFile(entry) {
  2229. const stats = entry && entry[this._statsProp];
  2230. return stats && this._wantsEverything && !stats.isDirectory();
  2231. }
  2232. }
  2233. /**
  2234. * @typedef {Object} ReaddirpArguments
  2235. * @property {Function=} fileFilter
  2236. * @property {Function=} directoryFilter
  2237. * @property {String=} type
  2238. * @property {Number=} depth
  2239. * @property {String=} root
  2240. * @property {Boolean=} lstat
  2241. * @property {Boolean=} bigint
  2242. */
  2243. /**
  2244. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  2245. * @param {String} root Root directory
  2246. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  2247. */
  2248. const readdirp = (root, options = {}) => {
  2249. let type = options.entryType || options.type;
  2250. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  2251. if (type) options.type = type;
  2252. if (!root) {
  2253. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  2254. } else if (typeof root !== 'string') {
  2255. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  2256. } else if (type && !ALL_TYPES.includes(type)) {
  2257. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  2258. }
  2259. options.root = root;
  2260. return new ReaddirpStream(options);
  2261. };
  2262. const readdirpPromise = (root, options = {}) => {
  2263. return new Promise((resolve, reject) => {
  2264. const files = [];
  2265. readdirp(root, options)
  2266. .on('data', entry => files.push(entry))
  2267. .on('end', () => resolve(files))
  2268. .on('error', error => reject(error));
  2269. });
  2270. };
  2271. readdirp.promise = readdirpPromise;
  2272. readdirp.ReaddirpStream = ReaddirpStream;
  2273. readdirp.default = readdirp;
  2274. readdirp_1 = readdirp;
  2275. return readdirp_1;
  2276. }
  2277. var anymatch = {exports: {}};
  2278. var utils$1 = {};
  2279. var constants$2;
  2280. var hasRequiredConstants$2;
  2281. function requireConstants$2 () {
  2282. if (hasRequiredConstants$2) return constants$2;
  2283. hasRequiredConstants$2 = 1;
  2284. const path = require$$0$1;
  2285. const WIN_SLASH = '\\\\/';
  2286. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2287. const DEFAULT_MAX_EXTGLOB_RECURSION = 0;
  2288. /**
  2289. * Posix glob regex
  2290. */
  2291. const DOT_LITERAL = '\\.';
  2292. const PLUS_LITERAL = '\\+';
  2293. const QMARK_LITERAL = '\\?';
  2294. const SLASH_LITERAL = '\\/';
  2295. const ONE_CHAR = '(?=.)';
  2296. const QMARK = '[^/]';
  2297. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2298. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2299. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2300. const NO_DOT = `(?!${DOT_LITERAL})`;
  2301. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2302. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2303. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2304. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2305. const STAR = `${QMARK}*?`;
  2306. const POSIX_CHARS = {
  2307. DOT_LITERAL,
  2308. PLUS_LITERAL,
  2309. QMARK_LITERAL,
  2310. SLASH_LITERAL,
  2311. ONE_CHAR,
  2312. QMARK,
  2313. END_ANCHOR,
  2314. DOTS_SLASH,
  2315. NO_DOT,
  2316. NO_DOTS,
  2317. NO_DOT_SLASH,
  2318. NO_DOTS_SLASH,
  2319. QMARK_NO_DOT,
  2320. STAR,
  2321. START_ANCHOR
  2322. };
  2323. /**
  2324. * Windows glob regex
  2325. */
  2326. const WINDOWS_CHARS = {
  2327. ...POSIX_CHARS,
  2328. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2329. QMARK: WIN_NO_SLASH,
  2330. STAR: `${WIN_NO_SLASH}*?`,
  2331. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2332. NO_DOT: `(?!${DOT_LITERAL})`,
  2333. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2334. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2335. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2336. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2337. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2338. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2339. };
  2340. /**
  2341. * POSIX Bracket Regex
  2342. */
  2343. const POSIX_REGEX_SOURCE = {
  2344. __proto__: null,
  2345. alnum: 'a-zA-Z0-9',
  2346. alpha: 'a-zA-Z',
  2347. ascii: '\\x00-\\x7F',
  2348. blank: ' \\t',
  2349. cntrl: '\\x00-\\x1F\\x7F',
  2350. digit: '0-9',
  2351. graph: '\\x21-\\x7E',
  2352. lower: 'a-z',
  2353. print: '\\x20-\\x7E ',
  2354. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2355. space: ' \\t\\r\\n\\v\\f',
  2356. upper: 'A-Z',
  2357. word: 'A-Za-z0-9_',
  2358. xdigit: 'A-Fa-f0-9'
  2359. };
  2360. constants$2 = {
  2361. DEFAULT_MAX_EXTGLOB_RECURSION,
  2362. MAX_LENGTH: 1024 * 64,
  2363. POSIX_REGEX_SOURCE,
  2364. // regular expressions
  2365. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2366. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2367. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2368. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2369. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2370. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2371. // Replace globs with equivalent patterns to reduce parsing time.
  2372. REPLACEMENTS: {
  2373. __proto__: null,
  2374. '***': '*',
  2375. '**/**': '**',
  2376. '**/**/**': '**'
  2377. },
  2378. // Digits
  2379. CHAR_0: 48, /* 0 */
  2380. CHAR_9: 57, /* 9 */
  2381. // Alphabet chars.
  2382. CHAR_UPPERCASE_A: 65, /* A */
  2383. CHAR_LOWERCASE_A: 97, /* a */
  2384. CHAR_UPPERCASE_Z: 90, /* Z */
  2385. CHAR_LOWERCASE_Z: 122, /* z */
  2386. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2387. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2388. CHAR_ASTERISK: 42, /* * */
  2389. // Non-alphabetic chars.
  2390. CHAR_AMPERSAND: 38, /* & */
  2391. CHAR_AT: 64, /* @ */
  2392. CHAR_BACKWARD_SLASH: 92, /* \ */
  2393. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2394. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2395. CHAR_COLON: 58, /* : */
  2396. CHAR_COMMA: 44, /* , */
  2397. CHAR_DOT: 46, /* . */
  2398. CHAR_DOUBLE_QUOTE: 34, /* " */
  2399. CHAR_EQUAL: 61, /* = */
  2400. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2401. CHAR_FORM_FEED: 12, /* \f */
  2402. CHAR_FORWARD_SLASH: 47, /* / */
  2403. CHAR_GRAVE_ACCENT: 96, /* ` */
  2404. CHAR_HASH: 35, /* # */
  2405. CHAR_HYPHEN_MINUS: 45, /* - */
  2406. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2407. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2408. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2409. CHAR_LINE_FEED: 10, /* \n */
  2410. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2411. CHAR_PERCENT: 37, /* % */
  2412. CHAR_PLUS: 43, /* + */
  2413. CHAR_QUESTION_MARK: 63, /* ? */
  2414. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2415. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2416. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2417. CHAR_SEMICOLON: 59, /* ; */
  2418. CHAR_SINGLE_QUOTE: 39, /* ' */
  2419. CHAR_SPACE: 32, /* */
  2420. CHAR_TAB: 9, /* \t */
  2421. CHAR_UNDERSCORE: 95, /* _ */
  2422. CHAR_VERTICAL_LINE: 124, /* | */
  2423. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2424. SEP: path.sep,
  2425. /**
  2426. * Create EXTGLOB_CHARS
  2427. */
  2428. extglobChars(chars) {
  2429. return {
  2430. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2431. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2432. '+': { type: 'plus', open: '(?:', close: ')+' },
  2433. '*': { type: 'star', open: '(?:', close: ')*' },
  2434. '@': { type: 'at', open: '(?:', close: ')' }
  2435. };
  2436. },
  2437. /**
  2438. * Create GLOB_CHARS
  2439. */
  2440. globChars(win32) {
  2441. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2442. }
  2443. };
  2444. return constants$2;
  2445. }
  2446. var hasRequiredUtils$1;
  2447. function requireUtils$1 () {
  2448. if (hasRequiredUtils$1) return utils$1;
  2449. hasRequiredUtils$1 = 1;
  2450. (function (exports$1) {
  2451. const path = require$$0$1;
  2452. const win32 = process.platform === 'win32';
  2453. const {
  2454. REGEX_BACKSLASH,
  2455. REGEX_REMOVE_BACKSLASH,
  2456. REGEX_SPECIAL_CHARS,
  2457. REGEX_SPECIAL_CHARS_GLOBAL
  2458. } = /*@__PURE__*/ requireConstants$2();
  2459. exports$1.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2460. exports$1.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2461. exports$1.isRegexChar = str => str.length === 1 && exports$1.hasRegexChars(str);
  2462. exports$1.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2463. exports$1.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2464. exports$1.removeBackslashes = str => {
  2465. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2466. return match === '\\' ? '' : match;
  2467. });
  2468. };
  2469. exports$1.supportsLookbehinds = () => {
  2470. const segs = process.version.slice(1).split('.').map(Number);
  2471. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2472. return true;
  2473. }
  2474. return false;
  2475. };
  2476. exports$1.isWindows = options => {
  2477. if (options && typeof options.windows === 'boolean') {
  2478. return options.windows;
  2479. }
  2480. return win32 === true || path.sep === '\\';
  2481. };
  2482. exports$1.escapeLast = (input, char, lastIdx) => {
  2483. const idx = input.lastIndexOf(char, lastIdx);
  2484. if (idx === -1) return input;
  2485. if (input[idx - 1] === '\\') return exports$1.escapeLast(input, char, idx - 1);
  2486. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2487. };
  2488. exports$1.removePrefix = (input, state = {}) => {
  2489. let output = input;
  2490. if (output.startsWith('./')) {
  2491. output = output.slice(2);
  2492. state.prefix = './';
  2493. }
  2494. return output;
  2495. };
  2496. exports$1.wrapOutput = (input, state = {}, options = {}) => {
  2497. const prepend = options.contains ? '' : '^';
  2498. const append = options.contains ? '' : '$';
  2499. let output = `${prepend}(?:${input})${append}`;
  2500. if (state.negated === true) {
  2501. output = `(?:^(?!${output}).*$)`;
  2502. }
  2503. return output;
  2504. };
  2505. } (utils$1));
  2506. return utils$1;
  2507. }
  2508. var scan_1;
  2509. var hasRequiredScan;
  2510. function requireScan () {
  2511. if (hasRequiredScan) return scan_1;
  2512. hasRequiredScan = 1;
  2513. const utils = /*@__PURE__*/ requireUtils$1();
  2514. const {
  2515. CHAR_ASTERISK, /* * */
  2516. CHAR_AT, /* @ */
  2517. CHAR_BACKWARD_SLASH, /* \ */
  2518. CHAR_COMMA, /* , */
  2519. CHAR_DOT, /* . */
  2520. CHAR_EXCLAMATION_MARK, /* ! */
  2521. CHAR_FORWARD_SLASH, /* / */
  2522. CHAR_LEFT_CURLY_BRACE, /* { */
  2523. CHAR_LEFT_PARENTHESES, /* ( */
  2524. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2525. CHAR_PLUS, /* + */
  2526. CHAR_QUESTION_MARK, /* ? */
  2527. CHAR_RIGHT_CURLY_BRACE, /* } */
  2528. CHAR_RIGHT_PARENTHESES, /* ) */
  2529. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2530. } = /*@__PURE__*/ requireConstants$2();
  2531. const isPathSeparator = code => {
  2532. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2533. };
  2534. const depth = token => {
  2535. if (token.isPrefix !== true) {
  2536. token.depth = token.isGlobstar ? Infinity : 1;
  2537. }
  2538. };
  2539. /**
  2540. * Quickly scans a glob pattern and returns an object with a handful of
  2541. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2542. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2543. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2544. *
  2545. * ```js
  2546. * const pm = require('picomatch');
  2547. * console.log(pm.scan('foo/bar/*.js'));
  2548. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2549. * ```
  2550. * @param {String} `str`
  2551. * @param {Object} `options`
  2552. * @return {Object} Returns an object with tokens and regex source string.
  2553. * @api public
  2554. */
  2555. const scan = (input, options) => {
  2556. const opts = options || {};
  2557. const length = input.length - 1;
  2558. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2559. const slashes = [];
  2560. const tokens = [];
  2561. const parts = [];
  2562. let str = input;
  2563. let index = -1;
  2564. let start = 0;
  2565. let lastIndex = 0;
  2566. let isBrace = false;
  2567. let isBracket = false;
  2568. let isGlob = false;
  2569. let isExtglob = false;
  2570. let isGlobstar = false;
  2571. let braceEscaped = false;
  2572. let backslashes = false;
  2573. let negated = false;
  2574. let negatedExtglob = false;
  2575. let finished = false;
  2576. let braces = 0;
  2577. let prev;
  2578. let code;
  2579. let token = { value: '', depth: 0, isGlob: false };
  2580. const eos = () => index >= length;
  2581. const peek = () => str.charCodeAt(index + 1);
  2582. const advance = () => {
  2583. prev = code;
  2584. return str.charCodeAt(++index);
  2585. };
  2586. while (index < length) {
  2587. code = advance();
  2588. let next;
  2589. if (code === CHAR_BACKWARD_SLASH) {
  2590. backslashes = token.backslashes = true;
  2591. code = advance();
  2592. if (code === CHAR_LEFT_CURLY_BRACE) {
  2593. braceEscaped = true;
  2594. }
  2595. continue;
  2596. }
  2597. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2598. braces++;
  2599. while (eos() !== true && (code = advance())) {
  2600. if (code === CHAR_BACKWARD_SLASH) {
  2601. backslashes = token.backslashes = true;
  2602. advance();
  2603. continue;
  2604. }
  2605. if (code === CHAR_LEFT_CURLY_BRACE) {
  2606. braces++;
  2607. continue;
  2608. }
  2609. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2610. isBrace = token.isBrace = true;
  2611. isGlob = token.isGlob = true;
  2612. finished = true;
  2613. if (scanToEnd === true) {
  2614. continue;
  2615. }
  2616. break;
  2617. }
  2618. if (braceEscaped !== true && code === CHAR_COMMA) {
  2619. isBrace = token.isBrace = true;
  2620. isGlob = token.isGlob = true;
  2621. finished = true;
  2622. if (scanToEnd === true) {
  2623. continue;
  2624. }
  2625. break;
  2626. }
  2627. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2628. braces--;
  2629. if (braces === 0) {
  2630. braceEscaped = false;
  2631. isBrace = token.isBrace = true;
  2632. finished = true;
  2633. break;
  2634. }
  2635. }
  2636. }
  2637. if (scanToEnd === true) {
  2638. continue;
  2639. }
  2640. break;
  2641. }
  2642. if (code === CHAR_FORWARD_SLASH) {
  2643. slashes.push(index);
  2644. tokens.push(token);
  2645. token = { value: '', depth: 0, isGlob: false };
  2646. if (finished === true) continue;
  2647. if (prev === CHAR_DOT && index === (start + 1)) {
  2648. start += 2;
  2649. continue;
  2650. }
  2651. lastIndex = index + 1;
  2652. continue;
  2653. }
  2654. if (opts.noext !== true) {
  2655. const isExtglobChar = code === CHAR_PLUS
  2656. || code === CHAR_AT
  2657. || code === CHAR_ASTERISK
  2658. || code === CHAR_QUESTION_MARK
  2659. || code === CHAR_EXCLAMATION_MARK;
  2660. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  2661. isGlob = token.isGlob = true;
  2662. isExtglob = token.isExtglob = true;
  2663. finished = true;
  2664. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2665. negatedExtglob = true;
  2666. }
  2667. if (scanToEnd === true) {
  2668. while (eos() !== true && (code = advance())) {
  2669. if (code === CHAR_BACKWARD_SLASH) {
  2670. backslashes = token.backslashes = true;
  2671. code = advance();
  2672. continue;
  2673. }
  2674. if (code === CHAR_RIGHT_PARENTHESES) {
  2675. isGlob = token.isGlob = true;
  2676. finished = true;
  2677. break;
  2678. }
  2679. }
  2680. continue;
  2681. }
  2682. break;
  2683. }
  2684. }
  2685. if (code === CHAR_ASTERISK) {
  2686. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2687. isGlob = token.isGlob = true;
  2688. finished = true;
  2689. if (scanToEnd === true) {
  2690. continue;
  2691. }
  2692. break;
  2693. }
  2694. if (code === CHAR_QUESTION_MARK) {
  2695. isGlob = token.isGlob = true;
  2696. finished = true;
  2697. if (scanToEnd === true) {
  2698. continue;
  2699. }
  2700. break;
  2701. }
  2702. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  2703. while (eos() !== true && (next = advance())) {
  2704. if (next === CHAR_BACKWARD_SLASH) {
  2705. backslashes = token.backslashes = true;
  2706. advance();
  2707. continue;
  2708. }
  2709. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  2710. isBracket = token.isBracket = true;
  2711. isGlob = token.isGlob = true;
  2712. finished = true;
  2713. break;
  2714. }
  2715. }
  2716. if (scanToEnd === true) {
  2717. continue;
  2718. }
  2719. break;
  2720. }
  2721. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2722. negated = token.negated = true;
  2723. start++;
  2724. continue;
  2725. }
  2726. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  2727. isGlob = token.isGlob = true;
  2728. if (scanToEnd === true) {
  2729. while (eos() !== true && (code = advance())) {
  2730. if (code === CHAR_LEFT_PARENTHESES) {
  2731. backslashes = token.backslashes = true;
  2732. code = advance();
  2733. continue;
  2734. }
  2735. if (code === CHAR_RIGHT_PARENTHESES) {
  2736. finished = true;
  2737. break;
  2738. }
  2739. }
  2740. continue;
  2741. }
  2742. break;
  2743. }
  2744. if (isGlob === true) {
  2745. finished = true;
  2746. if (scanToEnd === true) {
  2747. continue;
  2748. }
  2749. break;
  2750. }
  2751. }
  2752. if (opts.noext === true) {
  2753. isExtglob = false;
  2754. isGlob = false;
  2755. }
  2756. let base = str;
  2757. let prefix = '';
  2758. let glob = '';
  2759. if (start > 0) {
  2760. prefix = str.slice(0, start);
  2761. str = str.slice(start);
  2762. lastIndex -= start;
  2763. }
  2764. if (base && isGlob === true && lastIndex > 0) {
  2765. base = str.slice(0, lastIndex);
  2766. glob = str.slice(lastIndex);
  2767. } else if (isGlob === true) {
  2768. base = '';
  2769. glob = str;
  2770. } else {
  2771. base = str;
  2772. }
  2773. if (base && base !== '' && base !== '/' && base !== str) {
  2774. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2775. base = base.slice(0, -1);
  2776. }
  2777. }
  2778. if (opts.unescape === true) {
  2779. if (glob) glob = utils.removeBackslashes(glob);
  2780. if (base && backslashes === true) {
  2781. base = utils.removeBackslashes(base);
  2782. }
  2783. }
  2784. const state = {
  2785. prefix,
  2786. input,
  2787. start,
  2788. base,
  2789. glob,
  2790. isBrace,
  2791. isBracket,
  2792. isGlob,
  2793. isExtglob,
  2794. isGlobstar,
  2795. negated,
  2796. negatedExtglob
  2797. };
  2798. if (opts.tokens === true) {
  2799. state.maxDepth = 0;
  2800. if (!isPathSeparator(code)) {
  2801. tokens.push(token);
  2802. }
  2803. state.tokens = tokens;
  2804. }
  2805. if (opts.parts === true || opts.tokens === true) {
  2806. let prevIndex;
  2807. for (let idx = 0; idx < slashes.length; idx++) {
  2808. const n = prevIndex ? prevIndex + 1 : start;
  2809. const i = slashes[idx];
  2810. const value = input.slice(n, i);
  2811. if (opts.tokens) {
  2812. if (idx === 0 && start !== 0) {
  2813. tokens[idx].isPrefix = true;
  2814. tokens[idx].value = prefix;
  2815. } else {
  2816. tokens[idx].value = value;
  2817. }
  2818. depth(tokens[idx]);
  2819. state.maxDepth += tokens[idx].depth;
  2820. }
  2821. if (idx !== 0 || value !== '') {
  2822. parts.push(value);
  2823. }
  2824. prevIndex = i;
  2825. }
  2826. if (prevIndex && prevIndex + 1 < input.length) {
  2827. const value = input.slice(prevIndex + 1);
  2828. parts.push(value);
  2829. if (opts.tokens) {
  2830. tokens[tokens.length - 1].value = value;
  2831. depth(tokens[tokens.length - 1]);
  2832. state.maxDepth += tokens[tokens.length - 1].depth;
  2833. }
  2834. }
  2835. state.slashes = slashes;
  2836. state.parts = parts;
  2837. }
  2838. return state;
  2839. };
  2840. scan_1 = scan;
  2841. return scan_1;
  2842. }
  2843. var parse_1$1;
  2844. var hasRequiredParse$1;
  2845. function requireParse$1 () {
  2846. if (hasRequiredParse$1) return parse_1$1;
  2847. hasRequiredParse$1 = 1;
  2848. const constants = /*@__PURE__*/ requireConstants$2();
  2849. const utils = /*@__PURE__*/ requireUtils$1();
  2850. /**
  2851. * Constants
  2852. */
  2853. const {
  2854. MAX_LENGTH,
  2855. POSIX_REGEX_SOURCE,
  2856. REGEX_NON_SPECIAL_CHARS,
  2857. REGEX_SPECIAL_CHARS_BACKREF,
  2858. REPLACEMENTS
  2859. } = constants;
  2860. /**
  2861. * Helpers
  2862. */
  2863. const expandRange = (args, options) => {
  2864. if (typeof options.expandRange === 'function') {
  2865. return options.expandRange(...args, options);
  2866. }
  2867. args.sort();
  2868. const value = `[${args.join('-')}]`;
  2869. return value;
  2870. };
  2871. /**
  2872. * Create the message for a syntax error
  2873. */
  2874. const syntaxError = (type, char) => {
  2875. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2876. };
  2877. const splitTopLevel = input => {
  2878. const parts = [];
  2879. let bracket = 0;
  2880. let paren = 0;
  2881. let quote = 0;
  2882. let value = '';
  2883. let escaped = false;
  2884. for (const ch of input) {
  2885. if (escaped === true) {
  2886. value += ch;
  2887. escaped = false;
  2888. continue;
  2889. }
  2890. if (ch === '\\') {
  2891. value += ch;
  2892. escaped = true;
  2893. continue;
  2894. }
  2895. if (ch === '"') {
  2896. quote = quote === 1 ? 0 : 1;
  2897. value += ch;
  2898. continue;
  2899. }
  2900. if (quote === 0) {
  2901. if (ch === '[') {
  2902. bracket++;
  2903. } else if (ch === ']' && bracket > 0) {
  2904. bracket--;
  2905. } else if (bracket === 0) {
  2906. if (ch === '(') {
  2907. paren++;
  2908. } else if (ch === ')' && paren > 0) {
  2909. paren--;
  2910. } else if (ch === '|' && paren === 0) {
  2911. parts.push(value);
  2912. value = '';
  2913. continue;
  2914. }
  2915. }
  2916. }
  2917. value += ch;
  2918. }
  2919. parts.push(value);
  2920. return parts;
  2921. };
  2922. const isPlainBranch = branch => {
  2923. let escaped = false;
  2924. for (const ch of branch) {
  2925. if (escaped === true) {
  2926. escaped = false;
  2927. continue;
  2928. }
  2929. if (ch === '\\') {
  2930. escaped = true;
  2931. continue;
  2932. }
  2933. if (/[?*+@!()[\]{}]/.test(ch)) {
  2934. return false;
  2935. }
  2936. }
  2937. return true;
  2938. };
  2939. const normalizeSimpleBranch = branch => {
  2940. let value = branch.trim();
  2941. let changed = true;
  2942. while (changed === true) {
  2943. changed = false;
  2944. if (/^@\([^\\()[\]{}|]+\)$/.test(value)) {
  2945. value = value.slice(2, -1);
  2946. changed = true;
  2947. }
  2948. }
  2949. if (!isPlainBranch(value)) {
  2950. return;
  2951. }
  2952. return value.replace(/\\(.)/g, '$1');
  2953. };
  2954. const hasRepeatedCharPrefixOverlap = branches => {
  2955. const values = branches.map(normalizeSimpleBranch).filter(Boolean);
  2956. for (let i = 0; i < values.length; i++) {
  2957. for (let j = i + 1; j < values.length; j++) {
  2958. const a = values[i];
  2959. const b = values[j];
  2960. const char = a[0];
  2961. if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) {
  2962. continue;
  2963. }
  2964. if (a === b || a.startsWith(b) || b.startsWith(a)) {
  2965. return true;
  2966. }
  2967. }
  2968. }
  2969. return false;
  2970. };
  2971. const parseRepeatedExtglob = (pattern, requireEnd = true) => {
  2972. if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') {
  2973. return;
  2974. }
  2975. let bracket = 0;
  2976. let paren = 0;
  2977. let quote = 0;
  2978. let escaped = false;
  2979. for (let i = 1; i < pattern.length; i++) {
  2980. const ch = pattern[i];
  2981. if (escaped === true) {
  2982. escaped = false;
  2983. continue;
  2984. }
  2985. if (ch === '\\') {
  2986. escaped = true;
  2987. continue;
  2988. }
  2989. if (ch === '"') {
  2990. quote = quote === 1 ? 0 : 1;
  2991. continue;
  2992. }
  2993. if (quote === 1) {
  2994. continue;
  2995. }
  2996. if (ch === '[') {
  2997. bracket++;
  2998. continue;
  2999. }
  3000. if (ch === ']' && bracket > 0) {
  3001. bracket--;
  3002. continue;
  3003. }
  3004. if (bracket > 0) {
  3005. continue;
  3006. }
  3007. if (ch === '(') {
  3008. paren++;
  3009. continue;
  3010. }
  3011. if (ch === ')') {
  3012. paren--;
  3013. if (paren === 0) {
  3014. if (requireEnd === true && i !== pattern.length - 1) {
  3015. return;
  3016. }
  3017. return {
  3018. type: pattern[0],
  3019. body: pattern.slice(2, i),
  3020. end: i
  3021. };
  3022. }
  3023. }
  3024. }
  3025. };
  3026. const getStarExtglobSequenceOutput = pattern => {
  3027. let index = 0;
  3028. const chars = [];
  3029. while (index < pattern.length) {
  3030. const match = parseRepeatedExtglob(pattern.slice(index), false);
  3031. if (!match || match.type !== '*') {
  3032. return;
  3033. }
  3034. const branches = splitTopLevel(match.body).map(branch => branch.trim());
  3035. if (branches.length !== 1) {
  3036. return;
  3037. }
  3038. const branch = normalizeSimpleBranch(branches[0]);
  3039. if (!branch || branch.length !== 1) {
  3040. return;
  3041. }
  3042. chars.push(branch);
  3043. index += match.end + 1;
  3044. }
  3045. if (chars.length < 1) {
  3046. return;
  3047. }
  3048. const source = chars.length === 1
  3049. ? utils.escapeRegex(chars[0])
  3050. : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`;
  3051. return `${source}*`;
  3052. };
  3053. const repeatedExtglobRecursion = pattern => {
  3054. let depth = 0;
  3055. let value = pattern.trim();
  3056. let match = parseRepeatedExtglob(value);
  3057. while (match) {
  3058. depth++;
  3059. value = match.body.trim();
  3060. match = parseRepeatedExtglob(value);
  3061. }
  3062. return depth;
  3063. };
  3064. const analyzeRepeatedExtglob = (body, options) => {
  3065. if (options.maxExtglobRecursion === false) {
  3066. return { risky: false };
  3067. }
  3068. const max =
  3069. typeof options.maxExtglobRecursion === 'number'
  3070. ? options.maxExtglobRecursion
  3071. : constants.DEFAULT_MAX_EXTGLOB_RECURSION;
  3072. const branches = splitTopLevel(body).map(branch => branch.trim());
  3073. if (branches.length > 1) {
  3074. if (
  3075. branches.some(branch => branch === '') ||
  3076. branches.some(branch => /^[*?]+$/.test(branch)) ||
  3077. hasRepeatedCharPrefixOverlap(branches)
  3078. ) {
  3079. return { risky: true };
  3080. }
  3081. }
  3082. for (const branch of branches) {
  3083. const safeOutput = getStarExtglobSequenceOutput(branch);
  3084. if (safeOutput) {
  3085. return { risky: true, safeOutput };
  3086. }
  3087. if (repeatedExtglobRecursion(branch) > max) {
  3088. return { risky: true };
  3089. }
  3090. }
  3091. return { risky: false };
  3092. };
  3093. /**
  3094. * Parse the given input string.
  3095. * @param {String} input
  3096. * @param {Object} options
  3097. * @return {Object}
  3098. */
  3099. const parse = (input, options) => {
  3100. if (typeof input !== 'string') {
  3101. throw new TypeError('Expected a string');
  3102. }
  3103. input = REPLACEMENTS[input] || input;
  3104. const opts = { ...options };
  3105. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3106. let len = input.length;
  3107. if (len > max) {
  3108. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3109. }
  3110. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  3111. const tokens = [bos];
  3112. const capture = opts.capture ? '' : '?:';
  3113. const win32 = utils.isWindows(options);
  3114. // create constants based on platform, for windows or posix
  3115. const PLATFORM_CHARS = constants.globChars(win32);
  3116. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  3117. const {
  3118. DOT_LITERAL,
  3119. PLUS_LITERAL,
  3120. SLASH_LITERAL,
  3121. ONE_CHAR,
  3122. DOTS_SLASH,
  3123. NO_DOT,
  3124. NO_DOT_SLASH,
  3125. NO_DOTS_SLASH,
  3126. QMARK,
  3127. QMARK_NO_DOT,
  3128. STAR,
  3129. START_ANCHOR
  3130. } = PLATFORM_CHARS;
  3131. const globstar = opts => {
  3132. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3133. };
  3134. const nodot = opts.dot ? '' : NO_DOT;
  3135. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  3136. let star = opts.bash === true ? globstar(opts) : STAR;
  3137. if (opts.capture) {
  3138. star = `(${star})`;
  3139. }
  3140. // minimatch options support
  3141. if (typeof opts.noext === 'boolean') {
  3142. opts.noextglob = opts.noext;
  3143. }
  3144. const state = {
  3145. input,
  3146. index: -1,
  3147. start: 0,
  3148. dot: opts.dot === true,
  3149. consumed: '',
  3150. output: '',
  3151. prefix: '',
  3152. backtrack: false,
  3153. negated: false,
  3154. brackets: 0,
  3155. braces: 0,
  3156. parens: 0,
  3157. quotes: 0,
  3158. globstar: false,
  3159. tokens
  3160. };
  3161. input = utils.removePrefix(input, state);
  3162. len = input.length;
  3163. const extglobs = [];
  3164. const braces = [];
  3165. const stack = [];
  3166. let prev = bos;
  3167. let value;
  3168. /**
  3169. * Tokenizing helpers
  3170. */
  3171. const eos = () => state.index === len - 1;
  3172. const peek = state.peek = (n = 1) => input[state.index + n];
  3173. const advance = state.advance = () => input[++state.index] || '';
  3174. const remaining = () => input.slice(state.index + 1);
  3175. const consume = (value = '', num = 0) => {
  3176. state.consumed += value;
  3177. state.index += num;
  3178. };
  3179. const append = token => {
  3180. state.output += token.output != null ? token.output : token.value;
  3181. consume(token.value);
  3182. };
  3183. const negate = () => {
  3184. let count = 1;
  3185. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  3186. advance();
  3187. state.start++;
  3188. count++;
  3189. }
  3190. if (count % 2 === 0) {
  3191. return false;
  3192. }
  3193. state.negated = true;
  3194. state.start++;
  3195. return true;
  3196. };
  3197. const increment = type => {
  3198. state[type]++;
  3199. stack.push(type);
  3200. };
  3201. const decrement = type => {
  3202. state[type]--;
  3203. stack.pop();
  3204. };
  3205. /**
  3206. * Push tokens onto the tokens array. This helper speeds up
  3207. * tokenizing by 1) helping us avoid backtracking as much as possible,
  3208. * and 2) helping us avoid creating extra tokens when consecutive
  3209. * characters are plain text. This improves performance and simplifies
  3210. * lookbehinds.
  3211. */
  3212. const push = tok => {
  3213. if (prev.type === 'globstar') {
  3214. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  3215. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  3216. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  3217. state.output = state.output.slice(0, -prev.output.length);
  3218. prev.type = 'star';
  3219. prev.value = '*';
  3220. prev.output = star;
  3221. state.output += prev.output;
  3222. }
  3223. }
  3224. if (extglobs.length && tok.type !== 'paren') {
  3225. extglobs[extglobs.length - 1].inner += tok.value;
  3226. }
  3227. if (tok.value || tok.output) append(tok);
  3228. if (prev && prev.type === 'text' && tok.type === 'text') {
  3229. prev.value += tok.value;
  3230. prev.output = (prev.output || '') + tok.value;
  3231. return;
  3232. }
  3233. tok.prev = prev;
  3234. tokens.push(tok);
  3235. prev = tok;
  3236. };
  3237. const extglobOpen = (type, value) => {
  3238. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  3239. token.prev = prev;
  3240. token.parens = state.parens;
  3241. token.output = state.output;
  3242. token.startIndex = state.index;
  3243. token.tokensIndex = tokens.length;
  3244. const output = (opts.capture ? '(' : '') + token.open;
  3245. increment('parens');
  3246. push({ type, value, output: state.output ? '' : ONE_CHAR });
  3247. push({ type: 'paren', extglob: true, value: advance(), output });
  3248. extglobs.push(token);
  3249. };
  3250. const extglobClose = token => {
  3251. const literal = input.slice(token.startIndex, state.index + 1);
  3252. const body = input.slice(token.startIndex + 2, state.index);
  3253. const analysis = analyzeRepeatedExtglob(body, opts);
  3254. if ((token.type === 'plus' || token.type === 'star') && analysis.risky) {
  3255. const safeOutput = analysis.safeOutput
  3256. ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput)
  3257. : undefined;
  3258. const open = tokens[token.tokensIndex];
  3259. open.type = 'text';
  3260. open.value = literal;
  3261. open.output = safeOutput || utils.escapeRegex(literal);
  3262. for (let i = token.tokensIndex + 1; i < tokens.length; i++) {
  3263. tokens[i].value = '';
  3264. tokens[i].output = '';
  3265. delete tokens[i].suffix;
  3266. }
  3267. state.output = token.output + open.output;
  3268. state.backtrack = true;
  3269. push({ type: 'paren', extglob: true, value, output: '' });
  3270. decrement('parens');
  3271. return;
  3272. }
  3273. let output = token.close + (opts.capture ? ')' : '');
  3274. let rest;
  3275. if (token.type === 'negate') {
  3276. let extglobStar = star;
  3277. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  3278. extglobStar = globstar(opts);
  3279. }
  3280. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  3281. output = token.close = `)$))${extglobStar}`;
  3282. }
  3283. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  3284. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  3285. // In this case, we need to parse the string and use it in the output of the original pattern.
  3286. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  3287. //
  3288. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  3289. const expression = parse(rest, { ...options, fastpaths: false }).output;
  3290. output = token.close = `)${expression})${extglobStar})`;
  3291. }
  3292. if (token.prev.type === 'bos') {
  3293. state.negatedExtglob = true;
  3294. }
  3295. }
  3296. push({ type: 'paren', extglob: true, value, output });
  3297. decrement('parens');
  3298. };
  3299. /**
  3300. * Fast paths
  3301. */
  3302. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  3303. let backslashes = false;
  3304. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  3305. if (first === '\\') {
  3306. backslashes = true;
  3307. return m;
  3308. }
  3309. if (first === '?') {
  3310. if (esc) {
  3311. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  3312. }
  3313. if (index === 0) {
  3314. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  3315. }
  3316. return QMARK.repeat(chars.length);
  3317. }
  3318. if (first === '.') {
  3319. return DOT_LITERAL.repeat(chars.length);
  3320. }
  3321. if (first === '*') {
  3322. if (esc) {
  3323. return esc + first + (rest ? star : '');
  3324. }
  3325. return star;
  3326. }
  3327. return esc ? m : `\\${m}`;
  3328. });
  3329. if (backslashes === true) {
  3330. if (opts.unescape === true) {
  3331. output = output.replace(/\\/g, '');
  3332. } else {
  3333. output = output.replace(/\\+/g, m => {
  3334. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  3335. });
  3336. }
  3337. }
  3338. if (output === input && opts.contains === true) {
  3339. state.output = input;
  3340. return state;
  3341. }
  3342. state.output = utils.wrapOutput(output, state, options);
  3343. return state;
  3344. }
  3345. /**
  3346. * Tokenize input until we reach end-of-string
  3347. */
  3348. while (!eos()) {
  3349. value = advance();
  3350. if (value === '\u0000') {
  3351. continue;
  3352. }
  3353. /**
  3354. * Escaped characters
  3355. */
  3356. if (value === '\\') {
  3357. const next = peek();
  3358. if (next === '/' && opts.bash !== true) {
  3359. continue;
  3360. }
  3361. if (next === '.' || next === ';') {
  3362. continue;
  3363. }
  3364. if (!next) {
  3365. value += '\\';
  3366. push({ type: 'text', value });
  3367. continue;
  3368. }
  3369. // collapse slashes to reduce potential for exploits
  3370. const match = /^\\+/.exec(remaining());
  3371. let slashes = 0;
  3372. if (match && match[0].length > 2) {
  3373. slashes = match[0].length;
  3374. state.index += slashes;
  3375. if (slashes % 2 !== 0) {
  3376. value += '\\';
  3377. }
  3378. }
  3379. if (opts.unescape === true) {
  3380. value = advance();
  3381. } else {
  3382. value += advance();
  3383. }
  3384. if (state.brackets === 0) {
  3385. push({ type: 'text', value });
  3386. continue;
  3387. }
  3388. }
  3389. /**
  3390. * If we're inside a regex character class, continue
  3391. * until we reach the closing bracket.
  3392. */
  3393. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  3394. if (opts.posix !== false && value === ':') {
  3395. const inner = prev.value.slice(1);
  3396. if (inner.includes('[')) {
  3397. prev.posix = true;
  3398. if (inner.includes(':')) {
  3399. const idx = prev.value.lastIndexOf('[');
  3400. const pre = prev.value.slice(0, idx);
  3401. const rest = prev.value.slice(idx + 2);
  3402. const posix = POSIX_REGEX_SOURCE[rest];
  3403. if (posix) {
  3404. prev.value = pre + posix;
  3405. state.backtrack = true;
  3406. advance();
  3407. if (!bos.output && tokens.indexOf(prev) === 1) {
  3408. bos.output = ONE_CHAR;
  3409. }
  3410. continue;
  3411. }
  3412. }
  3413. }
  3414. }
  3415. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  3416. value = `\\${value}`;
  3417. }
  3418. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  3419. value = `\\${value}`;
  3420. }
  3421. if (opts.posix === true && value === '!' && prev.value === '[') {
  3422. value = '^';
  3423. }
  3424. prev.value += value;
  3425. append({ value });
  3426. continue;
  3427. }
  3428. /**
  3429. * If we're inside a quoted string, continue
  3430. * until we reach the closing double quote.
  3431. */
  3432. if (state.quotes === 1 && value !== '"') {
  3433. value = utils.escapeRegex(value);
  3434. prev.value += value;
  3435. append({ value });
  3436. continue;
  3437. }
  3438. /**
  3439. * Double quotes
  3440. */
  3441. if (value === '"') {
  3442. state.quotes = state.quotes === 1 ? 0 : 1;
  3443. if (opts.keepQuotes === true) {
  3444. push({ type: 'text', value });
  3445. }
  3446. continue;
  3447. }
  3448. /**
  3449. * Parentheses
  3450. */
  3451. if (value === '(') {
  3452. increment('parens');
  3453. push({ type: 'paren', value });
  3454. continue;
  3455. }
  3456. if (value === ')') {
  3457. if (state.parens === 0 && opts.strictBrackets === true) {
  3458. throw new SyntaxError(syntaxError('opening', '('));
  3459. }
  3460. const extglob = extglobs[extglobs.length - 1];
  3461. if (extglob && state.parens === extglob.parens + 1) {
  3462. extglobClose(extglobs.pop());
  3463. continue;
  3464. }
  3465. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3466. decrement('parens');
  3467. continue;
  3468. }
  3469. /**
  3470. * Square brackets
  3471. */
  3472. if (value === '[') {
  3473. if (opts.nobracket === true || !remaining().includes(']')) {
  3474. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3475. throw new SyntaxError(syntaxError('closing', ']'));
  3476. }
  3477. value = `\\${value}`;
  3478. } else {
  3479. increment('brackets');
  3480. }
  3481. push({ type: 'bracket', value });
  3482. continue;
  3483. }
  3484. if (value === ']') {
  3485. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3486. push({ type: 'text', value, output: `\\${value}` });
  3487. continue;
  3488. }
  3489. if (state.brackets === 0) {
  3490. if (opts.strictBrackets === true) {
  3491. throw new SyntaxError(syntaxError('opening', '['));
  3492. }
  3493. push({ type: 'text', value, output: `\\${value}` });
  3494. continue;
  3495. }
  3496. decrement('brackets');
  3497. const prevValue = prev.value.slice(1);
  3498. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3499. value = `/${value}`;
  3500. }
  3501. prev.value += value;
  3502. append({ value });
  3503. // when literal brackets are explicitly disabled
  3504. // assume we should match with a regex character class
  3505. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  3506. continue;
  3507. }
  3508. const escaped = utils.escapeRegex(prev.value);
  3509. state.output = state.output.slice(0, -prev.value.length);
  3510. // when literal brackets are explicitly enabled
  3511. // assume we should escape the brackets to match literal characters
  3512. if (opts.literalBrackets === true) {
  3513. state.output += escaped;
  3514. prev.value = escaped;
  3515. continue;
  3516. }
  3517. // when the user specifies nothing, try to match both
  3518. prev.value = `(${capture}${escaped}|${prev.value})`;
  3519. state.output += prev.value;
  3520. continue;
  3521. }
  3522. /**
  3523. * Braces
  3524. */
  3525. if (value === '{' && opts.nobrace !== true) {
  3526. increment('braces');
  3527. const open = {
  3528. type: 'brace',
  3529. value,
  3530. output: '(',
  3531. outputIndex: state.output.length,
  3532. tokensIndex: state.tokens.length
  3533. };
  3534. braces.push(open);
  3535. push(open);
  3536. continue;
  3537. }
  3538. if (value === '}') {
  3539. const brace = braces[braces.length - 1];
  3540. if (opts.nobrace === true || !brace) {
  3541. push({ type: 'text', value, output: value });
  3542. continue;
  3543. }
  3544. let output = ')';
  3545. if (brace.dots === true) {
  3546. const arr = tokens.slice();
  3547. const range = [];
  3548. for (let i = arr.length - 1; i >= 0; i--) {
  3549. tokens.pop();
  3550. if (arr[i].type === 'brace') {
  3551. break;
  3552. }
  3553. if (arr[i].type !== 'dots') {
  3554. range.unshift(arr[i].value);
  3555. }
  3556. }
  3557. output = expandRange(range, opts);
  3558. state.backtrack = true;
  3559. }
  3560. if (brace.comma !== true && brace.dots !== true) {
  3561. const out = state.output.slice(0, brace.outputIndex);
  3562. const toks = state.tokens.slice(brace.tokensIndex);
  3563. brace.value = brace.output = '\\{';
  3564. value = output = '\\}';
  3565. state.output = out;
  3566. for (const t of toks) {
  3567. state.output += (t.output || t.value);
  3568. }
  3569. }
  3570. push({ type: 'brace', value, output });
  3571. decrement('braces');
  3572. braces.pop();
  3573. continue;
  3574. }
  3575. /**
  3576. * Pipes
  3577. */
  3578. if (value === '|') {
  3579. if (extglobs.length > 0) {
  3580. extglobs[extglobs.length - 1].conditions++;
  3581. }
  3582. push({ type: 'text', value });
  3583. continue;
  3584. }
  3585. /**
  3586. * Commas
  3587. */
  3588. if (value === ',') {
  3589. let output = value;
  3590. const brace = braces[braces.length - 1];
  3591. if (brace && stack[stack.length - 1] === 'braces') {
  3592. brace.comma = true;
  3593. output = '|';
  3594. }
  3595. push({ type: 'comma', value, output });
  3596. continue;
  3597. }
  3598. /**
  3599. * Slashes
  3600. */
  3601. if (value === '/') {
  3602. // if the beginning of the glob is "./", advance the start
  3603. // to the current index, and don't add the "./" characters
  3604. // to the state. This greatly simplifies lookbehinds when
  3605. // checking for BOS characters like "!" and "." (not "./")
  3606. if (prev.type === 'dot' && state.index === state.start + 1) {
  3607. state.start = state.index + 1;
  3608. state.consumed = '';
  3609. state.output = '';
  3610. tokens.pop();
  3611. prev = bos; // reset "prev" to the first token
  3612. continue;
  3613. }
  3614. push({ type: 'slash', value, output: SLASH_LITERAL });
  3615. continue;
  3616. }
  3617. /**
  3618. * Dots
  3619. */
  3620. if (value === '.') {
  3621. if (state.braces > 0 && prev.type === 'dot') {
  3622. if (prev.value === '.') prev.output = DOT_LITERAL;
  3623. const brace = braces[braces.length - 1];
  3624. prev.type = 'dots';
  3625. prev.output += value;
  3626. prev.value += value;
  3627. brace.dots = true;
  3628. continue;
  3629. }
  3630. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3631. push({ type: 'text', value, output: DOT_LITERAL });
  3632. continue;
  3633. }
  3634. push({ type: 'dot', value, output: DOT_LITERAL });
  3635. continue;
  3636. }
  3637. /**
  3638. * Question marks
  3639. */
  3640. if (value === '?') {
  3641. const isGroup = prev && prev.value === '(';
  3642. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3643. extglobOpen('qmark', value);
  3644. continue;
  3645. }
  3646. if (prev && prev.type === 'paren') {
  3647. const next = peek();
  3648. let output = value;
  3649. if (next === '<' && !utils.supportsLookbehinds()) {
  3650. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3651. }
  3652. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3653. output = `\\${value}`;
  3654. }
  3655. push({ type: 'text', value, output });
  3656. continue;
  3657. }
  3658. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3659. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3660. continue;
  3661. }
  3662. push({ type: 'qmark', value, output: QMARK });
  3663. continue;
  3664. }
  3665. /**
  3666. * Exclamation
  3667. */
  3668. if (value === '!') {
  3669. if (opts.noextglob !== true && peek() === '(') {
  3670. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3671. extglobOpen('negate', value);
  3672. continue;
  3673. }
  3674. }
  3675. if (opts.nonegate !== true && state.index === 0) {
  3676. negate();
  3677. continue;
  3678. }
  3679. }
  3680. /**
  3681. * Plus
  3682. */
  3683. if (value === '+') {
  3684. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3685. extglobOpen('plus', value);
  3686. continue;
  3687. }
  3688. if ((prev && prev.value === '(') || opts.regex === false) {
  3689. push({ type: 'plus', value, output: PLUS_LITERAL });
  3690. continue;
  3691. }
  3692. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3693. push({ type: 'plus', value });
  3694. continue;
  3695. }
  3696. push({ type: 'plus', value: PLUS_LITERAL });
  3697. continue;
  3698. }
  3699. /**
  3700. * Plain text
  3701. */
  3702. if (value === '@') {
  3703. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3704. push({ type: 'at', extglob: true, value, output: '' });
  3705. continue;
  3706. }
  3707. push({ type: 'text', value });
  3708. continue;
  3709. }
  3710. /**
  3711. * Plain text
  3712. */
  3713. if (value !== '*') {
  3714. if (value === '$' || value === '^') {
  3715. value = `\\${value}`;
  3716. }
  3717. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3718. if (match) {
  3719. value += match[0];
  3720. state.index += match[0].length;
  3721. }
  3722. push({ type: 'text', value });
  3723. continue;
  3724. }
  3725. /**
  3726. * Stars
  3727. */
  3728. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3729. prev.type = 'star';
  3730. prev.star = true;
  3731. prev.value += value;
  3732. prev.output = star;
  3733. state.backtrack = true;
  3734. state.globstar = true;
  3735. consume(value);
  3736. continue;
  3737. }
  3738. let rest = remaining();
  3739. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3740. extglobOpen('star', value);
  3741. continue;
  3742. }
  3743. if (prev.type === 'star') {
  3744. if (opts.noglobstar === true) {
  3745. consume(value);
  3746. continue;
  3747. }
  3748. const prior = prev.prev;
  3749. const before = prior.prev;
  3750. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3751. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3752. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3753. push({ type: 'star', value, output: '' });
  3754. continue;
  3755. }
  3756. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3757. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3758. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3759. push({ type: 'star', value, output: '' });
  3760. continue;
  3761. }
  3762. // strip consecutive `/**/`
  3763. while (rest.slice(0, 3) === '/**') {
  3764. const after = input[state.index + 4];
  3765. if (after && after !== '/') {
  3766. break;
  3767. }
  3768. rest = rest.slice(3);
  3769. consume('/**', 3);
  3770. }
  3771. if (prior.type === 'bos' && eos()) {
  3772. prev.type = 'globstar';
  3773. prev.value += value;
  3774. prev.output = globstar(opts);
  3775. state.output = prev.output;
  3776. state.globstar = true;
  3777. consume(value);
  3778. continue;
  3779. }
  3780. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3781. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3782. prior.output = `(?:${prior.output}`;
  3783. prev.type = 'globstar';
  3784. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3785. prev.value += value;
  3786. state.globstar = true;
  3787. state.output += prior.output + prev.output;
  3788. consume(value);
  3789. continue;
  3790. }
  3791. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3792. const end = rest[1] !== void 0 ? '|$' : '';
  3793. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3794. prior.output = `(?:${prior.output}`;
  3795. prev.type = 'globstar';
  3796. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3797. prev.value += value;
  3798. state.output += prior.output + prev.output;
  3799. state.globstar = true;
  3800. consume(value + advance());
  3801. push({ type: 'slash', value: '/', output: '' });
  3802. continue;
  3803. }
  3804. if (prior.type === 'bos' && rest[0] === '/') {
  3805. prev.type = 'globstar';
  3806. prev.value += value;
  3807. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3808. state.output = prev.output;
  3809. state.globstar = true;
  3810. consume(value + advance());
  3811. push({ type: 'slash', value: '/', output: '' });
  3812. continue;
  3813. }
  3814. // remove single star from output
  3815. state.output = state.output.slice(0, -prev.output.length);
  3816. // reset previous token to globstar
  3817. prev.type = 'globstar';
  3818. prev.output = globstar(opts);
  3819. prev.value += value;
  3820. // reset output with globstar
  3821. state.output += prev.output;
  3822. state.globstar = true;
  3823. consume(value);
  3824. continue;
  3825. }
  3826. const token = { type: 'star', value, output: star };
  3827. if (opts.bash === true) {
  3828. token.output = '.*?';
  3829. if (prev.type === 'bos' || prev.type === 'slash') {
  3830. token.output = nodot + token.output;
  3831. }
  3832. push(token);
  3833. continue;
  3834. }
  3835. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3836. token.output = value;
  3837. push(token);
  3838. continue;
  3839. }
  3840. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3841. if (prev.type === 'dot') {
  3842. state.output += NO_DOT_SLASH;
  3843. prev.output += NO_DOT_SLASH;
  3844. } else if (opts.dot === true) {
  3845. state.output += NO_DOTS_SLASH;
  3846. prev.output += NO_DOTS_SLASH;
  3847. } else {
  3848. state.output += nodot;
  3849. prev.output += nodot;
  3850. }
  3851. if (peek() !== '*') {
  3852. state.output += ONE_CHAR;
  3853. prev.output += ONE_CHAR;
  3854. }
  3855. }
  3856. push(token);
  3857. }
  3858. while (state.brackets > 0) {
  3859. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3860. state.output = utils.escapeLast(state.output, '[');
  3861. decrement('brackets');
  3862. }
  3863. while (state.parens > 0) {
  3864. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3865. state.output = utils.escapeLast(state.output, '(');
  3866. decrement('parens');
  3867. }
  3868. while (state.braces > 0) {
  3869. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3870. state.output = utils.escapeLast(state.output, '{');
  3871. decrement('braces');
  3872. }
  3873. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3874. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3875. }
  3876. // rebuild the output if we had to backtrack at any point
  3877. if (state.backtrack === true) {
  3878. state.output = '';
  3879. for (const token of state.tokens) {
  3880. state.output += token.output != null ? token.output : token.value;
  3881. if (token.suffix) {
  3882. state.output += token.suffix;
  3883. }
  3884. }
  3885. }
  3886. return state;
  3887. };
  3888. /**
  3889. * Fast paths for creating regular expressions for common glob patterns.
  3890. * This can significantly speed up processing and has very little downside
  3891. * impact when none of the fast paths match.
  3892. */
  3893. parse.fastpaths = (input, options) => {
  3894. const opts = { ...options };
  3895. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3896. const len = input.length;
  3897. if (len > max) {
  3898. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3899. }
  3900. input = REPLACEMENTS[input] || input;
  3901. const win32 = utils.isWindows(options);
  3902. // create constants based on platform, for windows or posix
  3903. const {
  3904. DOT_LITERAL,
  3905. SLASH_LITERAL,
  3906. ONE_CHAR,
  3907. DOTS_SLASH,
  3908. NO_DOT,
  3909. NO_DOTS,
  3910. NO_DOTS_SLASH,
  3911. STAR,
  3912. START_ANCHOR
  3913. } = constants.globChars(win32);
  3914. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3915. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3916. const capture = opts.capture ? '' : '?:';
  3917. const state = { negated: false, prefix: '' };
  3918. let star = opts.bash === true ? '.*?' : STAR;
  3919. if (opts.capture) {
  3920. star = `(${star})`;
  3921. }
  3922. const globstar = opts => {
  3923. if (opts.noglobstar === true) return star;
  3924. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3925. };
  3926. const create = str => {
  3927. switch (str) {
  3928. case '*':
  3929. return `${nodot}${ONE_CHAR}${star}`;
  3930. case '.*':
  3931. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3932. case '*.*':
  3933. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3934. case '*/*':
  3935. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3936. case '**':
  3937. return nodot + globstar(opts);
  3938. case '**/*':
  3939. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3940. case '**/*.*':
  3941. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3942. case '**/.*':
  3943. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3944. default: {
  3945. const match = /^(.*?)\.(\w+)$/.exec(str);
  3946. if (!match) return;
  3947. const source = create(match[1]);
  3948. if (!source) return;
  3949. return source + DOT_LITERAL + match[2];
  3950. }
  3951. }
  3952. };
  3953. const output = utils.removePrefix(input, state);
  3954. let source = create(output);
  3955. if (source && opts.strictSlashes !== true) {
  3956. source += `${SLASH_LITERAL}?`;
  3957. }
  3958. return source;
  3959. };
  3960. parse_1$1 = parse;
  3961. return parse_1$1;
  3962. }
  3963. var picomatch_1;
  3964. var hasRequiredPicomatch$1;
  3965. function requirePicomatch$1 () {
  3966. if (hasRequiredPicomatch$1) return picomatch_1;
  3967. hasRequiredPicomatch$1 = 1;
  3968. const path = require$$0$1;
  3969. const scan = /*@__PURE__*/ requireScan();
  3970. const parse = /*@__PURE__*/ requireParse$1();
  3971. const utils = /*@__PURE__*/ requireUtils$1();
  3972. const constants = /*@__PURE__*/ requireConstants$2();
  3973. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  3974. /**
  3975. * Creates a matcher function from one or more glob patterns. The
  3976. * returned function takes a string to match as its first argument,
  3977. * and returns true if the string is a match. The returned matcher
  3978. * function also takes a boolean as the second argument that, when true,
  3979. * returns an object with additional information.
  3980. *
  3981. * ```js
  3982. * const picomatch = require('picomatch');
  3983. * // picomatch(glob[, options]);
  3984. *
  3985. * const isMatch = picomatch('*.!(*a)');
  3986. * console.log(isMatch('a.a')); //=> false
  3987. * console.log(isMatch('a.b')); //=> true
  3988. * ```
  3989. * @name picomatch
  3990. * @param {String|Array} `globs` One or more glob patterns.
  3991. * @param {Object=} `options`
  3992. * @return {Function=} Returns a matcher function.
  3993. * @api public
  3994. */
  3995. const picomatch = (glob, options, returnState = false) => {
  3996. if (Array.isArray(glob)) {
  3997. const fns = glob.map(input => picomatch(input, options, returnState));
  3998. const arrayMatcher = str => {
  3999. for (const isMatch of fns) {
  4000. const state = isMatch(str);
  4001. if (state) return state;
  4002. }
  4003. return false;
  4004. };
  4005. return arrayMatcher;
  4006. }
  4007. const isState = isObject(glob) && glob.tokens && glob.input;
  4008. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  4009. throw new TypeError('Expected pattern to be a non-empty string');
  4010. }
  4011. const opts = options || {};
  4012. const posix = utils.isWindows(options);
  4013. const regex = isState
  4014. ? picomatch.compileRe(glob, options)
  4015. : picomatch.makeRe(glob, options, false, true);
  4016. const state = regex.state;
  4017. delete regex.state;
  4018. let isIgnored = () => false;
  4019. if (opts.ignore) {
  4020. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  4021. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  4022. }
  4023. const matcher = (input, returnObject = false) => {
  4024. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  4025. const result = { glob, state, regex, posix, input, output, match, isMatch };
  4026. if (typeof opts.onResult === 'function') {
  4027. opts.onResult(result);
  4028. }
  4029. if (isMatch === false) {
  4030. result.isMatch = false;
  4031. return returnObject ? result : false;
  4032. }
  4033. if (isIgnored(input)) {
  4034. if (typeof opts.onIgnore === 'function') {
  4035. opts.onIgnore(result);
  4036. }
  4037. result.isMatch = false;
  4038. return returnObject ? result : false;
  4039. }
  4040. if (typeof opts.onMatch === 'function') {
  4041. opts.onMatch(result);
  4042. }
  4043. return returnObject ? result : true;
  4044. };
  4045. if (returnState) {
  4046. matcher.state = state;
  4047. }
  4048. return matcher;
  4049. };
  4050. /**
  4051. * Test `input` with the given `regex`. This is used by the main
  4052. * `picomatch()` function to test the input string.
  4053. *
  4054. * ```js
  4055. * const picomatch = require('picomatch');
  4056. * // picomatch.test(input, regex[, options]);
  4057. *
  4058. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  4059. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  4060. * ```
  4061. * @param {String} `input` String to test.
  4062. * @param {RegExp} `regex`
  4063. * @return {Object} Returns an object with matching info.
  4064. * @api public
  4065. */
  4066. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  4067. if (typeof input !== 'string') {
  4068. throw new TypeError('Expected input to be a string');
  4069. }
  4070. if (input === '') {
  4071. return { isMatch: false, output: '' };
  4072. }
  4073. const opts = options || {};
  4074. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  4075. let match = input === glob;
  4076. let output = (match && format) ? format(input) : input;
  4077. if (match === false) {
  4078. output = format ? format(input) : input;
  4079. match = output === glob;
  4080. }
  4081. if (match === false || opts.capture === true) {
  4082. if (opts.matchBase === true || opts.basename === true) {
  4083. match = picomatch.matchBase(input, regex, options, posix);
  4084. } else {
  4085. match = regex.exec(output);
  4086. }
  4087. }
  4088. return { isMatch: Boolean(match), match, output };
  4089. };
  4090. /**
  4091. * Match the basename of a filepath.
  4092. *
  4093. * ```js
  4094. * const picomatch = require('picomatch');
  4095. * // picomatch.matchBase(input, glob[, options]);
  4096. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  4097. * ```
  4098. * @param {String} `input` String to test.
  4099. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  4100. * @return {Boolean}
  4101. * @api public
  4102. */
  4103. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  4104. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  4105. return regex.test(path.basename(input));
  4106. };
  4107. /**
  4108. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  4109. *
  4110. * ```js
  4111. * const picomatch = require('picomatch');
  4112. * // picomatch.isMatch(string, patterns[, options]);
  4113. *
  4114. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  4115. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  4116. * ```
  4117. * @param {String|Array} str The string to test.
  4118. * @param {String|Array} patterns One or more glob patterns to use for matching.
  4119. * @param {Object} [options] See available [options](#options).
  4120. * @return {Boolean} Returns true if any patterns match `str`
  4121. * @api public
  4122. */
  4123. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  4124. /**
  4125. * Parse a glob pattern to create the source string for a regular
  4126. * expression.
  4127. *
  4128. * ```js
  4129. * const picomatch = require('picomatch');
  4130. * const result = picomatch.parse(pattern[, options]);
  4131. * ```
  4132. * @param {String} `pattern`
  4133. * @param {Object} `options`
  4134. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  4135. * @api public
  4136. */
  4137. picomatch.parse = (pattern, options) => {
  4138. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  4139. return parse(pattern, { ...options, fastpaths: false });
  4140. };
  4141. /**
  4142. * Scan a glob pattern to separate the pattern into segments.
  4143. *
  4144. * ```js
  4145. * const picomatch = require('picomatch');
  4146. * // picomatch.scan(input[, options]);
  4147. *
  4148. * const result = picomatch.scan('!./foo/*.js');
  4149. * console.log(result);
  4150. * { prefix: '!./',
  4151. * input: '!./foo/*.js',
  4152. * start: 3,
  4153. * base: 'foo',
  4154. * glob: '*.js',
  4155. * isBrace: false,
  4156. * isBracket: false,
  4157. * isGlob: true,
  4158. * isExtglob: false,
  4159. * isGlobstar: false,
  4160. * negated: true }
  4161. * ```
  4162. * @param {String} `input` Glob pattern to scan.
  4163. * @param {Object} `options`
  4164. * @return {Object} Returns an object with
  4165. * @api public
  4166. */
  4167. picomatch.scan = (input, options) => scan(input, options);
  4168. /**
  4169. * Compile a regular expression from the `state` object returned by the
  4170. * [parse()](#parse) method.
  4171. *
  4172. * @param {Object} `state`
  4173. * @param {Object} `options`
  4174. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  4175. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  4176. * @return {RegExp}
  4177. * @api public
  4178. */
  4179. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  4180. if (returnOutput === true) {
  4181. return state.output;
  4182. }
  4183. const opts = options || {};
  4184. const prepend = opts.contains ? '' : '^';
  4185. const append = opts.contains ? '' : '$';
  4186. let source = `${prepend}(?:${state.output})${append}`;
  4187. if (state && state.negated === true) {
  4188. source = `^(?!${source}).*$`;
  4189. }
  4190. const regex = picomatch.toRegex(source, options);
  4191. if (returnState === true) {
  4192. regex.state = state;
  4193. }
  4194. return regex;
  4195. };
  4196. /**
  4197. * Create a regular expression from a parsed glob pattern.
  4198. *
  4199. * ```js
  4200. * const picomatch = require('picomatch');
  4201. * const state = picomatch.parse('*.js');
  4202. * // picomatch.compileRe(state[, options]);
  4203. *
  4204. * console.log(picomatch.compileRe(state));
  4205. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  4206. * ```
  4207. * @param {String} `state` The object returned from the `.parse` method.
  4208. * @param {Object} `options`
  4209. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  4210. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  4211. * @return {RegExp} Returns a regex created from the given pattern.
  4212. * @api public
  4213. */
  4214. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  4215. if (!input || typeof input !== 'string') {
  4216. throw new TypeError('Expected a non-empty string');
  4217. }
  4218. let parsed = { negated: false, fastpaths: true };
  4219. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  4220. parsed.output = parse.fastpaths(input, options);
  4221. }
  4222. if (!parsed.output) {
  4223. parsed = parse(input, options);
  4224. }
  4225. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  4226. };
  4227. /**
  4228. * Create a regular expression from the given regex source string.
  4229. *
  4230. * ```js
  4231. * const picomatch = require('picomatch');
  4232. * // picomatch.toRegex(source[, options]);
  4233. *
  4234. * const { output } = picomatch.parse('*.js');
  4235. * console.log(picomatch.toRegex(output));
  4236. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  4237. * ```
  4238. * @param {String} `source` Regular expression source string.
  4239. * @param {Object} `options`
  4240. * @return {RegExp}
  4241. * @api public
  4242. */
  4243. picomatch.toRegex = (source, options) => {
  4244. try {
  4245. const opts = options || {};
  4246. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  4247. } catch (err) {
  4248. if (options && options.debug === true) throw err;
  4249. return /$^/;
  4250. }
  4251. };
  4252. /**
  4253. * Picomatch constants.
  4254. * @return {Object}
  4255. */
  4256. picomatch.constants = constants;
  4257. /**
  4258. * Expose "picomatch"
  4259. */
  4260. picomatch_1 = picomatch;
  4261. return picomatch_1;
  4262. }
  4263. var picomatch;
  4264. var hasRequiredPicomatch;
  4265. function requirePicomatch () {
  4266. if (hasRequiredPicomatch) return picomatch;
  4267. hasRequiredPicomatch = 1;
  4268. picomatch = /*@__PURE__*/ requirePicomatch$1();
  4269. return picomatch;
  4270. }
  4271. /*!
  4272. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  4273. *
  4274. * Copyright (c) 2014-2018, Jon Schlinkert.
  4275. * Released under the MIT License.
  4276. */
  4277. var normalizePath;
  4278. var hasRequiredNormalizePath;
  4279. function requireNormalizePath () {
  4280. if (hasRequiredNormalizePath) return normalizePath;
  4281. hasRequiredNormalizePath = 1;
  4282. normalizePath = function(path, stripTrailing) {
  4283. if (typeof path !== 'string') {
  4284. throw new TypeError('expected path to be a string');
  4285. }
  4286. if (path === '\\' || path === '/') return '/';
  4287. var len = path.length;
  4288. if (len <= 1) return path;
  4289. // ensure that win32 namespaces has two leading slashes, so that the path is
  4290. // handled properly by the win32 version of path.parse() after being normalized
  4291. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  4292. var prefix = '';
  4293. if (len > 4 && path[3] === '\\') {
  4294. var ch = path[2];
  4295. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  4296. path = path.slice(2);
  4297. prefix = '//';
  4298. }
  4299. }
  4300. var segs = path.split(/[/\\]+/);
  4301. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  4302. segs.pop();
  4303. }
  4304. return prefix + segs.join('/');
  4305. };
  4306. return normalizePath;
  4307. }
  4308. var anymatch_1 = anymatch.exports;
  4309. var hasRequiredAnymatch;
  4310. function requireAnymatch () {
  4311. if (hasRequiredAnymatch) return anymatch.exports;
  4312. hasRequiredAnymatch = 1;
  4313. Object.defineProperty(anymatch_1, "__esModule", { value: true });
  4314. const picomatch = /*@__PURE__*/ requirePicomatch();
  4315. const normalizePath = /*@__PURE__*/ requireNormalizePath();
  4316. /**
  4317. * @typedef {(testString: string) => boolean} AnymatchFn
  4318. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  4319. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  4320. */
  4321. const BANG = '!';
  4322. const DEFAULT_OPTIONS = {returnIndex: false};
  4323. const arrify = (item) => Array.isArray(item) ? item : [item];
  4324. /**
  4325. * @param {AnymatchPattern} matcher
  4326. * @param {object} options
  4327. * @returns {AnymatchFn}
  4328. */
  4329. const createPattern = (matcher, options) => {
  4330. if (typeof matcher === 'function') {
  4331. return matcher;
  4332. }
  4333. if (typeof matcher === 'string') {
  4334. const glob = picomatch(matcher, options);
  4335. return (string) => matcher === string || glob(string);
  4336. }
  4337. if (matcher instanceof RegExp) {
  4338. return (string) => matcher.test(string);
  4339. }
  4340. return (string) => false;
  4341. };
  4342. /**
  4343. * @param {Array<Function>} patterns
  4344. * @param {Array<Function>} negPatterns
  4345. * @param {String|Array} args
  4346. * @param {Boolean} returnIndex
  4347. * @returns {boolean|number}
  4348. */
  4349. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  4350. const isList = Array.isArray(args);
  4351. const _path = isList ? args[0] : args;
  4352. if (!isList && typeof _path !== 'string') {
  4353. throw new TypeError('anymatch: second argument must be a string: got ' +
  4354. Object.prototype.toString.call(_path))
  4355. }
  4356. const path = normalizePath(_path, false);
  4357. for (let index = 0; index < negPatterns.length; index++) {
  4358. const nglob = negPatterns[index];
  4359. if (nglob(path)) {
  4360. return returnIndex ? -1 : false;
  4361. }
  4362. }
  4363. const applied = isList && [path].concat(args.slice(1));
  4364. for (let index = 0; index < patterns.length; index++) {
  4365. const pattern = patterns[index];
  4366. if (isList ? pattern(...applied) : pattern(path)) {
  4367. return returnIndex ? index : true;
  4368. }
  4369. }
  4370. return returnIndex ? -1 : false;
  4371. };
  4372. /**
  4373. * @param {AnymatchMatcher} matchers
  4374. * @param {Array|string} testString
  4375. * @param {object} options
  4376. * @returns {boolean|number|Function}
  4377. */
  4378. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  4379. if (matchers == null) {
  4380. throw new TypeError('anymatch: specify first argument');
  4381. }
  4382. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  4383. const returnIndex = opts.returnIndex || false;
  4384. // Early cache for matchers.
  4385. const mtchers = arrify(matchers);
  4386. const negatedGlobs = mtchers
  4387. .filter(item => typeof item === 'string' && item.charAt(0) === BANG)
  4388. .map(item => item.slice(1))
  4389. .map(item => picomatch(item, opts));
  4390. const patterns = mtchers
  4391. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG))
  4392. .map(matcher => createPattern(matcher, opts));
  4393. if (testString == null) {
  4394. return (testString, ri = false) => {
  4395. const returnIndex = typeof ri === 'boolean' ? ri : false;
  4396. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  4397. }
  4398. }
  4399. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  4400. };
  4401. anymatch$1.default = anymatch$1;
  4402. anymatch.exports = anymatch$1;
  4403. return anymatch.exports;
  4404. }
  4405. /*!
  4406. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  4407. *
  4408. * Copyright (c) 2014-2016, Jon Schlinkert.
  4409. * Licensed under the MIT License.
  4410. */
  4411. var isExtglob;
  4412. var hasRequiredIsExtglob;
  4413. function requireIsExtglob () {
  4414. if (hasRequiredIsExtglob) return isExtglob;
  4415. hasRequiredIsExtglob = 1;
  4416. isExtglob = function isExtglob(str) {
  4417. if (typeof str !== 'string' || str === '') {
  4418. return false;
  4419. }
  4420. var match;
  4421. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  4422. if (match[2]) return true;
  4423. str = str.slice(match.index + match[0].length);
  4424. }
  4425. return false;
  4426. };
  4427. return isExtglob;
  4428. }
  4429. /*!
  4430. * is-glob <https://github.com/jonschlinkert/is-glob>
  4431. *
  4432. * Copyright (c) 2014-2017, Jon Schlinkert.
  4433. * Released under the MIT License.
  4434. */
  4435. var isGlob;
  4436. var hasRequiredIsGlob;
  4437. function requireIsGlob () {
  4438. if (hasRequiredIsGlob) return isGlob;
  4439. hasRequiredIsGlob = 1;
  4440. var isExtglob = /*@__PURE__*/ requireIsExtglob();
  4441. var chars = { '{': '}', '(': ')', '[': ']'};
  4442. var strictCheck = function(str) {
  4443. if (str[0] === '!') {
  4444. return true;
  4445. }
  4446. var index = 0;
  4447. var pipeIndex = -2;
  4448. var closeSquareIndex = -2;
  4449. var closeCurlyIndex = -2;
  4450. var closeParenIndex = -2;
  4451. var backSlashIndex = -2;
  4452. while (index < str.length) {
  4453. if (str[index] === '*') {
  4454. return true;
  4455. }
  4456. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  4457. return true;
  4458. }
  4459. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  4460. if (closeSquareIndex < index) {
  4461. closeSquareIndex = str.indexOf(']', index);
  4462. }
  4463. if (closeSquareIndex > index) {
  4464. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  4465. return true;
  4466. }
  4467. backSlashIndex = str.indexOf('\\', index);
  4468. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  4469. return true;
  4470. }
  4471. }
  4472. }
  4473. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  4474. closeCurlyIndex = str.indexOf('}', index);
  4475. if (closeCurlyIndex > index) {
  4476. backSlashIndex = str.indexOf('\\', index);
  4477. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  4478. return true;
  4479. }
  4480. }
  4481. }
  4482. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  4483. closeParenIndex = str.indexOf(')', index);
  4484. if (closeParenIndex > index) {
  4485. backSlashIndex = str.indexOf('\\', index);
  4486. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  4487. return true;
  4488. }
  4489. }
  4490. }
  4491. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  4492. if (pipeIndex < index) {
  4493. pipeIndex = str.indexOf('|', index);
  4494. }
  4495. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  4496. closeParenIndex = str.indexOf(')', pipeIndex);
  4497. if (closeParenIndex > pipeIndex) {
  4498. backSlashIndex = str.indexOf('\\', pipeIndex);
  4499. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  4500. return true;
  4501. }
  4502. }
  4503. }
  4504. }
  4505. if (str[index] === '\\') {
  4506. var open = str[index + 1];
  4507. index += 2;
  4508. var close = chars[open];
  4509. if (close) {
  4510. var n = str.indexOf(close, index);
  4511. if (n !== -1) {
  4512. index = n + 1;
  4513. }
  4514. }
  4515. if (str[index] === '!') {
  4516. return true;
  4517. }
  4518. } else {
  4519. index++;
  4520. }
  4521. }
  4522. return false;
  4523. };
  4524. var relaxedCheck = function(str) {
  4525. if (str[0] === '!') {
  4526. return true;
  4527. }
  4528. var index = 0;
  4529. while (index < str.length) {
  4530. if (/[*?{}()[\]]/.test(str[index])) {
  4531. return true;
  4532. }
  4533. if (str[index] === '\\') {
  4534. var open = str[index + 1];
  4535. index += 2;
  4536. var close = chars[open];
  4537. if (close) {
  4538. var n = str.indexOf(close, index);
  4539. if (n !== -1) {
  4540. index = n + 1;
  4541. }
  4542. }
  4543. if (str[index] === '!') {
  4544. return true;
  4545. }
  4546. } else {
  4547. index++;
  4548. }
  4549. }
  4550. return false;
  4551. };
  4552. isGlob = function isGlob(str, options) {
  4553. if (typeof str !== 'string' || str === '') {
  4554. return false;
  4555. }
  4556. if (isExtglob(str)) {
  4557. return true;
  4558. }
  4559. var check = strictCheck;
  4560. // optionally relax check
  4561. if (options && options.strict === false) {
  4562. check = relaxedCheck;
  4563. }
  4564. return check(str);
  4565. };
  4566. return isGlob;
  4567. }
  4568. var globParent;
  4569. var hasRequiredGlobParent;
  4570. function requireGlobParent () {
  4571. if (hasRequiredGlobParent) return globParent;
  4572. hasRequiredGlobParent = 1;
  4573. var isGlob = /*@__PURE__*/ requireIsGlob();
  4574. var pathPosixDirname = require$$0$1.posix.dirname;
  4575. var isWin32 = require$$2$1.platform() === 'win32';
  4576. var slash = '/';
  4577. var backslash = /\\/g;
  4578. var enclosure = /[\{\[].*[\}\]]$/;
  4579. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  4580. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  4581. /**
  4582. * @param {string} str
  4583. * @param {Object} opts
  4584. * @param {boolean} [opts.flipBackslashes=true]
  4585. * @returns {string}
  4586. */
  4587. globParent = function globParent(str, opts) {
  4588. var options = Object.assign({ flipBackslashes: true }, opts);
  4589. // flip windows path separators
  4590. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  4591. str = str.replace(backslash, slash);
  4592. }
  4593. // special case for strings ending in enclosure containing path separator
  4594. if (enclosure.test(str)) {
  4595. str += slash;
  4596. }
  4597. // preserves full path in case of trailing path separator
  4598. str += 'a';
  4599. // remove path parts that are globby
  4600. do {
  4601. str = pathPosixDirname(str);
  4602. } while (isGlob(str) || globby.test(str));
  4603. // remove escape chars and return result
  4604. return str.replace(escaped, '$1');
  4605. };
  4606. return globParent;
  4607. }
  4608. var utils = {};
  4609. var hasRequiredUtils;
  4610. function requireUtils () {
  4611. if (hasRequiredUtils) return utils;
  4612. hasRequiredUtils = 1;
  4613. (function (exports$1) {
  4614. exports$1.isInteger = num => {
  4615. if (typeof num === 'number') {
  4616. return Number.isInteger(num);
  4617. }
  4618. if (typeof num === 'string' && num.trim() !== '') {
  4619. return Number.isInteger(Number(num));
  4620. }
  4621. return false;
  4622. };
  4623. /**
  4624. * Find a node of the given type
  4625. */
  4626. exports$1.find = (node, type) => node.nodes.find(node => node.type === type);
  4627. /**
  4628. * Find a node of the given type
  4629. */
  4630. exports$1.exceedsLimit = (min, max, step = 1, limit) => {
  4631. if (limit === false) return false;
  4632. if (!exports$1.isInteger(min) || !exports$1.isInteger(max)) return false;
  4633. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  4634. };
  4635. /**
  4636. * Escape the given node with '\\' before node.value
  4637. */
  4638. exports$1.escapeNode = (block, n = 0, type) => {
  4639. const node = block.nodes[n];
  4640. if (!node) return;
  4641. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  4642. if (node.escaped !== true) {
  4643. node.value = '\\' + node.value;
  4644. node.escaped = true;
  4645. }
  4646. }
  4647. };
  4648. /**
  4649. * Returns true if the given brace node should be enclosed in literal braces
  4650. */
  4651. exports$1.encloseBrace = node => {
  4652. if (node.type !== 'brace') return false;
  4653. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  4654. node.invalid = true;
  4655. return true;
  4656. }
  4657. return false;
  4658. };
  4659. /**
  4660. * Returns true if a brace node is invalid.
  4661. */
  4662. exports$1.isInvalidBrace = block => {
  4663. if (block.type !== 'brace') return false;
  4664. if (block.invalid === true || block.dollar) return true;
  4665. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  4666. block.invalid = true;
  4667. return true;
  4668. }
  4669. if (block.open !== true || block.close !== true) {
  4670. block.invalid = true;
  4671. return true;
  4672. }
  4673. return false;
  4674. };
  4675. /**
  4676. * Returns true if a node is an open or close node
  4677. */
  4678. exports$1.isOpenOrClose = node => {
  4679. if (node.type === 'open' || node.type === 'close') {
  4680. return true;
  4681. }
  4682. return node.open === true || node.close === true;
  4683. };
  4684. /**
  4685. * Reduce an array of text nodes.
  4686. */
  4687. exports$1.reduce = nodes => nodes.reduce((acc, node) => {
  4688. if (node.type === 'text') acc.push(node.value);
  4689. if (node.type === 'range') node.type = 'text';
  4690. return acc;
  4691. }, []);
  4692. /**
  4693. * Flatten an array
  4694. */
  4695. exports$1.flatten = (...args) => {
  4696. const result = [];
  4697. const flat = arr => {
  4698. for (let i = 0; i < arr.length; i++) {
  4699. const ele = arr[i];
  4700. if (Array.isArray(ele)) {
  4701. flat(ele);
  4702. continue;
  4703. }
  4704. if (ele !== undefined) {
  4705. result.push(ele);
  4706. }
  4707. }
  4708. return result;
  4709. };
  4710. flat(args);
  4711. return result;
  4712. };
  4713. } (utils));
  4714. return utils;
  4715. }
  4716. var stringify;
  4717. var hasRequiredStringify;
  4718. function requireStringify () {
  4719. if (hasRequiredStringify) return stringify;
  4720. hasRequiredStringify = 1;
  4721. const utils = /*@__PURE__*/ requireUtils();
  4722. stringify = (ast, options = {}) => {
  4723. const stringify = (node, parent = {}) => {
  4724. const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
  4725. const invalidNode = node.invalid === true && options.escapeInvalid === true;
  4726. let output = '';
  4727. if (node.value) {
  4728. if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
  4729. return '\\' + node.value;
  4730. }
  4731. return node.value;
  4732. }
  4733. if (node.value) {
  4734. return node.value;
  4735. }
  4736. if (node.nodes) {
  4737. for (const child of node.nodes) {
  4738. output += stringify(child);
  4739. }
  4740. }
  4741. return output;
  4742. };
  4743. return stringify(ast);
  4744. };
  4745. return stringify;
  4746. }
  4747. /*!
  4748. * is-number <https://github.com/jonschlinkert/is-number>
  4749. *
  4750. * Copyright (c) 2014-present, Jon Schlinkert.
  4751. * Released under the MIT License.
  4752. */
  4753. var isNumber;
  4754. var hasRequiredIsNumber;
  4755. function requireIsNumber () {
  4756. if (hasRequiredIsNumber) return isNumber;
  4757. hasRequiredIsNumber = 1;
  4758. isNumber = function(num) {
  4759. if (typeof num === 'number') {
  4760. return num - num === 0;
  4761. }
  4762. if (typeof num === 'string' && num.trim() !== '') {
  4763. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  4764. }
  4765. return false;
  4766. };
  4767. return isNumber;
  4768. }
  4769. /*!
  4770. * to-regex-range <https://github.com/micromatch/to-regex-range>
  4771. *
  4772. * Copyright (c) 2015-present, Jon Schlinkert.
  4773. * Released under the MIT License.
  4774. */
  4775. var toRegexRange_1;
  4776. var hasRequiredToRegexRange;
  4777. function requireToRegexRange () {
  4778. if (hasRequiredToRegexRange) return toRegexRange_1;
  4779. hasRequiredToRegexRange = 1;
  4780. const isNumber = /*@__PURE__*/ requireIsNumber();
  4781. const toRegexRange = (min, max, options) => {
  4782. if (isNumber(min) === false) {
  4783. throw new TypeError('toRegexRange: expected the first argument to be a number');
  4784. }
  4785. if (max === void 0 || min === max) {
  4786. return String(min);
  4787. }
  4788. if (isNumber(max) === false) {
  4789. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  4790. }
  4791. let opts = { relaxZeros: true, ...options };
  4792. if (typeof opts.strictZeros === 'boolean') {
  4793. opts.relaxZeros = opts.strictZeros === false;
  4794. }
  4795. let relax = String(opts.relaxZeros);
  4796. let shorthand = String(opts.shorthand);
  4797. let capture = String(opts.capture);
  4798. let wrap = String(opts.wrap);
  4799. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  4800. if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
  4801. return toRegexRange.cache[cacheKey].result;
  4802. }
  4803. let a = Math.min(min, max);
  4804. let b = Math.max(min, max);
  4805. if (Math.abs(a - b) === 1) {
  4806. let result = min + '|' + max;
  4807. if (opts.capture) {
  4808. return `(${result})`;
  4809. }
  4810. if (opts.wrap === false) {
  4811. return result;
  4812. }
  4813. return `(?:${result})`;
  4814. }
  4815. let isPadded = hasPadding(min) || hasPadding(max);
  4816. let state = { min, max, a, b };
  4817. let positives = [];
  4818. let negatives = [];
  4819. if (isPadded) {
  4820. state.isPadded = isPadded;
  4821. state.maxLen = String(state.max).length;
  4822. }
  4823. if (a < 0) {
  4824. let newMin = b < 0 ? Math.abs(b) : 1;
  4825. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  4826. a = state.a = 0;
  4827. }
  4828. if (b >= 0) {
  4829. positives = splitToPatterns(a, b, state, opts);
  4830. }
  4831. state.negatives = negatives;
  4832. state.positives = positives;
  4833. state.result = collatePatterns(negatives, positives);
  4834. if (opts.capture === true) {
  4835. state.result = `(${state.result})`;
  4836. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  4837. state.result = `(?:${state.result})`;
  4838. }
  4839. toRegexRange.cache[cacheKey] = state;
  4840. return state.result;
  4841. };
  4842. function collatePatterns(neg, pos, options) {
  4843. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  4844. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  4845. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  4846. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  4847. return subpatterns.join('|');
  4848. }
  4849. function splitToRanges(min, max) {
  4850. let nines = 1;
  4851. let zeros = 1;
  4852. let stop = countNines(min, nines);
  4853. let stops = new Set([max]);
  4854. while (min <= stop && stop <= max) {
  4855. stops.add(stop);
  4856. nines += 1;
  4857. stop = countNines(min, nines);
  4858. }
  4859. stop = countZeros(max + 1, zeros) - 1;
  4860. while (min < stop && stop <= max) {
  4861. stops.add(stop);
  4862. zeros += 1;
  4863. stop = countZeros(max + 1, zeros) - 1;
  4864. }
  4865. stops = [...stops];
  4866. stops.sort(compare);
  4867. return stops;
  4868. }
  4869. /**
  4870. * Convert a range to a regex pattern
  4871. * @param {Number} `start`
  4872. * @param {Number} `stop`
  4873. * @return {String}
  4874. */
  4875. function rangeToPattern(start, stop, options) {
  4876. if (start === stop) {
  4877. return { pattern: start, count: [], digits: 0 };
  4878. }
  4879. let zipped = zip(start, stop);
  4880. let digits = zipped.length;
  4881. let pattern = '';
  4882. let count = 0;
  4883. for (let i = 0; i < digits; i++) {
  4884. let [startDigit, stopDigit] = zipped[i];
  4885. if (startDigit === stopDigit) {
  4886. pattern += startDigit;
  4887. } else if (startDigit !== '0' || stopDigit !== '9') {
  4888. pattern += toCharacterClass(startDigit, stopDigit);
  4889. } else {
  4890. count++;
  4891. }
  4892. }
  4893. if (count) {
  4894. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  4895. }
  4896. return { pattern, count: [count], digits };
  4897. }
  4898. function splitToPatterns(min, max, tok, options) {
  4899. let ranges = splitToRanges(min, max);
  4900. let tokens = [];
  4901. let start = min;
  4902. let prev;
  4903. for (let i = 0; i < ranges.length; i++) {
  4904. let max = ranges[i];
  4905. let obj = rangeToPattern(String(start), String(max), options);
  4906. let zeros = '';
  4907. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  4908. if (prev.count.length > 1) {
  4909. prev.count.pop();
  4910. }
  4911. prev.count.push(obj.count[0]);
  4912. prev.string = prev.pattern + toQuantifier(prev.count);
  4913. start = max + 1;
  4914. continue;
  4915. }
  4916. if (tok.isPadded) {
  4917. zeros = padZeros(max, tok, options);
  4918. }
  4919. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  4920. tokens.push(obj);
  4921. start = max + 1;
  4922. prev = obj;
  4923. }
  4924. return tokens;
  4925. }
  4926. function filterPatterns(arr, comparison, prefix, intersection, options) {
  4927. let result = [];
  4928. for (let ele of arr) {
  4929. let { string } = ele;
  4930. // only push if _both_ are negative...
  4931. if (!intersection && !contains(comparison, 'string', string)) {
  4932. result.push(prefix + string);
  4933. }
  4934. // or _both_ are positive
  4935. if (intersection && contains(comparison, 'string', string)) {
  4936. result.push(prefix + string);
  4937. }
  4938. }
  4939. return result;
  4940. }
  4941. /**
  4942. * Zip strings
  4943. */
  4944. function zip(a, b) {
  4945. let arr = [];
  4946. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  4947. return arr;
  4948. }
  4949. function compare(a, b) {
  4950. return a > b ? 1 : b > a ? -1 : 0;
  4951. }
  4952. function contains(arr, key, val) {
  4953. return arr.some(ele => ele[key] === val);
  4954. }
  4955. function countNines(min, len) {
  4956. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  4957. }
  4958. function countZeros(integer, zeros) {
  4959. return integer - (integer % Math.pow(10, zeros));
  4960. }
  4961. function toQuantifier(digits) {
  4962. let [start = 0, stop = ''] = digits;
  4963. if (stop || start > 1) {
  4964. return `{${start + (stop ? ',' + stop : '')}}`;
  4965. }
  4966. return '';
  4967. }
  4968. function toCharacterClass(a, b, options) {
  4969. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  4970. }
  4971. function hasPadding(str) {
  4972. return /^-?(0+)\d/.test(str);
  4973. }
  4974. function padZeros(value, tok, options) {
  4975. if (!tok.isPadded) {
  4976. return value;
  4977. }
  4978. let diff = Math.abs(tok.maxLen - String(value).length);
  4979. let relax = options.relaxZeros !== false;
  4980. switch (diff) {
  4981. case 0:
  4982. return '';
  4983. case 1:
  4984. return relax ? '0?' : '0';
  4985. case 2:
  4986. return relax ? '0{0,2}' : '00';
  4987. default: {
  4988. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  4989. }
  4990. }
  4991. }
  4992. /**
  4993. * Cache
  4994. */
  4995. toRegexRange.cache = {};
  4996. toRegexRange.clearCache = () => (toRegexRange.cache = {});
  4997. /**
  4998. * Expose `toRegexRange`
  4999. */
  5000. toRegexRange_1 = toRegexRange;
  5001. return toRegexRange_1;
  5002. }
  5003. /*!
  5004. * fill-range <https://github.com/jonschlinkert/fill-range>
  5005. *
  5006. * Copyright (c) 2014-present, Jon Schlinkert.
  5007. * Licensed under the MIT License.
  5008. */
  5009. var fillRange;
  5010. var hasRequiredFillRange;
  5011. function requireFillRange () {
  5012. if (hasRequiredFillRange) return fillRange;
  5013. hasRequiredFillRange = 1;
  5014. const util = require$$2;
  5015. const toRegexRange = /*@__PURE__*/ requireToRegexRange();
  5016. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  5017. const transform = toNumber => {
  5018. return value => toNumber === true ? Number(value) : String(value);
  5019. };
  5020. const isValidValue = value => {
  5021. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  5022. };
  5023. const isNumber = num => Number.isInteger(+num);
  5024. const zeros = input => {
  5025. let value = `${input}`;
  5026. let index = -1;
  5027. if (value[0] === '-') value = value.slice(1);
  5028. if (value === '0') return false;
  5029. while (value[++index] === '0');
  5030. return index > 0;
  5031. };
  5032. const stringify = (start, end, options) => {
  5033. if (typeof start === 'string' || typeof end === 'string') {
  5034. return true;
  5035. }
  5036. return options.stringify === true;
  5037. };
  5038. const pad = (input, maxLength, toNumber) => {
  5039. if (maxLength > 0) {
  5040. let dash = input[0] === '-' ? '-' : '';
  5041. if (dash) input = input.slice(1);
  5042. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  5043. }
  5044. if (toNumber === false) {
  5045. return String(input);
  5046. }
  5047. return input;
  5048. };
  5049. const toMaxLen = (input, maxLength) => {
  5050. let negative = input[0] === '-' ? '-' : '';
  5051. if (negative) {
  5052. input = input.slice(1);
  5053. maxLength--;
  5054. }
  5055. while (input.length < maxLength) input = '0' + input;
  5056. return negative ? ('-' + input) : input;
  5057. };
  5058. const toSequence = (parts, options, maxLen) => {
  5059. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  5060. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  5061. let prefix = options.capture ? '' : '?:';
  5062. let positives = '';
  5063. let negatives = '';
  5064. let result;
  5065. if (parts.positives.length) {
  5066. positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|');
  5067. }
  5068. if (parts.negatives.length) {
  5069. negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`;
  5070. }
  5071. if (positives && negatives) {
  5072. result = `${positives}|${negatives}`;
  5073. } else {
  5074. result = positives || negatives;
  5075. }
  5076. if (options.wrap) {
  5077. return `(${prefix}${result})`;
  5078. }
  5079. return result;
  5080. };
  5081. const toRange = (a, b, isNumbers, options) => {
  5082. if (isNumbers) {
  5083. return toRegexRange(a, b, { wrap: false, ...options });
  5084. }
  5085. let start = String.fromCharCode(a);
  5086. if (a === b) return start;
  5087. let stop = String.fromCharCode(b);
  5088. return `[${start}-${stop}]`;
  5089. };
  5090. const toRegex = (start, end, options) => {
  5091. if (Array.isArray(start)) {
  5092. let wrap = options.wrap === true;
  5093. let prefix = options.capture ? '' : '?:';
  5094. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  5095. }
  5096. return toRegexRange(start, end, options);
  5097. };
  5098. const rangeError = (...args) => {
  5099. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  5100. };
  5101. const invalidRange = (start, end, options) => {
  5102. if (options.strictRanges === true) throw rangeError([start, end]);
  5103. return [];
  5104. };
  5105. const invalidStep = (step, options) => {
  5106. if (options.strictRanges === true) {
  5107. throw new TypeError(`Expected step "${step}" to be a number`);
  5108. }
  5109. return [];
  5110. };
  5111. const fillNumbers = (start, end, step = 1, options = {}) => {
  5112. let a = Number(start);
  5113. let b = Number(end);
  5114. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  5115. if (options.strictRanges === true) throw rangeError([start, end]);
  5116. return [];
  5117. }
  5118. // fix negative zero
  5119. if (a === 0) a = 0;
  5120. if (b === 0) b = 0;
  5121. let descending = a > b;
  5122. let startString = String(start);
  5123. let endString = String(end);
  5124. let stepString = String(step);
  5125. step = Math.max(Math.abs(step), 1);
  5126. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  5127. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  5128. let toNumber = padded === false && stringify(start, end, options) === false;
  5129. let format = options.transform || transform(toNumber);
  5130. if (options.toRegex && step === 1) {
  5131. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  5132. }
  5133. let parts = { negatives: [], positives: [] };
  5134. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  5135. let range = [];
  5136. let index = 0;
  5137. while (descending ? a >= b : a <= b) {
  5138. if (options.toRegex === true && step > 1) {
  5139. push(a);
  5140. } else {
  5141. range.push(pad(format(a, index), maxLen, toNumber));
  5142. }
  5143. a = descending ? a - step : a + step;
  5144. index++;
  5145. }
  5146. if (options.toRegex === true) {
  5147. return step > 1
  5148. ? toSequence(parts, options, maxLen)
  5149. : toRegex(range, null, { wrap: false, ...options });
  5150. }
  5151. return range;
  5152. };
  5153. const fillLetters = (start, end, step = 1, options = {}) => {
  5154. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  5155. return invalidRange(start, end, options);
  5156. }
  5157. let format = options.transform || (val => String.fromCharCode(val));
  5158. let a = `${start}`.charCodeAt(0);
  5159. let b = `${end}`.charCodeAt(0);
  5160. let descending = a > b;
  5161. let min = Math.min(a, b);
  5162. let max = Math.max(a, b);
  5163. if (options.toRegex && step === 1) {
  5164. return toRange(min, max, false, options);
  5165. }
  5166. let range = [];
  5167. let index = 0;
  5168. while (descending ? a >= b : a <= b) {
  5169. range.push(format(a, index));
  5170. a = descending ? a - step : a + step;
  5171. index++;
  5172. }
  5173. if (options.toRegex === true) {
  5174. return toRegex(range, null, { wrap: false, options });
  5175. }
  5176. return range;
  5177. };
  5178. const fill = (start, end, step, options = {}) => {
  5179. if (end == null && isValidValue(start)) {
  5180. return [start];
  5181. }
  5182. if (!isValidValue(start) || !isValidValue(end)) {
  5183. return invalidRange(start, end, options);
  5184. }
  5185. if (typeof step === 'function') {
  5186. return fill(start, end, 1, { transform: step });
  5187. }
  5188. if (isObject(step)) {
  5189. return fill(start, end, 0, step);
  5190. }
  5191. let opts = { ...options };
  5192. if (opts.capture === true) opts.wrap = true;
  5193. step = step || opts.step || 1;
  5194. if (!isNumber(step)) {
  5195. if (step != null && !isObject(step)) return invalidStep(step, opts);
  5196. return fill(start, end, 1, step);
  5197. }
  5198. if (isNumber(start) && isNumber(end)) {
  5199. return fillNumbers(start, end, step, opts);
  5200. }
  5201. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  5202. };
  5203. fillRange = fill;
  5204. return fillRange;
  5205. }
  5206. var compile_1;
  5207. var hasRequiredCompile;
  5208. function requireCompile () {
  5209. if (hasRequiredCompile) return compile_1;
  5210. hasRequiredCompile = 1;
  5211. const fill = /*@__PURE__*/ requireFillRange();
  5212. const utils = /*@__PURE__*/ requireUtils();
  5213. const compile = (ast, options = {}) => {
  5214. const walk = (node, parent = {}) => {
  5215. const invalidBlock = utils.isInvalidBrace(parent);
  5216. const invalidNode = node.invalid === true && options.escapeInvalid === true;
  5217. const invalid = invalidBlock === true || invalidNode === true;
  5218. const prefix = options.escapeInvalid === true ? '\\' : '';
  5219. let output = '';
  5220. if (node.isOpen === true) {
  5221. return prefix + node.value;
  5222. }
  5223. if (node.isClose === true) {
  5224. console.log('node.isClose', prefix, node.value);
  5225. return prefix + node.value;
  5226. }
  5227. if (node.type === 'open') {
  5228. return invalid ? prefix + node.value : '(';
  5229. }
  5230. if (node.type === 'close') {
  5231. return invalid ? prefix + node.value : ')';
  5232. }
  5233. if (node.type === 'comma') {
  5234. return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
  5235. }
  5236. if (node.value) {
  5237. return node.value;
  5238. }
  5239. if (node.nodes && node.ranges > 0) {
  5240. const args = utils.reduce(node.nodes);
  5241. const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true });
  5242. if (range.length !== 0) {
  5243. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  5244. }
  5245. }
  5246. if (node.nodes) {
  5247. for (const child of node.nodes) {
  5248. output += walk(child, node);
  5249. }
  5250. }
  5251. return output;
  5252. };
  5253. return walk(ast);
  5254. };
  5255. compile_1 = compile;
  5256. return compile_1;
  5257. }
  5258. var expand_1;
  5259. var hasRequiredExpand;
  5260. function requireExpand () {
  5261. if (hasRequiredExpand) return expand_1;
  5262. hasRequiredExpand = 1;
  5263. const fill = /*@__PURE__*/ requireFillRange();
  5264. const stringify = /*@__PURE__*/ requireStringify();
  5265. const utils = /*@__PURE__*/ requireUtils();
  5266. const append = (queue = '', stash = '', enclose = false) => {
  5267. const result = [];
  5268. queue = [].concat(queue);
  5269. stash = [].concat(stash);
  5270. if (!stash.length) return queue;
  5271. if (!queue.length) {
  5272. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  5273. }
  5274. for (const item of queue) {
  5275. if (Array.isArray(item)) {
  5276. for (const value of item) {
  5277. result.push(append(value, stash, enclose));
  5278. }
  5279. } else {
  5280. for (let ele of stash) {
  5281. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  5282. result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
  5283. }
  5284. }
  5285. }
  5286. return utils.flatten(result);
  5287. };
  5288. const expand = (ast, options = {}) => {
  5289. const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit;
  5290. const walk = (node, parent = {}) => {
  5291. node.queue = [];
  5292. let p = parent;
  5293. let q = parent.queue;
  5294. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  5295. p = p.parent;
  5296. q = p.queue;
  5297. }
  5298. if (node.invalid || node.dollar) {
  5299. q.push(append(q.pop(), stringify(node, options)));
  5300. return;
  5301. }
  5302. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  5303. q.push(append(q.pop(), ['{}']));
  5304. return;
  5305. }
  5306. if (node.nodes && node.ranges > 0) {
  5307. const args = utils.reduce(node.nodes);
  5308. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  5309. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  5310. }
  5311. let range = fill(...args, options);
  5312. if (range.length === 0) {
  5313. range = stringify(node, options);
  5314. }
  5315. q.push(append(q.pop(), range));
  5316. node.nodes = [];
  5317. return;
  5318. }
  5319. const enclose = utils.encloseBrace(node);
  5320. let queue = node.queue;
  5321. let block = node;
  5322. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  5323. block = block.parent;
  5324. queue = block.queue;
  5325. }
  5326. for (let i = 0; i < node.nodes.length; i++) {
  5327. const child = node.nodes[i];
  5328. if (child.type === 'comma' && node.type === 'brace') {
  5329. if (i === 1) queue.push('');
  5330. queue.push('');
  5331. continue;
  5332. }
  5333. if (child.type === 'close') {
  5334. q.push(append(q.pop(), queue, enclose));
  5335. continue;
  5336. }
  5337. if (child.value && child.type !== 'open') {
  5338. queue.push(append(queue.pop(), child.value));
  5339. continue;
  5340. }
  5341. if (child.nodes) {
  5342. walk(child, node);
  5343. }
  5344. }
  5345. return queue;
  5346. };
  5347. return utils.flatten(walk(ast));
  5348. };
  5349. expand_1 = expand;
  5350. return expand_1;
  5351. }
  5352. var constants$1;
  5353. var hasRequiredConstants$1;
  5354. function requireConstants$1 () {
  5355. if (hasRequiredConstants$1) return constants$1;
  5356. hasRequiredConstants$1 = 1;
  5357. constants$1 = {
  5358. MAX_LENGTH: 10000,
  5359. // Digits
  5360. CHAR_0: '0', /* 0 */
  5361. CHAR_9: '9', /* 9 */
  5362. // Alphabet chars.
  5363. CHAR_UPPERCASE_A: 'A', /* A */
  5364. CHAR_LOWERCASE_A: 'a', /* a */
  5365. CHAR_UPPERCASE_Z: 'Z', /* Z */
  5366. CHAR_LOWERCASE_Z: 'z', /* z */
  5367. CHAR_LEFT_PARENTHESES: '(', /* ( */
  5368. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  5369. CHAR_ASTERISK: '*', /* * */
  5370. // Non-alphabetic chars.
  5371. CHAR_AMPERSAND: '&', /* & */
  5372. CHAR_AT: '@', /* @ */
  5373. CHAR_BACKSLASH: '\\', /* \ */
  5374. CHAR_BACKTICK: '`', /* ` */
  5375. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  5376. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  5377. CHAR_COLON: ':', /* : */
  5378. CHAR_COMMA: ',', /* , */
  5379. CHAR_DOLLAR: '$', /* . */
  5380. CHAR_DOT: '.', /* . */
  5381. CHAR_DOUBLE_QUOTE: '"', /* " */
  5382. CHAR_EQUAL: '=', /* = */
  5383. CHAR_EXCLAMATION_MARK: '!', /* ! */
  5384. CHAR_FORM_FEED: '\f', /* \f */
  5385. CHAR_FORWARD_SLASH: '/', /* / */
  5386. CHAR_HASH: '#', /* # */
  5387. CHAR_HYPHEN_MINUS: '-', /* - */
  5388. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  5389. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  5390. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  5391. CHAR_LINE_FEED: '\n', /* \n */
  5392. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  5393. CHAR_PERCENT: '%', /* % */
  5394. CHAR_PLUS: '+', /* + */
  5395. CHAR_QUESTION_MARK: '?', /* ? */
  5396. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  5397. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  5398. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  5399. CHAR_SEMICOLON: ';', /* ; */
  5400. CHAR_SINGLE_QUOTE: '\'', /* ' */
  5401. CHAR_SPACE: ' ', /* */
  5402. CHAR_TAB: '\t', /* \t */
  5403. CHAR_UNDERSCORE: '_', /* _ */
  5404. CHAR_VERTICAL_LINE: '|', /* | */
  5405. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  5406. };
  5407. return constants$1;
  5408. }
  5409. var parse_1;
  5410. var hasRequiredParse;
  5411. function requireParse () {
  5412. if (hasRequiredParse) return parse_1;
  5413. hasRequiredParse = 1;
  5414. const stringify = /*@__PURE__*/ requireStringify();
  5415. /**
  5416. * Constants
  5417. */
  5418. const {
  5419. MAX_LENGTH,
  5420. CHAR_BACKSLASH, /* \ */
  5421. CHAR_BACKTICK, /* ` */
  5422. CHAR_COMMA, /* , */
  5423. CHAR_DOT, /* . */
  5424. CHAR_LEFT_PARENTHESES, /* ( */
  5425. CHAR_RIGHT_PARENTHESES, /* ) */
  5426. CHAR_LEFT_CURLY_BRACE, /* { */
  5427. CHAR_RIGHT_CURLY_BRACE, /* } */
  5428. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  5429. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  5430. CHAR_DOUBLE_QUOTE, /* " */
  5431. CHAR_SINGLE_QUOTE, /* ' */
  5432. CHAR_NO_BREAK_SPACE,
  5433. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  5434. } = /*@__PURE__*/ requireConstants$1();
  5435. /**
  5436. * parse
  5437. */
  5438. const parse = (input, options = {}) => {
  5439. if (typeof input !== 'string') {
  5440. throw new TypeError('Expected a string');
  5441. }
  5442. const opts = options || {};
  5443. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  5444. if (input.length > max) {
  5445. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  5446. }
  5447. const ast = { type: 'root', input, nodes: [] };
  5448. const stack = [ast];
  5449. let block = ast;
  5450. let prev = ast;
  5451. let brackets = 0;
  5452. const length = input.length;
  5453. let index = 0;
  5454. let depth = 0;
  5455. let value;
  5456. /**
  5457. * Helpers
  5458. */
  5459. const advance = () => input[index++];
  5460. const push = node => {
  5461. if (node.type === 'text' && prev.type === 'dot') {
  5462. prev.type = 'text';
  5463. }
  5464. if (prev && prev.type === 'text' && node.type === 'text') {
  5465. prev.value += node.value;
  5466. return;
  5467. }
  5468. block.nodes.push(node);
  5469. node.parent = block;
  5470. node.prev = prev;
  5471. prev = node;
  5472. return node;
  5473. };
  5474. push({ type: 'bos' });
  5475. while (index < length) {
  5476. block = stack[stack.length - 1];
  5477. value = advance();
  5478. /**
  5479. * Invalid chars
  5480. */
  5481. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  5482. continue;
  5483. }
  5484. /**
  5485. * Escaped chars
  5486. */
  5487. if (value === CHAR_BACKSLASH) {
  5488. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  5489. continue;
  5490. }
  5491. /**
  5492. * Right square bracket (literal): ']'
  5493. */
  5494. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  5495. push({ type: 'text', value: '\\' + value });
  5496. continue;
  5497. }
  5498. /**
  5499. * Left square bracket: '['
  5500. */
  5501. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  5502. brackets++;
  5503. let next;
  5504. while (index < length && (next = advance())) {
  5505. value += next;
  5506. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  5507. brackets++;
  5508. continue;
  5509. }
  5510. if (next === CHAR_BACKSLASH) {
  5511. value += advance();
  5512. continue;
  5513. }
  5514. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  5515. brackets--;
  5516. if (brackets === 0) {
  5517. break;
  5518. }
  5519. }
  5520. }
  5521. push({ type: 'text', value });
  5522. continue;
  5523. }
  5524. /**
  5525. * Parentheses
  5526. */
  5527. if (value === CHAR_LEFT_PARENTHESES) {
  5528. block = push({ type: 'paren', nodes: [] });
  5529. stack.push(block);
  5530. push({ type: 'text', value });
  5531. continue;
  5532. }
  5533. if (value === CHAR_RIGHT_PARENTHESES) {
  5534. if (block.type !== 'paren') {
  5535. push({ type: 'text', value });
  5536. continue;
  5537. }
  5538. block = stack.pop();
  5539. push({ type: 'text', value });
  5540. block = stack[stack.length - 1];
  5541. continue;
  5542. }
  5543. /**
  5544. * Quotes: '|"|`
  5545. */
  5546. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  5547. const open = value;
  5548. let next;
  5549. if (options.keepQuotes !== true) {
  5550. value = '';
  5551. }
  5552. while (index < length && (next = advance())) {
  5553. if (next === CHAR_BACKSLASH) {
  5554. value += next + advance();
  5555. continue;
  5556. }
  5557. if (next === open) {
  5558. if (options.keepQuotes === true) value += next;
  5559. break;
  5560. }
  5561. value += next;
  5562. }
  5563. push({ type: 'text', value });
  5564. continue;
  5565. }
  5566. /**
  5567. * Left curly brace: '{'
  5568. */
  5569. if (value === CHAR_LEFT_CURLY_BRACE) {
  5570. depth++;
  5571. const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  5572. const brace = {
  5573. type: 'brace',
  5574. open: true,
  5575. close: false,
  5576. dollar,
  5577. depth,
  5578. commas: 0,
  5579. ranges: 0,
  5580. nodes: []
  5581. };
  5582. block = push(brace);
  5583. stack.push(block);
  5584. push({ type: 'open', value });
  5585. continue;
  5586. }
  5587. /**
  5588. * Right curly brace: '}'
  5589. */
  5590. if (value === CHAR_RIGHT_CURLY_BRACE) {
  5591. if (block.type !== 'brace') {
  5592. push({ type: 'text', value });
  5593. continue;
  5594. }
  5595. const type = 'close';
  5596. block = stack.pop();
  5597. block.close = true;
  5598. push({ type, value });
  5599. depth--;
  5600. block = stack[stack.length - 1];
  5601. continue;
  5602. }
  5603. /**
  5604. * Comma: ','
  5605. */
  5606. if (value === CHAR_COMMA && depth > 0) {
  5607. if (block.ranges > 0) {
  5608. block.ranges = 0;
  5609. const open = block.nodes.shift();
  5610. block.nodes = [open, { type: 'text', value: stringify(block) }];
  5611. }
  5612. push({ type: 'comma', value });
  5613. block.commas++;
  5614. continue;
  5615. }
  5616. /**
  5617. * Dot: '.'
  5618. */
  5619. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  5620. const siblings = block.nodes;
  5621. if (depth === 0 || siblings.length === 0) {
  5622. push({ type: 'text', value });
  5623. continue;
  5624. }
  5625. if (prev.type === 'dot') {
  5626. block.range = [];
  5627. prev.value += value;
  5628. prev.type = 'range';
  5629. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  5630. block.invalid = true;
  5631. block.ranges = 0;
  5632. prev.type = 'text';
  5633. continue;
  5634. }
  5635. block.ranges++;
  5636. block.args = [];
  5637. continue;
  5638. }
  5639. if (prev.type === 'range') {
  5640. siblings.pop();
  5641. const before = siblings[siblings.length - 1];
  5642. before.value += prev.value + value;
  5643. prev = before;
  5644. block.ranges--;
  5645. continue;
  5646. }
  5647. push({ type: 'dot', value });
  5648. continue;
  5649. }
  5650. /**
  5651. * Text
  5652. */
  5653. push({ type: 'text', value });
  5654. }
  5655. // Mark imbalanced braces and brackets as invalid
  5656. do {
  5657. block = stack.pop();
  5658. if (block.type !== 'root') {
  5659. block.nodes.forEach(node => {
  5660. if (!node.nodes) {
  5661. if (node.type === 'open') node.isOpen = true;
  5662. if (node.type === 'close') node.isClose = true;
  5663. if (!node.nodes) node.type = 'text';
  5664. node.invalid = true;
  5665. }
  5666. });
  5667. // get the location of the block on parent.nodes (block's siblings)
  5668. const parent = stack[stack.length - 1];
  5669. const index = parent.nodes.indexOf(block);
  5670. // replace the (invalid) block with it's nodes
  5671. parent.nodes.splice(index, 1, ...block.nodes);
  5672. }
  5673. } while (stack.length > 0);
  5674. push({ type: 'eos' });
  5675. return ast;
  5676. };
  5677. parse_1 = parse;
  5678. return parse_1;
  5679. }
  5680. var braces_1;
  5681. var hasRequiredBraces;
  5682. function requireBraces () {
  5683. if (hasRequiredBraces) return braces_1;
  5684. hasRequiredBraces = 1;
  5685. const stringify = /*@__PURE__*/ requireStringify();
  5686. const compile = /*@__PURE__*/ requireCompile();
  5687. const expand = /*@__PURE__*/ requireExpand();
  5688. const parse = /*@__PURE__*/ requireParse();
  5689. /**
  5690. * Expand the given pattern or create a regex-compatible string.
  5691. *
  5692. * ```js
  5693. * const braces = require('braces');
  5694. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  5695. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  5696. * ```
  5697. * @param {String} `str`
  5698. * @param {Object} `options`
  5699. * @return {String}
  5700. * @api public
  5701. */
  5702. const braces = (input, options = {}) => {
  5703. let output = [];
  5704. if (Array.isArray(input)) {
  5705. for (const pattern of input) {
  5706. const result = braces.create(pattern, options);
  5707. if (Array.isArray(result)) {
  5708. output.push(...result);
  5709. } else {
  5710. output.push(result);
  5711. }
  5712. }
  5713. } else {
  5714. output = [].concat(braces.create(input, options));
  5715. }
  5716. if (options && options.expand === true && options.nodupes === true) {
  5717. output = [...new Set(output)];
  5718. }
  5719. return output;
  5720. };
  5721. /**
  5722. * Parse the given `str` with the given `options`.
  5723. *
  5724. * ```js
  5725. * // braces.parse(pattern, [, options]);
  5726. * const ast = braces.parse('a/{b,c}/d');
  5727. * console.log(ast);
  5728. * ```
  5729. * @param {String} pattern Brace pattern to parse
  5730. * @param {Object} options
  5731. * @return {Object} Returns an AST
  5732. * @api public
  5733. */
  5734. braces.parse = (input, options = {}) => parse(input, options);
  5735. /**
  5736. * Creates a braces string from an AST, or an AST node.
  5737. *
  5738. * ```js
  5739. * const braces = require('braces');
  5740. * let ast = braces.parse('foo/{a,b}/bar');
  5741. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  5742. * ```
  5743. * @param {String} `input` Brace pattern or AST.
  5744. * @param {Object} `options`
  5745. * @return {Array} Returns an array of expanded values.
  5746. * @api public
  5747. */
  5748. braces.stringify = (input, options = {}) => {
  5749. if (typeof input === 'string') {
  5750. return stringify(braces.parse(input, options), options);
  5751. }
  5752. return stringify(input, options);
  5753. };
  5754. /**
  5755. * Compiles a brace pattern into a regex-compatible, optimized string.
  5756. * This method is called by the main [braces](#braces) function by default.
  5757. *
  5758. * ```js
  5759. * const braces = require('braces');
  5760. * console.log(braces.compile('a/{b,c}/d'));
  5761. * //=> ['a/(b|c)/d']
  5762. * ```
  5763. * @param {String} `input` Brace pattern or AST.
  5764. * @param {Object} `options`
  5765. * @return {Array} Returns an array of expanded values.
  5766. * @api public
  5767. */
  5768. braces.compile = (input, options = {}) => {
  5769. if (typeof input === 'string') {
  5770. input = braces.parse(input, options);
  5771. }
  5772. return compile(input, options);
  5773. };
  5774. /**
  5775. * Expands a brace pattern into an array. This method is called by the
  5776. * main [braces](#braces) function when `options.expand` is true. Before
  5777. * using this method it's recommended that you read the [performance notes](#performance))
  5778. * and advantages of using [.compile](#compile) instead.
  5779. *
  5780. * ```js
  5781. * const braces = require('braces');
  5782. * console.log(braces.expand('a/{b,c}/d'));
  5783. * //=> ['a/b/d', 'a/c/d'];
  5784. * ```
  5785. * @param {String} `pattern` Brace pattern
  5786. * @param {Object} `options`
  5787. * @return {Array} Returns an array of expanded values.
  5788. * @api public
  5789. */
  5790. braces.expand = (input, options = {}) => {
  5791. if (typeof input === 'string') {
  5792. input = braces.parse(input, options);
  5793. }
  5794. let result = expand(input, options);
  5795. // filter out empty strings if specified
  5796. if (options.noempty === true) {
  5797. result = result.filter(Boolean);
  5798. }
  5799. // filter out duplicates if specified
  5800. if (options.nodupes === true) {
  5801. result = [...new Set(result)];
  5802. }
  5803. return result;
  5804. };
  5805. /**
  5806. * Processes a brace pattern and returns either an expanded array
  5807. * (if `options.expand` is true), a highly optimized regex-compatible string.
  5808. * This method is called by the main [braces](#braces) function.
  5809. *
  5810. * ```js
  5811. * const braces = require('braces');
  5812. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  5813. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  5814. * ```
  5815. * @param {String} `pattern` Brace pattern
  5816. * @param {Object} `options`
  5817. * @return {Array} Returns an array of expanded values.
  5818. * @api public
  5819. */
  5820. braces.create = (input, options = {}) => {
  5821. if (input === '' || input.length < 3) {
  5822. return [input];
  5823. }
  5824. return options.expand !== true
  5825. ? braces.compile(input, options)
  5826. : braces.expand(input, options);
  5827. };
  5828. /**
  5829. * Expose "braces"
  5830. */
  5831. braces_1 = braces;
  5832. return braces_1;
  5833. }
  5834. const require$$0 = [
  5835. "3dm",
  5836. "3ds",
  5837. "3g2",
  5838. "3gp",
  5839. "7z",
  5840. "a",
  5841. "aac",
  5842. "adp",
  5843. "afdesign",
  5844. "afphoto",
  5845. "afpub",
  5846. "ai",
  5847. "aif",
  5848. "aiff",
  5849. "alz",
  5850. "ape",
  5851. "apk",
  5852. "appimage",
  5853. "ar",
  5854. "arj",
  5855. "asf",
  5856. "au",
  5857. "avi",
  5858. "bak",
  5859. "baml",
  5860. "bh",
  5861. "bin",
  5862. "bk",
  5863. "bmp",
  5864. "btif",
  5865. "bz2",
  5866. "bzip2",
  5867. "cab",
  5868. "caf",
  5869. "cgm",
  5870. "class",
  5871. "cmx",
  5872. "cpio",
  5873. "cr2",
  5874. "cur",
  5875. "dat",
  5876. "dcm",
  5877. "deb",
  5878. "dex",
  5879. "djvu",
  5880. "dll",
  5881. "dmg",
  5882. "dng",
  5883. "doc",
  5884. "docm",
  5885. "docx",
  5886. "dot",
  5887. "dotm",
  5888. "dra",
  5889. "DS_Store",
  5890. "dsk",
  5891. "dts",
  5892. "dtshd",
  5893. "dvb",
  5894. "dwg",
  5895. "dxf",
  5896. "ecelp4800",
  5897. "ecelp7470",
  5898. "ecelp9600",
  5899. "egg",
  5900. "eol",
  5901. "eot",
  5902. "epub",
  5903. "exe",
  5904. "f4v",
  5905. "fbs",
  5906. "fh",
  5907. "fla",
  5908. "flac",
  5909. "flatpak",
  5910. "fli",
  5911. "flv",
  5912. "fpx",
  5913. "fst",
  5914. "fvt",
  5915. "g3",
  5916. "gh",
  5917. "gif",
  5918. "graffle",
  5919. "gz",
  5920. "gzip",
  5921. "h261",
  5922. "h263",
  5923. "h264",
  5924. "icns",
  5925. "ico",
  5926. "ief",
  5927. "img",
  5928. "ipa",
  5929. "iso",
  5930. "jar",
  5931. "jpeg",
  5932. "jpg",
  5933. "jpgv",
  5934. "jpm",
  5935. "jxr",
  5936. "key",
  5937. "ktx",
  5938. "lha",
  5939. "lib",
  5940. "lvp",
  5941. "lz",
  5942. "lzh",
  5943. "lzma",
  5944. "lzo",
  5945. "m3u",
  5946. "m4a",
  5947. "m4v",
  5948. "mar",
  5949. "mdi",
  5950. "mht",
  5951. "mid",
  5952. "midi",
  5953. "mj2",
  5954. "mka",
  5955. "mkv",
  5956. "mmr",
  5957. "mng",
  5958. "mobi",
  5959. "mov",
  5960. "movie",
  5961. "mp3",
  5962. "mp4",
  5963. "mp4a",
  5964. "mpeg",
  5965. "mpg",
  5966. "mpga",
  5967. "mxu",
  5968. "nef",
  5969. "npx",
  5970. "numbers",
  5971. "nupkg",
  5972. "o",
  5973. "odp",
  5974. "ods",
  5975. "odt",
  5976. "oga",
  5977. "ogg",
  5978. "ogv",
  5979. "otf",
  5980. "ott",
  5981. "pages",
  5982. "pbm",
  5983. "pcx",
  5984. "pdb",
  5985. "pdf",
  5986. "pea",
  5987. "pgm",
  5988. "pic",
  5989. "png",
  5990. "pnm",
  5991. "pot",
  5992. "potm",
  5993. "potx",
  5994. "ppa",
  5995. "ppam",
  5996. "ppm",
  5997. "pps",
  5998. "ppsm",
  5999. "ppsx",
  6000. "ppt",
  6001. "pptm",
  6002. "pptx",
  6003. "psd",
  6004. "pya",
  6005. "pyc",
  6006. "pyo",
  6007. "pyv",
  6008. "qt",
  6009. "rar",
  6010. "ras",
  6011. "raw",
  6012. "resources",
  6013. "rgb",
  6014. "rip",
  6015. "rlc",
  6016. "rmf",
  6017. "rmvb",
  6018. "rpm",
  6019. "rtf",
  6020. "rz",
  6021. "s3m",
  6022. "s7z",
  6023. "scpt",
  6024. "sgi",
  6025. "shar",
  6026. "snap",
  6027. "sil",
  6028. "sketch",
  6029. "slk",
  6030. "smv",
  6031. "snk",
  6032. "so",
  6033. "stl",
  6034. "suo",
  6035. "sub",
  6036. "swf",
  6037. "tar",
  6038. "tbz",
  6039. "tbz2",
  6040. "tga",
  6041. "tgz",
  6042. "thmx",
  6043. "tif",
  6044. "tiff",
  6045. "tlz",
  6046. "ttc",
  6047. "ttf",
  6048. "txz",
  6049. "udf",
  6050. "uvh",
  6051. "uvi",
  6052. "uvm",
  6053. "uvp",
  6054. "uvs",
  6055. "uvu",
  6056. "viv",
  6057. "vob",
  6058. "war",
  6059. "wav",
  6060. "wax",
  6061. "wbmp",
  6062. "wdp",
  6063. "weba",
  6064. "webm",
  6065. "webp",
  6066. "whl",
  6067. "wim",
  6068. "wm",
  6069. "wma",
  6070. "wmv",
  6071. "wmx",
  6072. "woff",
  6073. "woff2",
  6074. "wrm",
  6075. "wvx",
  6076. "xbm",
  6077. "xif",
  6078. "xla",
  6079. "xlam",
  6080. "xls",
  6081. "xlsb",
  6082. "xlsm",
  6083. "xlsx",
  6084. "xlt",
  6085. "xltm",
  6086. "xltx",
  6087. "xm",
  6088. "xmind",
  6089. "xpi",
  6090. "xpm",
  6091. "xwd",
  6092. "xz",
  6093. "z",
  6094. "zip",
  6095. "zipx"
  6096. ];
  6097. var binaryExtensions;
  6098. var hasRequiredBinaryExtensions;
  6099. function requireBinaryExtensions () {
  6100. if (hasRequiredBinaryExtensions) return binaryExtensions;
  6101. hasRequiredBinaryExtensions = 1;
  6102. binaryExtensions = require$$0;
  6103. return binaryExtensions;
  6104. }
  6105. var isBinaryPath;
  6106. var hasRequiredIsBinaryPath;
  6107. function requireIsBinaryPath () {
  6108. if (hasRequiredIsBinaryPath) return isBinaryPath;
  6109. hasRequiredIsBinaryPath = 1;
  6110. const path = require$$0$1;
  6111. const binaryExtensions = /*@__PURE__*/ requireBinaryExtensions();
  6112. const extensions = new Set(binaryExtensions);
  6113. isBinaryPath = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());
  6114. return isBinaryPath;
  6115. }
  6116. var constants = {};
  6117. var hasRequiredConstants;
  6118. function requireConstants () {
  6119. if (hasRequiredConstants) return constants;
  6120. hasRequiredConstants = 1;
  6121. (function (exports$1) {
  6122. const {sep} = require$$0$1;
  6123. const {platform} = process;
  6124. const os = require$$2$1;
  6125. exports$1.EV_ALL = 'all';
  6126. exports$1.EV_READY = 'ready';
  6127. exports$1.EV_ADD = 'add';
  6128. exports$1.EV_CHANGE = 'change';
  6129. exports$1.EV_ADD_DIR = 'addDir';
  6130. exports$1.EV_UNLINK = 'unlink';
  6131. exports$1.EV_UNLINK_DIR = 'unlinkDir';
  6132. exports$1.EV_RAW = 'raw';
  6133. exports$1.EV_ERROR = 'error';
  6134. exports$1.STR_DATA = 'data';
  6135. exports$1.STR_END = 'end';
  6136. exports$1.STR_CLOSE = 'close';
  6137. exports$1.FSEVENT_CREATED = 'created';
  6138. exports$1.FSEVENT_MODIFIED = 'modified';
  6139. exports$1.FSEVENT_DELETED = 'deleted';
  6140. exports$1.FSEVENT_MOVED = 'moved';
  6141. exports$1.FSEVENT_CLONED = 'cloned';
  6142. exports$1.FSEVENT_UNKNOWN = 'unknown';
  6143. exports$1.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
  6144. exports$1.FSEVENT_TYPE_FILE = 'file';
  6145. exports$1.FSEVENT_TYPE_DIRECTORY = 'directory';
  6146. exports$1.FSEVENT_TYPE_SYMLINK = 'symlink';
  6147. exports$1.KEY_LISTENERS = 'listeners';
  6148. exports$1.KEY_ERR = 'errHandlers';
  6149. exports$1.KEY_RAW = 'rawEmitters';
  6150. exports$1.HANDLER_KEYS = [exports$1.KEY_LISTENERS, exports$1.KEY_ERR, exports$1.KEY_RAW];
  6151. exports$1.DOT_SLASH = `.${sep}`;
  6152. exports$1.BACK_SLASH_RE = /\\/g;
  6153. exports$1.DOUBLE_SLASH_RE = /\/\//;
  6154. exports$1.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  6155. exports$1.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  6156. exports$1.REPLACER_RE = /^\.[/\\]/;
  6157. exports$1.SLASH = '/';
  6158. exports$1.SLASH_SLASH = '//';
  6159. exports$1.BRACE_START = '{';
  6160. exports$1.BANG = '!';
  6161. exports$1.ONE_DOT = '.';
  6162. exports$1.TWO_DOTS = '..';
  6163. exports$1.STAR = '*';
  6164. exports$1.GLOBSTAR = '**';
  6165. exports$1.ROOT_GLOBSTAR = '/**/*';
  6166. exports$1.SLASH_GLOBSTAR = '/**';
  6167. exports$1.DIR_SUFFIX = 'Dir';
  6168. exports$1.ANYMATCH_OPTS = {dot: true};
  6169. exports$1.STRING_TYPE = 'string';
  6170. exports$1.FUNCTION_TYPE = 'function';
  6171. exports$1.EMPTY_STR = '';
  6172. exports$1.EMPTY_FN = () => {};
  6173. exports$1.IDENTITY_FN = val => val;
  6174. exports$1.isWindows = platform === 'win32';
  6175. exports$1.isMacos = platform === 'darwin';
  6176. exports$1.isLinux = platform === 'linux';
  6177. exports$1.isIBMi = os.type() === 'OS400';
  6178. } (constants));
  6179. return constants;
  6180. }
  6181. var nodefsHandler;
  6182. var hasRequiredNodefsHandler;
  6183. function requireNodefsHandler () {
  6184. if (hasRequiredNodefsHandler) return nodefsHandler;
  6185. hasRequiredNodefsHandler = 1;
  6186. const fs = require$$0$2;
  6187. const sysPath = require$$0$1;
  6188. const { promisify } = require$$2;
  6189. const isBinaryPath = /*@__PURE__*/ requireIsBinaryPath();
  6190. const {
  6191. isWindows,
  6192. isLinux,
  6193. EMPTY_FN,
  6194. EMPTY_STR,
  6195. KEY_LISTENERS,
  6196. KEY_ERR,
  6197. KEY_RAW,
  6198. HANDLER_KEYS,
  6199. EV_CHANGE,
  6200. EV_ADD,
  6201. EV_ADD_DIR,
  6202. EV_ERROR,
  6203. STR_DATA,
  6204. STR_END,
  6205. BRACE_START,
  6206. STAR
  6207. } = /*@__PURE__*/ requireConstants();
  6208. const THROTTLE_MODE_WATCH = 'watch';
  6209. const open = promisify(fs.open);
  6210. const stat = promisify(fs.stat);
  6211. const lstat = promisify(fs.lstat);
  6212. const close = promisify(fs.close);
  6213. const fsrealpath = promisify(fs.realpath);
  6214. const statMethods = { lstat, stat };
  6215. // TODO: emit errors properly. Example: EMFILE on Macos.
  6216. const foreach = (val, fn) => {
  6217. if (val instanceof Set) {
  6218. val.forEach(fn);
  6219. } else {
  6220. fn(val);
  6221. }
  6222. };
  6223. const addAndConvert = (main, prop, item) => {
  6224. let container = main[prop];
  6225. if (!(container instanceof Set)) {
  6226. main[prop] = container = new Set([container]);
  6227. }
  6228. container.add(item);
  6229. };
  6230. const clearItem = cont => key => {
  6231. const set = cont[key];
  6232. if (set instanceof Set) {
  6233. set.clear();
  6234. } else {
  6235. delete cont[key];
  6236. }
  6237. };
  6238. const delFromSet = (main, prop, item) => {
  6239. const container = main[prop];
  6240. if (container instanceof Set) {
  6241. container.delete(item);
  6242. } else if (container === item) {
  6243. delete main[prop];
  6244. }
  6245. };
  6246. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  6247. /**
  6248. * @typedef {String} Path
  6249. */
  6250. // fs_watch helpers
  6251. // object to hold per-process fs_watch instances
  6252. // (may be shared across chokidar FSWatcher instances)
  6253. /**
  6254. * @typedef {Object} FsWatchContainer
  6255. * @property {Set} listeners
  6256. * @property {Set} errHandlers
  6257. * @property {Set} rawEmitters
  6258. * @property {fs.FSWatcher=} watcher
  6259. * @property {Boolean=} watcherUnusable
  6260. */
  6261. /**
  6262. * @type {Map<String,FsWatchContainer>}
  6263. */
  6264. const FsWatchInstances = new Map();
  6265. /**
  6266. * Instantiates the fs_watch interface
  6267. * @param {String} path to be watched
  6268. * @param {Object} options to be passed to fs_watch
  6269. * @param {Function} listener main event handler
  6270. * @param {Function} errHandler emits info about errors
  6271. * @param {Function} emitRaw emits raw event data
  6272. * @returns {fs.FSWatcher} new fsevents instance
  6273. */
  6274. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  6275. const handleEvent = (rawEvent, evPath) => {
  6276. listener(path);
  6277. emitRaw(rawEvent, evPath, {watchedPath: path});
  6278. // emit based on events occurring for files from a directory's watcher in
  6279. // case the file's watcher misses it (and rely on throttling to de-dupe)
  6280. if (evPath && path !== evPath) {
  6281. fsWatchBroadcast(
  6282. sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)
  6283. );
  6284. }
  6285. };
  6286. try {
  6287. return fs.watch(path, options, handleEvent);
  6288. } catch (error) {
  6289. errHandler(error);
  6290. }
  6291. }
  6292. /**
  6293. * Helper for passing fs_watch event data to a collection of listeners
  6294. * @param {Path} fullPath absolute path bound to fs_watch instance
  6295. * @param {String} type listener type
  6296. * @param {*=} val1 arguments to be passed to listeners
  6297. * @param {*=} val2
  6298. * @param {*=} val3
  6299. */
  6300. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  6301. const cont = FsWatchInstances.get(fullPath);
  6302. if (!cont) return;
  6303. foreach(cont[type], (listener) => {
  6304. listener(val1, val2, val3);
  6305. });
  6306. };
  6307. /**
  6308. * Instantiates the fs_watch interface or binds listeners
  6309. * to an existing one covering the same file system entry
  6310. * @param {String} path
  6311. * @param {String} fullPath absolute path
  6312. * @param {Object} options to be passed to fs_watch
  6313. * @param {Object} handlers container for event listener functions
  6314. */
  6315. const setFsWatchListener = (path, fullPath, options, handlers) => {
  6316. const {listener, errHandler, rawEmitter} = handlers;
  6317. let cont = FsWatchInstances.get(fullPath);
  6318. /** @type {fs.FSWatcher=} */
  6319. let watcher;
  6320. if (!options.persistent) {
  6321. watcher = createFsWatchInstance(
  6322. path, options, listener, errHandler, rawEmitter
  6323. );
  6324. return watcher.close.bind(watcher);
  6325. }
  6326. if (cont) {
  6327. addAndConvert(cont, KEY_LISTENERS, listener);
  6328. addAndConvert(cont, KEY_ERR, errHandler);
  6329. addAndConvert(cont, KEY_RAW, rawEmitter);
  6330. } else {
  6331. watcher = createFsWatchInstance(
  6332. path,
  6333. options,
  6334. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  6335. errHandler, // no need to use broadcast here
  6336. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  6337. );
  6338. if (!watcher) return;
  6339. watcher.on(EV_ERROR, async (error) => {
  6340. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  6341. cont.watcherUnusable = true; // documented since Node 10.4.1
  6342. // Workaround for https://github.com/joyent/node/issues/4337
  6343. if (isWindows && error.code === 'EPERM') {
  6344. try {
  6345. const fd = await open(path, 'r');
  6346. await close(fd);
  6347. broadcastErr(error);
  6348. } catch (err) {}
  6349. } else {
  6350. broadcastErr(error);
  6351. }
  6352. });
  6353. cont = {
  6354. listeners: listener,
  6355. errHandlers: errHandler,
  6356. rawEmitters: rawEmitter,
  6357. watcher
  6358. };
  6359. FsWatchInstances.set(fullPath, cont);
  6360. }
  6361. // const index = cont.listeners.indexOf(listener);
  6362. // removes this instance's listeners and closes the underlying fs_watch
  6363. // instance if there are no more listeners left
  6364. return () => {
  6365. delFromSet(cont, KEY_LISTENERS, listener);
  6366. delFromSet(cont, KEY_ERR, errHandler);
  6367. delFromSet(cont, KEY_RAW, rawEmitter);
  6368. if (isEmptySet(cont.listeners)) {
  6369. // Check to protect against issue gh-730.
  6370. // if (cont.watcherUnusable) {
  6371. cont.watcher.close();
  6372. // }
  6373. FsWatchInstances.delete(fullPath);
  6374. HANDLER_KEYS.forEach(clearItem(cont));
  6375. cont.watcher = undefined;
  6376. Object.freeze(cont);
  6377. }
  6378. };
  6379. };
  6380. // fs_watchFile helpers
  6381. // object to hold per-process fs_watchFile instances
  6382. // (may be shared across chokidar FSWatcher instances)
  6383. const FsWatchFileInstances = new Map();
  6384. /**
  6385. * Instantiates the fs_watchFile interface or binds listeners
  6386. * to an existing one covering the same file system entry
  6387. * @param {String} path to be watched
  6388. * @param {String} fullPath absolute path
  6389. * @param {Object} options options to be passed to fs_watchFile
  6390. * @param {Object} handlers container for event listener functions
  6391. * @returns {Function} closer
  6392. */
  6393. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  6394. const {listener, rawEmitter} = handlers;
  6395. let cont = FsWatchFileInstances.get(fullPath);
  6396. const copts = cont && cont.options;
  6397. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  6398. fs.unwatchFile(fullPath);
  6399. cont = undefined;
  6400. }
  6401. /* eslint-enable no-unused-vars, prefer-destructuring */
  6402. if (cont) {
  6403. addAndConvert(cont, KEY_LISTENERS, listener);
  6404. addAndConvert(cont, KEY_RAW, rawEmitter);
  6405. } else {
  6406. // TODO
  6407. // listeners.add(listener);
  6408. // rawEmitters.add(rawEmitter);
  6409. cont = {
  6410. listeners: listener,
  6411. rawEmitters: rawEmitter,
  6412. options,
  6413. watcher: fs.watchFile(fullPath, options, (curr, prev) => {
  6414. foreach(cont.rawEmitters, (rawEmitter) => {
  6415. rawEmitter(EV_CHANGE, fullPath, {curr, prev});
  6416. });
  6417. const currmtime = curr.mtimeMs;
  6418. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  6419. foreach(cont.listeners, (listener) => listener(path, curr));
  6420. }
  6421. })
  6422. };
  6423. FsWatchFileInstances.set(fullPath, cont);
  6424. }
  6425. // const index = cont.listeners.indexOf(listener);
  6426. // Removes this instance's listeners and closes the underlying fs_watchFile
  6427. // instance if there are no more listeners left.
  6428. return () => {
  6429. delFromSet(cont, KEY_LISTENERS, listener);
  6430. delFromSet(cont, KEY_RAW, rawEmitter);
  6431. if (isEmptySet(cont.listeners)) {
  6432. FsWatchFileInstances.delete(fullPath);
  6433. fs.unwatchFile(fullPath);
  6434. cont.options = cont.watcher = undefined;
  6435. Object.freeze(cont);
  6436. }
  6437. };
  6438. };
  6439. /**
  6440. * @mixin
  6441. */
  6442. class NodeFsHandler {
  6443. /**
  6444. * @param {import("../index").FSWatcher} fsW
  6445. */
  6446. constructor(fsW) {
  6447. this.fsw = fsW;
  6448. this._boundHandleError = (error) => fsW._handleError(error);
  6449. }
  6450. /**
  6451. * Watch file for changes with fs_watchFile or fs_watch.
  6452. * @param {String} path to file or dir
  6453. * @param {Function} listener on fs change
  6454. * @returns {Function} closer for the watcher instance
  6455. */
  6456. _watchWithNodeFs(path, listener) {
  6457. const opts = this.fsw.options;
  6458. const directory = sysPath.dirname(path);
  6459. const basename = sysPath.basename(path);
  6460. const parent = this.fsw._getWatchedDir(directory);
  6461. parent.add(basename);
  6462. const absolutePath = sysPath.resolve(path);
  6463. const options = {persistent: opts.persistent};
  6464. if (!listener) listener = EMPTY_FN;
  6465. let closer;
  6466. if (opts.usePolling) {
  6467. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  6468. opts.binaryInterval : opts.interval;
  6469. closer = setFsWatchFileListener(path, absolutePath, options, {
  6470. listener,
  6471. rawEmitter: this.fsw._emitRaw
  6472. });
  6473. } else {
  6474. closer = setFsWatchListener(path, absolutePath, options, {
  6475. listener,
  6476. errHandler: this._boundHandleError,
  6477. rawEmitter: this.fsw._emitRaw
  6478. });
  6479. }
  6480. return closer;
  6481. }
  6482. /**
  6483. * Watch a file and emit add event if warranted.
  6484. * @param {Path} file Path
  6485. * @param {fs.Stats} stats result of fs_stat
  6486. * @param {Boolean} initialAdd was the file added at watch instantiation?
  6487. * @returns {Function} closer for the watcher instance
  6488. */
  6489. _handleFile(file, stats, initialAdd) {
  6490. if (this.fsw.closed) {
  6491. return;
  6492. }
  6493. const dirname = sysPath.dirname(file);
  6494. const basename = sysPath.basename(file);
  6495. const parent = this.fsw._getWatchedDir(dirname);
  6496. // stats is always present
  6497. let prevStats = stats;
  6498. // if the file is already being watched, do nothing
  6499. if (parent.has(basename)) return;
  6500. const listener = async (path, newStats) => {
  6501. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  6502. if (!newStats || newStats.mtimeMs === 0) {
  6503. try {
  6504. const newStats = await stat(file);
  6505. if (this.fsw.closed) return;
  6506. // Check that change event was not fired because of changed only accessTime.
  6507. const at = newStats.atimeMs;
  6508. const mt = newStats.mtimeMs;
  6509. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  6510. this.fsw._emit(EV_CHANGE, file, newStats);
  6511. }
  6512. if (isLinux && prevStats.ino !== newStats.ino) {
  6513. this.fsw._closeFile(path);
  6514. prevStats = newStats;
  6515. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  6516. } else {
  6517. prevStats = newStats;
  6518. }
  6519. } catch (error) {
  6520. // Fix issues where mtime is null but file is still present
  6521. this.fsw._remove(dirname, basename);
  6522. }
  6523. // add is about to be emitted if file not already tracked in parent
  6524. } else if (parent.has(basename)) {
  6525. // Check that change event was not fired because of changed only accessTime.
  6526. const at = newStats.atimeMs;
  6527. const mt = newStats.mtimeMs;
  6528. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  6529. this.fsw._emit(EV_CHANGE, file, newStats);
  6530. }
  6531. prevStats = newStats;
  6532. }
  6533. };
  6534. // kick off the watcher
  6535. const closer = this._watchWithNodeFs(file, listener);
  6536. // emit an add event if we're supposed to
  6537. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  6538. if (!this.fsw._throttle(EV_ADD, file, 0)) return;
  6539. this.fsw._emit(EV_ADD, file, stats);
  6540. }
  6541. return closer;
  6542. }
  6543. /**
  6544. * Handle symlinks encountered while reading a dir.
  6545. * @param {Object} entry returned by readdirp
  6546. * @param {String} directory path of dir being read
  6547. * @param {String} path of this item
  6548. * @param {String} item basename of this item
  6549. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  6550. */
  6551. async _handleSymlink(entry, directory, path, item) {
  6552. if (this.fsw.closed) {
  6553. return;
  6554. }
  6555. const full = entry.fullPath;
  6556. const dir = this.fsw._getWatchedDir(directory);
  6557. if (!this.fsw.options.followSymlinks) {
  6558. // watch symlink directly (don't follow) and detect changes
  6559. this.fsw._incrReadyCount();
  6560. let linkPath;
  6561. try {
  6562. linkPath = await fsrealpath(path);
  6563. } catch (e) {
  6564. this.fsw._emitReady();
  6565. return true;
  6566. }
  6567. if (this.fsw.closed) return;
  6568. if (dir.has(item)) {
  6569. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  6570. this.fsw._symlinkPaths.set(full, linkPath);
  6571. this.fsw._emit(EV_CHANGE, path, entry.stats);
  6572. }
  6573. } else {
  6574. dir.add(item);
  6575. this.fsw._symlinkPaths.set(full, linkPath);
  6576. this.fsw._emit(EV_ADD, path, entry.stats);
  6577. }
  6578. this.fsw._emitReady();
  6579. return true;
  6580. }
  6581. // don't follow the same symlink more than once
  6582. if (this.fsw._symlinkPaths.has(full)) {
  6583. return true;
  6584. }
  6585. this.fsw._symlinkPaths.set(full, true);
  6586. }
  6587. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  6588. // Normalize the directory name on Windows
  6589. directory = sysPath.join(directory, EMPTY_STR);
  6590. if (!wh.hasGlob) {
  6591. throttler = this.fsw._throttle('readdir', directory, 1000);
  6592. if (!throttler) return;
  6593. }
  6594. const previous = this.fsw._getWatchedDir(wh.path);
  6595. const current = new Set();
  6596. let stream = this.fsw._readdirp(directory, {
  6597. fileFilter: entry => wh.filterPath(entry),
  6598. directoryFilter: entry => wh.filterDir(entry),
  6599. depth: 0
  6600. }).on(STR_DATA, async (entry) => {
  6601. if (this.fsw.closed) {
  6602. stream = undefined;
  6603. return;
  6604. }
  6605. const item = entry.path;
  6606. let path = sysPath.join(directory, item);
  6607. current.add(item);
  6608. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  6609. return;
  6610. }
  6611. if (this.fsw.closed) {
  6612. stream = undefined;
  6613. return;
  6614. }
  6615. // Files that present in current directory snapshot
  6616. // but absent in previous are added to watch list and
  6617. // emit `add` event.
  6618. if (item === target || !target && !previous.has(item)) {
  6619. this.fsw._incrReadyCount();
  6620. // ensure relativeness of path is preserved in case of watcher reuse
  6621. path = sysPath.join(dir, sysPath.relative(dir, path));
  6622. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  6623. }
  6624. }).on(EV_ERROR, this._boundHandleError);
  6625. return new Promise(resolve =>
  6626. stream.once(STR_END, () => {
  6627. if (this.fsw.closed) {
  6628. stream = undefined;
  6629. return;
  6630. }
  6631. const wasThrottled = throttler ? throttler.clear() : false;
  6632. resolve();
  6633. // Files that absent in current directory snapshot
  6634. // but present in previous emit `remove` event
  6635. // and are removed from @watched[directory].
  6636. previous.getChildren().filter((item) => {
  6637. return item !== directory &&
  6638. !current.has(item) &&
  6639. // in case of intersecting globs;
  6640. // a path may have been filtered out of this readdir, but
  6641. // shouldn't be removed because it matches a different glob
  6642. (!wh.hasGlob || wh.filterPath({
  6643. fullPath: sysPath.resolve(directory, item)
  6644. }));
  6645. }).forEach((item) => {
  6646. this.fsw._remove(directory, item);
  6647. });
  6648. stream = undefined;
  6649. // one more time for any missed in case changes came in extremely quickly
  6650. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  6651. })
  6652. );
  6653. }
  6654. /**
  6655. * Read directory to add / remove files from `@watched` list and re-read it on change.
  6656. * @param {String} dir fs path
  6657. * @param {fs.Stats} stats
  6658. * @param {Boolean} initialAdd
  6659. * @param {Number} depth relative to user-supplied path
  6660. * @param {String} target child path targeted for watch
  6661. * @param {Object} wh Common watch helpers for this path
  6662. * @param {String} realpath
  6663. * @returns {Promise<Function>} closer for the watcher instance.
  6664. */
  6665. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  6666. const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
  6667. const tracked = parentDir.has(sysPath.basename(dir));
  6668. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  6669. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
  6670. }
  6671. // ensure dir is tracked (harmless if redundant)
  6672. parentDir.add(sysPath.basename(dir));
  6673. this.fsw._getWatchedDir(dir);
  6674. let throttler;
  6675. let closer;
  6676. const oDepth = this.fsw.options.depth;
  6677. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  6678. if (!target) {
  6679. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  6680. if (this.fsw.closed) return;
  6681. }
  6682. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  6683. // if current directory is removed, do nothing
  6684. if (stats && stats.mtimeMs === 0) return;
  6685. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  6686. });
  6687. }
  6688. return closer;
  6689. }
  6690. /**
  6691. * Handle added file, directory, or glob pattern.
  6692. * Delegates call to _handleFile / _handleDir after checks.
  6693. * @param {String} path to file or ir
  6694. * @param {Boolean} initialAdd was the file added at watch instantiation?
  6695. * @param {Object} priorWh depth relative to user-supplied path
  6696. * @param {Number} depth Child path actually targeted for watch
  6697. * @param {String=} target Child path actually targeted for watch
  6698. * @returns {Promise}
  6699. */
  6700. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  6701. const ready = this.fsw._emitReady;
  6702. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  6703. ready();
  6704. return false;
  6705. }
  6706. const wh = this.fsw._getWatchHelpers(path, depth);
  6707. if (!wh.hasGlob && priorWh) {
  6708. wh.hasGlob = priorWh.hasGlob;
  6709. wh.globFilter = priorWh.globFilter;
  6710. wh.filterPath = entry => priorWh.filterPath(entry);
  6711. wh.filterDir = entry => priorWh.filterDir(entry);
  6712. }
  6713. // evaluate what is at the path we're being asked to watch
  6714. try {
  6715. const stats = await statMethods[wh.statMethod](wh.watchPath);
  6716. if (this.fsw.closed) return;
  6717. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  6718. ready();
  6719. return false;
  6720. }
  6721. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
  6722. let closer;
  6723. if (stats.isDirectory()) {
  6724. const absPath = sysPath.resolve(path);
  6725. const targetPath = follow ? await fsrealpath(path) : path;
  6726. if (this.fsw.closed) return;
  6727. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  6728. if (this.fsw.closed) return;
  6729. // preserve this symlink's target path
  6730. if (absPath !== targetPath && targetPath !== undefined) {
  6731. this.fsw._symlinkPaths.set(absPath, targetPath);
  6732. }
  6733. } else if (stats.isSymbolicLink()) {
  6734. const targetPath = follow ? await fsrealpath(path) : path;
  6735. if (this.fsw.closed) return;
  6736. const parent = sysPath.dirname(wh.watchPath);
  6737. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  6738. this.fsw._emit(EV_ADD, wh.watchPath, stats);
  6739. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  6740. if (this.fsw.closed) return;
  6741. // preserve this symlink's target path
  6742. if (targetPath !== undefined) {
  6743. this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
  6744. }
  6745. } else {
  6746. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  6747. }
  6748. ready();
  6749. this.fsw._addPathCloser(path, closer);
  6750. return false;
  6751. } catch (error) {
  6752. if (this.fsw._handleError(error)) {
  6753. ready();
  6754. return path;
  6755. }
  6756. }
  6757. }
  6758. }
  6759. nodefsHandler = NodeFsHandler;
  6760. return nodefsHandler;
  6761. }
  6762. var fseventsHandler = {exports: {}};
  6763. const require$$3 = /*@__PURE__*/getAugmentedNamespace(fseventsImporter);
  6764. var hasRequiredFseventsHandler;
  6765. function requireFseventsHandler () {
  6766. if (hasRequiredFseventsHandler) return fseventsHandler.exports;
  6767. hasRequiredFseventsHandler = 1;
  6768. const fs = require$$0$2;
  6769. const sysPath = require$$0$1;
  6770. const { promisify } = require$$2;
  6771. let fsevents;
  6772. try {
  6773. fsevents = require$$3.getFsEvents();
  6774. } catch (error) {
  6775. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  6776. }
  6777. if (fsevents) {
  6778. // TODO: real check
  6779. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  6780. if (mtch && mtch[1] && mtch[2]) {
  6781. const maj = Number.parseInt(mtch[1], 10);
  6782. const min = Number.parseInt(mtch[2], 10);
  6783. if (maj === 8 && min < 16) {
  6784. fsevents = undefined;
  6785. }
  6786. }
  6787. }
  6788. const {
  6789. EV_ADD,
  6790. EV_CHANGE,
  6791. EV_ADD_DIR,
  6792. EV_UNLINK,
  6793. EV_ERROR,
  6794. STR_DATA,
  6795. STR_END,
  6796. FSEVENT_CREATED,
  6797. FSEVENT_MODIFIED,
  6798. FSEVENT_DELETED,
  6799. FSEVENT_MOVED,
  6800. // FSEVENT_CLONED,
  6801. FSEVENT_UNKNOWN,
  6802. FSEVENT_FLAG_MUST_SCAN_SUBDIRS,
  6803. FSEVENT_TYPE_FILE,
  6804. FSEVENT_TYPE_DIRECTORY,
  6805. FSEVENT_TYPE_SYMLINK,
  6806. ROOT_GLOBSTAR,
  6807. DIR_SUFFIX,
  6808. DOT_SLASH,
  6809. FUNCTION_TYPE,
  6810. EMPTY_FN,
  6811. IDENTITY_FN
  6812. } = /*@__PURE__*/ requireConstants();
  6813. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  6814. const stat = promisify(fs.stat);
  6815. const lstat = promisify(fs.lstat);
  6816. const realpath = promisify(fs.realpath);
  6817. const statMethods = { stat, lstat };
  6818. /**
  6819. * @typedef {String} Path
  6820. */
  6821. /**
  6822. * @typedef {Object} FsEventsWatchContainer
  6823. * @property {Set<Function>} listeners
  6824. * @property {Function} rawEmitter
  6825. * @property {{stop: Function}} watcher
  6826. */
  6827. // fsevents instance helper functions
  6828. /**
  6829. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  6830. * @type {Map<Path,FsEventsWatchContainer>}
  6831. */
  6832. const FSEventsWatchers = new Map();
  6833. // Threshold of duplicate path prefixes at which to start
  6834. // consolidating going forward
  6835. const consolidateThreshhold = 10;
  6836. const wrongEventFlags = new Set([
  6837. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  6838. ]);
  6839. /**
  6840. * Instantiates the fsevents interface
  6841. * @param {Path} path path to be watched
  6842. * @param {Function} callback called when fsevents is bound and ready
  6843. * @returns {{stop: Function}} new fsevents instance
  6844. */
  6845. const createFSEventsInstance = (path, callback) => {
  6846. const stop = fsevents.watch(path, callback);
  6847. return {stop};
  6848. };
  6849. /**
  6850. * Instantiates the fsevents interface or binds listeners to an existing one covering
  6851. * the same file tree.
  6852. * @param {Path} path - to be watched
  6853. * @param {Path} realPath - real path for symlinks
  6854. * @param {Function} listener - called when fsevents emits events
  6855. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  6856. * @returns {Function} closer
  6857. */
  6858. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  6859. let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath;
  6860. const parentPath = sysPath.dirname(watchPath);
  6861. let cont = FSEventsWatchers.get(watchPath);
  6862. // If we've accumulated a substantial number of paths that
  6863. // could have been consolidated by watching one directory
  6864. // above the current one, create a watcher on the parent
  6865. // path instead, so that we do consolidate going forward.
  6866. if (couldConsolidate(parentPath)) {
  6867. watchPath = parentPath;
  6868. }
  6869. const resolvedPath = sysPath.resolve(path);
  6870. const hasSymlink = resolvedPath !== realPath;
  6871. const filteredListener = (fullPath, flags, info) => {
  6872. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  6873. if (
  6874. fullPath === resolvedPath ||
  6875. !fullPath.indexOf(resolvedPath + sysPath.sep)
  6876. ) listener(fullPath, flags, info);
  6877. };
  6878. // check if there is already a watcher on a parent path
  6879. // modifies `watchPath` to the parent path when it finds a match
  6880. let watchedParent = false;
  6881. for (const watchedPath of FSEventsWatchers.keys()) {
  6882. if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) {
  6883. watchPath = watchedPath;
  6884. cont = FSEventsWatchers.get(watchPath);
  6885. watchedParent = true;
  6886. break;
  6887. }
  6888. }
  6889. if (cont || watchedParent) {
  6890. cont.listeners.add(filteredListener);
  6891. } else {
  6892. cont = {
  6893. listeners: new Set([filteredListener]),
  6894. rawEmitter,
  6895. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  6896. if (!cont.listeners.size) return;
  6897. if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return;
  6898. const info = fsevents.getInfo(fullPath, flags);
  6899. cont.listeners.forEach(list => {
  6900. list(fullPath, flags, info);
  6901. });
  6902. cont.rawEmitter(info.event, fullPath, info);
  6903. })
  6904. };
  6905. FSEventsWatchers.set(watchPath, cont);
  6906. }
  6907. // removes this instance's listeners and closes the underlying fsevents
  6908. // instance if there are no more listeners left
  6909. return () => {
  6910. const lst = cont.listeners;
  6911. lst.delete(filteredListener);
  6912. if (!lst.size) {
  6913. FSEventsWatchers.delete(watchPath);
  6914. if (cont.watcher) return cont.watcher.stop().then(() => {
  6915. cont.rawEmitter = cont.watcher = undefined;
  6916. Object.freeze(cont);
  6917. });
  6918. }
  6919. };
  6920. }
  6921. // Decide whether or not we should start a new higher-level
  6922. // parent watcher
  6923. const couldConsolidate = (path) => {
  6924. let count = 0;
  6925. for (const watchPath of FSEventsWatchers.keys()) {
  6926. if (watchPath.indexOf(path) === 0) {
  6927. count++;
  6928. if (count >= consolidateThreshhold) {
  6929. return true;
  6930. }
  6931. }
  6932. }
  6933. return false;
  6934. };
  6935. // returns boolean indicating whether fsevents can be used
  6936. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  6937. // determines subdirectory traversal levels from root to path
  6938. const calcDepth = (path, root) => {
  6939. let i = 0;
  6940. while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++;
  6941. return i;
  6942. };
  6943. // returns boolean indicating whether the fsevents' event info has the same type
  6944. // as the one returned by fs.stat
  6945. const sameTypes = (info, stats) => (
  6946. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  6947. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  6948. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  6949. );
  6950. /**
  6951. * @mixin
  6952. */
  6953. class FsEventsHandler {
  6954. /**
  6955. * @param {import('../index').FSWatcher} fsw
  6956. */
  6957. constructor(fsw) {
  6958. this.fsw = fsw;
  6959. }
  6960. checkIgnored(path, stats) {
  6961. const ipaths = this.fsw._ignoredPaths;
  6962. if (this.fsw._isIgnored(path, stats)) {
  6963. ipaths.add(path);
  6964. if (stats && stats.isDirectory()) {
  6965. ipaths.add(path + ROOT_GLOBSTAR);
  6966. }
  6967. return true;
  6968. }
  6969. ipaths.delete(path);
  6970. ipaths.delete(path + ROOT_GLOBSTAR);
  6971. }
  6972. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  6973. const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD;
  6974. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6975. }
  6976. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  6977. try {
  6978. const stats = await stat(path);
  6979. if (this.fsw.closed) return;
  6980. if (sameTypes(info, stats)) {
  6981. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6982. } else {
  6983. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6984. }
  6985. } catch (error) {
  6986. if (error.code === 'EACCES') {
  6987. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6988. } else {
  6989. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  6990. }
  6991. }
  6992. }
  6993. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  6994. if (this.fsw.closed || this.checkIgnored(path)) return;
  6995. if (event === EV_UNLINK) {
  6996. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  6997. // suppress unlink events on never before seen files
  6998. if (isDirectory || watchedDir.has(item)) {
  6999. this.fsw._remove(parent, item, isDirectory);
  7000. }
  7001. } else {
  7002. if (event === EV_ADD) {
  7003. // track new directories
  7004. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  7005. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  7006. // push symlinks back to the top of the stack to get handled
  7007. const curDepth = opts.depth === undefined ?
  7008. undefined : calcDepth(fullPath, realPath) + 1;
  7009. return this._addToFsEvents(path, false, true, curDepth);
  7010. }
  7011. // track new paths
  7012. // (other than symlinks being followed, which will be tracked soon)
  7013. this.fsw._getWatchedDir(parent).add(item);
  7014. }
  7015. /**
  7016. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  7017. */
  7018. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  7019. this.fsw._emit(eventName, path);
  7020. if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true);
  7021. }
  7022. }
  7023. /**
  7024. * Handle symlinks encountered during directory scan
  7025. * @param {String} watchPath - file/dir path to be watched with fsevents
  7026. * @param {String} realPath - real path (in case of symlinks)
  7027. * @param {Function} transform - path transformer
  7028. * @param {Function} globFilter - path filter in case a glob pattern was provided
  7029. * @returns {Function} closer for the watcher instance
  7030. */
  7031. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  7032. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  7033. const opts = this.fsw.options;
  7034. const watchCallback = async (fullPath, flags, info) => {
  7035. if (this.fsw.closed) return;
  7036. if (
  7037. opts.depth !== undefined &&
  7038. calcDepth(fullPath, realPath) > opts.depth
  7039. ) return;
  7040. const path = transform(sysPath.join(
  7041. watchPath, sysPath.relative(watchPath, fullPath)
  7042. ));
  7043. if (globFilter && !globFilter(path)) return;
  7044. // ensure directories are tracked
  7045. const parent = sysPath.dirname(path);
  7046. const item = sysPath.basename(path);
  7047. const watchedDir = this.fsw._getWatchedDir(
  7048. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  7049. );
  7050. // correct for wrong events emitted
  7051. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  7052. if (typeof opts.ignored === FUNCTION_TYPE) {
  7053. let stats;
  7054. try {
  7055. stats = await stat(path);
  7056. } catch (error) {}
  7057. if (this.fsw.closed) return;
  7058. if (this.checkIgnored(path, stats)) return;
  7059. if (sameTypes(info, stats)) {
  7060. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  7061. } else {
  7062. this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  7063. }
  7064. } else {
  7065. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  7066. }
  7067. } else {
  7068. switch (info.event) {
  7069. case FSEVENT_CREATED:
  7070. case FSEVENT_MODIFIED:
  7071. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  7072. case FSEVENT_DELETED:
  7073. case FSEVENT_MOVED:
  7074. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  7075. }
  7076. }
  7077. };
  7078. const closer = setFSEventsListener(
  7079. watchPath,
  7080. realPath,
  7081. watchCallback,
  7082. this.fsw._emitRaw
  7083. );
  7084. this.fsw._emitReady();
  7085. return closer;
  7086. }
  7087. /**
  7088. * Handle symlinks encountered during directory scan
  7089. * @param {String} linkPath path to symlink
  7090. * @param {String} fullPath absolute path to the symlink
  7091. * @param {Function} transform pre-existing path transformer
  7092. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  7093. * @returns {Promise<void>}
  7094. */
  7095. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  7096. // don't follow the same symlink more than once
  7097. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  7098. this.fsw._symlinkPaths.set(fullPath, true);
  7099. this.fsw._incrReadyCount();
  7100. try {
  7101. const linkTarget = await realpath(linkPath);
  7102. if (this.fsw.closed) return;
  7103. if (this.fsw._isIgnored(linkTarget)) {
  7104. return this.fsw._emitReady();
  7105. }
  7106. this.fsw._incrReadyCount();
  7107. // add the linkTarget for watching with a wrapper for transform
  7108. // that causes emitted paths to incorporate the link's path
  7109. this._addToFsEvents(linkTarget || linkPath, (path) => {
  7110. let aliasedPath = linkPath;
  7111. if (linkTarget && linkTarget !== DOT_SLASH) {
  7112. aliasedPath = path.replace(linkTarget, linkPath);
  7113. } else if (path !== DOT_SLASH) {
  7114. aliasedPath = sysPath.join(linkPath, path);
  7115. }
  7116. return transform(aliasedPath);
  7117. }, false, curDepth);
  7118. } catch(error) {
  7119. if (this.fsw._handleError(error)) {
  7120. return this.fsw._emitReady();
  7121. }
  7122. }
  7123. }
  7124. /**
  7125. *
  7126. * @param {Path} newPath
  7127. * @param {fs.Stats} stats
  7128. */
  7129. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  7130. const pp = processPath(newPath);
  7131. const isDir = stats.isDirectory();
  7132. const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp));
  7133. const base = sysPath.basename(pp);
  7134. // ensure empty dirs get tracked
  7135. if (isDir) this.fsw._getWatchedDir(pp);
  7136. if (dirObj.has(base)) return;
  7137. dirObj.add(base);
  7138. if (!opts.ignoreInitial || forceAdd === true) {
  7139. this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats);
  7140. }
  7141. }
  7142. initWatch(realPath, path, wh, processPath) {
  7143. if (this.fsw.closed) return;
  7144. const closer = this._watchWithFsEvents(
  7145. wh.watchPath,
  7146. sysPath.resolve(realPath || wh.watchPath),
  7147. processPath,
  7148. wh.globFilter
  7149. );
  7150. this.fsw._addPathCloser(path, closer);
  7151. }
  7152. /**
  7153. * Handle added path with fsevents
  7154. * @param {String} path file/dir path or glob pattern
  7155. * @param {Function|Boolean=} transform converts working path to what the user expects
  7156. * @param {Boolean=} forceAdd ensure add is emitted
  7157. * @param {Number=} priorDepth Level of subdirectories already traversed.
  7158. * @returns {Promise<void>}
  7159. */
  7160. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  7161. if (this.fsw.closed) {
  7162. return;
  7163. }
  7164. const opts = this.fsw.options;
  7165. const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN;
  7166. const wh = this.fsw._getWatchHelpers(path);
  7167. // evaluate what is at the path we're being asked to watch
  7168. try {
  7169. const stats = await statMethods[wh.statMethod](wh.watchPath);
  7170. if (this.fsw.closed) return;
  7171. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  7172. throw null;
  7173. }
  7174. if (stats.isDirectory()) {
  7175. // emit addDir unless this is a glob parent
  7176. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  7177. // don't recurse further if it would exceed depth setting
  7178. if (priorDepth && priorDepth > opts.depth) return;
  7179. // scan the contents of the dir
  7180. this.fsw._readdirp(wh.watchPath, {
  7181. fileFilter: entry => wh.filterPath(entry),
  7182. directoryFilter: entry => wh.filterDir(entry),
  7183. ...Depth(opts.depth - (priorDepth || 0))
  7184. }).on(STR_DATA, (entry) => {
  7185. // need to check filterPath on dirs b/c filterDir is less restrictive
  7186. if (this.fsw.closed) {
  7187. return;
  7188. }
  7189. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  7190. const joinedPath = sysPath.join(wh.watchPath, entry.path);
  7191. const {fullPath} = entry;
  7192. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  7193. // preserve the current depth here since it can't be derived from
  7194. // real paths past the symlink
  7195. const curDepth = opts.depth === undefined ?
  7196. undefined : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1;
  7197. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  7198. } else {
  7199. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  7200. }
  7201. }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => {
  7202. this.fsw._emitReady();
  7203. });
  7204. } else {
  7205. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  7206. this.fsw._emitReady();
  7207. }
  7208. } catch (error) {
  7209. if (!error || this.fsw._handleError(error)) {
  7210. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  7211. this.fsw._emitReady();
  7212. this.fsw._emitReady();
  7213. }
  7214. }
  7215. if (opts.persistent && forceAdd !== true) {
  7216. if (typeof transform === FUNCTION_TYPE) {
  7217. // realpath has already been resolved
  7218. this.initWatch(undefined, path, wh, processPath);
  7219. } else {
  7220. let realPath;
  7221. try {
  7222. realPath = await realpath(wh.watchPath);
  7223. } catch (e) {}
  7224. this.initWatch(realPath, path, wh, processPath);
  7225. }
  7226. }
  7227. }
  7228. }
  7229. fseventsHandler.exports = FsEventsHandler;
  7230. fseventsHandler.exports.canUse = canUse;
  7231. return fseventsHandler.exports;
  7232. }
  7233. var hasRequiredChokidar;
  7234. function requireChokidar () {
  7235. if (hasRequiredChokidar) return chokidar$1;
  7236. hasRequiredChokidar = 1;
  7237. const { EventEmitter } = require$$0$3;
  7238. const fs = require$$0$2;
  7239. const sysPath = require$$0$1;
  7240. const { promisify } = require$$2;
  7241. const readdirp = /*@__PURE__*/ requireReaddirp();
  7242. const anymatch = /*@__PURE__*/ requireAnymatch().default;
  7243. const globParent = /*@__PURE__*/ requireGlobParent();
  7244. const isGlob = /*@__PURE__*/ requireIsGlob();
  7245. const braces = /*@__PURE__*/ requireBraces();
  7246. const normalizePath = /*@__PURE__*/ requireNormalizePath();
  7247. const NodeFsHandler = /*@__PURE__*/ requireNodefsHandler();
  7248. const FsEventsHandler = /*@__PURE__*/ requireFseventsHandler();
  7249. const {
  7250. EV_ALL,
  7251. EV_READY,
  7252. EV_ADD,
  7253. EV_CHANGE,
  7254. EV_UNLINK,
  7255. EV_ADD_DIR,
  7256. EV_UNLINK_DIR,
  7257. EV_RAW,
  7258. EV_ERROR,
  7259. STR_CLOSE,
  7260. STR_END,
  7261. BACK_SLASH_RE,
  7262. DOUBLE_SLASH_RE,
  7263. SLASH_OR_BACK_SLASH_RE,
  7264. DOT_RE,
  7265. REPLACER_RE,
  7266. SLASH,
  7267. SLASH_SLASH,
  7268. BRACE_START,
  7269. BANG,
  7270. ONE_DOT,
  7271. TWO_DOTS,
  7272. GLOBSTAR,
  7273. SLASH_GLOBSTAR,
  7274. ANYMATCH_OPTS,
  7275. STRING_TYPE,
  7276. FUNCTION_TYPE,
  7277. EMPTY_STR,
  7278. EMPTY_FN,
  7279. isWindows,
  7280. isMacos,
  7281. isIBMi
  7282. } = /*@__PURE__*/ requireConstants();
  7283. const stat = promisify(fs.stat);
  7284. const readdir = promisify(fs.readdir);
  7285. /**
  7286. * @typedef {String} Path
  7287. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  7288. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  7289. */
  7290. /**
  7291. *
  7292. * @typedef {Object} WatchHelpers
  7293. * @property {Boolean} followSymlinks
  7294. * @property {'stat'|'lstat'} statMethod
  7295. * @property {Path} path
  7296. * @property {Path} watchPath
  7297. * @property {Function} entryPath
  7298. * @property {Boolean} hasGlob
  7299. * @property {Object} globFilter
  7300. * @property {Function} filterPath
  7301. * @property {Function} filterDir
  7302. */
  7303. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  7304. const flatten = (list, result = []) => {
  7305. list.forEach(item => {
  7306. if (Array.isArray(item)) {
  7307. flatten(item, result);
  7308. } else {
  7309. result.push(item);
  7310. }
  7311. });
  7312. return result;
  7313. };
  7314. const unifyPaths = (paths_) => {
  7315. /**
  7316. * @type {Array<String>}
  7317. */
  7318. const paths = flatten(arrify(paths_));
  7319. if (!paths.every(p => typeof p === STRING_TYPE)) {
  7320. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  7321. }
  7322. return paths.map(normalizePathToUnix);
  7323. };
  7324. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  7325. // because "//StoragePC/DrivePool/Movies" is a valid network path
  7326. const toUnix = (string) => {
  7327. let str = string.replace(BACK_SLASH_RE, SLASH);
  7328. let prepend = false;
  7329. if (str.startsWith(SLASH_SLASH)) {
  7330. prepend = true;
  7331. }
  7332. while (str.match(DOUBLE_SLASH_RE)) {
  7333. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  7334. }
  7335. if (prepend) {
  7336. str = SLASH + str;
  7337. }
  7338. return str;
  7339. };
  7340. // Our version of upath.normalize
  7341. // TODO: this is not equal to path-normalize module - investigate why
  7342. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  7343. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  7344. if (typeof path !== STRING_TYPE) return path;
  7345. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  7346. };
  7347. const getAbsolutePath = (path, cwd) => {
  7348. if (sysPath.isAbsolute(path)) {
  7349. return path;
  7350. }
  7351. if (path.startsWith(BANG)) {
  7352. return BANG + sysPath.join(cwd, path.slice(1));
  7353. }
  7354. return sysPath.join(cwd, path);
  7355. };
  7356. const undef = (opts, key) => opts[key] === undefined;
  7357. /**
  7358. * Directory entry.
  7359. * @property {Path} path
  7360. * @property {Set<Path>} items
  7361. */
  7362. class DirEntry {
  7363. /**
  7364. * @param {Path} dir
  7365. * @param {Function} removeWatcher
  7366. */
  7367. constructor(dir, removeWatcher) {
  7368. this.path = dir;
  7369. this._removeWatcher = removeWatcher;
  7370. /** @type {Set<Path>} */
  7371. this.items = new Set();
  7372. }
  7373. add(item) {
  7374. const {items} = this;
  7375. if (!items) return;
  7376. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  7377. }
  7378. async remove(item) {
  7379. const {items} = this;
  7380. if (!items) return;
  7381. items.delete(item);
  7382. if (items.size > 0) return;
  7383. const dir = this.path;
  7384. try {
  7385. await readdir(dir);
  7386. } catch (err) {
  7387. if (this._removeWatcher) {
  7388. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  7389. }
  7390. }
  7391. }
  7392. has(item) {
  7393. const {items} = this;
  7394. if (!items) return;
  7395. return items.has(item);
  7396. }
  7397. /**
  7398. * @returns {Array<String>}
  7399. */
  7400. getChildren() {
  7401. const {items} = this;
  7402. if (!items) return;
  7403. return [...items.values()];
  7404. }
  7405. dispose() {
  7406. this.items.clear();
  7407. delete this.path;
  7408. delete this._removeWatcher;
  7409. delete this.items;
  7410. Object.freeze(this);
  7411. }
  7412. }
  7413. const STAT_METHOD_F = 'stat';
  7414. const STAT_METHOD_L = 'lstat';
  7415. class WatchHelper {
  7416. constructor(path, watchPath, follow, fsw) {
  7417. this.fsw = fsw;
  7418. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  7419. this.watchPath = watchPath;
  7420. this.fullWatchPath = sysPath.resolve(watchPath);
  7421. this.hasGlob = watchPath !== path;
  7422. /** @type {object|boolean} */
  7423. if (path === EMPTY_STR) this.hasGlob = false;
  7424. this.globSymlink = this.hasGlob && follow ? undefined : false;
  7425. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  7426. this.dirParts = this.getDirParts(path);
  7427. this.dirParts.forEach((parts) => {
  7428. if (parts.length > 1) parts.pop();
  7429. });
  7430. this.followSymlinks = follow;
  7431. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  7432. }
  7433. checkGlobSymlink(entry) {
  7434. // only need to resolve once
  7435. // first entry should always have entry.parentDir === EMPTY_STR
  7436. if (this.globSymlink === undefined) {
  7437. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  7438. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  7439. }
  7440. if (this.globSymlink) {
  7441. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  7442. }
  7443. return entry.fullPath;
  7444. }
  7445. entryPath(entry) {
  7446. return sysPath.join(this.watchPath,
  7447. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  7448. );
  7449. }
  7450. filterPath(entry) {
  7451. const {stats} = entry;
  7452. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  7453. const resolvedPath = this.entryPath(entry);
  7454. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  7455. this.globFilter(resolvedPath) : true;
  7456. return matchesGlob &&
  7457. this.fsw._isntIgnored(resolvedPath, stats) &&
  7458. this.fsw._hasReadPermissions(stats);
  7459. }
  7460. getDirParts(path) {
  7461. if (!this.hasGlob) return [];
  7462. const parts = [];
  7463. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  7464. expandedPath.forEach((path) => {
  7465. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  7466. });
  7467. return parts;
  7468. }
  7469. filterDir(entry) {
  7470. if (this.hasGlob) {
  7471. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  7472. let globstar = false;
  7473. this.unmatchedGlob = !this.dirParts.some((parts) => {
  7474. return parts.every((part, i) => {
  7475. if (part === GLOBSTAR) globstar = true;
  7476. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  7477. });
  7478. });
  7479. }
  7480. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  7481. }
  7482. }
  7483. /**
  7484. * Watches files & directories for changes. Emitted events:
  7485. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  7486. *
  7487. * new FSWatcher()
  7488. * .add(directories)
  7489. * .on('add', path => log('File', path, 'was added'))
  7490. */
  7491. class FSWatcher extends EventEmitter {
  7492. // Not indenting methods for history sake; for now.
  7493. constructor(_opts) {
  7494. super();
  7495. const opts = {};
  7496. if (_opts) Object.assign(opts, _opts); // for frozen objects
  7497. /** @type {Map<String, DirEntry>} */
  7498. this._watched = new Map();
  7499. /** @type {Map<String, Array>} */
  7500. this._closers = new Map();
  7501. /** @type {Set<String>} */
  7502. this._ignoredPaths = new Set();
  7503. /** @type {Map<ThrottleType, Map>} */
  7504. this._throttled = new Map();
  7505. /** @type {Map<Path, String|Boolean>} */
  7506. this._symlinkPaths = new Map();
  7507. this._streams = new Set();
  7508. this.closed = false;
  7509. // Set up default options.
  7510. if (undef(opts, 'persistent')) opts.persistent = true;
  7511. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  7512. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  7513. if (undef(opts, 'interval')) opts.interval = 100;
  7514. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  7515. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  7516. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  7517. // Enable fsevents on OS X when polling isn't explicitly enabled.
  7518. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  7519. // If we can't use fsevents, ensure the options reflect it's disabled.
  7520. const canUseFsEvents = FsEventsHandler.canUse();
  7521. if (!canUseFsEvents) opts.useFsEvents = false;
  7522. // Use polling on Mac if not using fsevents.
  7523. // Other platforms use non-polling fs_watch.
  7524. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  7525. opts.usePolling = isMacos;
  7526. }
  7527. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  7528. if(isIBMi) {
  7529. opts.usePolling = true;
  7530. }
  7531. // Global override (useful for end-developers that need to force polling for all
  7532. // instances of chokidar, regardless of usage/dependency depth)
  7533. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  7534. if (envPoll !== undefined) {
  7535. const envLower = envPoll.toLowerCase();
  7536. if (envLower === 'false' || envLower === '0') {
  7537. opts.usePolling = false;
  7538. } else if (envLower === 'true' || envLower === '1') {
  7539. opts.usePolling = true;
  7540. } else {
  7541. opts.usePolling = !!envLower;
  7542. }
  7543. }
  7544. const envInterval = process.env.CHOKIDAR_INTERVAL;
  7545. if (envInterval) {
  7546. opts.interval = Number.parseInt(envInterval, 10);
  7547. }
  7548. // Editor atomic write normalization enabled by default with fs.watch
  7549. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  7550. if (opts.atomic) this._pendingUnlinks = new Map();
  7551. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  7552. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  7553. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  7554. const awf = opts.awaitWriteFinish;
  7555. if (awf) {
  7556. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  7557. if (!awf.pollInterval) awf.pollInterval = 100;
  7558. this._pendingWrites = new Map();
  7559. }
  7560. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  7561. let readyCalls = 0;
  7562. this._emitReady = () => {
  7563. readyCalls++;
  7564. if (readyCalls >= this._readyCount) {
  7565. this._emitReady = EMPTY_FN;
  7566. this._readyEmitted = true;
  7567. // use process.nextTick to allow time for listener to be bound
  7568. process.nextTick(() => this.emit(EV_READY));
  7569. }
  7570. };
  7571. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  7572. this._readyEmitted = false;
  7573. this.options = opts;
  7574. // Initialize with proper watcher.
  7575. if (opts.useFsEvents) {
  7576. this._fsEventsHandler = new FsEventsHandler(this);
  7577. } else {
  7578. this._nodeFsHandler = new NodeFsHandler(this);
  7579. }
  7580. // You’re frozen when your heart’s not open.
  7581. Object.freeze(opts);
  7582. }
  7583. // Public methods
  7584. /**
  7585. * Adds paths to be watched on an existing FSWatcher instance
  7586. * @param {Path|Array<Path>} paths_
  7587. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  7588. * @param {Boolean=} _internal private; indicates a non-user add
  7589. * @returns {FSWatcher} for chaining
  7590. */
  7591. add(paths_, _origAdd, _internal) {
  7592. const {cwd, disableGlobbing} = this.options;
  7593. this.closed = false;
  7594. let paths = unifyPaths(paths_);
  7595. if (cwd) {
  7596. paths = paths.map((path) => {
  7597. const absPath = getAbsolutePath(path, cwd);
  7598. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  7599. if (disableGlobbing || !isGlob(path)) {
  7600. return absPath;
  7601. }
  7602. return normalizePath(absPath);
  7603. });
  7604. }
  7605. // set aside negated glob strings
  7606. paths = paths.filter((path) => {
  7607. if (path.startsWith(BANG)) {
  7608. this._ignoredPaths.add(path.slice(1));
  7609. return false;
  7610. }
  7611. // if a path is being added that was previously ignored, stop ignoring it
  7612. this._ignoredPaths.delete(path);
  7613. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  7614. // reset the cached userIgnored anymatch fn
  7615. // to make ignoredPaths changes effective
  7616. this._userIgnored = undefined;
  7617. return true;
  7618. });
  7619. if (this.options.useFsEvents && this._fsEventsHandler) {
  7620. if (!this._readyCount) this._readyCount = paths.length;
  7621. if (this.options.persistent) this._readyCount += paths.length;
  7622. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  7623. } else {
  7624. if (!this._readyCount) this._readyCount = 0;
  7625. this._readyCount += paths.length;
  7626. Promise.all(
  7627. paths.map(async path => {
  7628. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  7629. if (res) this._emitReady();
  7630. return res;
  7631. })
  7632. ).then(results => {
  7633. if (this.closed) return;
  7634. results.filter(item => item).forEach(item => {
  7635. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  7636. });
  7637. });
  7638. }
  7639. return this;
  7640. }
  7641. /**
  7642. * Close watchers or start ignoring events from specified paths.
  7643. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  7644. * @returns {FSWatcher} for chaining
  7645. */
  7646. unwatch(paths_) {
  7647. if (this.closed) return this;
  7648. const paths = unifyPaths(paths_);
  7649. const {cwd} = this.options;
  7650. paths.forEach((path) => {
  7651. // convert to absolute path unless relative path already matches
  7652. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  7653. if (cwd) path = sysPath.join(cwd, path);
  7654. path = sysPath.resolve(path);
  7655. }
  7656. this._closePath(path);
  7657. this._ignoredPaths.add(path);
  7658. if (this._watched.has(path)) {
  7659. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  7660. }
  7661. // reset the cached userIgnored anymatch fn
  7662. // to make ignoredPaths changes effective
  7663. this._userIgnored = undefined;
  7664. });
  7665. return this;
  7666. }
  7667. /**
  7668. * Close watchers and remove all listeners from watched paths.
  7669. * @returns {Promise<void>}.
  7670. */
  7671. close() {
  7672. if (this.closed) return this._closePromise;
  7673. this.closed = true;
  7674. // Memory management.
  7675. this.removeAllListeners();
  7676. const closers = [];
  7677. this._closers.forEach(closerList => closerList.forEach(closer => {
  7678. const promise = closer();
  7679. if (promise instanceof Promise) closers.push(promise);
  7680. }));
  7681. this._streams.forEach(stream => stream.destroy());
  7682. this._userIgnored = undefined;
  7683. this._readyCount = 0;
  7684. this._readyEmitted = false;
  7685. this._watched.forEach(dirent => dirent.dispose());
  7686. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  7687. this[`_${key}`].clear();
  7688. });
  7689. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  7690. return this._closePromise;
  7691. }
  7692. /**
  7693. * Expose list of watched paths
  7694. * @returns {Object} for chaining
  7695. */
  7696. getWatched() {
  7697. const watchList = {};
  7698. this._watched.forEach((entry, dir) => {
  7699. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  7700. watchList[key || ONE_DOT] = entry.getChildren().sort();
  7701. });
  7702. return watchList;
  7703. }
  7704. emitWithAll(event, args) {
  7705. this.emit(...args);
  7706. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  7707. }
  7708. // Common helpers
  7709. // --------------
  7710. /**
  7711. * Normalize and emit events.
  7712. * Calling _emit DOES NOT MEAN emit() would be called!
  7713. * @param {EventName} event Type of event
  7714. * @param {Path} path File or directory path
  7715. * @param {*=} val1 arguments to be passed with event
  7716. * @param {*=} val2
  7717. * @param {*=} val3
  7718. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  7719. */
  7720. async _emit(event, path, val1, val2, val3) {
  7721. if (this.closed) return;
  7722. const opts = this.options;
  7723. if (isWindows) path = sysPath.normalize(path);
  7724. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  7725. /** @type Array<any> */
  7726. const args = [event, path];
  7727. if (val3 !== undefined) args.push(val1, val2, val3);
  7728. else if (val2 !== undefined) args.push(val1, val2);
  7729. else if (val1 !== undefined) args.push(val1);
  7730. const awf = opts.awaitWriteFinish;
  7731. let pw;
  7732. if (awf && (pw = this._pendingWrites.get(path))) {
  7733. pw.lastChange = new Date();
  7734. return this;
  7735. }
  7736. if (opts.atomic) {
  7737. if (event === EV_UNLINK) {
  7738. this._pendingUnlinks.set(path, args);
  7739. setTimeout(() => {
  7740. this._pendingUnlinks.forEach((entry, path) => {
  7741. this.emit(...entry);
  7742. this.emit(EV_ALL, ...entry);
  7743. this._pendingUnlinks.delete(path);
  7744. });
  7745. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  7746. return this;
  7747. }
  7748. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  7749. event = args[0] = EV_CHANGE;
  7750. this._pendingUnlinks.delete(path);
  7751. }
  7752. }
  7753. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  7754. const awfEmit = (err, stats) => {
  7755. if (err) {
  7756. event = args[0] = EV_ERROR;
  7757. args[1] = err;
  7758. this.emitWithAll(event, args);
  7759. } else if (stats) {
  7760. // if stats doesn't exist the file must have been deleted
  7761. if (args.length > 2) {
  7762. args[2] = stats;
  7763. } else {
  7764. args.push(stats);
  7765. }
  7766. this.emitWithAll(event, args);
  7767. }
  7768. };
  7769. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  7770. return this;
  7771. }
  7772. if (event === EV_CHANGE) {
  7773. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  7774. if (isThrottled) return this;
  7775. }
  7776. if (opts.alwaysStat && val1 === undefined &&
  7777. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  7778. ) {
  7779. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  7780. let stats;
  7781. try {
  7782. stats = await stat(fullPath);
  7783. } catch (err) {}
  7784. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  7785. if (!stats || this.closed) return;
  7786. args.push(stats);
  7787. }
  7788. this.emitWithAll(event, args);
  7789. return this;
  7790. }
  7791. /**
  7792. * Common handler for errors
  7793. * @param {Error} error
  7794. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  7795. */
  7796. _handleError(error) {
  7797. const code = error && error.code;
  7798. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  7799. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  7800. ) {
  7801. this.emit(EV_ERROR, error);
  7802. }
  7803. return error || this.closed;
  7804. }
  7805. /**
  7806. * Helper utility for throttling
  7807. * @param {ThrottleType} actionType type being throttled
  7808. * @param {Path} path being acted upon
  7809. * @param {Number} timeout duration of time to suppress duplicate actions
  7810. * @returns {Object|false} tracking object or false if action should be suppressed
  7811. */
  7812. _throttle(actionType, path, timeout) {
  7813. if (!this._throttled.has(actionType)) {
  7814. this._throttled.set(actionType, new Map());
  7815. }
  7816. /** @type {Map<Path, Object>} */
  7817. const action = this._throttled.get(actionType);
  7818. /** @type {Object} */
  7819. const actionPath = action.get(path);
  7820. if (actionPath) {
  7821. actionPath.count++;
  7822. return false;
  7823. }
  7824. let timeoutObject;
  7825. const clear = () => {
  7826. const item = action.get(path);
  7827. const count = item ? item.count : 0;
  7828. action.delete(path);
  7829. clearTimeout(timeoutObject);
  7830. if (item) clearTimeout(item.timeoutObject);
  7831. return count;
  7832. };
  7833. timeoutObject = setTimeout(clear, timeout);
  7834. const thr = {timeoutObject, clear, count: 0};
  7835. action.set(path, thr);
  7836. return thr;
  7837. }
  7838. _incrReadyCount() {
  7839. return this._readyCount++;
  7840. }
  7841. /**
  7842. * Awaits write operation to finish.
  7843. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  7844. * @param {Path} path being acted upon
  7845. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  7846. * @param {EventName} event
  7847. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  7848. */
  7849. _awaitWriteFinish(path, threshold, event, awfEmit) {
  7850. let timeoutHandler;
  7851. let fullPath = path;
  7852. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  7853. fullPath = sysPath.join(this.options.cwd, path);
  7854. }
  7855. const now = new Date();
  7856. const awaitWriteFinish = (prevStat) => {
  7857. fs.stat(fullPath, (err, curStat) => {
  7858. if (err || !this._pendingWrites.has(path)) {
  7859. if (err && err.code !== 'ENOENT') awfEmit(err);
  7860. return;
  7861. }
  7862. const now = Number(new Date());
  7863. if (prevStat && curStat.size !== prevStat.size) {
  7864. this._pendingWrites.get(path).lastChange = now;
  7865. }
  7866. const pw = this._pendingWrites.get(path);
  7867. const df = now - pw.lastChange;
  7868. if (df >= threshold) {
  7869. this._pendingWrites.delete(path);
  7870. awfEmit(undefined, curStat);
  7871. } else {
  7872. timeoutHandler = setTimeout(
  7873. awaitWriteFinish,
  7874. this.options.awaitWriteFinish.pollInterval,
  7875. curStat
  7876. );
  7877. }
  7878. });
  7879. };
  7880. if (!this._pendingWrites.has(path)) {
  7881. this._pendingWrites.set(path, {
  7882. lastChange: now,
  7883. cancelWait: () => {
  7884. this._pendingWrites.delete(path);
  7885. clearTimeout(timeoutHandler);
  7886. return event;
  7887. }
  7888. });
  7889. timeoutHandler = setTimeout(
  7890. awaitWriteFinish,
  7891. this.options.awaitWriteFinish.pollInterval
  7892. );
  7893. }
  7894. }
  7895. _getGlobIgnored() {
  7896. return [...this._ignoredPaths.values()];
  7897. }
  7898. /**
  7899. * Determines whether user has asked to ignore this path.
  7900. * @param {Path} path filepath or dir
  7901. * @param {fs.Stats=} stats result of fs.stat
  7902. * @returns {Boolean}
  7903. */
  7904. _isIgnored(path, stats) {
  7905. if (this.options.atomic && DOT_RE.test(path)) return true;
  7906. if (!this._userIgnored) {
  7907. const {cwd} = this.options;
  7908. const ign = this.options.ignored;
  7909. const ignored = ign && ign.map(normalizeIgnored(cwd));
  7910. const paths = arrify(ignored)
  7911. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  7912. .map((path) => path + SLASH_GLOBSTAR);
  7913. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  7914. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  7915. }
  7916. return this._userIgnored([path, stats]);
  7917. }
  7918. _isntIgnored(path, stat) {
  7919. return !this._isIgnored(path, stat);
  7920. }
  7921. /**
  7922. * Provides a set of common helpers and properties relating to symlink and glob handling.
  7923. * @param {Path} path file, directory, or glob pattern being watched
  7924. * @param {Number=} depth at any depth > 0, this isn't a glob
  7925. * @returns {WatchHelper} object containing helpers for this path
  7926. */
  7927. _getWatchHelpers(path, depth) {
  7928. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  7929. const follow = this.options.followSymlinks;
  7930. return new WatchHelper(path, watchPath, follow, this);
  7931. }
  7932. // Directory helpers
  7933. // -----------------
  7934. /**
  7935. * Provides directory tracking objects
  7936. * @param {String} directory path of the directory
  7937. * @returns {DirEntry} the directory's tracking object
  7938. */
  7939. _getWatchedDir(directory) {
  7940. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  7941. const dir = sysPath.resolve(directory);
  7942. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  7943. return this._watched.get(dir);
  7944. }
  7945. // File helpers
  7946. // ------------
  7947. /**
  7948. * Check for read permissions.
  7949. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  7950. * @param {fs.Stats} stats - object, result of fs_stat
  7951. * @returns {Boolean} indicates whether the file can be read
  7952. */
  7953. _hasReadPermissions(stats) {
  7954. if (this.options.ignorePermissionErrors) return true;
  7955. // stats.mode may be bigint
  7956. const md = stats && Number.parseInt(stats.mode, 10);
  7957. const st = md & 0o777;
  7958. const it = Number.parseInt(st.toString(8)[0], 10);
  7959. return Boolean(4 & it);
  7960. }
  7961. /**
  7962. * Handles emitting unlink events for
  7963. * files and directories, and via recursion, for
  7964. * files and directories within directories that are unlinked
  7965. * @param {String} directory within which the following item is located
  7966. * @param {String} item base path of item/directory
  7967. * @returns {void}
  7968. */
  7969. _remove(directory, item, isDirectory) {
  7970. // if what is being deleted is a directory, get that directory's paths
  7971. // for recursive deleting and cleaning of watched object
  7972. // if it is not a directory, nestedDirectoryChildren will be empty array
  7973. const path = sysPath.join(directory, item);
  7974. const fullPath = sysPath.resolve(path);
  7975. isDirectory = isDirectory != null
  7976. ? isDirectory
  7977. : this._watched.has(path) || this._watched.has(fullPath);
  7978. // prevent duplicate handling in case of arriving here nearly simultaneously
  7979. // via multiple paths (such as _handleFile and _handleDir)
  7980. if (!this._throttle('remove', path, 100)) return;
  7981. // if the only watched file is removed, watch for its return
  7982. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  7983. this.add(directory, item, true);
  7984. }
  7985. // This will create a new entry in the watched object in either case
  7986. // so we got to do the directory check beforehand
  7987. const wp = this._getWatchedDir(path);
  7988. const nestedDirectoryChildren = wp.getChildren();
  7989. // Recursively remove children directories / files.
  7990. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  7991. // Check if item was on the watched list and remove it
  7992. const parent = this._getWatchedDir(directory);
  7993. const wasTracked = parent.has(item);
  7994. parent.remove(item);
  7995. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  7996. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  7997. // but never removed from the map in case the path was deleted.
  7998. // This leads to an incorrect state if the path was recreated:
  7999. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  8000. if (this._symlinkPaths.has(fullPath)) {
  8001. this._symlinkPaths.delete(fullPath);
  8002. }
  8003. // If we wait for this file to be fully written, cancel the wait.
  8004. let relPath = path;
  8005. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  8006. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  8007. const event = this._pendingWrites.get(relPath).cancelWait();
  8008. if (event === EV_ADD) return;
  8009. }
  8010. // The Entry will either be a directory that just got removed
  8011. // or a bogus entry to a file, in either case we have to remove it
  8012. this._watched.delete(path);
  8013. this._watched.delete(fullPath);
  8014. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  8015. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  8016. // Avoid conflicts if we later create another file with the same name
  8017. if (!this.options.useFsEvents) {
  8018. this._closePath(path);
  8019. }
  8020. }
  8021. /**
  8022. * Closes all watchers for a path
  8023. * @param {Path} path
  8024. */
  8025. _closePath(path) {
  8026. this._closeFile(path);
  8027. const dir = sysPath.dirname(path);
  8028. this._getWatchedDir(dir).remove(sysPath.basename(path));
  8029. }
  8030. /**
  8031. * Closes only file-specific watchers
  8032. * @param {Path} path
  8033. */
  8034. _closeFile(path) {
  8035. const closers = this._closers.get(path);
  8036. if (!closers) return;
  8037. closers.forEach(closer => closer());
  8038. this._closers.delete(path);
  8039. }
  8040. /**
  8041. *
  8042. * @param {Path} path
  8043. * @param {Function} closer
  8044. */
  8045. _addPathCloser(path, closer) {
  8046. if (!closer) return;
  8047. let list = this._closers.get(path);
  8048. if (!list) {
  8049. list = [];
  8050. this._closers.set(path, list);
  8051. }
  8052. list.push(closer);
  8053. }
  8054. _readdirp(root, opts) {
  8055. if (this.closed) return;
  8056. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  8057. let stream = readdirp(root, options);
  8058. this._streams.add(stream);
  8059. stream.once(STR_CLOSE, () => {
  8060. stream = undefined;
  8061. });
  8062. stream.once(STR_END, () => {
  8063. if (stream) {
  8064. this._streams.delete(stream);
  8065. stream = undefined;
  8066. }
  8067. });
  8068. return stream;
  8069. }
  8070. }
  8071. // Export FSWatcher class
  8072. chokidar$1.FSWatcher = FSWatcher;
  8073. /**
  8074. * Instantiates watcher with paths to be tracked.
  8075. * @param {String|Array<String>} paths file/directory paths and/or globs
  8076. * @param {Object=} options chokidar opts
  8077. * @returns an instance of FSWatcher for chaining.
  8078. */
  8079. const watch = (paths, options) => {
  8080. const watcher = new FSWatcher(options);
  8081. watcher.add(paths);
  8082. return watcher;
  8083. };
  8084. chokidar$1.watch = watch;
  8085. return chokidar$1;
  8086. }
  8087. var chokidarExports = /*@__PURE__*/ requireChokidar();
  8088. const chokidar = /*@__PURE__*/getDefaultExportFromCjs(chokidarExports);
  8089. class FileWatcher {
  8090. constructor(task, chokidarOptions) {
  8091. this.transformWatchers = new Map();
  8092. this.chokidarOptions = chokidarOptions;
  8093. this.task = task;
  8094. this.watcher = this.createWatcher(null);
  8095. }
  8096. close() {
  8097. this.watcher.close();
  8098. for (const watcher of this.transformWatchers.values()) {
  8099. watcher.close();
  8100. }
  8101. }
  8102. unwatch(id) {
  8103. this.watcher.unwatch(id);
  8104. const transformWatcher = this.transformWatchers.get(id);
  8105. if (transformWatcher) {
  8106. this.transformWatchers.delete(id);
  8107. transformWatcher.close();
  8108. }
  8109. }
  8110. watch(id, isTransformDependency) {
  8111. if (isTransformDependency) {
  8112. const watcher = this.transformWatchers.get(id) ?? this.createWatcher(id);
  8113. watcher.add(id);
  8114. this.transformWatchers.set(id, watcher);
  8115. }
  8116. else {
  8117. this.watcher.add(id);
  8118. }
  8119. }
  8120. createWatcher(transformWatcherId) {
  8121. const task = this.task;
  8122. const isLinux = platform() === 'linux';
  8123. const isFreeBSD = platform() === 'freebsd';
  8124. const isTransformDependency = transformWatcherId !== null;
  8125. const handleChange = (id, event) => {
  8126. const changedId = transformWatcherId || id;
  8127. if (isLinux || isFreeBSD) {
  8128. // unwatching and watching fixes an issue with chokidar where on certain systems,
  8129. // a file that was unlinked and immediately recreated would create a change event
  8130. // but then no longer any further events
  8131. watcher.unwatch(changedId);
  8132. watcher.add(changedId);
  8133. }
  8134. task.invalidate(changedId, { event, isTransformDependency });
  8135. };
  8136. const watcher = chokidar
  8137. .watch([], this.chokidarOptions)
  8138. .on('add', id => handleChange(id, 'create'))
  8139. .on('change', id => handleChange(id, 'update'))
  8140. .on('unlink', id => handleChange(id, 'delete'));
  8141. return watcher;
  8142. }
  8143. }
  8144. const eventsRewrites = {
  8145. create: {
  8146. create: 'buggy',
  8147. delete: null, //delete file from map
  8148. update: 'create'
  8149. },
  8150. delete: {
  8151. create: 'update',
  8152. delete: 'buggy',
  8153. update: 'buggy'
  8154. },
  8155. update: {
  8156. create: 'buggy',
  8157. delete: 'delete',
  8158. update: 'update'
  8159. }
  8160. };
  8161. class Watcher {
  8162. constructor(optionsList, emitter) {
  8163. this.buildDelay = 0;
  8164. this.buildTimeout = null;
  8165. this.closed = false;
  8166. this.invalidatedIds = new Map();
  8167. this.rerun = false;
  8168. this.running = true;
  8169. this.emitter = emitter;
  8170. emitter.close = this.close.bind(this);
  8171. this.tasks = optionsList.map(options => new Task(this, options));
  8172. for (const { watch } of optionsList) {
  8173. if (watch && typeof watch.buildDelay === 'number') {
  8174. this.buildDelay = Math.max(this.buildDelay, watch.buildDelay);
  8175. }
  8176. }
  8177. process$1.nextTick(() => this.run());
  8178. }
  8179. async close() {
  8180. if (this.closed)
  8181. return;
  8182. this.closed = true;
  8183. if (this.buildTimeout)
  8184. clearTimeout(this.buildTimeout);
  8185. for (const task of this.tasks) {
  8186. task.close();
  8187. }
  8188. await this.emitter.emit('close');
  8189. this.emitter.removeAllListeners();
  8190. }
  8191. invalidate(file) {
  8192. if (file) {
  8193. const previousEvent = this.invalidatedIds.get(file.id);
  8194. const event = previousEvent ? eventsRewrites[previousEvent][file.event] : file.event;
  8195. if (event === 'buggy') {
  8196. //TODO: throws or warn? Currently just ignore, uses new event
  8197. this.invalidatedIds.set(file.id, file.event);
  8198. }
  8199. else if (event === null) {
  8200. this.invalidatedIds.delete(file.id);
  8201. }
  8202. else {
  8203. this.invalidatedIds.set(file.id, event);
  8204. }
  8205. }
  8206. if (this.running) {
  8207. this.rerun = true;
  8208. return;
  8209. }
  8210. if (this.buildTimeout)
  8211. clearTimeout(this.buildTimeout);
  8212. this.buildTimeout = setTimeout(async () => {
  8213. this.buildTimeout = null;
  8214. try {
  8215. await Promise.all([...this.invalidatedIds].map(([id, event]) => this.emitter.emit('change', id, { event })));
  8216. this.invalidatedIds.clear();
  8217. await this.emitter.emit('restart');
  8218. this.emitter.removeListenersForCurrentRun();
  8219. this.run();
  8220. }
  8221. catch (error) {
  8222. this.invalidatedIds.clear();
  8223. await this.emitter.emit('event', {
  8224. code: 'ERROR',
  8225. error,
  8226. result: null
  8227. });
  8228. await this.emitter.emit('event', {
  8229. code: 'END'
  8230. });
  8231. }
  8232. }, this.buildDelay);
  8233. }
  8234. async run() {
  8235. this.running = true;
  8236. await this.emitter.emit('event', {
  8237. code: 'START'
  8238. });
  8239. for (const task of this.tasks) {
  8240. await task.run();
  8241. }
  8242. this.running = false;
  8243. await this.emitter.emit('event', {
  8244. code: 'END'
  8245. });
  8246. if (this.rerun) {
  8247. this.rerun = false;
  8248. this.invalidate();
  8249. }
  8250. }
  8251. }
  8252. class Task {
  8253. constructor(watcher, options) {
  8254. this.cache = { modules: [] };
  8255. this.watchFiles = [];
  8256. this.closed = false;
  8257. this.invalidated = true;
  8258. this.watched = new Set();
  8259. this.watcher = watcher;
  8260. this.options = options;
  8261. this.skipWrite = Boolean(options.watch && options.watch.skipWrite);
  8262. this.outputs = this.options.output;
  8263. this.outputFiles = this.outputs.map(output => {
  8264. if (output.file || output.dir)
  8265. return path.resolve(output.file || output.dir);
  8266. return undefined;
  8267. });
  8268. this.watchOptions = this.options.watch || {};
  8269. this.filter = createFilter(this.watchOptions.include, this.watchOptions.exclude);
  8270. this.fileWatcher = new FileWatcher(this, {
  8271. ...this.watchOptions.chokidar,
  8272. disableGlobbing: true,
  8273. ignoreInitial: true
  8274. });
  8275. }
  8276. close() {
  8277. this.closed = true;
  8278. this.fileWatcher.close();
  8279. }
  8280. invalidate(id, details) {
  8281. this.invalidated = true;
  8282. if (details.isTransformDependency) {
  8283. for (const module of this.cache.modules) {
  8284. if (!module.transformDependencies.includes(id))
  8285. continue;
  8286. // effective invalidation
  8287. module.originalCode = null;
  8288. }
  8289. }
  8290. this.watcher.invalidate({ event: details.event, id });
  8291. this.watchOptions.onInvalidate?.(id);
  8292. }
  8293. async run() {
  8294. if (!this.invalidated)
  8295. return;
  8296. this.invalidated = false;
  8297. const options = {
  8298. ...this.options,
  8299. cache: this.cache
  8300. };
  8301. const start = Date.now();
  8302. await this.watcher.emitter.emit('event', {
  8303. code: 'BUNDLE_START',
  8304. input: this.options.input,
  8305. output: this.outputFiles
  8306. });
  8307. let result = null;
  8308. try {
  8309. result = await rollupInternal(options, this.watcher.emitter);
  8310. if (this.closed) {
  8311. return;
  8312. }
  8313. this.updateWatchedFiles(result);
  8314. if (!this.skipWrite) {
  8315. await Promise.all(this.outputs.map(output => result.write(output)));
  8316. if (this.closed) {
  8317. return;
  8318. }
  8319. this.updateWatchedFiles(result);
  8320. }
  8321. await this.watcher.emitter.emit('event', {
  8322. code: 'BUNDLE_END',
  8323. duration: Date.now() - start,
  8324. input: this.options.input,
  8325. output: this.outputFiles,
  8326. result
  8327. });
  8328. }
  8329. catch (error) {
  8330. if (!this.closed) {
  8331. if (Array.isArray(error.watchFiles)) {
  8332. for (const id of error.watchFiles) {
  8333. this.watchFile(id);
  8334. }
  8335. }
  8336. if (error.id) {
  8337. this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);
  8338. }
  8339. }
  8340. await this.watcher.emitter.emit('event', {
  8341. code: 'ERROR',
  8342. error,
  8343. result
  8344. });
  8345. }
  8346. }
  8347. updateWatchedFiles(result) {
  8348. const previouslyWatched = this.watched;
  8349. this.watched = new Set();
  8350. this.watchFiles = result.watchFiles;
  8351. this.cache = result.cache;
  8352. for (const id of this.watchFiles) {
  8353. this.watchFile(id);
  8354. }
  8355. for (const module of this.cache.modules) {
  8356. for (const depId of module.transformDependencies) {
  8357. this.watchFile(depId, true);
  8358. }
  8359. }
  8360. for (const id of previouslyWatched) {
  8361. if (!this.watched.has(id)) {
  8362. this.fileWatcher.unwatch(id);
  8363. }
  8364. }
  8365. }
  8366. watchFile(id, isTransformDependency = false) {
  8367. if (!this.filter(id))
  8368. return;
  8369. this.watched.add(id);
  8370. if (this.outputFiles.includes(id)) {
  8371. throw new Error('Cannot import the generated bundle');
  8372. }
  8373. // this is necessary to ensure that any 'renamed' files
  8374. // continue to be watched following an error
  8375. this.fileWatcher.watch(id, isTransformDependency);
  8376. }
  8377. }
  8378. export { Task, Watcher };