index.js 168 KB

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