compiler-sfc.cjs.js 651 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677
  1. /**
  2. * @vue/compiler-sfc v3.4.23
  3. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  4. * @license MIT
  5. **/
  6. 'use strict';
  7. Object.defineProperty(exports, '__esModule', { value: true });
  8. var compilerCore = require('@vue/compiler-core');
  9. var CompilerDOM = require('@vue/compiler-dom');
  10. var sourceMapJs = require('source-map-js');
  11. var path$3 = require('path');
  12. var shared = require('@vue/shared');
  13. var url = require('url');
  14. var CompilerSSR = require('@vue/compiler-ssr');
  15. var require$$2 = require('util');
  16. var require$$0 = require('fs');
  17. var require$$0$1 = require('postcss');
  18. var estreeWalker = require('estree-walker');
  19. var MagicString = require('magic-string');
  20. var parser$1 = require('@babel/parser');
  21. var process$1 = require('process');
  22. function _interopNamespaceDefault(e) {
  23. var n = Object.create(null);
  24. if (e) {
  25. for (var k in e) {
  26. n[k] = e[k];
  27. }
  28. }
  29. n.default = e;
  30. return Object.freeze(n);
  31. }
  32. var CompilerDOM__namespace = /*#__PURE__*/_interopNamespaceDefault(CompilerDOM);
  33. var CompilerSSR__namespace = /*#__PURE__*/_interopNamespaceDefault(CompilerSSR);
  34. var process__namespace = /*#__PURE__*/_interopNamespaceDefault(process$1);
  35. const UNKNOWN_TYPE = "Unknown";
  36. function resolveObjectKey(node, computed) {
  37. switch (node.type) {
  38. case "StringLiteral":
  39. case "NumericLiteral":
  40. return String(node.value);
  41. case "Identifier":
  42. if (!computed)
  43. return node.name;
  44. }
  45. return void 0;
  46. }
  47. function concatStrings(strs) {
  48. return strs.filter((s) => !!s).join(", ");
  49. }
  50. function isLiteralNode(node) {
  51. return node.type.endsWith("Literal");
  52. }
  53. function isCallOf(node, test) {
  54. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  55. }
  56. function toRuntimeTypeString(types) {
  57. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  58. }
  59. function getImportedName(specifier) {
  60. if (specifier.type === "ImportSpecifier")
  61. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  62. else if (specifier.type === "ImportNamespaceSpecifier")
  63. return "*";
  64. return "default";
  65. }
  66. function getId(node) {
  67. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  68. }
  69. const identity = (str) => str;
  70. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  71. const toLowerCase = (str) => str.toLowerCase();
  72. function toFileNameLowerCase(x) {
  73. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  74. }
  75. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  76. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  77. }
  78. const normalize = (path$3.posix || path$3).normalize;
  79. const windowsSlashRE = /\\/g;
  80. function normalizePath(p) {
  81. return normalize(p.replace(windowsSlashRE, "/"));
  82. }
  83. const joinPaths = (path$3.posix || path$3).join;
  84. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  85. function getEscapedPropName(key) {
  86. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  87. }
  88. const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g;
  89. function getEscapedCssVarName(key, doubleEscape) {
  90. return key.replace(
  91. cssVarNameEscapeSymbolsRE,
  92. (s) => doubleEscape ? `\\\\${s}` : `\\${s}`
  93. );
  94. }
  95. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  96. function getDefaultExportFromCjs (x) {
  97. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  98. }
  99. function pad (hash, len) {
  100. while (hash.length < len) {
  101. hash = '0' + hash;
  102. }
  103. return hash;
  104. }
  105. function fold (hash, text) {
  106. var i;
  107. var chr;
  108. var len;
  109. if (text.length === 0) {
  110. return hash;
  111. }
  112. for (i = 0, len = text.length; i < len; i++) {
  113. chr = text.charCodeAt(i);
  114. hash = ((hash << 5) - hash) + chr;
  115. hash |= 0;
  116. }
  117. return hash < 0 ? hash * -2 : hash;
  118. }
  119. function foldObject (hash, o, seen) {
  120. return Object.keys(o).sort().reduce(foldKey, hash);
  121. function foldKey (hash, key) {
  122. return foldValue(hash, o[key], key, seen);
  123. }
  124. }
  125. function foldValue (input, value, key, seen) {
  126. var hash = fold(fold(fold(input, key), toString$1(value)), typeof value);
  127. if (value === null) {
  128. return fold(hash, 'null');
  129. }
  130. if (value === undefined) {
  131. return fold(hash, 'undefined');
  132. }
  133. if (typeof value === 'object' || typeof value === 'function') {
  134. if (seen.indexOf(value) !== -1) {
  135. return fold(hash, '[Circular]' + key);
  136. }
  137. seen.push(value);
  138. var objHash = foldObject(hash, value, seen);
  139. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  140. return objHash;
  141. }
  142. try {
  143. return fold(objHash, String(value.valueOf()))
  144. } catch (err) {
  145. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  146. }
  147. }
  148. return fold(hash, value.toString());
  149. }
  150. function toString$1 (o) {
  151. return Object.prototype.toString.call(o);
  152. }
  153. function sum (o) {
  154. return pad(foldValue(0, o, '', []).toString(16), 8);
  155. }
  156. var hashSum = sum;
  157. var hash$1 = /*@__PURE__*/getDefaultExportFromCjs(hashSum);
  158. const CSS_VARS_HELPER = `useCssVars`;
  159. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  160. return `{
  161. ${vars.map(
  162. (key) => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  163. ).join(",\n ")}
  164. }`;
  165. }
  166. function genVarName(id, raw, isProd, isSSR = false) {
  167. if (isProd) {
  168. return hash$1(id + raw);
  169. } else {
  170. return `${id}-${getEscapedCssVarName(raw, isSSR)}`;
  171. }
  172. }
  173. function normalizeExpression(exp) {
  174. exp = exp.trim();
  175. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  176. return exp.slice(1, -1);
  177. }
  178. return exp;
  179. }
  180. const vBindRE = /v-bind\s*\(/g;
  181. function parseCssVars(sfc) {
  182. const vars = [];
  183. sfc.styles.forEach((style) => {
  184. let match;
  185. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  186. while (match = vBindRE.exec(content)) {
  187. const start = match.index + match[0].length;
  188. const end = lexBinding(content, start);
  189. if (end !== null) {
  190. const variable = normalizeExpression(content.slice(start, end));
  191. if (!vars.includes(variable)) {
  192. vars.push(variable);
  193. }
  194. }
  195. }
  196. });
  197. return vars;
  198. }
  199. function lexBinding(content, start) {
  200. let state = 0 /* inParens */;
  201. let parenDepth = 0;
  202. for (let i = start; i < content.length; i++) {
  203. const char = content.charAt(i);
  204. switch (state) {
  205. case 0 /* inParens */:
  206. if (char === `'`) {
  207. state = 1 /* inSingleQuoteString */;
  208. } else if (char === `"`) {
  209. state = 2 /* inDoubleQuoteString */;
  210. } else if (char === `(`) {
  211. parenDepth++;
  212. } else if (char === `)`) {
  213. if (parenDepth > 0) {
  214. parenDepth--;
  215. } else {
  216. return i;
  217. }
  218. }
  219. break;
  220. case 1 /* inSingleQuoteString */:
  221. if (char === `'`) {
  222. state = 0 /* inParens */;
  223. }
  224. break;
  225. case 2 /* inDoubleQuoteString */:
  226. if (char === `"`) {
  227. state = 0 /* inParens */;
  228. }
  229. break;
  230. }
  231. }
  232. return null;
  233. }
  234. const cssVarsPlugin = (opts) => {
  235. const { id, isProd } = opts;
  236. return {
  237. postcssPlugin: "vue-sfc-vars",
  238. Declaration(decl) {
  239. const value = decl.value;
  240. if (vBindRE.test(value)) {
  241. vBindRE.lastIndex = 0;
  242. let transformed = "";
  243. let lastIndex = 0;
  244. let match;
  245. while (match = vBindRE.exec(value)) {
  246. const start = match.index + match[0].length;
  247. const end = lexBinding(value, start);
  248. if (end !== null) {
  249. const variable = normalizeExpression(value.slice(start, end));
  250. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  251. lastIndex = end + 1;
  252. }
  253. }
  254. decl.value = transformed + value.slice(lastIndex);
  255. }
  256. }
  257. };
  258. };
  259. cssVarsPlugin.postcss = true;
  260. function genCssVarsCode(vars, bindings, id, isProd) {
  261. const varsExp = genCssVarsFromList(vars, id, isProd);
  262. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  263. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  264. prefixIdentifiers: true,
  265. inline: true,
  266. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  267. });
  268. const transformed = CompilerDOM.processExpression(exp, context);
  269. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  270. return typeof c === "string" ? c : c.content;
  271. }).join("");
  272. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  273. }
  274. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  275. return `
  276. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  277. const __injectCSSVars__ = () => {
  278. ${genCssVarsCode(
  279. cssVars,
  280. bindings,
  281. id,
  282. isProd
  283. )}}
  284. const __setup__ = ${defaultVar}.setup
  285. ${defaultVar}.setup = __setup__
  286. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  287. : __injectCSSVars__
  288. `;
  289. }
  290. /**
  291. * @module LRUCache
  292. */
  293. const perf = typeof performance === 'object' &&
  294. performance &&
  295. typeof performance.now === 'function'
  296. ? performance
  297. : Date;
  298. const warned = new Set();
  299. /* c8 ignore start */
  300. const PROCESS = (typeof process === 'object' && !!process ? process : {});
  301. /* c8 ignore start */
  302. const emitWarning = (msg, type, code, fn) => {
  303. typeof PROCESS.emitWarning === 'function'
  304. ? PROCESS.emitWarning(msg, type, code, fn)
  305. : console.error(`[${code}] ${type}: ${msg}`);
  306. };
  307. let AC = globalThis.AbortController;
  308. let AS = globalThis.AbortSignal;
  309. /* c8 ignore start */
  310. if (typeof AC === 'undefined') {
  311. //@ts-ignore
  312. AS = class AbortSignal {
  313. onabort;
  314. _onabort = [];
  315. reason;
  316. aborted = false;
  317. addEventListener(_, fn) {
  318. this._onabort.push(fn);
  319. }
  320. };
  321. //@ts-ignore
  322. AC = class AbortController {
  323. constructor() {
  324. warnACPolyfill();
  325. }
  326. signal = new AS();
  327. abort(reason) {
  328. if (this.signal.aborted)
  329. return;
  330. //@ts-ignore
  331. this.signal.reason = reason;
  332. //@ts-ignore
  333. this.signal.aborted = true;
  334. //@ts-ignore
  335. for (const fn of this.signal._onabort) {
  336. fn(reason);
  337. }
  338. this.signal.onabort?.(reason);
  339. }
  340. };
  341. let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
  342. const warnACPolyfill = () => {
  343. if (!printACPolyfillWarning)
  344. return;
  345. printACPolyfillWarning = false;
  346. emitWarning('AbortController is not defined. If using lru-cache in ' +
  347. 'node 14, load an AbortController polyfill from the ' +
  348. '`node-abort-controller` package. A minimal polyfill is ' +
  349. 'provided for use by LRUCache.fetch(), but it should not be ' +
  350. 'relied upon in other contexts (eg, passing it to other APIs that ' +
  351. 'use AbortController/AbortSignal might have undesirable effects). ' +
  352. 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
  353. };
  354. }
  355. /* c8 ignore stop */
  356. const shouldWarn = (code) => !warned.has(code);
  357. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  358. /* c8 ignore start */
  359. // This is a little bit ridiculous, tbh.
  360. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  361. // And well before that point, you're caching the entire world, I mean,
  362. // that's ~32GB of just integers for the next/prev links, plus whatever
  363. // else to hold that many keys and values. Just filling the memory with
  364. // zeroes at init time is brutal when you get that big.
  365. // But why not be complete?
  366. // Maybe in the future, these limits will have expanded.
  367. const getUintArray = (max) => !isPosInt(max)
  368. ? null
  369. : max <= Math.pow(2, 8)
  370. ? Uint8Array
  371. : max <= Math.pow(2, 16)
  372. ? Uint16Array
  373. : max <= Math.pow(2, 32)
  374. ? Uint32Array
  375. : max <= Number.MAX_SAFE_INTEGER
  376. ? ZeroArray
  377. : null;
  378. /* c8 ignore stop */
  379. class ZeroArray extends Array {
  380. constructor(size) {
  381. super(size);
  382. this.fill(0);
  383. }
  384. }
  385. class Stack {
  386. heap;
  387. length;
  388. // private constructor
  389. static #constructing = false;
  390. static create(max) {
  391. const HeapCls = getUintArray(max);
  392. if (!HeapCls)
  393. return [];
  394. Stack.#constructing = true;
  395. const s = new Stack(max, HeapCls);
  396. Stack.#constructing = false;
  397. return s;
  398. }
  399. constructor(max, HeapCls) {
  400. /* c8 ignore start */
  401. if (!Stack.#constructing) {
  402. throw new TypeError('instantiate Stack using Stack.create(n)');
  403. }
  404. /* c8 ignore stop */
  405. this.heap = new HeapCls(max);
  406. this.length = 0;
  407. }
  408. push(n) {
  409. this.heap[this.length++] = n;
  410. }
  411. pop() {
  412. return this.heap[--this.length];
  413. }
  414. }
  415. /**
  416. * Default export, the thing you're using this module to get.
  417. *
  418. * All properties from the options object (with the exception of
  419. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  420. * normal public members. (`max` and `maxBase` are read-only getters.)
  421. * Changing any of these will alter the defaults for subsequent method calls,
  422. * but is otherwise safe.
  423. */
  424. class LRUCache {
  425. // properties coming in from the options of these, only max and maxSize
  426. // really *need* to be protected. The rest can be modified, as they just
  427. // set defaults for various methods.
  428. #max;
  429. #maxSize;
  430. #dispose;
  431. #disposeAfter;
  432. #fetchMethod;
  433. /**
  434. * {@link LRUCache.OptionsBase.ttl}
  435. */
  436. ttl;
  437. /**
  438. * {@link LRUCache.OptionsBase.ttlResolution}
  439. */
  440. ttlResolution;
  441. /**
  442. * {@link LRUCache.OptionsBase.ttlAutopurge}
  443. */
  444. ttlAutopurge;
  445. /**
  446. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  447. */
  448. updateAgeOnGet;
  449. /**
  450. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  451. */
  452. updateAgeOnHas;
  453. /**
  454. * {@link LRUCache.OptionsBase.allowStale}
  455. */
  456. allowStale;
  457. /**
  458. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  459. */
  460. noDisposeOnSet;
  461. /**
  462. * {@link LRUCache.OptionsBase.noUpdateTTL}
  463. */
  464. noUpdateTTL;
  465. /**
  466. * {@link LRUCache.OptionsBase.maxEntrySize}
  467. */
  468. maxEntrySize;
  469. /**
  470. * {@link LRUCache.OptionsBase.sizeCalculation}
  471. */
  472. sizeCalculation;
  473. /**
  474. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  475. */
  476. noDeleteOnFetchRejection;
  477. /**
  478. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  479. */
  480. noDeleteOnStaleGet;
  481. /**
  482. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  483. */
  484. allowStaleOnFetchAbort;
  485. /**
  486. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  487. */
  488. allowStaleOnFetchRejection;
  489. /**
  490. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  491. */
  492. ignoreFetchAbort;
  493. // computed properties
  494. #size;
  495. #calculatedSize;
  496. #keyMap;
  497. #keyList;
  498. #valList;
  499. #next;
  500. #prev;
  501. #head;
  502. #tail;
  503. #free;
  504. #disposed;
  505. #sizes;
  506. #starts;
  507. #ttls;
  508. #hasDispose;
  509. #hasFetchMethod;
  510. #hasDisposeAfter;
  511. /**
  512. * Do not call this method unless you need to inspect the
  513. * inner workings of the cache. If anything returned by this
  514. * object is modified in any way, strange breakage may occur.
  515. *
  516. * These fields are private for a reason!
  517. *
  518. * @internal
  519. */
  520. static unsafeExposeInternals(c) {
  521. return {
  522. // properties
  523. starts: c.#starts,
  524. ttls: c.#ttls,
  525. sizes: c.#sizes,
  526. keyMap: c.#keyMap,
  527. keyList: c.#keyList,
  528. valList: c.#valList,
  529. next: c.#next,
  530. prev: c.#prev,
  531. get head() {
  532. return c.#head;
  533. },
  534. get tail() {
  535. return c.#tail;
  536. },
  537. free: c.#free,
  538. // methods
  539. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  540. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  541. moveToTail: (index) => c.#moveToTail(index),
  542. indexes: (options) => c.#indexes(options),
  543. rindexes: (options) => c.#rindexes(options),
  544. isStale: (index) => c.#isStale(index),
  545. };
  546. }
  547. // Protected read-only members
  548. /**
  549. * {@link LRUCache.OptionsBase.max} (read-only)
  550. */
  551. get max() {
  552. return this.#max;
  553. }
  554. /**
  555. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  556. */
  557. get maxSize() {
  558. return this.#maxSize;
  559. }
  560. /**
  561. * The total computed size of items in the cache (read-only)
  562. */
  563. get calculatedSize() {
  564. return this.#calculatedSize;
  565. }
  566. /**
  567. * The number of items stored in the cache (read-only)
  568. */
  569. get size() {
  570. return this.#size;
  571. }
  572. /**
  573. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  574. */
  575. get fetchMethod() {
  576. return this.#fetchMethod;
  577. }
  578. /**
  579. * {@link LRUCache.OptionsBase.dispose} (read-only)
  580. */
  581. get dispose() {
  582. return this.#dispose;
  583. }
  584. /**
  585. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  586. */
  587. get disposeAfter() {
  588. return this.#disposeAfter;
  589. }
  590. constructor(options) {
  591. const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
  592. if (max !== 0 && !isPosInt(max)) {
  593. throw new TypeError('max option must be a nonnegative integer');
  594. }
  595. const UintArray = max ? getUintArray(max) : Array;
  596. if (!UintArray) {
  597. throw new Error('invalid max value: ' + max);
  598. }
  599. this.#max = max;
  600. this.#maxSize = maxSize;
  601. this.maxEntrySize = maxEntrySize || this.#maxSize;
  602. this.sizeCalculation = sizeCalculation;
  603. if (this.sizeCalculation) {
  604. if (!this.#maxSize && !this.maxEntrySize) {
  605. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  606. }
  607. if (typeof this.sizeCalculation !== 'function') {
  608. throw new TypeError('sizeCalculation set to non-function');
  609. }
  610. }
  611. if (fetchMethod !== undefined &&
  612. typeof fetchMethod !== 'function') {
  613. throw new TypeError('fetchMethod must be a function if specified');
  614. }
  615. this.#fetchMethod = fetchMethod;
  616. this.#hasFetchMethod = !!fetchMethod;
  617. this.#keyMap = new Map();
  618. this.#keyList = new Array(max).fill(undefined);
  619. this.#valList = new Array(max).fill(undefined);
  620. this.#next = new UintArray(max);
  621. this.#prev = new UintArray(max);
  622. this.#head = 0;
  623. this.#tail = 0;
  624. this.#free = Stack.create(max);
  625. this.#size = 0;
  626. this.#calculatedSize = 0;
  627. if (typeof dispose === 'function') {
  628. this.#dispose = dispose;
  629. }
  630. if (typeof disposeAfter === 'function') {
  631. this.#disposeAfter = disposeAfter;
  632. this.#disposed = [];
  633. }
  634. else {
  635. this.#disposeAfter = undefined;
  636. this.#disposed = undefined;
  637. }
  638. this.#hasDispose = !!this.#dispose;
  639. this.#hasDisposeAfter = !!this.#disposeAfter;
  640. this.noDisposeOnSet = !!noDisposeOnSet;
  641. this.noUpdateTTL = !!noUpdateTTL;
  642. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  643. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  644. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  645. this.ignoreFetchAbort = !!ignoreFetchAbort;
  646. // NB: maxEntrySize is set to maxSize if it's set
  647. if (this.maxEntrySize !== 0) {
  648. if (this.#maxSize !== 0) {
  649. if (!isPosInt(this.#maxSize)) {
  650. throw new TypeError('maxSize must be a positive integer if specified');
  651. }
  652. }
  653. if (!isPosInt(this.maxEntrySize)) {
  654. throw new TypeError('maxEntrySize must be a positive integer if specified');
  655. }
  656. this.#initializeSizeTracking();
  657. }
  658. this.allowStale = !!allowStale;
  659. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  660. this.updateAgeOnGet = !!updateAgeOnGet;
  661. this.updateAgeOnHas = !!updateAgeOnHas;
  662. this.ttlResolution =
  663. isPosInt(ttlResolution) || ttlResolution === 0
  664. ? ttlResolution
  665. : 1;
  666. this.ttlAutopurge = !!ttlAutopurge;
  667. this.ttl = ttl || 0;
  668. if (this.ttl) {
  669. if (!isPosInt(this.ttl)) {
  670. throw new TypeError('ttl must be a positive integer if specified');
  671. }
  672. this.#initializeTTLTracking();
  673. }
  674. // do not allow completely unbounded caches
  675. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  676. throw new TypeError('At least one of max, maxSize, or ttl is required');
  677. }
  678. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  679. const code = 'LRU_CACHE_UNBOUNDED';
  680. if (shouldWarn(code)) {
  681. warned.add(code);
  682. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  683. 'result in unbounded memory consumption.';
  684. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  685. }
  686. }
  687. }
  688. /**
  689. * Return the remaining TTL time for a given entry key
  690. */
  691. getRemainingTTL(key) {
  692. return this.#keyMap.has(key) ? Infinity : 0;
  693. }
  694. #initializeTTLTracking() {
  695. const ttls = new ZeroArray(this.#max);
  696. const starts = new ZeroArray(this.#max);
  697. this.#ttls = ttls;
  698. this.#starts = starts;
  699. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  700. starts[index] = ttl !== 0 ? start : 0;
  701. ttls[index] = ttl;
  702. if (ttl !== 0 && this.ttlAutopurge) {
  703. const t = setTimeout(() => {
  704. if (this.#isStale(index)) {
  705. this.delete(this.#keyList[index]);
  706. }
  707. }, ttl + 1);
  708. // unref() not supported on all platforms
  709. /* c8 ignore start */
  710. if (t.unref) {
  711. t.unref();
  712. }
  713. /* c8 ignore stop */
  714. }
  715. };
  716. this.#updateItemAge = index => {
  717. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  718. };
  719. this.#statusTTL = (status, index) => {
  720. if (ttls[index]) {
  721. const ttl = ttls[index];
  722. const start = starts[index];
  723. /* c8 ignore next */
  724. if (!ttl || !start)
  725. return;
  726. status.ttl = ttl;
  727. status.start = start;
  728. status.now = cachedNow || getNow();
  729. const age = status.now - start;
  730. status.remainingTTL = ttl - age;
  731. }
  732. };
  733. // debounce calls to perf.now() to 1s so we're not hitting
  734. // that costly call repeatedly.
  735. let cachedNow = 0;
  736. const getNow = () => {
  737. const n = perf.now();
  738. if (this.ttlResolution > 0) {
  739. cachedNow = n;
  740. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  741. // not available on all platforms
  742. /* c8 ignore start */
  743. if (t.unref) {
  744. t.unref();
  745. }
  746. /* c8 ignore stop */
  747. }
  748. return n;
  749. };
  750. this.getRemainingTTL = key => {
  751. const index = this.#keyMap.get(key);
  752. if (index === undefined) {
  753. return 0;
  754. }
  755. const ttl = ttls[index];
  756. const start = starts[index];
  757. if (!ttl || !start) {
  758. return Infinity;
  759. }
  760. const age = (cachedNow || getNow()) - start;
  761. return ttl - age;
  762. };
  763. this.#isStale = index => {
  764. const s = starts[index];
  765. const t = ttls[index];
  766. return !!t && !!s && (cachedNow || getNow()) - s > t;
  767. };
  768. }
  769. // conditionally set private methods related to TTL
  770. #updateItemAge = () => { };
  771. #statusTTL = () => { };
  772. #setItemTTL = () => { };
  773. /* c8 ignore stop */
  774. #isStale = () => false;
  775. #initializeSizeTracking() {
  776. const sizes = new ZeroArray(this.#max);
  777. this.#calculatedSize = 0;
  778. this.#sizes = sizes;
  779. this.#removeItemSize = index => {
  780. this.#calculatedSize -= sizes[index];
  781. sizes[index] = 0;
  782. };
  783. this.#requireSize = (k, v, size, sizeCalculation) => {
  784. // provisionally accept background fetches.
  785. // actual value size will be checked when they return.
  786. if (this.#isBackgroundFetch(v)) {
  787. return 0;
  788. }
  789. if (!isPosInt(size)) {
  790. if (sizeCalculation) {
  791. if (typeof sizeCalculation !== 'function') {
  792. throw new TypeError('sizeCalculation must be a function');
  793. }
  794. size = sizeCalculation(v, k);
  795. if (!isPosInt(size)) {
  796. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  797. }
  798. }
  799. else {
  800. throw new TypeError('invalid size value (must be positive integer). ' +
  801. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  802. 'or size must be set.');
  803. }
  804. }
  805. return size;
  806. };
  807. this.#addItemSize = (index, size, status) => {
  808. sizes[index] = size;
  809. if (this.#maxSize) {
  810. const maxSize = this.#maxSize - sizes[index];
  811. while (this.#calculatedSize > maxSize) {
  812. this.#evict(true);
  813. }
  814. }
  815. this.#calculatedSize += sizes[index];
  816. if (status) {
  817. status.entrySize = size;
  818. status.totalCalculatedSize = this.#calculatedSize;
  819. }
  820. };
  821. }
  822. #removeItemSize = _i => { };
  823. #addItemSize = (_i, _s, _st) => { };
  824. #requireSize = (_k, _v, size, sizeCalculation) => {
  825. if (size || sizeCalculation) {
  826. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  827. }
  828. return 0;
  829. };
  830. *#indexes({ allowStale = this.allowStale } = {}) {
  831. if (this.#size) {
  832. for (let i = this.#tail; true;) {
  833. if (!this.#isValidIndex(i)) {
  834. break;
  835. }
  836. if (allowStale || !this.#isStale(i)) {
  837. yield i;
  838. }
  839. if (i === this.#head) {
  840. break;
  841. }
  842. else {
  843. i = this.#prev[i];
  844. }
  845. }
  846. }
  847. }
  848. *#rindexes({ allowStale = this.allowStale } = {}) {
  849. if (this.#size) {
  850. for (let i = this.#head; true;) {
  851. if (!this.#isValidIndex(i)) {
  852. break;
  853. }
  854. if (allowStale || !this.#isStale(i)) {
  855. yield i;
  856. }
  857. if (i === this.#tail) {
  858. break;
  859. }
  860. else {
  861. i = this.#next[i];
  862. }
  863. }
  864. }
  865. }
  866. #isValidIndex(index) {
  867. return (index !== undefined &&
  868. this.#keyMap.get(this.#keyList[index]) === index);
  869. }
  870. /**
  871. * Return a generator yielding `[key, value]` pairs,
  872. * in order from most recently used to least recently used.
  873. */
  874. *entries() {
  875. for (const i of this.#indexes()) {
  876. if (this.#valList[i] !== undefined &&
  877. this.#keyList[i] !== undefined &&
  878. !this.#isBackgroundFetch(this.#valList[i])) {
  879. yield [this.#keyList[i], this.#valList[i]];
  880. }
  881. }
  882. }
  883. /**
  884. * Inverse order version of {@link LRUCache.entries}
  885. *
  886. * Return a generator yielding `[key, value]` pairs,
  887. * in order from least recently used to most recently used.
  888. */
  889. *rentries() {
  890. for (const i of this.#rindexes()) {
  891. if (this.#valList[i] !== undefined &&
  892. this.#keyList[i] !== undefined &&
  893. !this.#isBackgroundFetch(this.#valList[i])) {
  894. yield [this.#keyList[i], this.#valList[i]];
  895. }
  896. }
  897. }
  898. /**
  899. * Return a generator yielding the keys in the cache,
  900. * in order from most recently used to least recently used.
  901. */
  902. *keys() {
  903. for (const i of this.#indexes()) {
  904. const k = this.#keyList[i];
  905. if (k !== undefined &&
  906. !this.#isBackgroundFetch(this.#valList[i])) {
  907. yield k;
  908. }
  909. }
  910. }
  911. /**
  912. * Inverse order version of {@link LRUCache.keys}
  913. *
  914. * Return a generator yielding the keys in the cache,
  915. * in order from least recently used to most recently used.
  916. */
  917. *rkeys() {
  918. for (const i of this.#rindexes()) {
  919. const k = this.#keyList[i];
  920. if (k !== undefined &&
  921. !this.#isBackgroundFetch(this.#valList[i])) {
  922. yield k;
  923. }
  924. }
  925. }
  926. /**
  927. * Return a generator yielding the values in the cache,
  928. * in order from most recently used to least recently used.
  929. */
  930. *values() {
  931. for (const i of this.#indexes()) {
  932. const v = this.#valList[i];
  933. if (v !== undefined &&
  934. !this.#isBackgroundFetch(this.#valList[i])) {
  935. yield this.#valList[i];
  936. }
  937. }
  938. }
  939. /**
  940. * Inverse order version of {@link LRUCache.values}
  941. *
  942. * Return a generator yielding the values in the cache,
  943. * in order from least recently used to most recently used.
  944. */
  945. *rvalues() {
  946. for (const i of this.#rindexes()) {
  947. const v = this.#valList[i];
  948. if (v !== undefined &&
  949. !this.#isBackgroundFetch(this.#valList[i])) {
  950. yield this.#valList[i];
  951. }
  952. }
  953. }
  954. /**
  955. * Iterating over the cache itself yields the same results as
  956. * {@link LRUCache.entries}
  957. */
  958. [Symbol.iterator]() {
  959. return this.entries();
  960. }
  961. /**
  962. * Find a value for which the supplied fn method returns a truthy value,
  963. * similar to Array.find(). fn is called as fn(value, key, cache).
  964. */
  965. find(fn, getOptions = {}) {
  966. for (const i of this.#indexes()) {
  967. const v = this.#valList[i];
  968. const value = this.#isBackgroundFetch(v)
  969. ? v.__staleWhileFetching
  970. : v;
  971. if (value === undefined)
  972. continue;
  973. if (fn(value, this.#keyList[i], this)) {
  974. return this.get(this.#keyList[i], getOptions);
  975. }
  976. }
  977. }
  978. /**
  979. * Call the supplied function on each item in the cache, in order from
  980. * most recently used to least recently used. fn is called as
  981. * fn(value, key, cache). Does not update age or recenty of use.
  982. * Does not iterate over stale values.
  983. */
  984. forEach(fn, thisp = this) {
  985. for (const i of this.#indexes()) {
  986. const v = this.#valList[i];
  987. const value = this.#isBackgroundFetch(v)
  988. ? v.__staleWhileFetching
  989. : v;
  990. if (value === undefined)
  991. continue;
  992. fn.call(thisp, value, this.#keyList[i], this);
  993. }
  994. }
  995. /**
  996. * The same as {@link LRUCache.forEach} but items are iterated over in
  997. * reverse order. (ie, less recently used items are iterated over first.)
  998. */
  999. rforEach(fn, thisp = this) {
  1000. for (const i of this.#rindexes()) {
  1001. const v = this.#valList[i];
  1002. const value = this.#isBackgroundFetch(v)
  1003. ? v.__staleWhileFetching
  1004. : v;
  1005. if (value === undefined)
  1006. continue;
  1007. fn.call(thisp, value, this.#keyList[i], this);
  1008. }
  1009. }
  1010. /**
  1011. * Delete any stale entries. Returns true if anything was removed,
  1012. * false otherwise.
  1013. */
  1014. purgeStale() {
  1015. let deleted = false;
  1016. for (const i of this.#rindexes({ allowStale: true })) {
  1017. if (this.#isStale(i)) {
  1018. this.delete(this.#keyList[i]);
  1019. deleted = true;
  1020. }
  1021. }
  1022. return deleted;
  1023. }
  1024. /**
  1025. * Get the extended info about a given entry, to get its value, size, and
  1026. * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
  1027. * single key. Always returns stale values, if their info is found in the
  1028. * cache, so be sure to check for expired TTLs if relevant.
  1029. */
  1030. info(key) {
  1031. const i = this.#keyMap.get(key);
  1032. if (i === undefined)
  1033. return undefined;
  1034. const v = this.#valList[i];
  1035. const value = this.#isBackgroundFetch(v)
  1036. ? v.__staleWhileFetching
  1037. : v;
  1038. if (value === undefined)
  1039. return undefined;
  1040. const entry = { value };
  1041. if (this.#ttls && this.#starts) {
  1042. const ttl = this.#ttls[i];
  1043. const start = this.#starts[i];
  1044. if (ttl && start) {
  1045. const remain = ttl - (perf.now() - start);
  1046. entry.ttl = remain;
  1047. entry.start = Date.now();
  1048. }
  1049. }
  1050. if (this.#sizes) {
  1051. entry.size = this.#sizes[i];
  1052. }
  1053. return entry;
  1054. }
  1055. /**
  1056. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1057. * passed to cache.load()
  1058. */
  1059. dump() {
  1060. const arr = [];
  1061. for (const i of this.#indexes({ allowStale: true })) {
  1062. const key = this.#keyList[i];
  1063. const v = this.#valList[i];
  1064. const value = this.#isBackgroundFetch(v)
  1065. ? v.__staleWhileFetching
  1066. : v;
  1067. if (value === undefined || key === undefined)
  1068. continue;
  1069. const entry = { value };
  1070. if (this.#ttls && this.#starts) {
  1071. entry.ttl = this.#ttls[i];
  1072. // always dump the start relative to a portable timestamp
  1073. // it's ok for this to be a bit slow, it's a rare operation.
  1074. const age = perf.now() - this.#starts[i];
  1075. entry.start = Math.floor(Date.now() - age);
  1076. }
  1077. if (this.#sizes) {
  1078. entry.size = this.#sizes[i];
  1079. }
  1080. arr.unshift([key, entry]);
  1081. }
  1082. return arr;
  1083. }
  1084. /**
  1085. * Reset the cache and load in the items in entries in the order listed.
  1086. * Note that the shape of the resulting cache may be different if the
  1087. * same options are not used in both caches.
  1088. */
  1089. load(arr) {
  1090. this.clear();
  1091. for (const [key, entry] of arr) {
  1092. if (entry.start) {
  1093. // entry.start is a portable timestamp, but we may be using
  1094. // node's performance.now(), so calculate the offset, so that
  1095. // we get the intended remaining TTL, no matter how long it's
  1096. // been on ice.
  1097. //
  1098. // it's ok for this to be a bit slow, it's a rare operation.
  1099. const age = Date.now() - entry.start;
  1100. entry.start = perf.now() - age;
  1101. }
  1102. this.set(key, entry.value, entry);
  1103. }
  1104. }
  1105. /**
  1106. * Add a value to the cache.
  1107. *
  1108. * Note: if `undefined` is specified as a value, this is an alias for
  1109. * {@link LRUCache#delete}
  1110. */
  1111. set(k, v, setOptions = {}) {
  1112. if (v === undefined) {
  1113. this.delete(k);
  1114. return this;
  1115. }
  1116. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  1117. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  1118. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  1119. // if the item doesn't fit, don't do anything
  1120. // NB: maxEntrySize set to maxSize by default
  1121. if (this.maxEntrySize && size > this.maxEntrySize) {
  1122. if (status) {
  1123. status.set = 'miss';
  1124. status.maxEntrySizeExceeded = true;
  1125. }
  1126. // have to delete, in case something is there already.
  1127. this.delete(k);
  1128. return this;
  1129. }
  1130. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  1131. if (index === undefined) {
  1132. // addition
  1133. index = (this.#size === 0
  1134. ? this.#tail
  1135. : this.#free.length !== 0
  1136. ? this.#free.pop()
  1137. : this.#size === this.#max
  1138. ? this.#evict(false)
  1139. : this.#size);
  1140. this.#keyList[index] = k;
  1141. this.#valList[index] = v;
  1142. this.#keyMap.set(k, index);
  1143. this.#next[this.#tail] = index;
  1144. this.#prev[index] = this.#tail;
  1145. this.#tail = index;
  1146. this.#size++;
  1147. this.#addItemSize(index, size, status);
  1148. if (status)
  1149. status.set = 'add';
  1150. noUpdateTTL = false;
  1151. }
  1152. else {
  1153. // update
  1154. this.#moveToTail(index);
  1155. const oldVal = this.#valList[index];
  1156. if (v !== oldVal) {
  1157. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  1158. oldVal.__abortController.abort(new Error('replaced'));
  1159. const { __staleWhileFetching: s } = oldVal;
  1160. if (s !== undefined && !noDisposeOnSet) {
  1161. if (this.#hasDispose) {
  1162. this.#dispose?.(s, k, 'set');
  1163. }
  1164. if (this.#hasDisposeAfter) {
  1165. this.#disposed?.push([s, k, 'set']);
  1166. }
  1167. }
  1168. }
  1169. else if (!noDisposeOnSet) {
  1170. if (this.#hasDispose) {
  1171. this.#dispose?.(oldVal, k, 'set');
  1172. }
  1173. if (this.#hasDisposeAfter) {
  1174. this.#disposed?.push([oldVal, k, 'set']);
  1175. }
  1176. }
  1177. this.#removeItemSize(index);
  1178. this.#addItemSize(index, size, status);
  1179. this.#valList[index] = v;
  1180. if (status) {
  1181. status.set = 'replace';
  1182. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  1183. ? oldVal.__staleWhileFetching
  1184. : oldVal;
  1185. if (oldValue !== undefined)
  1186. status.oldValue = oldValue;
  1187. }
  1188. }
  1189. else if (status) {
  1190. status.set = 'update';
  1191. }
  1192. }
  1193. if (ttl !== 0 && !this.#ttls) {
  1194. this.#initializeTTLTracking();
  1195. }
  1196. if (this.#ttls) {
  1197. if (!noUpdateTTL) {
  1198. this.#setItemTTL(index, ttl, start);
  1199. }
  1200. if (status)
  1201. this.#statusTTL(status, index);
  1202. }
  1203. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  1204. const dt = this.#disposed;
  1205. let task;
  1206. while ((task = dt?.shift())) {
  1207. this.#disposeAfter?.(...task);
  1208. }
  1209. }
  1210. return this;
  1211. }
  1212. /**
  1213. * Evict the least recently used item, returning its value or
  1214. * `undefined` if cache is empty.
  1215. */
  1216. pop() {
  1217. try {
  1218. while (this.#size) {
  1219. const val = this.#valList[this.#head];
  1220. this.#evict(true);
  1221. if (this.#isBackgroundFetch(val)) {
  1222. if (val.__staleWhileFetching) {
  1223. return val.__staleWhileFetching;
  1224. }
  1225. }
  1226. else if (val !== undefined) {
  1227. return val;
  1228. }
  1229. }
  1230. }
  1231. finally {
  1232. if (this.#hasDisposeAfter && this.#disposed) {
  1233. const dt = this.#disposed;
  1234. let task;
  1235. while ((task = dt?.shift())) {
  1236. this.#disposeAfter?.(...task);
  1237. }
  1238. }
  1239. }
  1240. }
  1241. #evict(free) {
  1242. const head = this.#head;
  1243. const k = this.#keyList[head];
  1244. const v = this.#valList[head];
  1245. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  1246. v.__abortController.abort(new Error('evicted'));
  1247. }
  1248. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1249. if (this.#hasDispose) {
  1250. this.#dispose?.(v, k, 'evict');
  1251. }
  1252. if (this.#hasDisposeAfter) {
  1253. this.#disposed?.push([v, k, 'evict']);
  1254. }
  1255. }
  1256. this.#removeItemSize(head);
  1257. // if we aren't about to use the index, then null these out
  1258. if (free) {
  1259. this.#keyList[head] = undefined;
  1260. this.#valList[head] = undefined;
  1261. this.#free.push(head);
  1262. }
  1263. if (this.#size === 1) {
  1264. this.#head = this.#tail = 0;
  1265. this.#free.length = 0;
  1266. }
  1267. else {
  1268. this.#head = this.#next[head];
  1269. }
  1270. this.#keyMap.delete(k);
  1271. this.#size--;
  1272. return head;
  1273. }
  1274. /**
  1275. * Check if a key is in the cache, without updating the recency of use.
  1276. * Will return false if the item is stale, even though it is technically
  1277. * in the cache.
  1278. *
  1279. * Will not update item age unless
  1280. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1281. */
  1282. has(k, hasOptions = {}) {
  1283. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  1284. const index = this.#keyMap.get(k);
  1285. if (index !== undefined) {
  1286. const v = this.#valList[index];
  1287. if (this.#isBackgroundFetch(v) &&
  1288. v.__staleWhileFetching === undefined) {
  1289. return false;
  1290. }
  1291. if (!this.#isStale(index)) {
  1292. if (updateAgeOnHas) {
  1293. this.#updateItemAge(index);
  1294. }
  1295. if (status) {
  1296. status.has = 'hit';
  1297. this.#statusTTL(status, index);
  1298. }
  1299. return true;
  1300. }
  1301. else if (status) {
  1302. status.has = 'stale';
  1303. this.#statusTTL(status, index);
  1304. }
  1305. }
  1306. else if (status) {
  1307. status.has = 'miss';
  1308. }
  1309. return false;
  1310. }
  1311. /**
  1312. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1313. * items.
  1314. *
  1315. * Returns `undefined` if the item is stale, unless
  1316. * {@link LRUCache.OptionsBase.allowStale} is set.
  1317. */
  1318. peek(k, peekOptions = {}) {
  1319. const { allowStale = this.allowStale } = peekOptions;
  1320. const index = this.#keyMap.get(k);
  1321. if (index === undefined ||
  1322. (!allowStale && this.#isStale(index))) {
  1323. return;
  1324. }
  1325. const v = this.#valList[index];
  1326. // either stale and allowed, or forcing a refresh of non-stale value
  1327. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  1328. }
  1329. #backgroundFetch(k, index, options, context) {
  1330. const v = index === undefined ? undefined : this.#valList[index];
  1331. if (this.#isBackgroundFetch(v)) {
  1332. return v;
  1333. }
  1334. const ac = new AC();
  1335. const { signal } = options;
  1336. // when/if our AC signals, then stop listening to theirs.
  1337. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  1338. signal: ac.signal,
  1339. });
  1340. const fetchOpts = {
  1341. signal: ac.signal,
  1342. options,
  1343. context,
  1344. };
  1345. const cb = (v, updateCache = false) => {
  1346. const { aborted } = ac.signal;
  1347. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  1348. if (options.status) {
  1349. if (aborted && !updateCache) {
  1350. options.status.fetchAborted = true;
  1351. options.status.fetchError = ac.signal.reason;
  1352. if (ignoreAbort)
  1353. options.status.fetchAbortIgnored = true;
  1354. }
  1355. else {
  1356. options.status.fetchResolved = true;
  1357. }
  1358. }
  1359. if (aborted && !ignoreAbort && !updateCache) {
  1360. return fetchFail(ac.signal.reason);
  1361. }
  1362. // either we didn't abort, and are still here, or we did, and ignored
  1363. const bf = p;
  1364. if (this.#valList[index] === p) {
  1365. if (v === undefined) {
  1366. if (bf.__staleWhileFetching) {
  1367. this.#valList[index] = bf.__staleWhileFetching;
  1368. }
  1369. else {
  1370. this.delete(k);
  1371. }
  1372. }
  1373. else {
  1374. if (options.status)
  1375. options.status.fetchUpdated = true;
  1376. this.set(k, v, fetchOpts.options);
  1377. }
  1378. }
  1379. return v;
  1380. };
  1381. const eb = (er) => {
  1382. if (options.status) {
  1383. options.status.fetchRejected = true;
  1384. options.status.fetchError = er;
  1385. }
  1386. return fetchFail(er);
  1387. };
  1388. const fetchFail = (er) => {
  1389. const { aborted } = ac.signal;
  1390. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1391. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1392. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1393. const bf = p;
  1394. if (this.#valList[index] === p) {
  1395. // if we allow stale on fetch rejections, then we need to ensure that
  1396. // the stale value is not removed from the cache when the fetch fails.
  1397. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1398. if (del) {
  1399. this.delete(k);
  1400. }
  1401. else if (!allowStaleAborted) {
  1402. // still replace the *promise* with the stale value,
  1403. // since we are done with the promise at this point.
  1404. // leave it untouched if we're still waiting for an
  1405. // aborted background fetch that hasn't yet returned.
  1406. this.#valList[index] = bf.__staleWhileFetching;
  1407. }
  1408. }
  1409. if (allowStale) {
  1410. if (options.status && bf.__staleWhileFetching !== undefined) {
  1411. options.status.returnedStale = true;
  1412. }
  1413. return bf.__staleWhileFetching;
  1414. }
  1415. else if (bf.__returned === bf) {
  1416. throw er;
  1417. }
  1418. };
  1419. const pcall = (res, rej) => {
  1420. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1421. if (fmp && fmp instanceof Promise) {
  1422. fmp.then(v => res(v === undefined ? undefined : v), rej);
  1423. }
  1424. // ignored, we go until we finish, regardless.
  1425. // defer check until we are actually aborting,
  1426. // so fetchMethod can override.
  1427. ac.signal.addEventListener('abort', () => {
  1428. if (!options.ignoreFetchAbort ||
  1429. options.allowStaleOnFetchAbort) {
  1430. res(undefined);
  1431. // when it eventually resolves, update the cache.
  1432. if (options.allowStaleOnFetchAbort) {
  1433. res = v => cb(v, true);
  1434. }
  1435. }
  1436. });
  1437. };
  1438. if (options.status)
  1439. options.status.fetchDispatched = true;
  1440. const p = new Promise(pcall).then(cb, eb);
  1441. const bf = Object.assign(p, {
  1442. __abortController: ac,
  1443. __staleWhileFetching: v,
  1444. __returned: undefined,
  1445. });
  1446. if (index === undefined) {
  1447. // internal, don't expose status.
  1448. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1449. index = this.#keyMap.get(k);
  1450. }
  1451. else {
  1452. this.#valList[index] = bf;
  1453. }
  1454. return bf;
  1455. }
  1456. #isBackgroundFetch(p) {
  1457. if (!this.#hasFetchMethod)
  1458. return false;
  1459. const b = p;
  1460. return (!!b &&
  1461. b instanceof Promise &&
  1462. b.hasOwnProperty('__staleWhileFetching') &&
  1463. b.__abortController instanceof AC);
  1464. }
  1465. async fetch(k, fetchOptions = {}) {
  1466. const {
  1467. // get options
  1468. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1469. // set options
  1470. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1471. // fetch exclusive options
  1472. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1473. if (!this.#hasFetchMethod) {
  1474. if (status)
  1475. status.fetch = 'get';
  1476. return this.get(k, {
  1477. allowStale,
  1478. updateAgeOnGet,
  1479. noDeleteOnStaleGet,
  1480. status,
  1481. });
  1482. }
  1483. const options = {
  1484. allowStale,
  1485. updateAgeOnGet,
  1486. noDeleteOnStaleGet,
  1487. ttl,
  1488. noDisposeOnSet,
  1489. size,
  1490. sizeCalculation,
  1491. noUpdateTTL,
  1492. noDeleteOnFetchRejection,
  1493. allowStaleOnFetchRejection,
  1494. allowStaleOnFetchAbort,
  1495. ignoreFetchAbort,
  1496. status,
  1497. signal,
  1498. };
  1499. let index = this.#keyMap.get(k);
  1500. if (index === undefined) {
  1501. if (status)
  1502. status.fetch = 'miss';
  1503. const p = this.#backgroundFetch(k, index, options, context);
  1504. return (p.__returned = p);
  1505. }
  1506. else {
  1507. // in cache, maybe already fetching
  1508. const v = this.#valList[index];
  1509. if (this.#isBackgroundFetch(v)) {
  1510. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1511. if (status) {
  1512. status.fetch = 'inflight';
  1513. if (stale)
  1514. status.returnedStale = true;
  1515. }
  1516. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1517. }
  1518. // if we force a refresh, that means do NOT serve the cached value,
  1519. // unless we are already in the process of refreshing the cache.
  1520. const isStale = this.#isStale(index);
  1521. if (!forceRefresh && !isStale) {
  1522. if (status)
  1523. status.fetch = 'hit';
  1524. this.#moveToTail(index);
  1525. if (updateAgeOnGet) {
  1526. this.#updateItemAge(index);
  1527. }
  1528. if (status)
  1529. this.#statusTTL(status, index);
  1530. return v;
  1531. }
  1532. // ok, it is stale or a forced refresh, and not already fetching.
  1533. // refresh the cache.
  1534. const p = this.#backgroundFetch(k, index, options, context);
  1535. const hasStale = p.__staleWhileFetching !== undefined;
  1536. const staleVal = hasStale && allowStale;
  1537. if (status) {
  1538. status.fetch = isStale ? 'stale' : 'refresh';
  1539. if (staleVal && isStale)
  1540. status.returnedStale = true;
  1541. }
  1542. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1543. }
  1544. }
  1545. /**
  1546. * Return a value from the cache. Will update the recency of the cache
  1547. * entry found.
  1548. *
  1549. * If the key is not found, get() will return `undefined`.
  1550. */
  1551. get(k, getOptions = {}) {
  1552. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1553. const index = this.#keyMap.get(k);
  1554. if (index !== undefined) {
  1555. const value = this.#valList[index];
  1556. const fetching = this.#isBackgroundFetch(value);
  1557. if (status)
  1558. this.#statusTTL(status, index);
  1559. if (this.#isStale(index)) {
  1560. if (status)
  1561. status.get = 'stale';
  1562. // delete only if not an in-flight background fetch
  1563. if (!fetching) {
  1564. if (!noDeleteOnStaleGet) {
  1565. this.delete(k);
  1566. }
  1567. if (status && allowStale)
  1568. status.returnedStale = true;
  1569. return allowStale ? value : undefined;
  1570. }
  1571. else {
  1572. if (status &&
  1573. allowStale &&
  1574. value.__staleWhileFetching !== undefined) {
  1575. status.returnedStale = true;
  1576. }
  1577. return allowStale ? value.__staleWhileFetching : undefined;
  1578. }
  1579. }
  1580. else {
  1581. if (status)
  1582. status.get = 'hit';
  1583. // if we're currently fetching it, we don't actually have it yet
  1584. // it's not stale, which means this isn't a staleWhileRefetching.
  1585. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1586. // value, then that means the user fetched with {forceRefresh:true},
  1587. // so it's safe to return that value.
  1588. if (fetching) {
  1589. return value.__staleWhileFetching;
  1590. }
  1591. this.#moveToTail(index);
  1592. if (updateAgeOnGet) {
  1593. this.#updateItemAge(index);
  1594. }
  1595. return value;
  1596. }
  1597. }
  1598. else if (status) {
  1599. status.get = 'miss';
  1600. }
  1601. }
  1602. #connect(p, n) {
  1603. this.#prev[n] = p;
  1604. this.#next[p] = n;
  1605. }
  1606. #moveToTail(index) {
  1607. // if tail already, nothing to do
  1608. // if head, move head to next[index]
  1609. // else
  1610. // move next[prev[index]] to next[index] (head has no prev)
  1611. // move prev[next[index]] to prev[index]
  1612. // prev[index] = tail
  1613. // next[tail] = index
  1614. // tail = index
  1615. if (index !== this.#tail) {
  1616. if (index === this.#head) {
  1617. this.#head = this.#next[index];
  1618. }
  1619. else {
  1620. this.#connect(this.#prev[index], this.#next[index]);
  1621. }
  1622. this.#connect(this.#tail, index);
  1623. this.#tail = index;
  1624. }
  1625. }
  1626. /**
  1627. * Deletes a key out of the cache.
  1628. * Returns true if the key was deleted, false otherwise.
  1629. */
  1630. delete(k) {
  1631. let deleted = false;
  1632. if (this.#size !== 0) {
  1633. const index = this.#keyMap.get(k);
  1634. if (index !== undefined) {
  1635. deleted = true;
  1636. if (this.#size === 1) {
  1637. this.clear();
  1638. }
  1639. else {
  1640. this.#removeItemSize(index);
  1641. const v = this.#valList[index];
  1642. if (this.#isBackgroundFetch(v)) {
  1643. v.__abortController.abort(new Error('deleted'));
  1644. }
  1645. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1646. if (this.#hasDispose) {
  1647. this.#dispose?.(v, k, 'delete');
  1648. }
  1649. if (this.#hasDisposeAfter) {
  1650. this.#disposed?.push([v, k, 'delete']);
  1651. }
  1652. }
  1653. this.#keyMap.delete(k);
  1654. this.#keyList[index] = undefined;
  1655. this.#valList[index] = undefined;
  1656. if (index === this.#tail) {
  1657. this.#tail = this.#prev[index];
  1658. }
  1659. else if (index === this.#head) {
  1660. this.#head = this.#next[index];
  1661. }
  1662. else {
  1663. const pi = this.#prev[index];
  1664. this.#next[pi] = this.#next[index];
  1665. const ni = this.#next[index];
  1666. this.#prev[ni] = this.#prev[index];
  1667. }
  1668. this.#size--;
  1669. this.#free.push(index);
  1670. }
  1671. }
  1672. }
  1673. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1674. const dt = this.#disposed;
  1675. let task;
  1676. while ((task = dt?.shift())) {
  1677. this.#disposeAfter?.(...task);
  1678. }
  1679. }
  1680. return deleted;
  1681. }
  1682. /**
  1683. * Clear the cache entirely, throwing away all values.
  1684. */
  1685. clear() {
  1686. for (const index of this.#rindexes({ allowStale: true })) {
  1687. const v = this.#valList[index];
  1688. if (this.#isBackgroundFetch(v)) {
  1689. v.__abortController.abort(new Error('deleted'));
  1690. }
  1691. else {
  1692. const k = this.#keyList[index];
  1693. if (this.#hasDispose) {
  1694. this.#dispose?.(v, k, 'delete');
  1695. }
  1696. if (this.#hasDisposeAfter) {
  1697. this.#disposed?.push([v, k, 'delete']);
  1698. }
  1699. }
  1700. }
  1701. this.#keyMap.clear();
  1702. this.#valList.fill(undefined);
  1703. this.#keyList.fill(undefined);
  1704. if (this.#ttls && this.#starts) {
  1705. this.#ttls.fill(0);
  1706. this.#starts.fill(0);
  1707. }
  1708. if (this.#sizes) {
  1709. this.#sizes.fill(0);
  1710. }
  1711. this.#head = 0;
  1712. this.#tail = 0;
  1713. this.#free.length = 0;
  1714. this.#calculatedSize = 0;
  1715. this.#size = 0;
  1716. if (this.#hasDisposeAfter && this.#disposed) {
  1717. const dt = this.#disposed;
  1718. let task;
  1719. while ((task = dt?.shift())) {
  1720. this.#disposeAfter?.(...task);
  1721. }
  1722. }
  1723. }
  1724. }
  1725. function createCache(max = 500) {
  1726. return new LRUCache({ max });
  1727. }
  1728. function isImportUsed(local, sfc) {
  1729. return resolveTemplateUsedIdentifiers(sfc).has(local);
  1730. }
  1731. const templateUsageCheckCache = createCache();
  1732. function resolveTemplateUsedIdentifiers(sfc) {
  1733. const { content, ast } = sfc.template;
  1734. const cached = templateUsageCheckCache.get(content);
  1735. if (cached) {
  1736. return cached;
  1737. }
  1738. const ids = /* @__PURE__ */ new Set();
  1739. ast.children.forEach(walk);
  1740. function walk(node) {
  1741. var _a;
  1742. switch (node.type) {
  1743. case 1:
  1744. let tag = node.tag;
  1745. if (tag.includes("."))
  1746. tag = tag.split(".")[0].trim();
  1747. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1748. ids.add(shared.camelize(tag));
  1749. ids.add(shared.capitalize(shared.camelize(tag)));
  1750. }
  1751. for (let i = 0; i < node.props.length; i++) {
  1752. const prop = node.props[i];
  1753. if (prop.type === 7) {
  1754. if (!shared.isBuiltInDirective(prop.name)) {
  1755. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1756. }
  1757. if (prop.arg && !prop.arg.isStatic) {
  1758. extractIdentifiers(ids, prop.arg);
  1759. }
  1760. if (prop.name === "for") {
  1761. extractIdentifiers(ids, prop.forParseResult.source);
  1762. } else if (prop.exp) {
  1763. extractIdentifiers(ids, prop.exp);
  1764. } else if (prop.name === "bind" && !prop.exp) {
  1765. ids.add(prop.arg.content);
  1766. }
  1767. }
  1768. if (prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1769. ids.add(prop.value.content);
  1770. }
  1771. }
  1772. node.children.forEach(walk);
  1773. break;
  1774. case 5:
  1775. extractIdentifiers(ids, node.content);
  1776. break;
  1777. }
  1778. }
  1779. templateUsageCheckCache.set(content, ids);
  1780. return ids;
  1781. }
  1782. function extractIdentifiers(ids, node) {
  1783. if (node.ast) {
  1784. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1785. } else if (node.ast === null) {
  1786. ids.add(node.content);
  1787. }
  1788. }
  1789. const DEFAULT_FILENAME = "anonymous.vue";
  1790. const parseCache$1 = createCache();
  1791. function genCacheKey(source, options) {
  1792. var _a;
  1793. return source + JSON.stringify(
  1794. {
  1795. ...options,
  1796. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1797. },
  1798. (_, val) => typeof val === "function" ? val.toString() : val
  1799. );
  1800. }
  1801. function parse$2(source, options = {}) {
  1802. const sourceKey = genCacheKey(source, options);
  1803. const cache = parseCache$1.get(sourceKey);
  1804. if (cache) {
  1805. return cache;
  1806. }
  1807. const {
  1808. sourceMap = true,
  1809. filename = DEFAULT_FILENAME,
  1810. sourceRoot = "",
  1811. pad = false,
  1812. ignoreEmpty = true,
  1813. compiler = CompilerDOM__namespace,
  1814. templateParseOptions = {},
  1815. parseExpressions = true
  1816. } = options;
  1817. const descriptor = {
  1818. filename,
  1819. source,
  1820. template: null,
  1821. script: null,
  1822. scriptSetup: null,
  1823. styles: [],
  1824. customBlocks: [],
  1825. cssVars: [],
  1826. slotted: false,
  1827. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1828. };
  1829. const errors = [];
  1830. const ast = compiler.parse(source, {
  1831. parseMode: "sfc",
  1832. prefixIdentifiers: parseExpressions,
  1833. ...templateParseOptions,
  1834. onError: (e) => {
  1835. errors.push(e);
  1836. }
  1837. });
  1838. ast.children.forEach((node) => {
  1839. if (node.type !== 1) {
  1840. return;
  1841. }
  1842. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1843. return;
  1844. }
  1845. switch (node.tag) {
  1846. case "template":
  1847. if (!descriptor.template) {
  1848. const templateBlock = descriptor.template = createBlock(
  1849. node,
  1850. source,
  1851. false
  1852. );
  1853. if (!templateBlock.attrs.src) {
  1854. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1855. }
  1856. if (templateBlock.attrs.functional) {
  1857. const err = new SyntaxError(
  1858. `<template functional> is no longer supported in Vue 3, since functional components no longer have significant performance difference from stateful ones. Just use a normal <template> instead.`
  1859. );
  1860. err.loc = node.props.find(
  1861. (p) => p.type === 6 && p.name === "functional"
  1862. ).loc;
  1863. errors.push(err);
  1864. }
  1865. } else {
  1866. errors.push(createDuplicateBlockError(node));
  1867. }
  1868. break;
  1869. case "script":
  1870. const scriptBlock = createBlock(node, source, pad);
  1871. const isSetup = !!scriptBlock.attrs.setup;
  1872. if (isSetup && !descriptor.scriptSetup) {
  1873. descriptor.scriptSetup = scriptBlock;
  1874. break;
  1875. }
  1876. if (!isSetup && !descriptor.script) {
  1877. descriptor.script = scriptBlock;
  1878. break;
  1879. }
  1880. errors.push(createDuplicateBlockError(node, isSetup));
  1881. break;
  1882. case "style":
  1883. const styleBlock = createBlock(node, source, pad);
  1884. if (styleBlock.attrs.vars) {
  1885. errors.push(
  1886. new SyntaxError(
  1887. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1888. )
  1889. );
  1890. }
  1891. descriptor.styles.push(styleBlock);
  1892. break;
  1893. default:
  1894. descriptor.customBlocks.push(createBlock(node, source, pad));
  1895. break;
  1896. }
  1897. });
  1898. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1899. errors.push(
  1900. new SyntaxError(
  1901. `At least one <template> or <script> is required in a single file component.`
  1902. )
  1903. );
  1904. }
  1905. if (descriptor.scriptSetup) {
  1906. if (descriptor.scriptSetup.src) {
  1907. errors.push(
  1908. new SyntaxError(
  1909. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1910. )
  1911. );
  1912. descriptor.scriptSetup = null;
  1913. }
  1914. if (descriptor.script && descriptor.script.src) {
  1915. errors.push(
  1916. new SyntaxError(
  1917. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1918. )
  1919. );
  1920. descriptor.script = null;
  1921. }
  1922. }
  1923. let templateColumnOffset = 0;
  1924. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1925. [descriptor.template.content, templateColumnOffset] = dedent(
  1926. descriptor.template.content
  1927. );
  1928. }
  1929. if (sourceMap) {
  1930. const genMap = (block, columnOffset = 0) => {
  1931. if (block && !block.src) {
  1932. block.map = generateSourceMap(
  1933. filename,
  1934. source,
  1935. block.content,
  1936. sourceRoot,
  1937. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1938. columnOffset
  1939. );
  1940. }
  1941. };
  1942. genMap(descriptor.template, templateColumnOffset);
  1943. genMap(descriptor.script);
  1944. descriptor.styles.forEach((s) => genMap(s));
  1945. descriptor.customBlocks.forEach((s) => genMap(s));
  1946. }
  1947. descriptor.cssVars = parseCssVars(descriptor);
  1948. const slottedRE = /(?:::v-|:)slotted\(/;
  1949. descriptor.slotted = descriptor.styles.some(
  1950. (s) => s.scoped && slottedRE.test(s.content)
  1951. );
  1952. const result = {
  1953. descriptor,
  1954. errors
  1955. };
  1956. parseCache$1.set(sourceKey, result);
  1957. return result;
  1958. }
  1959. function createDuplicateBlockError(node, isScriptSetup = false) {
  1960. const err = new SyntaxError(
  1961. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1962. );
  1963. err.loc = node.loc;
  1964. return err;
  1965. }
  1966. function createBlock(node, source, pad) {
  1967. const type = node.tag;
  1968. const loc = node.innerLoc;
  1969. const attrs = {};
  1970. const block = {
  1971. type,
  1972. content: source.slice(loc.start.offset, loc.end.offset),
  1973. loc,
  1974. attrs
  1975. };
  1976. if (pad) {
  1977. block.content = padContent(source, block, pad) + block.content;
  1978. }
  1979. node.props.forEach((p) => {
  1980. if (p.type === 6) {
  1981. const name = p.name;
  1982. attrs[name] = p.value ? p.value.content || true : true;
  1983. if (name === "lang") {
  1984. block.lang = p.value && p.value.content;
  1985. } else if (name === "src") {
  1986. block.src = p.value && p.value.content;
  1987. } else if (type === "style") {
  1988. if (name === "scoped") {
  1989. block.scoped = true;
  1990. } else if (name === "module") {
  1991. block.module = attrs[name];
  1992. }
  1993. } else if (type === "script" && name === "setup") {
  1994. block.setup = attrs.setup;
  1995. }
  1996. }
  1997. });
  1998. return block;
  1999. }
  2000. const splitRE = /\r?\n/g;
  2001. const emptyRE = /^(?:\/\/)?\s*$/;
  2002. const replaceRE = /./g;
  2003. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  2004. const map = new sourceMapJs.SourceMapGenerator({
  2005. file: filename.replace(/\\/g, "/"),
  2006. sourceRoot: sourceRoot.replace(/\\/g, "/")
  2007. });
  2008. map.setSourceContent(filename, source);
  2009. map._sources.add(filename);
  2010. generated.split(splitRE).forEach((line, index) => {
  2011. if (!emptyRE.test(line)) {
  2012. const originalLine = index + 1 + lineOffset;
  2013. const generatedLine = index + 1;
  2014. for (let i = 0; i < line.length; i++) {
  2015. if (!/\s/.test(line[i])) {
  2016. map._mappings.add({
  2017. originalLine,
  2018. originalColumn: i + columnOffset,
  2019. generatedLine,
  2020. generatedColumn: i,
  2021. source: filename,
  2022. name: null
  2023. });
  2024. }
  2025. }
  2026. }
  2027. });
  2028. return map.toJSON();
  2029. }
  2030. function padContent(content, block, pad) {
  2031. content = content.slice(0, block.loc.start.offset);
  2032. if (pad === "space") {
  2033. return content.replace(replaceRE, " ");
  2034. } else {
  2035. const offset = content.split(splitRE).length;
  2036. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  2037. return Array(offset).join(padChar);
  2038. }
  2039. }
  2040. function hasSrc(node) {
  2041. return node.props.some((p) => {
  2042. if (p.type !== 6) {
  2043. return false;
  2044. }
  2045. return p.name === "src";
  2046. });
  2047. }
  2048. function isEmpty(node) {
  2049. for (let i = 0; i < node.children.length; i++) {
  2050. const child = node.children[i];
  2051. if (child.type !== 2 || child.content.trim() !== "") {
  2052. return false;
  2053. }
  2054. }
  2055. return true;
  2056. }
  2057. function hmrShouldReload(prevImports, next) {
  2058. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  2059. return false;
  2060. }
  2061. for (const key in prevImports) {
  2062. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2063. return true;
  2064. }
  2065. }
  2066. return false;
  2067. }
  2068. function dedent(s) {
  2069. const lines = s.split("\n");
  2070. const minIndent = lines.reduce(function(minIndent2, line) {
  2071. var _a, _b;
  2072. if (line.trim() === "") {
  2073. return minIndent2;
  2074. }
  2075. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2076. return Math.min(indent, minIndent2);
  2077. }, Infinity);
  2078. if (minIndent === 0) {
  2079. return [s, minIndent];
  2080. }
  2081. return [
  2082. lines.map(function(line) {
  2083. return line.slice(minIndent);
  2084. }).join("\n"),
  2085. minIndent
  2086. ];
  2087. }
  2088. function isRelativeUrl(url) {
  2089. const firstChar = url.charAt(0);
  2090. return firstChar === "." || firstChar === "~" || firstChar === "@";
  2091. }
  2092. const externalRE = /^(https?:)?\/\//;
  2093. function isExternalUrl(url) {
  2094. return externalRE.test(url);
  2095. }
  2096. const dataUrlRE = /^\s*data:/i;
  2097. function isDataUrl(url) {
  2098. return dataUrlRE.test(url);
  2099. }
  2100. function parseUrl(url) {
  2101. const firstChar = url.charAt(0);
  2102. if (firstChar === "~") {
  2103. const secondChar = url.charAt(1);
  2104. url = url.slice(secondChar === "/" ? 2 : 1);
  2105. }
  2106. return parseUriParts(url);
  2107. }
  2108. function parseUriParts(urlString) {
  2109. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2110. }
  2111. const defaultAssetUrlOptions = {
  2112. base: null,
  2113. includeAbsolute: false,
  2114. tags: {
  2115. video: ["src", "poster"],
  2116. source: ["src"],
  2117. img: ["src"],
  2118. image: ["xlink:href", "href"],
  2119. use: ["xlink:href", "href"]
  2120. }
  2121. };
  2122. const normalizeOptions = (options) => {
  2123. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2124. return {
  2125. ...defaultAssetUrlOptions,
  2126. tags: options
  2127. };
  2128. }
  2129. return {
  2130. ...defaultAssetUrlOptions,
  2131. ...options
  2132. };
  2133. };
  2134. const createAssetUrlTransformWithOptions = (options) => {
  2135. return (node, context) => transformAssetUrl(node, context, options);
  2136. };
  2137. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2138. if (node.type === 1) {
  2139. if (!node.props.length) {
  2140. return;
  2141. }
  2142. const tags = options.tags || defaultAssetUrlOptions.tags;
  2143. const attrs = tags[node.tag];
  2144. const wildCardAttrs = tags["*"];
  2145. if (!attrs && !wildCardAttrs) {
  2146. return;
  2147. }
  2148. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2149. node.props.forEach((attr, index) => {
  2150. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value || isExternalUrl(attr.value.content) || isDataUrl(attr.value.content) || attr.value.content[0] === "#" || !options.includeAbsolute && !isRelativeUrl(attr.value.content)) {
  2151. return;
  2152. }
  2153. const url = parseUrl(attr.value.content);
  2154. if (options.base && attr.value.content[0] === ".") {
  2155. const base = parseUrl(options.base);
  2156. const protocol = base.protocol || "";
  2157. const host = base.host ? protocol + "//" + base.host : "";
  2158. const basePath = base.path || "/";
  2159. attr.value.content = host + (path$3.posix || path$3).join(basePath, url.path + (url.hash || ""));
  2160. return;
  2161. }
  2162. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2163. node.props[index] = {
  2164. type: 7,
  2165. name: "bind",
  2166. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2167. exp,
  2168. modifiers: [],
  2169. loc: attr.loc
  2170. };
  2171. });
  2172. }
  2173. };
  2174. function getImportsExpressionExp(path2, hash, loc, context) {
  2175. if (path2) {
  2176. let name;
  2177. let exp;
  2178. const existingIndex = context.imports.findIndex((i) => i.path === path2);
  2179. if (existingIndex > -1) {
  2180. name = `_imports_${existingIndex}`;
  2181. exp = context.imports[existingIndex].exp;
  2182. } else {
  2183. name = `_imports_${context.imports.length}`;
  2184. exp = compilerCore.createSimpleExpression(
  2185. name,
  2186. false,
  2187. loc,
  2188. 3
  2189. );
  2190. context.imports.push({
  2191. exp,
  2192. path: decodeURIComponent(path2)
  2193. });
  2194. }
  2195. if (!hash) {
  2196. return exp;
  2197. }
  2198. const hashExp = `${name} + '${hash}'`;
  2199. const finalExp = compilerCore.createSimpleExpression(
  2200. hashExp,
  2201. false,
  2202. loc,
  2203. 3
  2204. );
  2205. if (!context.hoistStatic) {
  2206. return finalExp;
  2207. }
  2208. const existingHoistIndex = context.hoists.findIndex((h) => {
  2209. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2210. });
  2211. if (existingHoistIndex > -1) {
  2212. return compilerCore.createSimpleExpression(
  2213. `_hoisted_${existingHoistIndex + 1}`,
  2214. false,
  2215. loc,
  2216. 3
  2217. );
  2218. }
  2219. return context.hoist(finalExp);
  2220. } else {
  2221. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2222. }
  2223. }
  2224. const srcsetTags = ["img", "source"];
  2225. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2226. const createSrcsetTransformWithOptions = (options) => {
  2227. return (node, context) => transformSrcset(node, context, options);
  2228. };
  2229. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2230. if (node.type === 1) {
  2231. if (srcsetTags.includes(node.tag) && node.props.length) {
  2232. node.props.forEach((attr, index) => {
  2233. if (attr.name === "srcset" && attr.type === 6) {
  2234. if (!attr.value)
  2235. return;
  2236. const value = attr.value.content;
  2237. if (!value)
  2238. return;
  2239. const imageCandidates = value.split(",").map((s) => {
  2240. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2241. return { url, descriptor };
  2242. });
  2243. for (let i = 0; i < imageCandidates.length; i++) {
  2244. const { url } = imageCandidates[i];
  2245. if (isDataUrl(url)) {
  2246. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2247. imageCandidates.splice(i, 1);
  2248. }
  2249. }
  2250. const shouldProcessUrl = (url) => {
  2251. return !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2252. };
  2253. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2254. return;
  2255. }
  2256. if (options.base) {
  2257. const base = options.base;
  2258. const set = [];
  2259. let needImportTransform = false;
  2260. imageCandidates.forEach((candidate) => {
  2261. let { url, descriptor } = candidate;
  2262. descriptor = descriptor ? ` ${descriptor}` : ``;
  2263. if (url[0] === ".") {
  2264. candidate.url = (path$3.posix || path$3).join(base, url);
  2265. set.push(candidate.url + descriptor);
  2266. } else if (shouldProcessUrl(url)) {
  2267. needImportTransform = true;
  2268. } else {
  2269. set.push(url + descriptor);
  2270. }
  2271. });
  2272. if (!needImportTransform) {
  2273. attr.value.content = set.join(", ");
  2274. return;
  2275. }
  2276. }
  2277. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2278. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2279. if (shouldProcessUrl(url)) {
  2280. const { path: path2 } = parseUrl(url);
  2281. let exp2;
  2282. if (path2) {
  2283. const existingImportsIndex = context.imports.findIndex(
  2284. (i) => i.path === path2
  2285. );
  2286. if (existingImportsIndex > -1) {
  2287. exp2 = compilerCore.createSimpleExpression(
  2288. `_imports_${existingImportsIndex}`,
  2289. false,
  2290. attr.loc,
  2291. 3
  2292. );
  2293. } else {
  2294. exp2 = compilerCore.createSimpleExpression(
  2295. `_imports_${context.imports.length}`,
  2296. false,
  2297. attr.loc,
  2298. 3
  2299. );
  2300. context.imports.push({ exp: exp2, path: path2 });
  2301. }
  2302. compoundExpression.children.push(exp2);
  2303. }
  2304. } else {
  2305. const exp2 = compilerCore.createSimpleExpression(
  2306. `"${url}"`,
  2307. false,
  2308. attr.loc,
  2309. 3
  2310. );
  2311. compoundExpression.children.push(exp2);
  2312. }
  2313. const isNotLast = imageCandidates.length - 1 > index2;
  2314. if (descriptor && isNotLast) {
  2315. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2316. } else if (descriptor) {
  2317. compoundExpression.children.push(` + ' ${descriptor}'`);
  2318. } else if (isNotLast) {
  2319. compoundExpression.children.push(` + ', ' + `);
  2320. }
  2321. });
  2322. let exp = compoundExpression;
  2323. if (context.hoistStatic) {
  2324. exp = context.hoist(compoundExpression);
  2325. exp.constType = 3;
  2326. }
  2327. node.props[index] = {
  2328. type: 7,
  2329. name: "bind",
  2330. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2331. exp,
  2332. modifiers: [],
  2333. loc: attr.loc
  2334. };
  2335. }
  2336. });
  2337. }
  2338. }
  2339. };
  2340. function commonjsRequire(path) {
  2341. throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  2342. }
  2343. var consolidate$2 = {exports: {}};
  2344. (function (module, exports) {
  2345. /*
  2346. * Engines which do not support caching of their file contents
  2347. * should use the `read()` function defined in consolidate.js
  2348. * On top of this, when an engine compiles to a `Function`,
  2349. * these functions should either be cached within consolidate.js
  2350. * or the engine itself via `options.cache`. This will allow
  2351. * users and frameworks to pass `options.cache = true` for
  2352. * `NODE_ENV=production`, however edit the file(s) without
  2353. * re-loading the application in development.
  2354. */
  2355. /**
  2356. * Module dependencies.
  2357. */
  2358. var fs = require$$0;
  2359. var path = path$3;
  2360. var util = require$$2;
  2361. var join = path.join;
  2362. var resolve = path.resolve;
  2363. var extname = path.extname;
  2364. var dirname = path.dirname;
  2365. var isAbsolute = path.isAbsolute;
  2366. var readCache = {};
  2367. /**
  2368. * Require cache.
  2369. */
  2370. var cacheStore = {};
  2371. /**
  2372. * Require cache.
  2373. */
  2374. var requires = {};
  2375. /**
  2376. * Clear the cache.
  2377. *
  2378. * @api public
  2379. */
  2380. exports.clearCache = function() {
  2381. readCache = {};
  2382. cacheStore = {};
  2383. };
  2384. /**
  2385. * Conditionally cache `compiled` template based
  2386. * on the `options` filename and `.cache` boolean.
  2387. *
  2388. * @param {Object} options
  2389. * @param {Function} compiled
  2390. * @return {Function}
  2391. * @api private
  2392. */
  2393. function cache(options, compiled) {
  2394. // cachable
  2395. if (compiled && options.filename && options.cache) {
  2396. delete readCache[options.filename];
  2397. cacheStore[options.filename] = compiled;
  2398. return compiled;
  2399. }
  2400. // check cache
  2401. if (options.filename && options.cache) {
  2402. return cacheStore[options.filename];
  2403. }
  2404. return compiled;
  2405. }
  2406. /**
  2407. * Read `path` with `options` with
  2408. * callback `(err, str)`. When `options.cache`
  2409. * is true the template string will be cached.
  2410. *
  2411. * @param {String} options
  2412. * @param {Function} cb
  2413. * @api private
  2414. */
  2415. function read(path, options, cb) {
  2416. var str = readCache[path];
  2417. var cached = options.cache && str && typeof str === 'string';
  2418. // cached (only if cached is a string and not a compiled template function)
  2419. if (cached) return cb(null, str);
  2420. // read
  2421. fs.readFile(path, 'utf8', function(err, str) {
  2422. if (err) return cb(err);
  2423. // remove extraneous utf8 BOM marker
  2424. str = str.replace(/^\uFEFF/, '');
  2425. if (options.cache) readCache[path] = str;
  2426. cb(null, str);
  2427. });
  2428. }
  2429. /**
  2430. * Read `path` with `options` with
  2431. * callback `(err, str)`. When `options.cache`
  2432. * is true the partial string will be cached.
  2433. *
  2434. * @param {String} options
  2435. * @param {Function} fn
  2436. * @api private
  2437. */
  2438. function readPartials(path, options, cb) {
  2439. if (!options.partials) return cb();
  2440. var keys = Object.keys(options.partials);
  2441. var partials = {};
  2442. function next(index) {
  2443. if (index === keys.length) return cb(null, partials);
  2444. var key = keys[index];
  2445. var partialPath = options.partials[key];
  2446. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2447. return next(++index);
  2448. }
  2449. var file;
  2450. if (isAbsolute(partialPath)) {
  2451. if (extname(partialPath) !== '') {
  2452. file = partialPath;
  2453. } else {
  2454. file = join(partialPath + extname(path));
  2455. }
  2456. } else {
  2457. file = join(dirname(path), partialPath + extname(path));
  2458. }
  2459. read(file, options, function(err, str) {
  2460. if (err) return cb(err);
  2461. partials[key] = str;
  2462. next(++index);
  2463. });
  2464. }
  2465. next(0);
  2466. }
  2467. /**
  2468. * promisify
  2469. */
  2470. function promisify(cb, fn) {
  2471. return new Promise(function(resolve, reject) {
  2472. cb = cb || function(err, html) {
  2473. if (err) {
  2474. return reject(err);
  2475. }
  2476. resolve(html);
  2477. };
  2478. fn(cb);
  2479. });
  2480. }
  2481. /**
  2482. * fromStringRenderer
  2483. */
  2484. function fromStringRenderer(name) {
  2485. return function(path, options, cb) {
  2486. options.filename = path;
  2487. return promisify(cb, function(cb) {
  2488. readPartials(path, options, function(err, partials) {
  2489. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2490. var opts = extend({}, options);
  2491. opts.partials = partials;
  2492. if (err) return cb(err);
  2493. if (cache(opts)) {
  2494. exports[name].render('', opts, cb);
  2495. } else {
  2496. read(path, opts, function(err, str) {
  2497. if (err) return cb(err);
  2498. exports[name].render(str, opts, cb);
  2499. });
  2500. }
  2501. });
  2502. });
  2503. };
  2504. }
  2505. /**
  2506. * velocity support.
  2507. */
  2508. exports.velocityjs = fromStringRenderer('velocityjs');
  2509. /**
  2510. * velocity string support.
  2511. */
  2512. exports.velocityjs.render = function(str, options, cb) {
  2513. return promisify(cb, function(cb) {
  2514. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2515. try {
  2516. options.locals = options;
  2517. cb(null, engine.render(str, options).trimLeft());
  2518. } catch (err) {
  2519. cb(err);
  2520. }
  2521. });
  2522. };
  2523. /**
  2524. * Liquid support.
  2525. */
  2526. exports.liquid = fromStringRenderer('liquid');
  2527. /**
  2528. * Liquid string support.
  2529. */
  2530. /**
  2531. * Note that in order to get filters and custom tags we've had to push
  2532. * all user-defined locals down into @locals. However, just to make things
  2533. * backwards-compatible, any property of `options` that is left after
  2534. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2535. * `includeDir` will also become a local.
  2536. */
  2537. function _renderTinyliquid(engine, str, options, cb) {
  2538. var context = engine.newContext();
  2539. var k;
  2540. /**
  2541. * Note that there's a bug in the library that doesn't allow us to pass
  2542. * the locals to newContext(), hence looping through the keys:
  2543. */
  2544. if (options.locals) {
  2545. for (k in options.locals) {
  2546. context.setLocals(k, options.locals[k]);
  2547. }
  2548. delete options.locals;
  2549. }
  2550. if (options.meta) {
  2551. context.setLocals('page', options.meta);
  2552. delete options.meta;
  2553. }
  2554. /**
  2555. * Add any defined filters:
  2556. */
  2557. if (options.filters) {
  2558. for (k in options.filters) {
  2559. context.setFilter(k, options.filters[k]);
  2560. }
  2561. delete options.filters;
  2562. }
  2563. /**
  2564. * Set up a callback for the include directory:
  2565. */
  2566. var includeDir = options.includeDir || process.cwd();
  2567. context.onInclude(function(name, callback) {
  2568. var extname = path.extname(name) ? '' : '.liquid';
  2569. var filename = path.resolve(includeDir, name + extname);
  2570. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2571. if (err) return callback(err);
  2572. callback(null, engine.parse(data));
  2573. });
  2574. });
  2575. delete options.includeDir;
  2576. /**
  2577. * The custom tag functions need to have their results pushed back
  2578. * through the parser, so set up a shim before calling the provided
  2579. * callback:
  2580. */
  2581. var compileOptions = {
  2582. customTags: {}
  2583. };
  2584. if (options.customTags) {
  2585. var tagFunctions = options.customTags;
  2586. for (k in options.customTags) {
  2587. /*Tell jshint there's no problem with having this function in the loop */
  2588. /*jshint -W083 */
  2589. compileOptions.customTags[k] = function(context, name, body) {
  2590. var tpl = tagFunctions[name](body.trim());
  2591. context.astStack.push(engine.parse(tpl));
  2592. };
  2593. /*jshint +W083 */
  2594. }
  2595. delete options.customTags;
  2596. }
  2597. /**
  2598. * Now anything left in `options` becomes a local:
  2599. */
  2600. for (k in options) {
  2601. context.setLocals(k, options[k]);
  2602. }
  2603. /**
  2604. * Finally, execute the template:
  2605. */
  2606. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2607. tmpl(context, cb);
  2608. }
  2609. exports.liquid.render = function(str, options, cb) {
  2610. return promisify(cb, function(cb) {
  2611. var engine = requires.liquid;
  2612. var Liquid;
  2613. try {
  2614. // set up tinyliquid engine
  2615. engine = requires.liquid = require('tinyliquid');
  2616. // use tinyliquid engine
  2617. _renderTinyliquid(engine, str, options, cb);
  2618. return;
  2619. } catch (err) {
  2620. // set up liquid-node engine
  2621. try {
  2622. Liquid = requires.liquid = require('liquid-node');
  2623. engine = new Liquid.Engine();
  2624. } catch (err) {
  2625. throw err;
  2626. }
  2627. }
  2628. // use liquid-node engine
  2629. try {
  2630. var locals = options.locals || {};
  2631. if (options.meta) {
  2632. locals.pages = options.meta;
  2633. delete options.meta;
  2634. }
  2635. /**
  2636. * Add any defined filters:
  2637. */
  2638. if (options.filters) {
  2639. engine.registerFilters(options.filters);
  2640. delete options.filters;
  2641. }
  2642. /**
  2643. * Set up a callback for the include directory:
  2644. */
  2645. var includeDir = options.includeDir || process.cwd();
  2646. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2647. delete options.includeDir;
  2648. /**
  2649. * The custom tag functions need to have their results pushed back
  2650. * through the parser, so set up a shim before calling the provided
  2651. * callback:
  2652. */
  2653. if (options.customTags) {
  2654. var tagFunctions = options.customTags;
  2655. for (k in options.customTags) {
  2656. engine.registerTag(k, tagFunctions[k]);
  2657. }
  2658. delete options.customTags;
  2659. }
  2660. /**
  2661. * Now anything left in `options` becomes a local:
  2662. */
  2663. for (var k in options) {
  2664. locals[k] = options[k];
  2665. }
  2666. /**
  2667. * Finally, execute the template:
  2668. */
  2669. return engine
  2670. .parseAndRender(str, locals)
  2671. .nodeify(function(err, result) {
  2672. if (err) {
  2673. throw new Error(err);
  2674. } else {
  2675. return cb(null, result);
  2676. }
  2677. });
  2678. } catch (err) {
  2679. cb(err);
  2680. }
  2681. });
  2682. };
  2683. /**
  2684. * Jade support.
  2685. */
  2686. exports.jade = function(path, options, cb) {
  2687. return promisify(cb, function(cb) {
  2688. var engine = requires.jade;
  2689. if (!engine) {
  2690. try {
  2691. engine = requires.jade = require('jade');
  2692. } catch (err) {
  2693. try {
  2694. engine = requires.jade = require('then-jade');
  2695. } catch (otherError) {
  2696. throw err;
  2697. }
  2698. }
  2699. }
  2700. try {
  2701. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2702. cb(null, tmpl(options));
  2703. } catch (err) {
  2704. cb(err);
  2705. }
  2706. });
  2707. };
  2708. /**
  2709. * Jade string support.
  2710. */
  2711. exports.jade.render = function(str, options, cb) {
  2712. return promisify(cb, function(cb) {
  2713. var engine = requires.jade;
  2714. if (!engine) {
  2715. try {
  2716. engine = requires.jade = require('jade');
  2717. } catch (err) {
  2718. try {
  2719. engine = requires.jade = require('then-jade');
  2720. } catch (otherError) {
  2721. throw err;
  2722. }
  2723. }
  2724. }
  2725. try {
  2726. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2727. cb(null, tmpl(options));
  2728. } catch (err) {
  2729. cb(err);
  2730. }
  2731. });
  2732. };
  2733. /**
  2734. * Dust support.
  2735. */
  2736. exports.dust = fromStringRenderer('dust');
  2737. /**
  2738. * Dust string support.
  2739. */
  2740. exports.dust.render = function(str, options, cb) {
  2741. return promisify(cb, function(cb) {
  2742. var engine = requires.dust;
  2743. if (!engine) {
  2744. try {
  2745. engine = requires.dust = require('dust');
  2746. } catch (err) {
  2747. try {
  2748. engine = requires.dust = require('dustjs-helpers');
  2749. } catch (err) {
  2750. engine = requires.dust = require('dustjs-linkedin');
  2751. }
  2752. }
  2753. }
  2754. var ext = 'dust';
  2755. var views = '.';
  2756. if (options) {
  2757. if (options.ext) ext = options.ext;
  2758. if (options.views) views = options.views;
  2759. if (options.settings && options.settings.views) views = options.settings.views;
  2760. }
  2761. if (!options || (options && !options.cache)) engine.cache = {};
  2762. engine.onLoad = function(path, callback) {
  2763. if (extname(path) === '') path += '.' + ext;
  2764. if (path[0] !== '/') path = views + '/' + path;
  2765. read(path, options, callback);
  2766. };
  2767. try {
  2768. var templateName;
  2769. if (options.filename) {
  2770. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2771. }
  2772. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2773. tmpl(options, cb);
  2774. } catch (err) {
  2775. cb(err);
  2776. }
  2777. });
  2778. };
  2779. /**
  2780. * Swig support.
  2781. */
  2782. exports.swig = fromStringRenderer('swig');
  2783. /**
  2784. * Swig string support.
  2785. */
  2786. exports.swig.render = function(str, options, cb) {
  2787. return promisify(cb, function(cb) {
  2788. var engine = requires.swig;
  2789. if (!engine) {
  2790. try {
  2791. engine = requires.swig = require('swig');
  2792. } catch (err) {
  2793. try {
  2794. engine = requires.swig = require('swig-templates');
  2795. } catch (otherError) {
  2796. throw err;
  2797. }
  2798. }
  2799. }
  2800. try {
  2801. if (options.cache === true) options.cache = 'memory';
  2802. engine.setDefaults({ cache: options.cache });
  2803. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2804. cb(null, tmpl(options));
  2805. } catch (err) {
  2806. cb(err);
  2807. }
  2808. });
  2809. };
  2810. /**
  2811. * Razor support.
  2812. */
  2813. exports.razor = function(path, options, cb) {
  2814. return promisify(cb, function(cb) {
  2815. var engine = requires.razor;
  2816. if (!engine) {
  2817. try {
  2818. engine = requires.razor = require('razor-tmpl');
  2819. } catch (err) {
  2820. throw err;
  2821. }
  2822. }
  2823. try {
  2824. var tmpl = cache(options) || cache(options, (locals) => {
  2825. console.log('Rendering razor file', path);
  2826. return engine.renderFileSync(path, locals);
  2827. });
  2828. cb(null, tmpl(options));
  2829. } catch (err) {
  2830. cb(err);
  2831. }
  2832. });
  2833. };
  2834. /**
  2835. * razor string support.
  2836. */
  2837. exports.razor.render = function(str, options, cb) {
  2838. return promisify(cb, function(cb) {
  2839. try {
  2840. var engine = requires.razor = require('razor-tmpl');
  2841. } catch (err) {
  2842. throw err;
  2843. }
  2844. try {
  2845. var tf = engine.compile(str);
  2846. var tmpl = cache(options) || cache(options, tf);
  2847. cb(null, tmpl(options));
  2848. } catch (err) {
  2849. cb(err);
  2850. }
  2851. });
  2852. };
  2853. /**
  2854. * Atpl support.
  2855. */
  2856. exports.atpl = fromStringRenderer('atpl');
  2857. /**
  2858. * Atpl string support.
  2859. */
  2860. exports.atpl.render = function(str, options, cb) {
  2861. return promisify(cb, function(cb) {
  2862. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2863. try {
  2864. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2865. cb(null, tmpl(options));
  2866. } catch (err) {
  2867. cb(err);
  2868. }
  2869. });
  2870. };
  2871. /**
  2872. * Liquor support,
  2873. */
  2874. exports.liquor = fromStringRenderer('liquor');
  2875. /**
  2876. * Liquor string support.
  2877. */
  2878. exports.liquor.render = function(str, options, cb) {
  2879. return promisify(cb, function(cb) {
  2880. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2881. try {
  2882. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2883. cb(null, tmpl(options));
  2884. } catch (err) {
  2885. cb(err);
  2886. }
  2887. });
  2888. };
  2889. /**
  2890. * Twig support.
  2891. */
  2892. exports.twig = fromStringRenderer('twig');
  2893. /**
  2894. * Twig string support.
  2895. */
  2896. exports.twig.render = function(str, options, cb) {
  2897. return promisify(cb, function(cb) {
  2898. var engine = requires.twig || (requires.twig = require('twig').twig);
  2899. var templateData = {
  2900. data: str,
  2901. allowInlineIncludes: options.allowInlineIncludes,
  2902. namespaces: options.namespaces,
  2903. path: options.path
  2904. };
  2905. try {
  2906. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2907. cb(null, tmpl.render(options));
  2908. } catch (err) {
  2909. cb(err);
  2910. }
  2911. });
  2912. };
  2913. /**
  2914. * EJS support.
  2915. */
  2916. exports.ejs = fromStringRenderer('ejs');
  2917. /**
  2918. * EJS string support.
  2919. */
  2920. exports.ejs.render = function(str, options, cb) {
  2921. return promisify(cb, function(cb) {
  2922. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2923. try {
  2924. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2925. cb(null, tmpl(options));
  2926. } catch (err) {
  2927. cb(err);
  2928. }
  2929. });
  2930. };
  2931. /**
  2932. * Eco support.
  2933. */
  2934. exports.eco = fromStringRenderer('eco');
  2935. /**
  2936. * Eco string support.
  2937. */
  2938. exports.eco.render = function(str, options, cb) {
  2939. return promisify(cb, function(cb) {
  2940. var engine = requires.eco || (requires.eco = require('eco'));
  2941. try {
  2942. cb(null, engine.render(str, options));
  2943. } catch (err) {
  2944. cb(err);
  2945. }
  2946. });
  2947. };
  2948. /**
  2949. * Jazz support.
  2950. */
  2951. exports.jazz = fromStringRenderer('jazz');
  2952. /**
  2953. * Jazz string support.
  2954. */
  2955. exports.jazz.render = function(str, options, cb) {
  2956. return promisify(cb, function(cb) {
  2957. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2958. try {
  2959. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2960. tmpl.eval(options, function(str) {
  2961. cb(null, str);
  2962. });
  2963. } catch (err) {
  2964. cb(err);
  2965. }
  2966. });
  2967. };
  2968. /**
  2969. * JQTPL support.
  2970. */
  2971. exports.jqtpl = fromStringRenderer('jqtpl');
  2972. /**
  2973. * JQTPL string support.
  2974. */
  2975. exports.jqtpl.render = function(str, options, cb) {
  2976. return promisify(cb, function(cb) {
  2977. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2978. try {
  2979. engine.template(str, str);
  2980. cb(null, engine.tmpl(str, options));
  2981. } catch (err) {
  2982. cb(err);
  2983. }
  2984. });
  2985. };
  2986. /**
  2987. * Haml support.
  2988. */
  2989. exports.haml = fromStringRenderer('haml');
  2990. /**
  2991. * Haml string support.
  2992. */
  2993. exports.haml.render = function(str, options, cb) {
  2994. return promisify(cb, function(cb) {
  2995. var engine = requires.haml || (requires.haml = require('hamljs'));
  2996. try {
  2997. options.locals = options;
  2998. cb(null, engine.render(str, options).trimLeft());
  2999. } catch (err) {
  3000. cb(err);
  3001. }
  3002. });
  3003. };
  3004. /**
  3005. * Hamlet support.
  3006. */
  3007. exports.hamlet = fromStringRenderer('hamlet');
  3008. /**
  3009. * Hamlet string support.
  3010. */
  3011. exports.hamlet.render = function(str, options, cb) {
  3012. return promisify(cb, function(cb) {
  3013. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  3014. try {
  3015. options.locals = options;
  3016. cb(null, engine.render(str, options).trimLeft());
  3017. } catch (err) {
  3018. cb(err);
  3019. }
  3020. });
  3021. };
  3022. /**
  3023. * Whiskers support.
  3024. */
  3025. exports.whiskers = function(path, options, cb) {
  3026. return promisify(cb, function(cb) {
  3027. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3028. engine.__express(path, options, cb);
  3029. });
  3030. };
  3031. /**
  3032. * Whiskers string support.
  3033. */
  3034. exports.whiskers.render = function(str, options, cb) {
  3035. return promisify(cb, function(cb) {
  3036. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3037. try {
  3038. cb(null, engine.render(str, options));
  3039. } catch (err) {
  3040. cb(err);
  3041. }
  3042. });
  3043. };
  3044. /**
  3045. * Coffee-HAML support.
  3046. */
  3047. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  3048. /**
  3049. * Coffee-HAML string support.
  3050. */
  3051. exports['haml-coffee'].render = function(str, options, cb) {
  3052. return promisify(cb, function(cb) {
  3053. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3054. try {
  3055. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3056. cb(null, tmpl(options));
  3057. } catch (err) {
  3058. cb(err);
  3059. }
  3060. });
  3061. };
  3062. /**
  3063. * Hogan support.
  3064. */
  3065. exports.hogan = fromStringRenderer('hogan');
  3066. /**
  3067. * Hogan string support.
  3068. */
  3069. exports.hogan.render = function(str, options, cb) {
  3070. return promisify(cb, function(cb) {
  3071. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3072. try {
  3073. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3074. cb(null, tmpl.render(options, options.partials));
  3075. } catch (err) {
  3076. cb(err);
  3077. }
  3078. });
  3079. };
  3080. /**
  3081. * templayed.js support.
  3082. */
  3083. exports.templayed = fromStringRenderer('templayed');
  3084. /**
  3085. * templayed.js string support.
  3086. */
  3087. exports.templayed.render = function(str, options, cb) {
  3088. return promisify(cb, function(cb) {
  3089. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3090. try {
  3091. var tmpl = cache(options) || cache(options, engine(str));
  3092. cb(null, tmpl(options));
  3093. } catch (err) {
  3094. cb(err);
  3095. }
  3096. });
  3097. };
  3098. /**
  3099. * Handlebars support.
  3100. */
  3101. exports.handlebars = fromStringRenderer('handlebars');
  3102. /**
  3103. * Handlebars string support.
  3104. */
  3105. exports.handlebars.render = function(str, options, cb) {
  3106. return promisify(cb, function(cb) {
  3107. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3108. try {
  3109. for (var partial in options.partials) {
  3110. engine.registerPartial(partial, options.partials[partial]);
  3111. }
  3112. for (var helper in options.helpers) {
  3113. engine.registerHelper(helper, options.helpers[helper]);
  3114. }
  3115. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3116. cb(null, tmpl(options));
  3117. } catch (err) {
  3118. cb(err);
  3119. }
  3120. });
  3121. };
  3122. /**
  3123. * Underscore support.
  3124. */
  3125. exports.underscore = fromStringRenderer('underscore');
  3126. /**
  3127. * Underscore string support.
  3128. */
  3129. exports.underscore.render = function(str, options, cb) {
  3130. return promisify(cb, function(cb) {
  3131. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3132. try {
  3133. const partials = {};
  3134. for (var partial in options.partials) {
  3135. partials[partial] = engine.template(options.partials[partial]);
  3136. }
  3137. options.partials = partials;
  3138. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3139. cb(null, tmpl(options).replace(/\n$/, ''));
  3140. } catch (err) {
  3141. cb(err);
  3142. }
  3143. });
  3144. };
  3145. /**
  3146. * Lodash support.
  3147. */
  3148. exports.lodash = fromStringRenderer('lodash');
  3149. /**
  3150. * Lodash string support.
  3151. */
  3152. exports.lodash.render = function(str, options, cb) {
  3153. return promisify(cb, function(cb) {
  3154. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3155. try {
  3156. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3157. cb(null, tmpl(options).replace(/\n$/, ''));
  3158. } catch (err) {
  3159. cb(err);
  3160. }
  3161. });
  3162. };
  3163. /**
  3164. * Pug support. (formerly Jade)
  3165. */
  3166. exports.pug = function(path, options, cb) {
  3167. return promisify(cb, function(cb) {
  3168. var engine = requires.pug;
  3169. if (!engine) {
  3170. try {
  3171. engine = requires.pug = require('pug');
  3172. } catch (err) {
  3173. try {
  3174. engine = requires.pug = require('then-pug');
  3175. } catch (otherError) {
  3176. throw err;
  3177. }
  3178. }
  3179. }
  3180. try {
  3181. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3182. cb(null, tmpl(options));
  3183. } catch (err) {
  3184. cb(err);
  3185. }
  3186. });
  3187. };
  3188. /**
  3189. * Pug string support.
  3190. */
  3191. exports.pug.render = function(str, options, cb) {
  3192. return promisify(cb, function(cb) {
  3193. var engine = requires.pug;
  3194. if (!engine) {
  3195. try {
  3196. engine = requires.pug = require('pug');
  3197. } catch (err) {
  3198. try {
  3199. engine = requires.pug = require('then-pug');
  3200. } catch (otherError) {
  3201. throw err;
  3202. }
  3203. }
  3204. }
  3205. try {
  3206. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3207. cb(null, tmpl(options));
  3208. } catch (err) {
  3209. cb(err);
  3210. }
  3211. });
  3212. };
  3213. /**
  3214. * QEJS support.
  3215. */
  3216. exports.qejs = fromStringRenderer('qejs');
  3217. /**
  3218. * QEJS string support.
  3219. */
  3220. exports.qejs.render = function(str, options, cb) {
  3221. return promisify(cb, function(cb) {
  3222. try {
  3223. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3224. engine.render(str, options).then(function(result) {
  3225. cb(null, result);
  3226. }, function(err) {
  3227. cb(err);
  3228. }).done();
  3229. } catch (err) {
  3230. cb(err);
  3231. }
  3232. });
  3233. };
  3234. /**
  3235. * Walrus support.
  3236. */
  3237. exports.walrus = fromStringRenderer('walrus');
  3238. /**
  3239. * Walrus string support.
  3240. */
  3241. exports.walrus.render = function(str, options, cb) {
  3242. return promisify(cb, function(cb) {
  3243. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3244. try {
  3245. var tmpl = cache(options) || cache(options, engine.parse(str));
  3246. cb(null, tmpl.compile(options));
  3247. } catch (err) {
  3248. cb(err);
  3249. }
  3250. });
  3251. };
  3252. /**
  3253. * Mustache support.
  3254. */
  3255. exports.mustache = fromStringRenderer('mustache');
  3256. /**
  3257. * Mustache string support.
  3258. */
  3259. exports.mustache.render = function(str, options, cb) {
  3260. return promisify(cb, function(cb) {
  3261. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3262. try {
  3263. cb(null, engine.render(str, options, options.partials));
  3264. } catch (err) {
  3265. cb(err);
  3266. }
  3267. });
  3268. };
  3269. /**
  3270. * Just support.
  3271. */
  3272. exports.just = function(path, options, cb) {
  3273. return promisify(cb, function(cb) {
  3274. var engine = requires.just;
  3275. if (!engine) {
  3276. var JUST = require('just');
  3277. engine = requires.just = new JUST();
  3278. }
  3279. engine.configure({ useCache: options.cache });
  3280. engine.render(path, options, cb);
  3281. });
  3282. };
  3283. /**
  3284. * Just string support.
  3285. */
  3286. exports.just.render = function(str, options, cb) {
  3287. return promisify(cb, function(cb) {
  3288. var JUST = require('just');
  3289. var engine = new JUST({ root: { page: str }});
  3290. engine.render('page', options, cb);
  3291. });
  3292. };
  3293. /**
  3294. * ECT support.
  3295. */
  3296. exports.ect = function(path, options, cb) {
  3297. return promisify(cb, function(cb) {
  3298. var engine = requires.ect;
  3299. if (!engine) {
  3300. var ECT = require('ect');
  3301. engine = requires.ect = new ECT(options);
  3302. }
  3303. engine.configure({ cache: options.cache });
  3304. engine.render(path, options, cb);
  3305. });
  3306. };
  3307. /**
  3308. * ECT string support.
  3309. */
  3310. exports.ect.render = function(str, options, cb) {
  3311. return promisify(cb, function(cb) {
  3312. var ECT = require('ect');
  3313. var engine = new ECT({ root: { page: str }});
  3314. engine.render('page', options, cb);
  3315. });
  3316. };
  3317. /**
  3318. * mote support.
  3319. */
  3320. exports.mote = fromStringRenderer('mote');
  3321. /**
  3322. * mote string support.
  3323. */
  3324. exports.mote.render = function(str, options, cb) {
  3325. return promisify(cb, function(cb) {
  3326. var engine = requires.mote || (requires.mote = require('mote'));
  3327. try {
  3328. var tmpl = cache(options) || cache(options, engine.compile(str));
  3329. cb(null, tmpl(options));
  3330. } catch (err) {
  3331. cb(err);
  3332. }
  3333. });
  3334. };
  3335. /**
  3336. * Toffee support.
  3337. */
  3338. exports.toffee = function(path, options, cb) {
  3339. return promisify(cb, function(cb) {
  3340. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3341. toffee.__consolidate_engine_render(path, options, cb);
  3342. });
  3343. };
  3344. /**
  3345. * Toffee string support.
  3346. */
  3347. exports.toffee.render = function(str, options, cb) {
  3348. return promisify(cb, function(cb) {
  3349. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3350. try {
  3351. engine.str_render(str, options, cb);
  3352. } catch (err) {
  3353. cb(err);
  3354. }
  3355. });
  3356. };
  3357. /**
  3358. * doT support.
  3359. */
  3360. exports.dot = fromStringRenderer('dot');
  3361. /**
  3362. * doT string support.
  3363. */
  3364. exports.dot.render = function(str, options, cb) {
  3365. return promisify(cb, function(cb) {
  3366. var engine = requires.dot || (requires.dot = require('dot'));
  3367. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3368. try {
  3369. var settings = {};
  3370. settings = extend(settings, engine.templateSettings);
  3371. settings = extend(settings, options ? options.dot : {});
  3372. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3373. cb(null, tmpl(options));
  3374. } catch (err) {
  3375. cb(err);
  3376. }
  3377. });
  3378. };
  3379. /**
  3380. * bracket support.
  3381. */
  3382. exports.bracket = fromStringRenderer('bracket');
  3383. /**
  3384. * bracket string support.
  3385. */
  3386. exports.bracket.render = function(str, options, cb) {
  3387. return promisify(cb, function(cb) {
  3388. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3389. try {
  3390. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3391. cb(null, tmpl(options));
  3392. } catch (err) {
  3393. cb(err);
  3394. }
  3395. });
  3396. };
  3397. /**
  3398. * Ractive support.
  3399. */
  3400. exports.ractive = fromStringRenderer('ractive');
  3401. /**
  3402. * Ractive string support.
  3403. */
  3404. exports.ractive.render = function(str, options, cb) {
  3405. return promisify(cb, function(cb) {
  3406. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3407. var template = cache(options) || cache(options, Engine.parse(str));
  3408. options.template = template;
  3409. if (options.data === null || options.data === undefined) {
  3410. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3411. // Shallow clone the options object
  3412. options.data = extend({}, options);
  3413. // Remove consolidate-specific properties from the clone
  3414. var i;
  3415. var length;
  3416. var properties = ['template', 'filename', 'cache', 'partials'];
  3417. for (i = 0, length = properties.length; i < length; i++) {
  3418. var property = properties[i];
  3419. delete options.data[property];
  3420. }
  3421. }
  3422. try {
  3423. cb(null, new Engine(options).toHTML());
  3424. } catch (err) {
  3425. cb(err);
  3426. }
  3427. });
  3428. };
  3429. /**
  3430. * Nunjucks support.
  3431. */
  3432. exports.nunjucks = fromStringRenderer('nunjucks');
  3433. /**
  3434. * Nunjucks string support.
  3435. */
  3436. exports.nunjucks.render = function(str, options, cb) {
  3437. return promisify(cb, function(cb) {
  3438. try {
  3439. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3440. var env = engine;
  3441. // deprecated fallback support for express
  3442. // <https://github.com/tj/consolidate.js/pull/152>
  3443. // <https://github.com/tj/consolidate.js/pull/224>
  3444. if (options.settings && options.settings.views) {
  3445. env = engine.configure(options.settings.views);
  3446. } else if (options.nunjucks && options.nunjucks.configure) {
  3447. env = engine.configure.apply(engine, options.nunjucks.configure);
  3448. }
  3449. //
  3450. // because `renderString` does not initiate loaders
  3451. // we must manually create a loader for it based off
  3452. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3453. //
  3454. // <https://github.com/mozilla/nunjucks/issues/730>
  3455. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3456. //
  3457. // so instead we simply check if we passed a custom loader
  3458. // otherwise we create a simple file based loader
  3459. if (options.loader) {
  3460. env = new engine.Environment(options.loader);
  3461. } else if (options.settings && options.settings.views) {
  3462. env = new engine.Environment(
  3463. new engine.FileSystemLoader(options.settings.views)
  3464. );
  3465. } else if (options.nunjucks && options.nunjucks.loader) {
  3466. if (typeof options.nunjucks.loader === 'string') {
  3467. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3468. } else {
  3469. env = new engine.Environment(
  3470. new engine.FileSystemLoader(
  3471. options.nunjucks.loader[0],
  3472. options.nunjucks.loader[1]
  3473. )
  3474. );
  3475. }
  3476. }
  3477. env.renderString(str, options, cb);
  3478. } catch (err) {
  3479. throw cb(err);
  3480. }
  3481. });
  3482. };
  3483. /**
  3484. * HTMLing support.
  3485. */
  3486. exports.htmling = fromStringRenderer('htmling');
  3487. /**
  3488. * HTMLing string support.
  3489. */
  3490. exports.htmling.render = function(str, options, cb) {
  3491. return promisify(cb, function(cb) {
  3492. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3493. try {
  3494. var tmpl = cache(options) || cache(options, engine.string(str));
  3495. cb(null, tmpl.render(options));
  3496. } catch (err) {
  3497. cb(err);
  3498. }
  3499. });
  3500. };
  3501. /**
  3502. * Rendering function
  3503. */
  3504. function requireReact(module, filename) {
  3505. var babel = requires.babel || (requires.babel = require('babel-core'));
  3506. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3507. return module._compile(compiled, filename);
  3508. }
  3509. exports.requireReact = requireReact;
  3510. /**
  3511. * Converting a string into a node module.
  3512. */
  3513. function requireReactString(src, filename) {
  3514. var babel = requires.babel || (requires.babel = require('babel-core'));
  3515. if (!filename) filename = '';
  3516. var m = new module.constructor();
  3517. filename = filename || '';
  3518. // Compile Using React
  3519. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3520. // Compile as a module
  3521. m.paths = module.paths;
  3522. m._compile(compiled, filename);
  3523. return m.exports;
  3524. }
  3525. /**
  3526. * A naive helper to replace {{tags}} with options.tags content
  3527. */
  3528. function reactBaseTmpl(data, options) {
  3529. var exp;
  3530. var regex;
  3531. // Iterates through the keys in file object
  3532. // and interpolate / replace {{key}} with it's value
  3533. for (var k in options) {
  3534. if (options.hasOwnProperty(k)) {
  3535. exp = '{{' + k + '}}';
  3536. regex = new RegExp(exp, 'g');
  3537. if (data.match(regex)) {
  3538. data = data.replace(regex, options[k]);
  3539. }
  3540. }
  3541. }
  3542. return data;
  3543. }
  3544. /**
  3545. * Plates Support.
  3546. */
  3547. exports.plates = fromStringRenderer('plates');
  3548. /**
  3549. * Plates string support.
  3550. */
  3551. exports.plates.render = function(str, options, cb) {
  3552. return promisify(cb, function(cb) {
  3553. var engine = requires.plates || (requires.plates = require('plates'));
  3554. var map = options.map || undefined;
  3555. try {
  3556. var tmpl = engine.bind(str, options, map);
  3557. cb(null, tmpl);
  3558. } catch (err) {
  3559. cb(err);
  3560. }
  3561. });
  3562. };
  3563. /**
  3564. * The main render parser for React bsaed templates
  3565. */
  3566. function reactRenderer(type) {
  3567. if (commonjsRequire.extensions) {
  3568. // Ensure JSX is transformed on require
  3569. if (!commonjsRequire.extensions['.jsx']) {
  3570. commonjsRequire.extensions['.jsx'] = requireReact;
  3571. }
  3572. // Supporting .react extension as well as test cases
  3573. // Using .react extension is not recommended.
  3574. if (!commonjsRequire.extensions['.react']) {
  3575. commonjsRequire.extensions['.react'] = requireReact;
  3576. }
  3577. }
  3578. // Return rendering fx
  3579. return function(str, options, cb) {
  3580. return promisify(cb, function(cb) {
  3581. // React Import
  3582. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3583. var react = requires.react || (requires.react = require('react'));
  3584. // Assign HTML Base
  3585. var base = options.base;
  3586. delete options.base;
  3587. var enableCache = options.cache;
  3588. delete options.cache;
  3589. var isNonStatic = options.isNonStatic;
  3590. delete options.isNonStatic;
  3591. // Start Conversion
  3592. try {
  3593. var Code;
  3594. var Factory;
  3595. var baseStr;
  3596. var content;
  3597. var parsed;
  3598. if (!cache(options)) {
  3599. // Parsing
  3600. if (type === 'path') {
  3601. var path = resolve(str);
  3602. delete require.cache[path];
  3603. Code = commonjsRequire(path);
  3604. } else {
  3605. Code = requireReactString(str);
  3606. }
  3607. Factory = cache(options, react.createFactory(Code));
  3608. } else {
  3609. Factory = cache(options);
  3610. }
  3611. parsed = new Factory(options);
  3612. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3613. if (base) {
  3614. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3615. if (enableCache) {
  3616. readCache[str] = baseStr;
  3617. }
  3618. options.content = content;
  3619. content = reactBaseTmpl(baseStr, options);
  3620. }
  3621. cb(null, content);
  3622. } catch (err) {
  3623. cb(err);
  3624. }
  3625. });
  3626. };
  3627. }
  3628. /**
  3629. * React JS Support
  3630. */
  3631. exports.react = reactRenderer('path');
  3632. /**
  3633. * React JS string support.
  3634. */
  3635. exports.react.render = reactRenderer('string');
  3636. /**
  3637. * ARC-templates support.
  3638. */
  3639. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3640. /**
  3641. * ARC-templates string support.
  3642. */
  3643. exports['arc-templates'].render = function(str, options, cb) {
  3644. var readFileWithOptions = util.promisify(read);
  3645. var consolidateFileSystem = {};
  3646. consolidateFileSystem.readFile = function(path) {
  3647. return readFileWithOptions(path, options);
  3648. };
  3649. return promisify(cb, function(cb) {
  3650. try {
  3651. var engine = requires['arc-templates'];
  3652. if (!engine) {
  3653. var Engine = require('arc-templates/dist/es5');
  3654. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3655. }
  3656. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3657. compiler.then(function(func) { return func(options); })
  3658. .then(function(result) { cb(null, result.content); })
  3659. .catch(cb);
  3660. } catch (err) {
  3661. cb(err);
  3662. }
  3663. });
  3664. };
  3665. /**
  3666. * Vash support
  3667. */
  3668. exports.vash = fromStringRenderer('vash');
  3669. /**
  3670. * Vash string support
  3671. */
  3672. exports.vash.render = function(str, options, cb) {
  3673. return promisify(cb, function(cb) {
  3674. var engine = requires.vash || (requires.vash = require('vash'));
  3675. try {
  3676. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3677. if (options.helpers) {
  3678. for (var key in options.helpers) {
  3679. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3680. continue;
  3681. }
  3682. engine.helpers[key] = options.helpers[key];
  3683. }
  3684. }
  3685. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3686. tmpl(options, function sealLayout(err, ctx) {
  3687. if (err) cb(err);
  3688. ctx.finishLayout();
  3689. cb(null, ctx.toString().replace(/\n$/, ''));
  3690. });
  3691. } catch (err) {
  3692. cb(err);
  3693. }
  3694. });
  3695. };
  3696. /**
  3697. * Slm support.
  3698. */
  3699. exports.slm = fromStringRenderer('slm');
  3700. /**
  3701. * Slm string support.
  3702. */
  3703. exports.slm.render = function(str, options, cb) {
  3704. return promisify(cb, function(cb) {
  3705. var engine = requires.slm || (requires.slm = require('slm'));
  3706. try {
  3707. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3708. cb(null, tmpl(options));
  3709. } catch (err) {
  3710. cb(err);
  3711. }
  3712. });
  3713. };
  3714. /**
  3715. * Marko support.
  3716. */
  3717. exports.marko = function(path, options, cb) {
  3718. return promisify(cb, function(cb) {
  3719. var engine = requires.marko || (requires.marko = require('marko'));
  3720. options.writeToDisk = !!options.cache;
  3721. try {
  3722. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3723. tmpl.renderToString(options, cb);
  3724. } catch (err) {
  3725. cb(err);
  3726. }
  3727. });
  3728. };
  3729. /**
  3730. * Marko string support.
  3731. */
  3732. exports.marko.render = function(str, options, cb) {
  3733. return promisify(cb, function(cb) {
  3734. var engine = requires.marko || (requires.marko = require('marko'));
  3735. options.writeToDisk = !!options.cache;
  3736. options.filename = options.filename || 'string.marko';
  3737. try {
  3738. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3739. tmpl.renderToString(options, cb);
  3740. } catch (err) {
  3741. cb(err);
  3742. }
  3743. });
  3744. };
  3745. /**
  3746. * Teacup support.
  3747. */
  3748. exports.teacup = function(path, options, cb) {
  3749. return promisify(cb, function(cb) {
  3750. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3751. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3752. if (path[0] !== '/') {
  3753. path = join(process.cwd(), path);
  3754. }
  3755. if (!options.cache) {
  3756. var callback = cb;
  3757. cb = function() {
  3758. delete require.cache[path];
  3759. callback.apply(this, arguments);
  3760. };
  3761. }
  3762. engine.renderFile(path, options, cb);
  3763. });
  3764. };
  3765. /**
  3766. * Teacup string support.
  3767. */
  3768. exports.teacup.render = function(str, options, cb) {
  3769. var coffee = require('coffee-script');
  3770. var vm = require('vm');
  3771. var sandbox = {
  3772. module: {exports: {}},
  3773. require: commonjsRequire
  3774. };
  3775. return promisify(cb, function(cb) {
  3776. vm.runInNewContext(coffee.compile(str), sandbox);
  3777. var tmpl = sandbox.module.exports;
  3778. cb(null, tmpl(options));
  3779. });
  3780. };
  3781. /**
  3782. * Squirrelly support.
  3783. */
  3784. exports.squirrelly = fromStringRenderer('squirrelly');
  3785. /**
  3786. * Squirrelly string support.
  3787. */
  3788. exports.squirrelly.render = function(str, options, cb) {
  3789. return promisify(cb, function(cb) {
  3790. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3791. try {
  3792. for (var partial in options.partials) {
  3793. engine.definePartial(partial, options.partials[partial]);
  3794. }
  3795. for (var helper in options.helpers) {
  3796. engine.defineHelper(helper, options.helpers[helper]);
  3797. }
  3798. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3799. cb(null, tmpl(options, engine));
  3800. } catch (err) {
  3801. cb(err);
  3802. }
  3803. });
  3804. };
  3805. /**
  3806. * Twing support.
  3807. */
  3808. exports.twing = fromStringRenderer('twing');
  3809. /**
  3810. * Twing string support.
  3811. */
  3812. exports.twing.render = function(str, options, cb) {
  3813. return promisify(cb, function(cb) {
  3814. var engine = requires.twing || (requires.twing = require('twing'));
  3815. try {
  3816. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3817. twingTemplate.render(options).then((rendTmpl) => {
  3818. var tmpl = cache(options) || cache(options, rendTmpl);
  3819. cb(null, tmpl);
  3820. });
  3821. });
  3822. } catch (err) {
  3823. cb(err);
  3824. }
  3825. });
  3826. };
  3827. /**
  3828. * expose the instance of the engine
  3829. */
  3830. exports.requires = requires;
  3831. } (consolidate$2, consolidate$2.exports));
  3832. var consolidateExports = consolidate$2.exports;
  3833. var consolidate = consolidateExports;
  3834. var consolidate$1 = /*@__PURE__*/getDefaultExportFromCjs(consolidate);
  3835. const hasWarned = {};
  3836. function warnOnce(msg) {
  3837. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3838. if (!isNodeProd && true && !hasWarned[msg]) {
  3839. hasWarned[msg] = true;
  3840. warn(msg);
  3841. }
  3842. }
  3843. function warn(msg) {
  3844. console.warn(
  3845. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3846. `
  3847. );
  3848. }
  3849. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3850. let res = "";
  3851. let err = null;
  3852. preprocessor.render(
  3853. source,
  3854. { filename, ...preprocessOptions },
  3855. (_err, _res) => {
  3856. if (_err)
  3857. err = _err;
  3858. res = _res;
  3859. }
  3860. );
  3861. if (err)
  3862. throw err;
  3863. return res;
  3864. }
  3865. function compileTemplate(options) {
  3866. const { preprocessLang, preprocessCustomRequire } = options;
  3867. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate$1[preprocessLang] : false;
  3868. if (preprocessor) {
  3869. try {
  3870. return doCompileTemplate({
  3871. ...options,
  3872. source: preprocess$1(options, preprocessor),
  3873. ast: void 0
  3874. // invalidate AST if template goes through preprocessor
  3875. });
  3876. } catch (e) {
  3877. return {
  3878. code: `export default function render() {}`,
  3879. source: options.source,
  3880. tips: [],
  3881. errors: [e]
  3882. };
  3883. }
  3884. } else if (preprocessLang) {
  3885. return {
  3886. code: `export default function render() {}`,
  3887. source: options.source,
  3888. tips: [
  3889. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3890. ],
  3891. errors: [
  3892. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3893. ]
  3894. };
  3895. } else {
  3896. return doCompileTemplate(options);
  3897. }
  3898. }
  3899. function doCompileTemplate({
  3900. filename,
  3901. id,
  3902. scoped,
  3903. slotted,
  3904. inMap,
  3905. source,
  3906. ast: inAST,
  3907. ssr = false,
  3908. ssrCssVars,
  3909. isProd = false,
  3910. compiler,
  3911. compilerOptions = {},
  3912. transformAssetUrls
  3913. }) {
  3914. const errors = [];
  3915. const warnings = [];
  3916. let nodeTransforms = [];
  3917. if (shared.isObject(transformAssetUrls)) {
  3918. const assetOptions = normalizeOptions(transformAssetUrls);
  3919. nodeTransforms = [
  3920. createAssetUrlTransformWithOptions(assetOptions),
  3921. createSrcsetTransformWithOptions(assetOptions)
  3922. ];
  3923. } else if (transformAssetUrls !== false) {
  3924. nodeTransforms = [transformAssetUrl, transformSrcset];
  3925. }
  3926. if (ssr && !ssrCssVars) {
  3927. warnOnce(
  3928. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.\`.`
  3929. );
  3930. }
  3931. if (!id) {
  3932. warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
  3933. id = "";
  3934. }
  3935. const shortId = id.replace(/^data-v-/, "");
  3936. const longId = `data-v-${shortId}`;
  3937. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3938. compiler = compiler || defaultCompiler;
  3939. if (compiler !== defaultCompiler) {
  3940. inAST = void 0;
  3941. }
  3942. if (inAST == null ? void 0 : inAST.transformed) {
  3943. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3944. prefixIdentifiers: true,
  3945. ...compilerOptions,
  3946. parseMode: "sfc",
  3947. onError: (e) => errors.push(e)
  3948. });
  3949. const template = newAST.children.find(
  3950. (node) => node.type === 1 && node.tag === "template"
  3951. );
  3952. inAST = compilerCore.createRoot(template.children, inAST.source);
  3953. }
  3954. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3955. mode: "module",
  3956. prefixIdentifiers: true,
  3957. hoistStatic: true,
  3958. cacheHandlers: true,
  3959. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3960. scopeId: scoped ? longId : void 0,
  3961. slotted,
  3962. sourceMap: true,
  3963. ...compilerOptions,
  3964. hmr: !isProd,
  3965. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3966. filename,
  3967. onError: (e) => errors.push(e),
  3968. onWarn: (w) => warnings.push(w)
  3969. });
  3970. if (inMap && !inAST) {
  3971. if (map) {
  3972. map = mapLines(inMap, map);
  3973. }
  3974. if (errors.length) {
  3975. patchErrors(errors, source, inMap);
  3976. }
  3977. }
  3978. const tips = warnings.map((w) => {
  3979. let msg = w.message;
  3980. if (w.loc) {
  3981. msg += `
  3982. ${shared.generateCodeFrame(
  3983. (inAST == null ? void 0 : inAST.source) || source,
  3984. w.loc.start.offset,
  3985. w.loc.end.offset
  3986. )}`;
  3987. }
  3988. return msg;
  3989. });
  3990. return { code, ast, preamble, source, errors, tips, map };
  3991. }
  3992. function mapLines(oldMap, newMap) {
  3993. if (!oldMap)
  3994. return newMap;
  3995. if (!newMap)
  3996. return oldMap;
  3997. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  3998. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  3999. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  4000. newMapConsumer.eachMapping((m) => {
  4001. if (m.originalLine == null) {
  4002. return;
  4003. }
  4004. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  4005. line: m.originalLine,
  4006. column: m.originalColumn
  4007. });
  4008. if (origPosInOldMap.source == null) {
  4009. return;
  4010. }
  4011. mergedMapGenerator.addMapping({
  4012. generated: {
  4013. line: m.generatedLine,
  4014. column: m.generatedColumn
  4015. },
  4016. original: {
  4017. line: origPosInOldMap.line,
  4018. // map line
  4019. // use current column, since the oldMap produced by @vue/compiler-sfc
  4020. // does not
  4021. column: m.originalColumn
  4022. },
  4023. source: origPosInOldMap.source,
  4024. name: origPosInOldMap.name
  4025. });
  4026. });
  4027. const generator = mergedMapGenerator;
  4028. oldMapConsumer.sources.forEach((sourceFile) => {
  4029. generator._sources.add(sourceFile);
  4030. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  4031. if (sourceContent != null) {
  4032. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  4033. }
  4034. });
  4035. generator._sourceRoot = oldMap.sourceRoot;
  4036. generator._file = oldMap.file;
  4037. return generator.toJSON();
  4038. }
  4039. function patchErrors(errors, source, inMap) {
  4040. const originalSource = inMap.sourcesContent[0];
  4041. const offset = originalSource.indexOf(source);
  4042. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  4043. errors.forEach((err) => {
  4044. if (err.loc) {
  4045. err.loc.start.line += lineOffset;
  4046. err.loc.start.offset += offset;
  4047. if (err.loc.end !== err.loc.start) {
  4048. err.loc.end.line += lineOffset;
  4049. err.loc.end.offset += offset;
  4050. }
  4051. }
  4052. });
  4053. }
  4054. const trimPlugin = () => {
  4055. return {
  4056. postcssPlugin: "vue-sfc-trim",
  4057. Once(root) {
  4058. root.walk(({ type, raws }) => {
  4059. if (type === "rule" || type === "atrule") {
  4060. if (raws.before)
  4061. raws.before = "\n";
  4062. if ("after" in raws && raws.after)
  4063. raws.after = "\n";
  4064. }
  4065. });
  4066. }
  4067. };
  4068. };
  4069. trimPlugin.postcss = true;
  4070. var dist = {exports: {}};
  4071. var processor = {exports: {}};
  4072. var parser = {exports: {}};
  4073. var root$2 = {exports: {}};
  4074. var container = {exports: {}};
  4075. var node$1 = {exports: {}};
  4076. var util$6 = {};
  4077. var unesc = {exports: {}};
  4078. (function (module, exports) {
  4079. exports.__esModule = true;
  4080. exports["default"] = unesc;
  4081. // Many thanks for this post which made this migration much easier.
  4082. // https://mathiasbynens.be/notes/css-escapes
  4083. /**
  4084. *
  4085. * @param {string} str
  4086. * @returns {[string, number]|undefined}
  4087. */
  4088. function gobbleHex(str) {
  4089. var lower = str.toLowerCase();
  4090. var hex = '';
  4091. var spaceTerminated = false;
  4092. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4093. var code = lower.charCodeAt(i);
  4094. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4095. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4096. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4097. spaceTerminated = code === 32;
  4098. if (!valid) {
  4099. break;
  4100. }
  4101. hex += lower[i];
  4102. }
  4103. if (hex.length === 0) {
  4104. return undefined;
  4105. }
  4106. var codePoint = parseInt(hex, 16);
  4107. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4108. // Add special case for
  4109. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4110. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4111. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4112. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4113. }
  4114. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4115. }
  4116. var CONTAINS_ESCAPE = /\\/;
  4117. function unesc(str) {
  4118. var needToProcess = CONTAINS_ESCAPE.test(str);
  4119. if (!needToProcess) {
  4120. return str;
  4121. }
  4122. var ret = "";
  4123. for (var i = 0; i < str.length; i++) {
  4124. if (str[i] === "\\") {
  4125. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4126. if (gobbled !== undefined) {
  4127. ret += gobbled[0];
  4128. i += gobbled[1];
  4129. continue;
  4130. }
  4131. // Retain a pair of \\ if double escaped `\\\\`
  4132. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4133. if (str[i + 1] === "\\") {
  4134. ret += "\\";
  4135. i++;
  4136. continue;
  4137. }
  4138. // if \\ is at the end of the string retain it
  4139. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4140. if (str.length === i + 1) {
  4141. ret += str[i];
  4142. }
  4143. continue;
  4144. }
  4145. ret += str[i];
  4146. }
  4147. return ret;
  4148. }
  4149. module.exports = exports.default;
  4150. } (unesc, unesc.exports));
  4151. var unescExports = unesc.exports;
  4152. var getProp = {exports: {}};
  4153. (function (module, exports) {
  4154. exports.__esModule = true;
  4155. exports["default"] = getProp;
  4156. function getProp(obj) {
  4157. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4158. props[_key - 1] = arguments[_key];
  4159. }
  4160. while (props.length > 0) {
  4161. var prop = props.shift();
  4162. if (!obj[prop]) {
  4163. return undefined;
  4164. }
  4165. obj = obj[prop];
  4166. }
  4167. return obj;
  4168. }
  4169. module.exports = exports.default;
  4170. } (getProp, getProp.exports));
  4171. var getPropExports = getProp.exports;
  4172. var ensureObject = {exports: {}};
  4173. (function (module, exports) {
  4174. exports.__esModule = true;
  4175. exports["default"] = ensureObject;
  4176. function ensureObject(obj) {
  4177. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4178. props[_key - 1] = arguments[_key];
  4179. }
  4180. while (props.length > 0) {
  4181. var prop = props.shift();
  4182. if (!obj[prop]) {
  4183. obj[prop] = {};
  4184. }
  4185. obj = obj[prop];
  4186. }
  4187. }
  4188. module.exports = exports.default;
  4189. } (ensureObject, ensureObject.exports));
  4190. var ensureObjectExports = ensureObject.exports;
  4191. var stripComments = {exports: {}};
  4192. (function (module, exports) {
  4193. exports.__esModule = true;
  4194. exports["default"] = stripComments;
  4195. function stripComments(str) {
  4196. var s = "";
  4197. var commentStart = str.indexOf("/*");
  4198. var lastEnd = 0;
  4199. while (commentStart >= 0) {
  4200. s = s + str.slice(lastEnd, commentStart);
  4201. var commentEnd = str.indexOf("*/", commentStart + 2);
  4202. if (commentEnd < 0) {
  4203. return s;
  4204. }
  4205. lastEnd = commentEnd + 2;
  4206. commentStart = str.indexOf("/*", lastEnd);
  4207. }
  4208. s = s + str.slice(lastEnd);
  4209. return s;
  4210. }
  4211. module.exports = exports.default;
  4212. } (stripComments, stripComments.exports));
  4213. var stripCommentsExports = stripComments.exports;
  4214. util$6.__esModule = true;
  4215. util$6.unesc = util$6.stripComments = util$6.getProp = util$6.ensureObject = void 0;
  4216. var _unesc = _interopRequireDefault$5(unescExports);
  4217. util$6.unesc = _unesc["default"];
  4218. var _getProp = _interopRequireDefault$5(getPropExports);
  4219. util$6.getProp = _getProp["default"];
  4220. var _ensureObject = _interopRequireDefault$5(ensureObjectExports);
  4221. util$6.ensureObject = _ensureObject["default"];
  4222. var _stripComments = _interopRequireDefault$5(stripCommentsExports);
  4223. util$6.stripComments = _stripComments["default"];
  4224. function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4225. (function (module, exports) {
  4226. exports.__esModule = true;
  4227. exports["default"] = void 0;
  4228. var _util = util$6;
  4229. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  4230. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4231. var cloneNode = function cloneNode(obj, parent) {
  4232. if (typeof obj !== 'object' || obj === null) {
  4233. return obj;
  4234. }
  4235. var cloned = new obj.constructor();
  4236. for (var i in obj) {
  4237. if (!obj.hasOwnProperty(i)) {
  4238. continue;
  4239. }
  4240. var value = obj[i];
  4241. var type = typeof value;
  4242. if (i === 'parent' && type === 'object') {
  4243. if (parent) {
  4244. cloned[i] = parent;
  4245. }
  4246. } else if (value instanceof Array) {
  4247. cloned[i] = value.map(function (j) {
  4248. return cloneNode(j, cloned);
  4249. });
  4250. } else {
  4251. cloned[i] = cloneNode(value, cloned);
  4252. }
  4253. }
  4254. return cloned;
  4255. };
  4256. var Node = /*#__PURE__*/function () {
  4257. function Node(opts) {
  4258. if (opts === void 0) {
  4259. opts = {};
  4260. }
  4261. Object.assign(this, opts);
  4262. this.spaces = this.spaces || {};
  4263. this.spaces.before = this.spaces.before || '';
  4264. this.spaces.after = this.spaces.after || '';
  4265. }
  4266. var _proto = Node.prototype;
  4267. _proto.remove = function remove() {
  4268. if (this.parent) {
  4269. this.parent.removeChild(this);
  4270. }
  4271. this.parent = undefined;
  4272. return this;
  4273. };
  4274. _proto.replaceWith = function replaceWith() {
  4275. if (this.parent) {
  4276. for (var index in arguments) {
  4277. this.parent.insertBefore(this, arguments[index]);
  4278. }
  4279. this.remove();
  4280. }
  4281. return this;
  4282. };
  4283. _proto.next = function next() {
  4284. return this.parent.at(this.parent.index(this) + 1);
  4285. };
  4286. _proto.prev = function prev() {
  4287. return this.parent.at(this.parent.index(this) - 1);
  4288. };
  4289. _proto.clone = function clone(overrides) {
  4290. if (overrides === void 0) {
  4291. overrides = {};
  4292. }
  4293. var cloned = cloneNode(this);
  4294. for (var name in overrides) {
  4295. cloned[name] = overrides[name];
  4296. }
  4297. return cloned;
  4298. }
  4299. /**
  4300. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4301. * This allows non standard syntax to be appended to an existing property
  4302. * by specifying the escaped value. By specifying the escaped value,
  4303. * illegal characters are allowed to be directly inserted into css output.
  4304. * @param {string} name the property to set
  4305. * @param {any} value the unescaped value of the property
  4306. * @param {string} valueEscaped optional. the escaped value of the property.
  4307. */;
  4308. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4309. if (!this.raws) {
  4310. this.raws = {};
  4311. }
  4312. var originalValue = this[name];
  4313. var originalEscaped = this.raws[name];
  4314. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4315. if (originalEscaped || valueEscaped !== value) {
  4316. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4317. } else {
  4318. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4319. }
  4320. }
  4321. /**
  4322. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4323. * This allows the escaped value to be specified directly, allowing illegal
  4324. * characters to be directly inserted into css output.
  4325. * @param {string} name the property to set
  4326. * @param {any} value the unescaped value of the property
  4327. * @param {string} valueEscaped the escaped value of the property.
  4328. */;
  4329. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4330. if (!this.raws) {
  4331. this.raws = {};
  4332. }
  4333. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4334. this.raws[name] = valueEscaped;
  4335. }
  4336. /**
  4337. * When you want a value to passed through to CSS directly. This method
  4338. * deletes the corresponding raw value causing the stringifier to fallback
  4339. * to the unescaped value.
  4340. * @param {string} name the property to set.
  4341. * @param {any} value The value that is both escaped and unescaped.
  4342. */;
  4343. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4344. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4345. if (this.raws) {
  4346. delete this.raws[name];
  4347. }
  4348. }
  4349. /**
  4350. *
  4351. * @param {number} line The number (starting with 1)
  4352. * @param {number} column The column number (starting with 1)
  4353. */;
  4354. _proto.isAtPosition = function isAtPosition(line, column) {
  4355. if (this.source && this.source.start && this.source.end) {
  4356. if (this.source.start.line > line) {
  4357. return false;
  4358. }
  4359. if (this.source.end.line < line) {
  4360. return false;
  4361. }
  4362. if (this.source.start.line === line && this.source.start.column > column) {
  4363. return false;
  4364. }
  4365. if (this.source.end.line === line && this.source.end.column < column) {
  4366. return false;
  4367. }
  4368. return true;
  4369. }
  4370. return undefined;
  4371. };
  4372. _proto.stringifyProperty = function stringifyProperty(name) {
  4373. return this.raws && this.raws[name] || this[name];
  4374. };
  4375. _proto.valueToString = function valueToString() {
  4376. return String(this.stringifyProperty("value"));
  4377. };
  4378. _proto.toString = function toString() {
  4379. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4380. };
  4381. _createClass(Node, [{
  4382. key: "rawSpaceBefore",
  4383. get: function get() {
  4384. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4385. if (rawSpace === undefined) {
  4386. rawSpace = this.spaces && this.spaces.before;
  4387. }
  4388. return rawSpace || "";
  4389. },
  4390. set: function set(raw) {
  4391. (0, _util.ensureObject)(this, "raws", "spaces");
  4392. this.raws.spaces.before = raw;
  4393. }
  4394. }, {
  4395. key: "rawSpaceAfter",
  4396. get: function get() {
  4397. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4398. if (rawSpace === undefined) {
  4399. rawSpace = this.spaces.after;
  4400. }
  4401. return rawSpace || "";
  4402. },
  4403. set: function set(raw) {
  4404. (0, _util.ensureObject)(this, "raws", "spaces");
  4405. this.raws.spaces.after = raw;
  4406. }
  4407. }]);
  4408. return Node;
  4409. }();
  4410. exports["default"] = Node;
  4411. module.exports = exports.default;
  4412. } (node$1, node$1.exports));
  4413. var nodeExports = node$1.exports;
  4414. var types$1 = {};
  4415. types$1.__esModule = true;
  4416. types$1.UNIVERSAL = types$1.TAG = types$1.STRING = types$1.SELECTOR = types$1.ROOT = types$1.PSEUDO = types$1.NESTING = types$1.ID = types$1.COMMENT = types$1.COMBINATOR = types$1.CLASS = types$1.ATTRIBUTE = void 0;
  4417. var TAG = 'tag';
  4418. types$1.TAG = TAG;
  4419. var STRING = 'string';
  4420. types$1.STRING = STRING;
  4421. var SELECTOR = 'selector';
  4422. types$1.SELECTOR = SELECTOR;
  4423. var ROOT = 'root';
  4424. types$1.ROOT = ROOT;
  4425. var PSEUDO = 'pseudo';
  4426. types$1.PSEUDO = PSEUDO;
  4427. var NESTING = 'nesting';
  4428. types$1.NESTING = NESTING;
  4429. var ID = 'id';
  4430. types$1.ID = ID;
  4431. var COMMENT = 'comment';
  4432. types$1.COMMENT = COMMENT;
  4433. var COMBINATOR = 'combinator';
  4434. types$1.COMBINATOR = COMBINATOR;
  4435. var CLASS = 'class';
  4436. types$1.CLASS = CLASS;
  4437. var ATTRIBUTE = 'attribute';
  4438. types$1.ATTRIBUTE = ATTRIBUTE;
  4439. var UNIVERSAL = 'universal';
  4440. types$1.UNIVERSAL = UNIVERSAL;
  4441. (function (module, exports) {
  4442. exports.__esModule = true;
  4443. exports["default"] = void 0;
  4444. var _node = _interopRequireDefault(nodeExports);
  4445. var types = _interopRequireWildcard(types$1);
  4446. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  4447. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  4448. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4449. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  4450. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  4451. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  4452. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  4453. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4454. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4455. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4456. var Container = /*#__PURE__*/function (_Node) {
  4457. _inheritsLoose(Container, _Node);
  4458. function Container(opts) {
  4459. var _this;
  4460. _this = _Node.call(this, opts) || this;
  4461. if (!_this.nodes) {
  4462. _this.nodes = [];
  4463. }
  4464. return _this;
  4465. }
  4466. var _proto = Container.prototype;
  4467. _proto.append = function append(selector) {
  4468. selector.parent = this;
  4469. this.nodes.push(selector);
  4470. return this;
  4471. };
  4472. _proto.prepend = function prepend(selector) {
  4473. selector.parent = this;
  4474. this.nodes.unshift(selector);
  4475. return this;
  4476. };
  4477. _proto.at = function at(index) {
  4478. return this.nodes[index];
  4479. };
  4480. _proto.index = function index(child) {
  4481. if (typeof child === 'number') {
  4482. return child;
  4483. }
  4484. return this.nodes.indexOf(child);
  4485. };
  4486. _proto.removeChild = function removeChild(child) {
  4487. child = this.index(child);
  4488. this.at(child).parent = undefined;
  4489. this.nodes.splice(child, 1);
  4490. var index;
  4491. for (var id in this.indexes) {
  4492. index = this.indexes[id];
  4493. if (index >= child) {
  4494. this.indexes[id] = index - 1;
  4495. }
  4496. }
  4497. return this;
  4498. };
  4499. _proto.removeAll = function removeAll() {
  4500. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4501. var node = _step.value;
  4502. node.parent = undefined;
  4503. }
  4504. this.nodes = [];
  4505. return this;
  4506. };
  4507. _proto.empty = function empty() {
  4508. return this.removeAll();
  4509. };
  4510. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4511. newNode.parent = this;
  4512. var oldIndex = this.index(oldNode);
  4513. this.nodes.splice(oldIndex + 1, 0, newNode);
  4514. newNode.parent = this;
  4515. var index;
  4516. for (var id in this.indexes) {
  4517. index = this.indexes[id];
  4518. if (oldIndex <= index) {
  4519. this.indexes[id] = index + 1;
  4520. }
  4521. }
  4522. return this;
  4523. };
  4524. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4525. newNode.parent = this;
  4526. var oldIndex = this.index(oldNode);
  4527. this.nodes.splice(oldIndex, 0, newNode);
  4528. newNode.parent = this;
  4529. var index;
  4530. for (var id in this.indexes) {
  4531. index = this.indexes[id];
  4532. if (index <= oldIndex) {
  4533. this.indexes[id] = index + 1;
  4534. }
  4535. }
  4536. return this;
  4537. };
  4538. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4539. var found = undefined;
  4540. this.each(function (node) {
  4541. if (node.atPosition) {
  4542. var foundChild = node.atPosition(line, col);
  4543. if (foundChild) {
  4544. found = foundChild;
  4545. return false;
  4546. }
  4547. } else if (node.isAtPosition(line, col)) {
  4548. found = node;
  4549. return false;
  4550. }
  4551. });
  4552. return found;
  4553. }
  4554. /**
  4555. * Return the most specific node at the line and column number given.
  4556. * The source location is based on the original parsed location, locations aren't
  4557. * updated as selector nodes are mutated.
  4558. *
  4559. * Note that this location is relative to the location of the first character
  4560. * of the selector, and not the location of the selector in the overall document
  4561. * when used in conjunction with postcss.
  4562. *
  4563. * If not found, returns undefined.
  4564. * @param {number} line The line number of the node to find. (1-based index)
  4565. * @param {number} col The column number of the node to find. (1-based index)
  4566. */;
  4567. _proto.atPosition = function atPosition(line, col) {
  4568. if (this.isAtPosition(line, col)) {
  4569. return this._findChildAtPosition(line, col) || this;
  4570. } else {
  4571. return undefined;
  4572. }
  4573. };
  4574. _proto._inferEndPosition = function _inferEndPosition() {
  4575. if (this.last && this.last.source && this.last.source.end) {
  4576. this.source = this.source || {};
  4577. this.source.end = this.source.end || {};
  4578. Object.assign(this.source.end, this.last.source.end);
  4579. }
  4580. };
  4581. _proto.each = function each(callback) {
  4582. if (!this.lastEach) {
  4583. this.lastEach = 0;
  4584. }
  4585. if (!this.indexes) {
  4586. this.indexes = {};
  4587. }
  4588. this.lastEach++;
  4589. var id = this.lastEach;
  4590. this.indexes[id] = 0;
  4591. if (!this.length) {
  4592. return undefined;
  4593. }
  4594. var index, result;
  4595. while (this.indexes[id] < this.length) {
  4596. index = this.indexes[id];
  4597. result = callback(this.at(index), index);
  4598. if (result === false) {
  4599. break;
  4600. }
  4601. this.indexes[id] += 1;
  4602. }
  4603. delete this.indexes[id];
  4604. if (result === false) {
  4605. return false;
  4606. }
  4607. };
  4608. _proto.walk = function walk(callback) {
  4609. return this.each(function (node, i) {
  4610. var result = callback(node, i);
  4611. if (result !== false && node.length) {
  4612. result = node.walk(callback);
  4613. }
  4614. if (result === false) {
  4615. return false;
  4616. }
  4617. });
  4618. };
  4619. _proto.walkAttributes = function walkAttributes(callback) {
  4620. var _this2 = this;
  4621. return this.walk(function (selector) {
  4622. if (selector.type === types.ATTRIBUTE) {
  4623. return callback.call(_this2, selector);
  4624. }
  4625. });
  4626. };
  4627. _proto.walkClasses = function walkClasses(callback) {
  4628. var _this3 = this;
  4629. return this.walk(function (selector) {
  4630. if (selector.type === types.CLASS) {
  4631. return callback.call(_this3, selector);
  4632. }
  4633. });
  4634. };
  4635. _proto.walkCombinators = function walkCombinators(callback) {
  4636. var _this4 = this;
  4637. return this.walk(function (selector) {
  4638. if (selector.type === types.COMBINATOR) {
  4639. return callback.call(_this4, selector);
  4640. }
  4641. });
  4642. };
  4643. _proto.walkComments = function walkComments(callback) {
  4644. var _this5 = this;
  4645. return this.walk(function (selector) {
  4646. if (selector.type === types.COMMENT) {
  4647. return callback.call(_this5, selector);
  4648. }
  4649. });
  4650. };
  4651. _proto.walkIds = function walkIds(callback) {
  4652. var _this6 = this;
  4653. return this.walk(function (selector) {
  4654. if (selector.type === types.ID) {
  4655. return callback.call(_this6, selector);
  4656. }
  4657. });
  4658. };
  4659. _proto.walkNesting = function walkNesting(callback) {
  4660. var _this7 = this;
  4661. return this.walk(function (selector) {
  4662. if (selector.type === types.NESTING) {
  4663. return callback.call(_this7, selector);
  4664. }
  4665. });
  4666. };
  4667. _proto.walkPseudos = function walkPseudos(callback) {
  4668. var _this8 = this;
  4669. return this.walk(function (selector) {
  4670. if (selector.type === types.PSEUDO) {
  4671. return callback.call(_this8, selector);
  4672. }
  4673. });
  4674. };
  4675. _proto.walkTags = function walkTags(callback) {
  4676. var _this9 = this;
  4677. return this.walk(function (selector) {
  4678. if (selector.type === types.TAG) {
  4679. return callback.call(_this9, selector);
  4680. }
  4681. });
  4682. };
  4683. _proto.walkUniversals = function walkUniversals(callback) {
  4684. var _this10 = this;
  4685. return this.walk(function (selector) {
  4686. if (selector.type === types.UNIVERSAL) {
  4687. return callback.call(_this10, selector);
  4688. }
  4689. });
  4690. };
  4691. _proto.split = function split(callback) {
  4692. var _this11 = this;
  4693. var current = [];
  4694. return this.reduce(function (memo, node, index) {
  4695. var split = callback.call(_this11, node);
  4696. current.push(node);
  4697. if (split) {
  4698. memo.push(current);
  4699. current = [];
  4700. } else if (index === _this11.length - 1) {
  4701. memo.push(current);
  4702. }
  4703. return memo;
  4704. }, []);
  4705. };
  4706. _proto.map = function map(callback) {
  4707. return this.nodes.map(callback);
  4708. };
  4709. _proto.reduce = function reduce(callback, memo) {
  4710. return this.nodes.reduce(callback, memo);
  4711. };
  4712. _proto.every = function every(callback) {
  4713. return this.nodes.every(callback);
  4714. };
  4715. _proto.some = function some(callback) {
  4716. return this.nodes.some(callback);
  4717. };
  4718. _proto.filter = function filter(callback) {
  4719. return this.nodes.filter(callback);
  4720. };
  4721. _proto.sort = function sort(callback) {
  4722. return this.nodes.sort(callback);
  4723. };
  4724. _proto.toString = function toString() {
  4725. return this.map(String).join('');
  4726. };
  4727. _createClass(Container, [{
  4728. key: "first",
  4729. get: function get() {
  4730. return this.at(0);
  4731. }
  4732. }, {
  4733. key: "last",
  4734. get: function get() {
  4735. return this.at(this.length - 1);
  4736. }
  4737. }, {
  4738. key: "length",
  4739. get: function get() {
  4740. return this.nodes.length;
  4741. }
  4742. }]);
  4743. return Container;
  4744. }(_node["default"]);
  4745. exports["default"] = Container;
  4746. module.exports = exports.default;
  4747. } (container, container.exports));
  4748. var containerExports = container.exports;
  4749. (function (module, exports) {
  4750. exports.__esModule = true;
  4751. exports["default"] = void 0;
  4752. var _container = _interopRequireDefault(containerExports);
  4753. var _types = types$1;
  4754. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4755. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  4756. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4757. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4758. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4759. var Root = /*#__PURE__*/function (_Container) {
  4760. _inheritsLoose(Root, _Container);
  4761. function Root(opts) {
  4762. var _this;
  4763. _this = _Container.call(this, opts) || this;
  4764. _this.type = _types.ROOT;
  4765. return _this;
  4766. }
  4767. var _proto = Root.prototype;
  4768. _proto.toString = function toString() {
  4769. var str = this.reduce(function (memo, selector) {
  4770. memo.push(String(selector));
  4771. return memo;
  4772. }, []).join(',');
  4773. return this.trailingComma ? str + ',' : str;
  4774. };
  4775. _proto.error = function error(message, options) {
  4776. if (this._error) {
  4777. return this._error(message, options);
  4778. } else {
  4779. return new Error(message);
  4780. }
  4781. };
  4782. _createClass(Root, [{
  4783. key: "errorGenerator",
  4784. set: function set(handler) {
  4785. this._error = handler;
  4786. }
  4787. }]);
  4788. return Root;
  4789. }(_container["default"]);
  4790. exports["default"] = Root;
  4791. module.exports = exports.default;
  4792. } (root$2, root$2.exports));
  4793. var rootExports = root$2.exports;
  4794. var selector$1 = {exports: {}};
  4795. (function (module, exports) {
  4796. exports.__esModule = true;
  4797. exports["default"] = void 0;
  4798. var _container = _interopRequireDefault(containerExports);
  4799. var _types = types$1;
  4800. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4801. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4802. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4803. var Selector = /*#__PURE__*/function (_Container) {
  4804. _inheritsLoose(Selector, _Container);
  4805. function Selector(opts) {
  4806. var _this;
  4807. _this = _Container.call(this, opts) || this;
  4808. _this.type = _types.SELECTOR;
  4809. return _this;
  4810. }
  4811. return Selector;
  4812. }(_container["default"]);
  4813. exports["default"] = Selector;
  4814. module.exports = exports.default;
  4815. } (selector$1, selector$1.exports));
  4816. var selectorExports = selector$1.exports;
  4817. var className$1 = {exports: {}};
  4818. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4819. var object = {};
  4820. var hasOwnProperty$1 = object.hasOwnProperty;
  4821. var merge$2 = function merge(options, defaults) {
  4822. if (!options) {
  4823. return defaults;
  4824. }
  4825. var result = {};
  4826. for (var key in defaults) {
  4827. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4828. // only recognized option names are used.
  4829. result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
  4830. }
  4831. return result;
  4832. };
  4833. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4834. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4835. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4836. // https://mathiasbynens.be/notes/css-escapes#css
  4837. var cssesc = function cssesc(string, options) {
  4838. options = merge$2(options, cssesc.options);
  4839. if (options.quotes != 'single' && options.quotes != 'double') {
  4840. options.quotes = 'single';
  4841. }
  4842. var quote = options.quotes == 'double' ? '"' : '\'';
  4843. var isIdentifier = options.isIdentifier;
  4844. var firstChar = string.charAt(0);
  4845. var output = '';
  4846. var counter = 0;
  4847. var length = string.length;
  4848. while (counter < length) {
  4849. var character = string.charAt(counter++);
  4850. var codePoint = character.charCodeAt();
  4851. var value = void 0;
  4852. // If it’s not a printable ASCII character…
  4853. if (codePoint < 0x20 || codePoint > 0x7E) {
  4854. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4855. // It’s a high surrogate, and there is a next character.
  4856. var extra = string.charCodeAt(counter++);
  4857. if ((extra & 0xFC00) == 0xDC00) {
  4858. // next character is low surrogate
  4859. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4860. } else {
  4861. // It’s an unmatched surrogate; only append this code unit, in case
  4862. // the next code unit is the high surrogate of a surrogate pair.
  4863. counter--;
  4864. }
  4865. }
  4866. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4867. } else {
  4868. if (options.escapeEverything) {
  4869. if (regexAnySingleEscape.test(character)) {
  4870. value = '\\' + character;
  4871. } else {
  4872. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4873. }
  4874. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4875. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4876. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4877. value = '\\' + character;
  4878. } else {
  4879. value = character;
  4880. }
  4881. }
  4882. output += value;
  4883. }
  4884. if (isIdentifier) {
  4885. if (/^-[-\d]/.test(output)) {
  4886. output = '\\-' + output.slice(1);
  4887. } else if (/\d/.test(firstChar)) {
  4888. output = '\\3' + firstChar + ' ' + output.slice(1);
  4889. }
  4890. }
  4891. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4892. // since they’re redundant. Note that this is only possible if the escape
  4893. // sequence isn’t preceded by an odd number of backslashes.
  4894. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4895. if ($1 && $1.length % 2) {
  4896. // It’s not safe to remove the space, so don’t.
  4897. return $0;
  4898. }
  4899. // Strip the space.
  4900. return ($1 || '') + $2;
  4901. });
  4902. if (!isIdentifier && options.wrap) {
  4903. return quote + output + quote;
  4904. }
  4905. return output;
  4906. };
  4907. // Expose default options (so they can be overridden globally).
  4908. cssesc.options = {
  4909. 'escapeEverything': false,
  4910. 'isIdentifier': false,
  4911. 'quotes': 'single',
  4912. 'wrap': false
  4913. };
  4914. cssesc.version = '3.0.0';
  4915. var cssesc_1 = cssesc;
  4916. (function (module, exports) {
  4917. exports.__esModule = true;
  4918. exports["default"] = void 0;
  4919. var _cssesc = _interopRequireDefault(cssesc_1);
  4920. var _util = util$6;
  4921. var _node = _interopRequireDefault(nodeExports);
  4922. var _types = types$1;
  4923. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4924. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  4925. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4926. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4927. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4928. var ClassName = /*#__PURE__*/function (_Node) {
  4929. _inheritsLoose(ClassName, _Node);
  4930. function ClassName(opts) {
  4931. var _this;
  4932. _this = _Node.call(this, opts) || this;
  4933. _this.type = _types.CLASS;
  4934. _this._constructed = true;
  4935. return _this;
  4936. }
  4937. var _proto = ClassName.prototype;
  4938. _proto.valueToString = function valueToString() {
  4939. return '.' + _Node.prototype.valueToString.call(this);
  4940. };
  4941. _createClass(ClassName, [{
  4942. key: "value",
  4943. get: function get() {
  4944. return this._value;
  4945. },
  4946. set: function set(v) {
  4947. if (this._constructed) {
  4948. var escaped = (0, _cssesc["default"])(v, {
  4949. isIdentifier: true
  4950. });
  4951. if (escaped !== v) {
  4952. (0, _util.ensureObject)(this, "raws");
  4953. this.raws.value = escaped;
  4954. } else if (this.raws) {
  4955. delete this.raws.value;
  4956. }
  4957. }
  4958. this._value = v;
  4959. }
  4960. }]);
  4961. return ClassName;
  4962. }(_node["default"]);
  4963. exports["default"] = ClassName;
  4964. module.exports = exports.default;
  4965. } (className$1, className$1.exports));
  4966. var classNameExports = className$1.exports;
  4967. var comment$2 = {exports: {}};
  4968. (function (module, exports) {
  4969. exports.__esModule = true;
  4970. exports["default"] = void 0;
  4971. var _node = _interopRequireDefault(nodeExports);
  4972. var _types = types$1;
  4973. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4974. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4975. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4976. var Comment = /*#__PURE__*/function (_Node) {
  4977. _inheritsLoose(Comment, _Node);
  4978. function Comment(opts) {
  4979. var _this;
  4980. _this = _Node.call(this, opts) || this;
  4981. _this.type = _types.COMMENT;
  4982. return _this;
  4983. }
  4984. return Comment;
  4985. }(_node["default"]);
  4986. exports["default"] = Comment;
  4987. module.exports = exports.default;
  4988. } (comment$2, comment$2.exports));
  4989. var commentExports = comment$2.exports;
  4990. var id$1 = {exports: {}};
  4991. (function (module, exports) {
  4992. exports.__esModule = true;
  4993. exports["default"] = void 0;
  4994. var _node = _interopRequireDefault(nodeExports);
  4995. var _types = types$1;
  4996. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4997. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4998. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4999. var ID = /*#__PURE__*/function (_Node) {
  5000. _inheritsLoose(ID, _Node);
  5001. function ID(opts) {
  5002. var _this;
  5003. _this = _Node.call(this, opts) || this;
  5004. _this.type = _types.ID;
  5005. return _this;
  5006. }
  5007. var _proto = ID.prototype;
  5008. _proto.valueToString = function valueToString() {
  5009. return '#' + _Node.prototype.valueToString.call(this);
  5010. };
  5011. return ID;
  5012. }(_node["default"]);
  5013. exports["default"] = ID;
  5014. module.exports = exports.default;
  5015. } (id$1, id$1.exports));
  5016. var idExports = id$1.exports;
  5017. var tag$1 = {exports: {}};
  5018. var namespace = {exports: {}};
  5019. (function (module, exports) {
  5020. exports.__esModule = true;
  5021. exports["default"] = void 0;
  5022. var _cssesc = _interopRequireDefault(cssesc_1);
  5023. var _util = util$6;
  5024. var _node = _interopRequireDefault(nodeExports);
  5025. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5026. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  5027. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5028. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5029. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5030. var Namespace = /*#__PURE__*/function (_Node) {
  5031. _inheritsLoose(Namespace, _Node);
  5032. function Namespace() {
  5033. return _Node.apply(this, arguments) || this;
  5034. }
  5035. var _proto = Namespace.prototype;
  5036. _proto.qualifiedName = function qualifiedName(value) {
  5037. if (this.namespace) {
  5038. return this.namespaceString + "|" + value;
  5039. } else {
  5040. return value;
  5041. }
  5042. };
  5043. _proto.valueToString = function valueToString() {
  5044. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5045. };
  5046. _createClass(Namespace, [{
  5047. key: "namespace",
  5048. get: function get() {
  5049. return this._namespace;
  5050. },
  5051. set: function set(namespace) {
  5052. if (namespace === true || namespace === "*" || namespace === "&") {
  5053. this._namespace = namespace;
  5054. if (this.raws) {
  5055. delete this.raws.namespace;
  5056. }
  5057. return;
  5058. }
  5059. var escaped = (0, _cssesc["default"])(namespace, {
  5060. isIdentifier: true
  5061. });
  5062. this._namespace = namespace;
  5063. if (escaped !== namespace) {
  5064. (0, _util.ensureObject)(this, "raws");
  5065. this.raws.namespace = escaped;
  5066. } else if (this.raws) {
  5067. delete this.raws.namespace;
  5068. }
  5069. }
  5070. }, {
  5071. key: "ns",
  5072. get: function get() {
  5073. return this._namespace;
  5074. },
  5075. set: function set(namespace) {
  5076. this.namespace = namespace;
  5077. }
  5078. }, {
  5079. key: "namespaceString",
  5080. get: function get() {
  5081. if (this.namespace) {
  5082. var ns = this.stringifyProperty("namespace");
  5083. if (ns === true) {
  5084. return '';
  5085. } else {
  5086. return ns;
  5087. }
  5088. } else {
  5089. return '';
  5090. }
  5091. }
  5092. }]);
  5093. return Namespace;
  5094. }(_node["default"]);
  5095. exports["default"] = Namespace;
  5096. module.exports = exports.default;
  5097. } (namespace, namespace.exports));
  5098. var namespaceExports = namespace.exports;
  5099. (function (module, exports) {
  5100. exports.__esModule = true;
  5101. exports["default"] = void 0;
  5102. var _namespace = _interopRequireDefault(namespaceExports);
  5103. var _types = types$1;
  5104. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5105. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5106. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5107. var Tag = /*#__PURE__*/function (_Namespace) {
  5108. _inheritsLoose(Tag, _Namespace);
  5109. function Tag(opts) {
  5110. var _this;
  5111. _this = _Namespace.call(this, opts) || this;
  5112. _this.type = _types.TAG;
  5113. return _this;
  5114. }
  5115. return Tag;
  5116. }(_namespace["default"]);
  5117. exports["default"] = Tag;
  5118. module.exports = exports.default;
  5119. } (tag$1, tag$1.exports));
  5120. var tagExports = tag$1.exports;
  5121. var string$1 = {exports: {}};
  5122. (function (module, exports) {
  5123. exports.__esModule = true;
  5124. exports["default"] = void 0;
  5125. var _node = _interopRequireDefault(nodeExports);
  5126. var _types = types$1;
  5127. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5128. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5129. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5130. var String = /*#__PURE__*/function (_Node) {
  5131. _inheritsLoose(String, _Node);
  5132. function String(opts) {
  5133. var _this;
  5134. _this = _Node.call(this, opts) || this;
  5135. _this.type = _types.STRING;
  5136. return _this;
  5137. }
  5138. return String;
  5139. }(_node["default"]);
  5140. exports["default"] = String;
  5141. module.exports = exports.default;
  5142. } (string$1, string$1.exports));
  5143. var stringExports = string$1.exports;
  5144. var pseudo$1 = {exports: {}};
  5145. (function (module, exports) {
  5146. exports.__esModule = true;
  5147. exports["default"] = void 0;
  5148. var _container = _interopRequireDefault(containerExports);
  5149. var _types = types$1;
  5150. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5151. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5152. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5153. var Pseudo = /*#__PURE__*/function (_Container) {
  5154. _inheritsLoose(Pseudo, _Container);
  5155. function Pseudo(opts) {
  5156. var _this;
  5157. _this = _Container.call(this, opts) || this;
  5158. _this.type = _types.PSEUDO;
  5159. return _this;
  5160. }
  5161. var _proto = Pseudo.prototype;
  5162. _proto.toString = function toString() {
  5163. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5164. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5165. };
  5166. return Pseudo;
  5167. }(_container["default"]);
  5168. exports["default"] = Pseudo;
  5169. module.exports = exports.default;
  5170. } (pseudo$1, pseudo$1.exports));
  5171. var pseudoExports = pseudo$1.exports;
  5172. var attribute$1 = {};
  5173. /**
  5174. * For Node.js, simply re-export the core `util.deprecate` function.
  5175. */
  5176. var node = require$$2.deprecate;
  5177. (function (exports) {
  5178. exports.__esModule = true;
  5179. exports["default"] = void 0;
  5180. exports.unescapeValue = unescapeValue;
  5181. var _cssesc = _interopRequireDefault(cssesc_1);
  5182. var _unesc = _interopRequireDefault(unescExports);
  5183. var _namespace = _interopRequireDefault(namespaceExports);
  5184. var _types = types$1;
  5185. var _CSSESC_QUOTE_OPTIONS;
  5186. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5187. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  5188. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5189. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5190. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5191. var deprecate = node;
  5192. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5193. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5194. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5195. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5196. function unescapeValue(value) {
  5197. var deprecatedUsage = false;
  5198. var quoteMark = null;
  5199. var unescaped = value;
  5200. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5201. if (m) {
  5202. quoteMark = m[1];
  5203. unescaped = m[2];
  5204. }
  5205. unescaped = (0, _unesc["default"])(unescaped);
  5206. if (unescaped !== value) {
  5207. deprecatedUsage = true;
  5208. }
  5209. return {
  5210. deprecatedUsage: deprecatedUsage,
  5211. unescaped: unescaped,
  5212. quoteMark: quoteMark
  5213. };
  5214. }
  5215. function handleDeprecatedContructorOpts(opts) {
  5216. if (opts.quoteMark !== undefined) {
  5217. return opts;
  5218. }
  5219. if (opts.value === undefined) {
  5220. return opts;
  5221. }
  5222. warnOfDeprecatedConstructor();
  5223. var _unescapeValue = unescapeValue(opts.value),
  5224. quoteMark = _unescapeValue.quoteMark,
  5225. unescaped = _unescapeValue.unescaped;
  5226. if (!opts.raws) {
  5227. opts.raws = {};
  5228. }
  5229. if (opts.raws.value === undefined) {
  5230. opts.raws.value = opts.value;
  5231. }
  5232. opts.value = unescaped;
  5233. opts.quoteMark = quoteMark;
  5234. return opts;
  5235. }
  5236. var Attribute = /*#__PURE__*/function (_Namespace) {
  5237. _inheritsLoose(Attribute, _Namespace);
  5238. function Attribute(opts) {
  5239. var _this;
  5240. if (opts === void 0) {
  5241. opts = {};
  5242. }
  5243. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5244. _this.type = _types.ATTRIBUTE;
  5245. _this.raws = _this.raws || {};
  5246. Object.defineProperty(_this.raws, 'unquoted', {
  5247. get: deprecate(function () {
  5248. return _this.value;
  5249. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5250. set: deprecate(function () {
  5251. return _this.value;
  5252. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5253. });
  5254. _this._constructed = true;
  5255. return _this;
  5256. }
  5257. /**
  5258. * Returns the Attribute's value quoted such that it would be legal to use
  5259. * in the value of a css file. The original value's quotation setting
  5260. * used for stringification is left unchanged. See `setValue(value, options)`
  5261. * if you want to control the quote settings of a new value for the attribute.
  5262. *
  5263. * You can also change the quotation used for the current value by setting quoteMark.
  5264. *
  5265. * Options:
  5266. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5267. * option is not set, the original value for quoteMark will be used. If
  5268. * indeterminate, a double quote is used. The legal values are:
  5269. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5270. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5271. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5272. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5273. * over the quoteMark option value.
  5274. * * smart {boolean} - if true, will select a quote mark based on the value
  5275. * and the other options specified here. See the `smartQuoteMark()`
  5276. * method.
  5277. **/
  5278. var _proto = Attribute.prototype;
  5279. _proto.getQuotedValue = function getQuotedValue(options) {
  5280. if (options === void 0) {
  5281. options = {};
  5282. }
  5283. var quoteMark = this._determineQuoteMark(options);
  5284. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5285. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5286. return escaped;
  5287. };
  5288. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5289. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5290. }
  5291. /**
  5292. * Set the unescaped value with the specified quotation options. The value
  5293. * provided must not include any wrapping quote marks -- those quotes will
  5294. * be interpreted as part of the value and escaped accordingly.
  5295. */;
  5296. _proto.setValue = function setValue(value, options) {
  5297. if (options === void 0) {
  5298. options = {};
  5299. }
  5300. this._value = value;
  5301. this._quoteMark = this._determineQuoteMark(options);
  5302. this._syncRawValue();
  5303. }
  5304. /**
  5305. * Intelligently select a quoteMark value based on the value's contents. If
  5306. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5307. * mark will be picked that minimizes the number of escapes.
  5308. *
  5309. * If there's no clear winner, the quote mark from these options is used,
  5310. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5311. * true). If the quoteMark is unspecified, a double quote is used.
  5312. *
  5313. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5314. * from the quoteValue method.
  5315. */;
  5316. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5317. var v = this.value;
  5318. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5319. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5320. if (numSingleQuotes + numDoubleQuotes === 0) {
  5321. var escaped = (0, _cssesc["default"])(v, {
  5322. isIdentifier: true
  5323. });
  5324. if (escaped === v) {
  5325. return Attribute.NO_QUOTE;
  5326. } else {
  5327. var pref = this.preferredQuoteMark(options);
  5328. if (pref === Attribute.NO_QUOTE) {
  5329. // pick a quote mark that isn't none and see if it's smaller
  5330. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5331. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5332. var quoteValue = (0, _cssesc["default"])(v, opts);
  5333. if (quoteValue.length < escaped.length) {
  5334. return quote;
  5335. }
  5336. }
  5337. return pref;
  5338. }
  5339. } else if (numDoubleQuotes === numSingleQuotes) {
  5340. return this.preferredQuoteMark(options);
  5341. } else if (numDoubleQuotes < numSingleQuotes) {
  5342. return Attribute.DOUBLE_QUOTE;
  5343. } else {
  5344. return Attribute.SINGLE_QUOTE;
  5345. }
  5346. }
  5347. /**
  5348. * Selects the preferred quote mark based on the options and the current quote mark value.
  5349. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5350. * instead.
  5351. */;
  5352. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5353. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5354. if (quoteMark === undefined) {
  5355. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5356. }
  5357. if (quoteMark === undefined) {
  5358. quoteMark = Attribute.DOUBLE_QUOTE;
  5359. }
  5360. return quoteMark;
  5361. };
  5362. _proto._syncRawValue = function _syncRawValue() {
  5363. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5364. if (rawValue === this._value) {
  5365. if (this.raws) {
  5366. delete this.raws.value;
  5367. }
  5368. } else {
  5369. this.raws.value = rawValue;
  5370. }
  5371. };
  5372. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5373. if (this._constructed) {
  5374. var escaped = (0, _cssesc["default"])(value, {
  5375. isIdentifier: true
  5376. });
  5377. if (escaped !== value) {
  5378. this.raws[prop] = escaped;
  5379. } else {
  5380. delete this.raws[prop];
  5381. }
  5382. }
  5383. };
  5384. _proto._spacesFor = function _spacesFor(name) {
  5385. var attrSpaces = {
  5386. before: '',
  5387. after: ''
  5388. };
  5389. var spaces = this.spaces[name] || {};
  5390. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5391. return Object.assign(attrSpaces, spaces, rawSpaces);
  5392. };
  5393. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5394. if (spaceName === void 0) {
  5395. spaceName = name;
  5396. }
  5397. if (concat === void 0) {
  5398. concat = defaultAttrConcat;
  5399. }
  5400. var attrSpaces = this._spacesFor(spaceName);
  5401. return concat(this.stringifyProperty(name), attrSpaces);
  5402. }
  5403. /**
  5404. * returns the offset of the attribute part specified relative to the
  5405. * start of the node of the output string.
  5406. *
  5407. * * "ns" - alias for "namespace"
  5408. * * "namespace" - the namespace if it exists.
  5409. * * "attribute" - the attribute name
  5410. * * "attributeNS" - the start of the attribute or its namespace
  5411. * * "operator" - the match operator of the attribute
  5412. * * "value" - The value (string or identifier)
  5413. * * "insensitive" - the case insensitivity flag;
  5414. * @param part One of the possible values inside an attribute.
  5415. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5416. */;
  5417. _proto.offsetOf = function offsetOf(name) {
  5418. var count = 1;
  5419. var attributeSpaces = this._spacesFor("attribute");
  5420. count += attributeSpaces.before.length;
  5421. if (name === "namespace" || name === "ns") {
  5422. return this.namespace ? count : -1;
  5423. }
  5424. if (name === "attributeNS") {
  5425. return count;
  5426. }
  5427. count += this.namespaceString.length;
  5428. if (this.namespace) {
  5429. count += 1;
  5430. }
  5431. if (name === "attribute") {
  5432. return count;
  5433. }
  5434. count += this.stringifyProperty("attribute").length;
  5435. count += attributeSpaces.after.length;
  5436. var operatorSpaces = this._spacesFor("operator");
  5437. count += operatorSpaces.before.length;
  5438. var operator = this.stringifyProperty("operator");
  5439. if (name === "operator") {
  5440. return operator ? count : -1;
  5441. }
  5442. count += operator.length;
  5443. count += operatorSpaces.after.length;
  5444. var valueSpaces = this._spacesFor("value");
  5445. count += valueSpaces.before.length;
  5446. var value = this.stringifyProperty("value");
  5447. if (name === "value") {
  5448. return value ? count : -1;
  5449. }
  5450. count += value.length;
  5451. count += valueSpaces.after.length;
  5452. var insensitiveSpaces = this._spacesFor("insensitive");
  5453. count += insensitiveSpaces.before.length;
  5454. if (name === "insensitive") {
  5455. return this.insensitive ? count : -1;
  5456. }
  5457. return -1;
  5458. };
  5459. _proto.toString = function toString() {
  5460. var _this2 = this;
  5461. var selector = [this.rawSpaceBefore, '['];
  5462. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5463. if (this.operator && (this.value || this.value === '')) {
  5464. selector.push(this._stringFor('operator'));
  5465. selector.push(this._stringFor('value'));
  5466. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5467. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5468. attrSpaces.before = " ";
  5469. }
  5470. return defaultAttrConcat(attrValue, attrSpaces);
  5471. }));
  5472. }
  5473. selector.push(']');
  5474. selector.push(this.rawSpaceAfter);
  5475. return selector.join('');
  5476. };
  5477. _createClass(Attribute, [{
  5478. key: "quoted",
  5479. get: function get() {
  5480. var qm = this.quoteMark;
  5481. return qm === "'" || qm === '"';
  5482. },
  5483. set: function set(value) {
  5484. warnOfDeprecatedQuotedAssignment();
  5485. }
  5486. /**
  5487. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5488. * returns `null` if the value is not quoted.
  5489. * returns `undefined` if the quotation state is unknown (this can happen when
  5490. * the attribute is constructed without specifying a quote mark.)
  5491. */
  5492. }, {
  5493. key: "quoteMark",
  5494. get: function get() {
  5495. return this._quoteMark;
  5496. }
  5497. /**
  5498. * Set the quote mark to be used by this attribute's value.
  5499. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5500. * value is updated accordingly.
  5501. *
  5502. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5503. */,
  5504. set: function set(quoteMark) {
  5505. if (!this._constructed) {
  5506. this._quoteMark = quoteMark;
  5507. return;
  5508. }
  5509. if (this._quoteMark !== quoteMark) {
  5510. this._quoteMark = quoteMark;
  5511. this._syncRawValue();
  5512. }
  5513. }
  5514. }, {
  5515. key: "qualifiedAttribute",
  5516. get: function get() {
  5517. return this.qualifiedName(this.raws.attribute || this.attribute);
  5518. }
  5519. }, {
  5520. key: "insensitiveFlag",
  5521. get: function get() {
  5522. return this.insensitive ? 'i' : '';
  5523. }
  5524. }, {
  5525. key: "value",
  5526. get: function get() {
  5527. return this._value;
  5528. },
  5529. set:
  5530. /**
  5531. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5532. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5533. * is unescaped during parsing and any quote marks are removed.
  5534. *
  5535. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5536. * a deprecation warning is raised when the new value contains any characters that would
  5537. * require escaping (including if it contains wrapped quotes).
  5538. *
  5539. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5540. * how the new value is quoted.
  5541. */
  5542. function set(v) {
  5543. if (this._constructed) {
  5544. var _unescapeValue2 = unescapeValue(v),
  5545. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5546. unescaped = _unescapeValue2.unescaped,
  5547. quoteMark = _unescapeValue2.quoteMark;
  5548. if (deprecatedUsage) {
  5549. warnOfDeprecatedValueAssignment();
  5550. }
  5551. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5552. return;
  5553. }
  5554. this._value = unescaped;
  5555. this._quoteMark = quoteMark;
  5556. this._syncRawValue();
  5557. } else {
  5558. this._value = v;
  5559. }
  5560. }
  5561. }, {
  5562. key: "insensitive",
  5563. get: function get() {
  5564. return this._insensitive;
  5565. }
  5566. /**
  5567. * Set the case insensitive flag.
  5568. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5569. * of the attribute is updated accordingly.
  5570. *
  5571. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5572. */,
  5573. set: function set(insensitive) {
  5574. if (!insensitive) {
  5575. this._insensitive = false;
  5576. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5577. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5578. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5579. this.raws.insensitiveFlag = undefined;
  5580. }
  5581. }
  5582. this._insensitive = insensitive;
  5583. }
  5584. }, {
  5585. key: "attribute",
  5586. get: function get() {
  5587. return this._attribute;
  5588. },
  5589. set: function set(name) {
  5590. this._handleEscapes("attribute", name);
  5591. this._attribute = name;
  5592. }
  5593. }]);
  5594. return Attribute;
  5595. }(_namespace["default"]);
  5596. exports["default"] = Attribute;
  5597. Attribute.NO_QUOTE = null;
  5598. Attribute.SINGLE_QUOTE = "'";
  5599. Attribute.DOUBLE_QUOTE = '"';
  5600. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5601. "'": {
  5602. quotes: 'single',
  5603. wrap: true
  5604. },
  5605. '"': {
  5606. quotes: 'double',
  5607. wrap: true
  5608. }
  5609. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5610. isIdentifier: true
  5611. }, _CSSESC_QUOTE_OPTIONS);
  5612. function defaultAttrConcat(attrValue, attrSpaces) {
  5613. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5614. }
  5615. } (attribute$1));
  5616. var universal$1 = {exports: {}};
  5617. (function (module, exports) {
  5618. exports.__esModule = true;
  5619. exports["default"] = void 0;
  5620. var _namespace = _interopRequireDefault(namespaceExports);
  5621. var _types = types$1;
  5622. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5623. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5624. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5625. var Universal = /*#__PURE__*/function (_Namespace) {
  5626. _inheritsLoose(Universal, _Namespace);
  5627. function Universal(opts) {
  5628. var _this;
  5629. _this = _Namespace.call(this, opts) || this;
  5630. _this.type = _types.UNIVERSAL;
  5631. _this.value = '*';
  5632. return _this;
  5633. }
  5634. return Universal;
  5635. }(_namespace["default"]);
  5636. exports["default"] = Universal;
  5637. module.exports = exports.default;
  5638. } (universal$1, universal$1.exports));
  5639. var universalExports = universal$1.exports;
  5640. var combinator$2 = {exports: {}};
  5641. (function (module, exports) {
  5642. exports.__esModule = true;
  5643. exports["default"] = void 0;
  5644. var _node = _interopRequireDefault(nodeExports);
  5645. var _types = types$1;
  5646. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5647. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5648. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5649. var Combinator = /*#__PURE__*/function (_Node) {
  5650. _inheritsLoose(Combinator, _Node);
  5651. function Combinator(opts) {
  5652. var _this;
  5653. _this = _Node.call(this, opts) || this;
  5654. _this.type = _types.COMBINATOR;
  5655. return _this;
  5656. }
  5657. return Combinator;
  5658. }(_node["default"]);
  5659. exports["default"] = Combinator;
  5660. module.exports = exports.default;
  5661. } (combinator$2, combinator$2.exports));
  5662. var combinatorExports = combinator$2.exports;
  5663. var nesting$1 = {exports: {}};
  5664. (function (module, exports) {
  5665. exports.__esModule = true;
  5666. exports["default"] = void 0;
  5667. var _node = _interopRequireDefault(nodeExports);
  5668. var _types = types$1;
  5669. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5670. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5671. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5672. var Nesting = /*#__PURE__*/function (_Node) {
  5673. _inheritsLoose(Nesting, _Node);
  5674. function Nesting(opts) {
  5675. var _this;
  5676. _this = _Node.call(this, opts) || this;
  5677. _this.type = _types.NESTING;
  5678. _this.value = '&';
  5679. return _this;
  5680. }
  5681. return Nesting;
  5682. }(_node["default"]);
  5683. exports["default"] = Nesting;
  5684. module.exports = exports.default;
  5685. } (nesting$1, nesting$1.exports));
  5686. var nestingExports = nesting$1.exports;
  5687. var sortAscending = {exports: {}};
  5688. (function (module, exports) {
  5689. exports.__esModule = true;
  5690. exports["default"] = sortAscending;
  5691. function sortAscending(list) {
  5692. return list.sort(function (a, b) {
  5693. return a - b;
  5694. });
  5695. }
  5696. module.exports = exports.default;
  5697. } (sortAscending, sortAscending.exports));
  5698. var sortAscendingExports = sortAscending.exports;
  5699. var tokenize = {};
  5700. var tokenTypes = {};
  5701. tokenTypes.__esModule = true;
  5702. tokenTypes.word = tokenTypes.tilde = tokenTypes.tab = tokenTypes.str = tokenTypes.space = tokenTypes.slash = tokenTypes.singleQuote = tokenTypes.semicolon = tokenTypes.plus = tokenTypes.pipe = tokenTypes.openSquare = tokenTypes.openParenthesis = tokenTypes.newline = tokenTypes.greaterThan = tokenTypes.feed = tokenTypes.equals = tokenTypes.doubleQuote = tokenTypes.dollar = tokenTypes.cr = tokenTypes.comment = tokenTypes.comma = tokenTypes.combinator = tokenTypes.colon = tokenTypes.closeSquare = tokenTypes.closeParenthesis = tokenTypes.caret = tokenTypes.bang = tokenTypes.backslash = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0;
  5703. var ampersand = 38; // `&`.charCodeAt(0);
  5704. tokenTypes.ampersand = ampersand;
  5705. var asterisk = 42; // `*`.charCodeAt(0);
  5706. tokenTypes.asterisk = asterisk;
  5707. var at = 64; // `@`.charCodeAt(0);
  5708. tokenTypes.at = at;
  5709. var comma$1 = 44; // `,`.charCodeAt(0);
  5710. tokenTypes.comma = comma$1;
  5711. var colon$1 = 58; // `:`.charCodeAt(0);
  5712. tokenTypes.colon = colon$1;
  5713. var semicolon = 59; // `;`.charCodeAt(0);
  5714. tokenTypes.semicolon = semicolon;
  5715. var openParenthesis = 40; // `(`.charCodeAt(0);
  5716. tokenTypes.openParenthesis = openParenthesis;
  5717. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5718. tokenTypes.closeParenthesis = closeParenthesis;
  5719. var openSquare = 91; // `[`.charCodeAt(0);
  5720. tokenTypes.openSquare = openSquare;
  5721. var closeSquare = 93; // `]`.charCodeAt(0);
  5722. tokenTypes.closeSquare = closeSquare;
  5723. var dollar = 36; // `$`.charCodeAt(0);
  5724. tokenTypes.dollar = dollar;
  5725. var tilde = 126; // `~`.charCodeAt(0);
  5726. tokenTypes.tilde = tilde;
  5727. var caret = 94; // `^`.charCodeAt(0);
  5728. tokenTypes.caret = caret;
  5729. var plus$1 = 43; // `+`.charCodeAt(0);
  5730. tokenTypes.plus = plus$1;
  5731. var equals = 61; // `=`.charCodeAt(0);
  5732. tokenTypes.equals = equals;
  5733. var pipe = 124; // `|`.charCodeAt(0);
  5734. tokenTypes.pipe = pipe;
  5735. var greaterThan = 62; // `>`.charCodeAt(0);
  5736. tokenTypes.greaterThan = greaterThan;
  5737. var space = 32; // ` `.charCodeAt(0);
  5738. tokenTypes.space = space;
  5739. var singleQuote$1 = 39; // `'`.charCodeAt(0);
  5740. tokenTypes.singleQuote = singleQuote$1;
  5741. var doubleQuote$1 = 34; // `"`.charCodeAt(0);
  5742. tokenTypes.doubleQuote = doubleQuote$1;
  5743. var slash$1 = 47; // `/`.charCodeAt(0);
  5744. tokenTypes.slash = slash$1;
  5745. var bang = 33; // `!`.charCodeAt(0);
  5746. tokenTypes.bang = bang;
  5747. var backslash$1 = 92; // '\\'.charCodeAt(0);
  5748. tokenTypes.backslash = backslash$1;
  5749. var cr = 13; // '\r'.charCodeAt(0);
  5750. tokenTypes.cr = cr;
  5751. var feed = 12; // '\f'.charCodeAt(0);
  5752. tokenTypes.feed = feed;
  5753. var newline = 10; // '\n'.charCodeAt(0);
  5754. tokenTypes.newline = newline;
  5755. var tab = 9; // '\t'.charCodeAt(0);
  5756. // Expose aliases primarily for readability.
  5757. tokenTypes.tab = tab;
  5758. var str = singleQuote$1;
  5759. // No good single character representation!
  5760. tokenTypes.str = str;
  5761. var comment$1 = -1;
  5762. tokenTypes.comment = comment$1;
  5763. var word = -2;
  5764. tokenTypes.word = word;
  5765. var combinator$1 = -3;
  5766. tokenTypes.combinator = combinator$1;
  5767. (function (exports) {
  5768. exports.__esModule = true;
  5769. exports.FIELDS = void 0;
  5770. exports["default"] = tokenize;
  5771. var t = _interopRequireWildcard(tokenTypes);
  5772. var _unescapable, _wordDelimiters;
  5773. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  5774. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  5775. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5776. var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
  5777. var hex = {};
  5778. var hexChars = "0123456789abcdefABCDEF";
  5779. for (var i = 0; i < hexChars.length; i++) {
  5780. hex[hexChars.charCodeAt(i)] = true;
  5781. }
  5782. /**
  5783. * Returns the last index of the bar css word
  5784. * @param {string} css The string in which the word begins
  5785. * @param {number} start The index into the string where word's first letter occurs
  5786. */
  5787. function consumeWord(css, start) {
  5788. var next = start;
  5789. var code;
  5790. do {
  5791. code = css.charCodeAt(next);
  5792. if (wordDelimiters[code]) {
  5793. return next - 1;
  5794. } else if (code === t.backslash) {
  5795. next = consumeEscape(css, next) + 1;
  5796. } else {
  5797. // All other characters are part of the word
  5798. next++;
  5799. }
  5800. } while (next < css.length);
  5801. return next - 1;
  5802. }
  5803. /**
  5804. * Returns the last index of the escape sequence
  5805. * @param {string} css The string in which the sequence begins
  5806. * @param {number} start The index into the string where escape character (`\`) occurs.
  5807. */
  5808. function consumeEscape(css, start) {
  5809. var next = start;
  5810. var code = css.charCodeAt(next + 1);
  5811. if (unescapable[code]) ; else if (hex[code]) {
  5812. var hexDigits = 0;
  5813. // consume up to 6 hex chars
  5814. do {
  5815. next++;
  5816. hexDigits++;
  5817. code = css.charCodeAt(next + 1);
  5818. } while (hex[code] && hexDigits < 6);
  5819. // if fewer than 6 hex chars, a trailing space ends the escape
  5820. if (hexDigits < 6 && code === t.space) {
  5821. next++;
  5822. }
  5823. } else {
  5824. // the next char is part of the current word
  5825. next++;
  5826. }
  5827. return next;
  5828. }
  5829. var FIELDS = {
  5830. TYPE: 0,
  5831. START_LINE: 1,
  5832. START_COL: 2,
  5833. END_LINE: 3,
  5834. END_COL: 4,
  5835. START_POS: 5,
  5836. END_POS: 6
  5837. };
  5838. exports.FIELDS = FIELDS;
  5839. function tokenize(input) {
  5840. var tokens = [];
  5841. var css = input.css.valueOf();
  5842. var _css = css,
  5843. length = _css.length;
  5844. var offset = -1;
  5845. var line = 1;
  5846. var start = 0;
  5847. var end = 0;
  5848. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5849. function unclosed(what, fix) {
  5850. if (input.safe) {
  5851. // fyi: this is never set to true.
  5852. css += fix;
  5853. next = css.length - 1;
  5854. } else {
  5855. throw input.error('Unclosed ' + what, line, start - offset, start);
  5856. }
  5857. }
  5858. while (start < length) {
  5859. code = css.charCodeAt(start);
  5860. if (code === t.newline) {
  5861. offset = start;
  5862. line += 1;
  5863. }
  5864. switch (code) {
  5865. case t.space:
  5866. case t.tab:
  5867. case t.newline:
  5868. case t.cr:
  5869. case t.feed:
  5870. next = start;
  5871. do {
  5872. next += 1;
  5873. code = css.charCodeAt(next);
  5874. if (code === t.newline) {
  5875. offset = next;
  5876. line += 1;
  5877. }
  5878. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  5879. tokenType = t.space;
  5880. endLine = line;
  5881. endColumn = next - offset - 1;
  5882. end = next;
  5883. break;
  5884. case t.plus:
  5885. case t.greaterThan:
  5886. case t.tilde:
  5887. case t.pipe:
  5888. next = start;
  5889. do {
  5890. next += 1;
  5891. code = css.charCodeAt(next);
  5892. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  5893. tokenType = t.combinator;
  5894. endLine = line;
  5895. endColumn = start - offset;
  5896. end = next;
  5897. break;
  5898. // Consume these characters as single tokens.
  5899. case t.asterisk:
  5900. case t.ampersand:
  5901. case t.bang:
  5902. case t.comma:
  5903. case t.equals:
  5904. case t.dollar:
  5905. case t.caret:
  5906. case t.openSquare:
  5907. case t.closeSquare:
  5908. case t.colon:
  5909. case t.semicolon:
  5910. case t.openParenthesis:
  5911. case t.closeParenthesis:
  5912. next = start;
  5913. tokenType = code;
  5914. endLine = line;
  5915. endColumn = start - offset;
  5916. end = next + 1;
  5917. break;
  5918. case t.singleQuote:
  5919. case t.doubleQuote:
  5920. quote = code === t.singleQuote ? "'" : '"';
  5921. next = start;
  5922. do {
  5923. escaped = false;
  5924. next = css.indexOf(quote, next + 1);
  5925. if (next === -1) {
  5926. unclosed('quote', quote);
  5927. }
  5928. escapePos = next;
  5929. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  5930. escapePos -= 1;
  5931. escaped = !escaped;
  5932. }
  5933. } while (escaped);
  5934. tokenType = t.str;
  5935. endLine = line;
  5936. endColumn = start - offset;
  5937. end = next + 1;
  5938. break;
  5939. default:
  5940. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  5941. next = css.indexOf('*/', start + 2) + 1;
  5942. if (next === 0) {
  5943. unclosed('comment', '*/');
  5944. }
  5945. content = css.slice(start, next + 1);
  5946. lines = content.split('\n');
  5947. last = lines.length - 1;
  5948. if (last > 0) {
  5949. nextLine = line + last;
  5950. nextOffset = next - lines[last].length;
  5951. } else {
  5952. nextLine = line;
  5953. nextOffset = offset;
  5954. }
  5955. tokenType = t.comment;
  5956. line = nextLine;
  5957. endLine = nextLine;
  5958. endColumn = next - nextOffset;
  5959. } else if (code === t.slash) {
  5960. next = start;
  5961. tokenType = code;
  5962. endLine = line;
  5963. endColumn = start - offset;
  5964. end = next + 1;
  5965. } else {
  5966. next = consumeWord(css, start);
  5967. tokenType = t.word;
  5968. endLine = line;
  5969. endColumn = next - offset;
  5970. }
  5971. end = next + 1;
  5972. break;
  5973. }
  5974. // Ensure that the token structure remains consistent
  5975. tokens.push([tokenType,
  5976. // [0] Token type
  5977. line,
  5978. // [1] Starting line
  5979. start - offset,
  5980. // [2] Starting column
  5981. endLine,
  5982. // [3] Ending line
  5983. endColumn,
  5984. // [4] Ending column
  5985. start,
  5986. // [5] Start position / Source index
  5987. end // [6] End position
  5988. ]);
  5989. // Reset offset for the next token
  5990. if (nextOffset) {
  5991. offset = nextOffset;
  5992. nextOffset = null;
  5993. }
  5994. start = end;
  5995. }
  5996. return tokens;
  5997. }
  5998. } (tokenize));
  5999. (function (module, exports) {
  6000. exports.__esModule = true;
  6001. exports["default"] = void 0;
  6002. var _root = _interopRequireDefault(rootExports);
  6003. var _selector = _interopRequireDefault(selectorExports);
  6004. var _className = _interopRequireDefault(classNameExports);
  6005. var _comment = _interopRequireDefault(commentExports);
  6006. var _id = _interopRequireDefault(idExports);
  6007. var _tag = _interopRequireDefault(tagExports);
  6008. var _string = _interopRequireDefault(stringExports);
  6009. var _pseudo = _interopRequireDefault(pseudoExports);
  6010. var _attribute = _interopRequireWildcard(attribute$1);
  6011. var _universal = _interopRequireDefault(universalExports);
  6012. var _combinator = _interopRequireDefault(combinatorExports);
  6013. var _nesting = _interopRequireDefault(nestingExports);
  6014. var _sortAscending = _interopRequireDefault(sortAscendingExports);
  6015. var _tokenize = _interopRequireWildcard(tokenize);
  6016. var tokens = _interopRequireWildcard(tokenTypes);
  6017. var types = _interopRequireWildcard(types$1);
  6018. var _util = util$6;
  6019. var _WHITESPACE_TOKENS, _Object$assign;
  6020. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  6021. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  6022. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6023. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  6024. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6025. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  6026. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6027. function tokenStart(token) {
  6028. return {
  6029. line: token[_tokenize.FIELDS.START_LINE],
  6030. column: token[_tokenize.FIELDS.START_COL]
  6031. };
  6032. }
  6033. function tokenEnd(token) {
  6034. return {
  6035. line: token[_tokenize.FIELDS.END_LINE],
  6036. column: token[_tokenize.FIELDS.END_COL]
  6037. };
  6038. }
  6039. function getSource(startLine, startColumn, endLine, endColumn) {
  6040. return {
  6041. start: {
  6042. line: startLine,
  6043. column: startColumn
  6044. },
  6045. end: {
  6046. line: endLine,
  6047. column: endColumn
  6048. }
  6049. };
  6050. }
  6051. function getTokenSource(token) {
  6052. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6053. }
  6054. function getTokenSourceSpan(startToken, endToken) {
  6055. if (!startToken) {
  6056. return undefined;
  6057. }
  6058. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6059. }
  6060. function unescapeProp(node, prop) {
  6061. var value = node[prop];
  6062. if (typeof value !== "string") {
  6063. return;
  6064. }
  6065. if (value.indexOf("\\") !== -1) {
  6066. (0, _util.ensureObject)(node, 'raws');
  6067. node[prop] = (0, _util.unesc)(value);
  6068. if (node.raws[prop] === undefined) {
  6069. node.raws[prop] = value;
  6070. }
  6071. }
  6072. return node;
  6073. }
  6074. function indexesOf(array, item) {
  6075. var i = -1;
  6076. var indexes = [];
  6077. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6078. indexes.push(i);
  6079. }
  6080. return indexes;
  6081. }
  6082. function uniqs() {
  6083. var list = Array.prototype.concat.apply([], arguments);
  6084. return list.filter(function (item, i) {
  6085. return i === list.indexOf(item);
  6086. });
  6087. }
  6088. var Parser = /*#__PURE__*/function () {
  6089. function Parser(rule, options) {
  6090. if (options === void 0) {
  6091. options = {};
  6092. }
  6093. this.rule = rule;
  6094. this.options = Object.assign({
  6095. lossy: false,
  6096. safe: false
  6097. }, options);
  6098. this.position = 0;
  6099. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6100. this.tokens = (0, _tokenize["default"])({
  6101. css: this.css,
  6102. error: this._errorGenerator(),
  6103. safe: this.options.safe
  6104. });
  6105. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6106. this.root = new _root["default"]({
  6107. source: rootSource
  6108. });
  6109. this.root.errorGenerator = this._errorGenerator();
  6110. var selector = new _selector["default"]({
  6111. source: {
  6112. start: {
  6113. line: 1,
  6114. column: 1
  6115. }
  6116. }
  6117. });
  6118. this.root.append(selector);
  6119. this.current = selector;
  6120. this.loop();
  6121. }
  6122. var _proto = Parser.prototype;
  6123. _proto._errorGenerator = function _errorGenerator() {
  6124. var _this = this;
  6125. return function (message, errorOptions) {
  6126. if (typeof _this.rule === 'string') {
  6127. return new Error(message);
  6128. }
  6129. return _this.rule.error(message, errorOptions);
  6130. };
  6131. };
  6132. _proto.attribute = function attribute() {
  6133. var attr = [];
  6134. var startingToken = this.currToken;
  6135. this.position++;
  6136. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6137. attr.push(this.currToken);
  6138. this.position++;
  6139. }
  6140. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6141. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6142. }
  6143. var len = attr.length;
  6144. var node = {
  6145. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6146. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6147. };
  6148. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6149. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6150. }
  6151. var pos = 0;
  6152. var spaceBefore = '';
  6153. var commentBefore = '';
  6154. var lastAdded = null;
  6155. var spaceAfterMeaningfulToken = false;
  6156. while (pos < len) {
  6157. var token = attr[pos];
  6158. var content = this.content(token);
  6159. var next = attr[pos + 1];
  6160. switch (token[_tokenize.FIELDS.TYPE]) {
  6161. case tokens.space:
  6162. // if (
  6163. // len === 1 ||
  6164. // pos === 0 && this.content(next) === '|'
  6165. // ) {
  6166. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6167. // }
  6168. spaceAfterMeaningfulToken = true;
  6169. if (this.options.lossy) {
  6170. break;
  6171. }
  6172. if (lastAdded) {
  6173. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6174. var prevContent = node.spaces[lastAdded].after || '';
  6175. node.spaces[lastAdded].after = prevContent + content;
  6176. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6177. if (existingComment) {
  6178. node.raws.spaces[lastAdded].after = existingComment + content;
  6179. }
  6180. } else {
  6181. spaceBefore = spaceBefore + content;
  6182. commentBefore = commentBefore + content;
  6183. }
  6184. break;
  6185. case tokens.asterisk:
  6186. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6187. node.operator = content;
  6188. lastAdded = 'operator';
  6189. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6190. if (spaceBefore) {
  6191. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6192. node.spaces.attribute.before = spaceBefore;
  6193. spaceBefore = '';
  6194. }
  6195. if (commentBefore) {
  6196. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6197. node.raws.spaces.attribute.before = spaceBefore;
  6198. commentBefore = '';
  6199. }
  6200. node.namespace = (node.namespace || "") + content;
  6201. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6202. if (rawValue) {
  6203. node.raws.namespace += content;
  6204. }
  6205. lastAdded = 'namespace';
  6206. }
  6207. spaceAfterMeaningfulToken = false;
  6208. break;
  6209. case tokens.dollar:
  6210. if (lastAdded === "value") {
  6211. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6212. node.value += "$";
  6213. if (oldRawValue) {
  6214. node.raws.value = oldRawValue + "$";
  6215. }
  6216. break;
  6217. }
  6218. // Falls through
  6219. case tokens.caret:
  6220. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6221. node.operator = content;
  6222. lastAdded = 'operator';
  6223. }
  6224. spaceAfterMeaningfulToken = false;
  6225. break;
  6226. case tokens.combinator:
  6227. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6228. node.operator = content;
  6229. lastAdded = 'operator';
  6230. }
  6231. if (content !== '|') {
  6232. spaceAfterMeaningfulToken = false;
  6233. break;
  6234. }
  6235. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6236. node.operator = content;
  6237. lastAdded = 'operator';
  6238. } else if (!node.namespace && !node.attribute) {
  6239. node.namespace = true;
  6240. }
  6241. spaceAfterMeaningfulToken = false;
  6242. break;
  6243. case tokens.word:
  6244. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6245. // this look-ahead probably fails with comment nodes involved.
  6246. !node.operator && !node.namespace) {
  6247. node.namespace = content;
  6248. lastAdded = 'namespace';
  6249. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6250. if (spaceBefore) {
  6251. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6252. node.spaces.attribute.before = spaceBefore;
  6253. spaceBefore = '';
  6254. }
  6255. if (commentBefore) {
  6256. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6257. node.raws.spaces.attribute.before = commentBefore;
  6258. commentBefore = '';
  6259. }
  6260. node.attribute = (node.attribute || "") + content;
  6261. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6262. if (_rawValue) {
  6263. node.raws.attribute += content;
  6264. }
  6265. lastAdded = 'attribute';
  6266. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6267. var _unescaped = (0, _util.unesc)(content);
  6268. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6269. var oldValue = node.value || '';
  6270. node.value = oldValue + _unescaped;
  6271. node.quoteMark = null;
  6272. if (_unescaped !== content || _oldRawValue) {
  6273. (0, _util.ensureObject)(node, 'raws');
  6274. node.raws.value = (_oldRawValue || oldValue) + content;
  6275. }
  6276. lastAdded = 'value';
  6277. } else {
  6278. var insensitive = content === 'i' || content === "I";
  6279. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6280. node.insensitive = insensitive;
  6281. if (!insensitive || content === "I") {
  6282. (0, _util.ensureObject)(node, 'raws');
  6283. node.raws.insensitiveFlag = content;
  6284. }
  6285. lastAdded = 'insensitive';
  6286. if (spaceBefore) {
  6287. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6288. node.spaces.insensitive.before = spaceBefore;
  6289. spaceBefore = '';
  6290. }
  6291. if (commentBefore) {
  6292. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6293. node.raws.spaces.insensitive.before = commentBefore;
  6294. commentBefore = '';
  6295. }
  6296. } else if (node.value || node.value === '') {
  6297. lastAdded = 'value';
  6298. node.value += content;
  6299. if (node.raws.value) {
  6300. node.raws.value += content;
  6301. }
  6302. }
  6303. }
  6304. spaceAfterMeaningfulToken = false;
  6305. break;
  6306. case tokens.str:
  6307. if (!node.attribute || !node.operator) {
  6308. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6309. index: token[_tokenize.FIELDS.START_POS]
  6310. });
  6311. }
  6312. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6313. unescaped = _unescapeValue.unescaped,
  6314. quoteMark = _unescapeValue.quoteMark;
  6315. node.value = unescaped;
  6316. node.quoteMark = quoteMark;
  6317. lastAdded = 'value';
  6318. (0, _util.ensureObject)(node, 'raws');
  6319. node.raws.value = content;
  6320. spaceAfterMeaningfulToken = false;
  6321. break;
  6322. case tokens.equals:
  6323. if (!node.attribute) {
  6324. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6325. }
  6326. if (node.value) {
  6327. return this.error('Unexpected "=" found; an operator was already defined.', {
  6328. index: token[_tokenize.FIELDS.START_POS]
  6329. });
  6330. }
  6331. node.operator = node.operator ? node.operator + content : content;
  6332. lastAdded = 'operator';
  6333. spaceAfterMeaningfulToken = false;
  6334. break;
  6335. case tokens.comment:
  6336. if (lastAdded) {
  6337. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6338. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6339. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6340. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6341. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6342. } else {
  6343. var lastValue = node[lastAdded] || '';
  6344. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6345. (0, _util.ensureObject)(node, 'raws');
  6346. node.raws[lastAdded] = rawLastValue + content;
  6347. }
  6348. } else {
  6349. commentBefore = commentBefore + content;
  6350. }
  6351. break;
  6352. default:
  6353. return this.error("Unexpected \"" + content + "\" found.", {
  6354. index: token[_tokenize.FIELDS.START_POS]
  6355. });
  6356. }
  6357. pos++;
  6358. }
  6359. unescapeProp(node, "attribute");
  6360. unescapeProp(node, "namespace");
  6361. this.newNode(new _attribute["default"](node));
  6362. this.position++;
  6363. }
  6364. /**
  6365. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6366. * if the token position is negative, all remaining tokens are consumed.
  6367. *
  6368. * This returns an array containing a single string node if all whitespace,
  6369. * otherwise an array of comment nodes with space before and after.
  6370. *
  6371. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6372. * a previous node's space metadata.
  6373. *
  6374. * In lossy mode, this returns only comments.
  6375. */;
  6376. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6377. if (stopPosition < 0) {
  6378. stopPosition = this.tokens.length;
  6379. }
  6380. var startPosition = this.position;
  6381. var nodes = [];
  6382. var space = "";
  6383. var lastComment = undefined;
  6384. do {
  6385. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6386. if (!this.options.lossy) {
  6387. space += this.content();
  6388. }
  6389. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6390. var spaces = {};
  6391. if (space) {
  6392. spaces.before = space;
  6393. space = "";
  6394. }
  6395. lastComment = new _comment["default"]({
  6396. value: this.content(),
  6397. source: getTokenSource(this.currToken),
  6398. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6399. spaces: spaces
  6400. });
  6401. nodes.push(lastComment);
  6402. }
  6403. } while (++this.position < stopPosition);
  6404. if (space) {
  6405. if (lastComment) {
  6406. lastComment.spaces.after = space;
  6407. } else if (!this.options.lossy) {
  6408. var firstToken = this.tokens[startPosition];
  6409. var lastToken = this.tokens[this.position - 1];
  6410. nodes.push(new _string["default"]({
  6411. value: '',
  6412. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6413. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6414. spaces: {
  6415. before: space,
  6416. after: ''
  6417. }
  6418. }));
  6419. }
  6420. }
  6421. return nodes;
  6422. }
  6423. /**
  6424. *
  6425. * @param {*} nodes
  6426. */;
  6427. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6428. var _this2 = this;
  6429. if (requiredSpace === void 0) {
  6430. requiredSpace = false;
  6431. }
  6432. var space = "";
  6433. var rawSpace = "";
  6434. nodes.forEach(function (n) {
  6435. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6436. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6437. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6438. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6439. });
  6440. if (rawSpace === space) {
  6441. rawSpace = undefined;
  6442. }
  6443. var result = {
  6444. space: space,
  6445. rawSpace: rawSpace
  6446. };
  6447. return result;
  6448. };
  6449. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6450. if (position === void 0) {
  6451. position = this.position;
  6452. }
  6453. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  6454. };
  6455. _proto.namedCombinator = function namedCombinator() {
  6456. if (this.isNamedCombinator()) {
  6457. var nameRaw = this.content(this.tokens[this.position + 1]);
  6458. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6459. var raws = {};
  6460. if (name !== nameRaw) {
  6461. raws.value = "/" + nameRaw + "/";
  6462. }
  6463. var node = new _combinator["default"]({
  6464. value: "/" + name + "/",
  6465. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  6466. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6467. raws: raws
  6468. });
  6469. this.position = this.position + 3;
  6470. return node;
  6471. } else {
  6472. this.unexpected();
  6473. }
  6474. };
  6475. _proto.combinator = function combinator() {
  6476. var _this3 = this;
  6477. if (this.content() === '|') {
  6478. return this.namespace();
  6479. }
  6480. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6481. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6482. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  6483. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6484. if (nodes.length > 0) {
  6485. var last = this.current.last;
  6486. if (last) {
  6487. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6488. space = _this$convertWhitespa.space,
  6489. rawSpace = _this$convertWhitespa.rawSpace;
  6490. if (rawSpace !== undefined) {
  6491. last.rawSpaceAfter += rawSpace;
  6492. }
  6493. last.spaces.after += space;
  6494. } else {
  6495. nodes.forEach(function (n) {
  6496. return _this3.newNode(n);
  6497. });
  6498. }
  6499. }
  6500. return;
  6501. }
  6502. var firstToken = this.currToken;
  6503. var spaceOrDescendantSelectorNodes = undefined;
  6504. if (nextSigTokenPos > this.position) {
  6505. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6506. }
  6507. var node;
  6508. if (this.isNamedCombinator()) {
  6509. node = this.namedCombinator();
  6510. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6511. node = new _combinator["default"]({
  6512. value: this.content(),
  6513. source: getTokenSource(this.currToken),
  6514. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6515. });
  6516. this.position++;
  6517. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6518. this.unexpected();
  6519. }
  6520. if (node) {
  6521. if (spaceOrDescendantSelectorNodes) {
  6522. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6523. _space = _this$convertWhitespa2.space,
  6524. _rawSpace = _this$convertWhitespa2.rawSpace;
  6525. node.spaces.before = _space;
  6526. node.rawSpaceBefore = _rawSpace;
  6527. }
  6528. } else {
  6529. // descendant combinator
  6530. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6531. _space2 = _this$convertWhitespa3.space,
  6532. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6533. if (!_rawSpace2) {
  6534. _rawSpace2 = _space2;
  6535. }
  6536. var spaces = {};
  6537. var raws = {
  6538. spaces: {}
  6539. };
  6540. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6541. spaces.before = _space2.slice(0, _space2.length - 1);
  6542. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6543. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  6544. spaces.after = _space2.slice(1);
  6545. raws.spaces.after = _rawSpace2.slice(1);
  6546. } else {
  6547. raws.value = _rawSpace2;
  6548. }
  6549. node = new _combinator["default"]({
  6550. value: ' ',
  6551. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6552. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6553. spaces: spaces,
  6554. raws: raws
  6555. });
  6556. }
  6557. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6558. node.spaces.after = this.optionalSpace(this.content());
  6559. this.position++;
  6560. }
  6561. return this.newNode(node);
  6562. };
  6563. _proto.comma = function comma() {
  6564. if (this.position === this.tokens.length - 1) {
  6565. this.root.trailingComma = true;
  6566. this.position++;
  6567. return;
  6568. }
  6569. this.current._inferEndPosition();
  6570. var selector = new _selector["default"]({
  6571. source: {
  6572. start: tokenStart(this.tokens[this.position + 1])
  6573. }
  6574. });
  6575. this.current.parent.append(selector);
  6576. this.current = selector;
  6577. this.position++;
  6578. };
  6579. _proto.comment = function comment() {
  6580. var current = this.currToken;
  6581. this.newNode(new _comment["default"]({
  6582. value: this.content(),
  6583. source: getTokenSource(current),
  6584. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6585. }));
  6586. this.position++;
  6587. };
  6588. _proto.error = function error(message, opts) {
  6589. throw this.root.error(message, opts);
  6590. };
  6591. _proto.missingBackslash = function missingBackslash() {
  6592. return this.error('Expected a backslash preceding the semicolon.', {
  6593. index: this.currToken[_tokenize.FIELDS.START_POS]
  6594. });
  6595. };
  6596. _proto.missingParenthesis = function missingParenthesis() {
  6597. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6598. };
  6599. _proto.missingSquareBracket = function missingSquareBracket() {
  6600. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6601. };
  6602. _proto.unexpected = function unexpected() {
  6603. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6604. };
  6605. _proto.unexpectedPipe = function unexpectedPipe() {
  6606. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6607. };
  6608. _proto.namespace = function namespace() {
  6609. var before = this.prevToken && this.content(this.prevToken) || true;
  6610. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6611. this.position++;
  6612. return this.word(before);
  6613. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6614. this.position++;
  6615. return this.universal(before);
  6616. }
  6617. this.unexpectedPipe();
  6618. };
  6619. _proto.nesting = function nesting() {
  6620. if (this.nextToken) {
  6621. var nextContent = this.content(this.nextToken);
  6622. if (nextContent === "|") {
  6623. this.position++;
  6624. return;
  6625. }
  6626. }
  6627. var current = this.currToken;
  6628. this.newNode(new _nesting["default"]({
  6629. value: this.content(),
  6630. source: getTokenSource(current),
  6631. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6632. }));
  6633. this.position++;
  6634. };
  6635. _proto.parentheses = function parentheses() {
  6636. var last = this.current.last;
  6637. var unbalanced = 1;
  6638. this.position++;
  6639. if (last && last.type === types.PSEUDO) {
  6640. var selector = new _selector["default"]({
  6641. source: {
  6642. start: tokenStart(this.tokens[this.position - 1])
  6643. }
  6644. });
  6645. var cache = this.current;
  6646. last.append(selector);
  6647. this.current = selector;
  6648. while (this.position < this.tokens.length && unbalanced) {
  6649. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6650. unbalanced++;
  6651. }
  6652. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6653. unbalanced--;
  6654. }
  6655. if (unbalanced) {
  6656. this.parse();
  6657. } else {
  6658. this.current.source.end = tokenEnd(this.currToken);
  6659. this.current.parent.source.end = tokenEnd(this.currToken);
  6660. this.position++;
  6661. }
  6662. }
  6663. this.current = cache;
  6664. } else {
  6665. // I think this case should be an error. It's used to implement a basic parse of media queries
  6666. // but I don't think it's a good idea.
  6667. var parenStart = this.currToken;
  6668. var parenValue = "(";
  6669. var parenEnd;
  6670. while (this.position < this.tokens.length && unbalanced) {
  6671. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6672. unbalanced++;
  6673. }
  6674. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6675. unbalanced--;
  6676. }
  6677. parenEnd = this.currToken;
  6678. parenValue += this.parseParenthesisToken(this.currToken);
  6679. this.position++;
  6680. }
  6681. if (last) {
  6682. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6683. } else {
  6684. this.newNode(new _string["default"]({
  6685. value: parenValue,
  6686. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6687. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6688. }));
  6689. }
  6690. }
  6691. if (unbalanced) {
  6692. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6693. }
  6694. };
  6695. _proto.pseudo = function pseudo() {
  6696. var _this4 = this;
  6697. var pseudoStr = '';
  6698. var startingToken = this.currToken;
  6699. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6700. pseudoStr += this.content();
  6701. this.position++;
  6702. }
  6703. if (!this.currToken) {
  6704. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6705. }
  6706. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6707. this.splitWord(false, function (first, length) {
  6708. pseudoStr += first;
  6709. _this4.newNode(new _pseudo["default"]({
  6710. value: pseudoStr,
  6711. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6712. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6713. }));
  6714. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6715. _this4.error('Misplaced parenthesis.', {
  6716. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6717. });
  6718. }
  6719. });
  6720. } else {
  6721. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6722. }
  6723. };
  6724. _proto.space = function space() {
  6725. var content = this.content();
  6726. // Handle space before and after the selector
  6727. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6728. return node.type === 'comment';
  6729. })) {
  6730. this.spaces = this.optionalSpace(content);
  6731. this.position++;
  6732. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6733. this.current.last.spaces.after = this.optionalSpace(content);
  6734. this.position++;
  6735. } else {
  6736. this.combinator();
  6737. }
  6738. };
  6739. _proto.string = function string() {
  6740. var current = this.currToken;
  6741. this.newNode(new _string["default"]({
  6742. value: this.content(),
  6743. source: getTokenSource(current),
  6744. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6745. }));
  6746. this.position++;
  6747. };
  6748. _proto.universal = function universal(namespace) {
  6749. var nextToken = this.nextToken;
  6750. if (nextToken && this.content(nextToken) === '|') {
  6751. this.position++;
  6752. return this.namespace();
  6753. }
  6754. var current = this.currToken;
  6755. this.newNode(new _universal["default"]({
  6756. value: this.content(),
  6757. source: getTokenSource(current),
  6758. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6759. }), namespace);
  6760. this.position++;
  6761. };
  6762. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6763. var _this5 = this;
  6764. var nextToken = this.nextToken;
  6765. var word = this.content();
  6766. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6767. this.position++;
  6768. var current = this.content();
  6769. word += current;
  6770. if (current.lastIndexOf('\\') === current.length - 1) {
  6771. var next = this.nextToken;
  6772. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6773. word += this.requiredSpace(this.content(next));
  6774. this.position++;
  6775. }
  6776. }
  6777. nextToken = this.nextToken;
  6778. }
  6779. var hasClass = indexesOf(word, '.').filter(function (i) {
  6780. // Allow escaped dot within class name
  6781. var escapedDot = word[i - 1] === '\\';
  6782. // Allow decimal numbers percent in @keyframes
  6783. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6784. return !escapedDot && !isKeyframesPercent;
  6785. });
  6786. var hasId = indexesOf(word, '#').filter(function (i) {
  6787. return word[i - 1] !== '\\';
  6788. });
  6789. // Eliminate Sass interpolations from the list of id indexes
  6790. var interpolations = indexesOf(word, '#{');
  6791. if (interpolations.length) {
  6792. hasId = hasId.filter(function (hashIndex) {
  6793. return !~interpolations.indexOf(hashIndex);
  6794. });
  6795. }
  6796. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6797. indices.forEach(function (ind, i) {
  6798. var index = indices[i + 1] || word.length;
  6799. var value = word.slice(ind, index);
  6800. if (i === 0 && firstCallback) {
  6801. return firstCallback.call(_this5, value, indices.length);
  6802. }
  6803. var node;
  6804. var current = _this5.currToken;
  6805. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6806. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6807. if (~hasClass.indexOf(ind)) {
  6808. var classNameOpts = {
  6809. value: value.slice(1),
  6810. source: source,
  6811. sourceIndex: sourceIndex
  6812. };
  6813. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6814. } else if (~hasId.indexOf(ind)) {
  6815. var idOpts = {
  6816. value: value.slice(1),
  6817. source: source,
  6818. sourceIndex: sourceIndex
  6819. };
  6820. node = new _id["default"](unescapeProp(idOpts, "value"));
  6821. } else {
  6822. var tagOpts = {
  6823. value: value,
  6824. source: source,
  6825. sourceIndex: sourceIndex
  6826. };
  6827. unescapeProp(tagOpts, "value");
  6828. node = new _tag["default"](tagOpts);
  6829. }
  6830. _this5.newNode(node, namespace);
  6831. // Ensure that the namespace is used only once
  6832. namespace = null;
  6833. });
  6834. this.position++;
  6835. };
  6836. _proto.word = function word(namespace) {
  6837. var nextToken = this.nextToken;
  6838. if (nextToken && this.content(nextToken) === '|') {
  6839. this.position++;
  6840. return this.namespace();
  6841. }
  6842. return this.splitWord(namespace);
  6843. };
  6844. _proto.loop = function loop() {
  6845. while (this.position < this.tokens.length) {
  6846. this.parse(true);
  6847. }
  6848. this.current._inferEndPosition();
  6849. return this.root;
  6850. };
  6851. _proto.parse = function parse(throwOnParenthesis) {
  6852. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6853. case tokens.space:
  6854. this.space();
  6855. break;
  6856. case tokens.comment:
  6857. this.comment();
  6858. break;
  6859. case tokens.openParenthesis:
  6860. this.parentheses();
  6861. break;
  6862. case tokens.closeParenthesis:
  6863. if (throwOnParenthesis) {
  6864. this.missingParenthesis();
  6865. }
  6866. break;
  6867. case tokens.openSquare:
  6868. this.attribute();
  6869. break;
  6870. case tokens.dollar:
  6871. case tokens.caret:
  6872. case tokens.equals:
  6873. case tokens.word:
  6874. this.word();
  6875. break;
  6876. case tokens.colon:
  6877. this.pseudo();
  6878. break;
  6879. case tokens.comma:
  6880. this.comma();
  6881. break;
  6882. case tokens.asterisk:
  6883. this.universal();
  6884. break;
  6885. case tokens.ampersand:
  6886. this.nesting();
  6887. break;
  6888. case tokens.slash:
  6889. case tokens.combinator:
  6890. this.combinator();
  6891. break;
  6892. case tokens.str:
  6893. this.string();
  6894. break;
  6895. // These cases throw; no break needed.
  6896. case tokens.closeSquare:
  6897. this.missingSquareBracket();
  6898. case tokens.semicolon:
  6899. this.missingBackslash();
  6900. default:
  6901. this.unexpected();
  6902. }
  6903. }
  6904. /**
  6905. * Helpers
  6906. */;
  6907. _proto.expected = function expected(description, index, found) {
  6908. if (Array.isArray(description)) {
  6909. var last = description.pop();
  6910. description = description.join(', ') + " or " + last;
  6911. }
  6912. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  6913. if (!found) {
  6914. return this.error("Expected " + an + " " + description + ".", {
  6915. index: index
  6916. });
  6917. }
  6918. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  6919. index: index
  6920. });
  6921. };
  6922. _proto.requiredSpace = function requiredSpace(space) {
  6923. return this.options.lossy ? ' ' : space;
  6924. };
  6925. _proto.optionalSpace = function optionalSpace(space) {
  6926. return this.options.lossy ? '' : space;
  6927. };
  6928. _proto.lossySpace = function lossySpace(space, required) {
  6929. if (this.options.lossy) {
  6930. return required ? ' ' : '';
  6931. } else {
  6932. return space;
  6933. }
  6934. };
  6935. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  6936. var content = this.content(token);
  6937. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  6938. return this.requiredSpace(content);
  6939. } else {
  6940. return content;
  6941. }
  6942. };
  6943. _proto.newNode = function newNode(node, namespace) {
  6944. if (namespace) {
  6945. if (/^ +$/.test(namespace)) {
  6946. if (!this.options.lossy) {
  6947. this.spaces = (this.spaces || '') + namespace;
  6948. }
  6949. namespace = true;
  6950. }
  6951. node.namespace = namespace;
  6952. unescapeProp(node, "namespace");
  6953. }
  6954. if (this.spaces) {
  6955. node.spaces.before = this.spaces;
  6956. this.spaces = '';
  6957. }
  6958. return this.current.append(node);
  6959. };
  6960. _proto.content = function content(token) {
  6961. if (token === void 0) {
  6962. token = this.currToken;
  6963. }
  6964. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  6965. };
  6966. /**
  6967. * returns the index of the next non-whitespace, non-comment token.
  6968. * returns -1 if no meaningful token is found.
  6969. */
  6970. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  6971. if (startPosition === void 0) {
  6972. startPosition = this.position + 1;
  6973. }
  6974. var searchPosition = startPosition;
  6975. while (searchPosition < this.tokens.length) {
  6976. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  6977. searchPosition++;
  6978. continue;
  6979. } else {
  6980. return searchPosition;
  6981. }
  6982. }
  6983. return -1;
  6984. };
  6985. _createClass(Parser, [{
  6986. key: "currToken",
  6987. get: function get() {
  6988. return this.tokens[this.position];
  6989. }
  6990. }, {
  6991. key: "nextToken",
  6992. get: function get() {
  6993. return this.tokens[this.position + 1];
  6994. }
  6995. }, {
  6996. key: "prevToken",
  6997. get: function get() {
  6998. return this.tokens[this.position - 1];
  6999. }
  7000. }]);
  7001. return Parser;
  7002. }();
  7003. exports["default"] = Parser;
  7004. module.exports = exports.default;
  7005. } (parser, parser.exports));
  7006. var parserExports = parser.exports;
  7007. (function (module, exports) {
  7008. exports.__esModule = true;
  7009. exports["default"] = void 0;
  7010. var _parser = _interopRequireDefault(parserExports);
  7011. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7012. var Processor = /*#__PURE__*/function () {
  7013. function Processor(func, options) {
  7014. this.func = func || function noop() {};
  7015. this.funcRes = null;
  7016. this.options = options;
  7017. }
  7018. var _proto = Processor.prototype;
  7019. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7020. if (options === void 0) {
  7021. options = {};
  7022. }
  7023. var merged = Object.assign({}, this.options, options);
  7024. if (merged.updateSelector === false) {
  7025. return false;
  7026. } else {
  7027. return typeof rule !== "string";
  7028. }
  7029. };
  7030. _proto._isLossy = function _isLossy(options) {
  7031. if (options === void 0) {
  7032. options = {};
  7033. }
  7034. var merged = Object.assign({}, this.options, options);
  7035. if (merged.lossless === false) {
  7036. return true;
  7037. } else {
  7038. return false;
  7039. }
  7040. };
  7041. _proto._root = function _root(rule, options) {
  7042. if (options === void 0) {
  7043. options = {};
  7044. }
  7045. var parser = new _parser["default"](rule, this._parseOptions(options));
  7046. return parser.root;
  7047. };
  7048. _proto._parseOptions = function _parseOptions(options) {
  7049. return {
  7050. lossy: this._isLossy(options)
  7051. };
  7052. };
  7053. _proto._run = function _run(rule, options) {
  7054. var _this = this;
  7055. if (options === void 0) {
  7056. options = {};
  7057. }
  7058. return new Promise(function (resolve, reject) {
  7059. try {
  7060. var root = _this._root(rule, options);
  7061. Promise.resolve(_this.func(root)).then(function (transform) {
  7062. var string = undefined;
  7063. if (_this._shouldUpdateSelector(rule, options)) {
  7064. string = root.toString();
  7065. rule.selector = string;
  7066. }
  7067. return {
  7068. transform: transform,
  7069. root: root,
  7070. string: string
  7071. };
  7072. }).then(resolve, reject);
  7073. } catch (e) {
  7074. reject(e);
  7075. return;
  7076. }
  7077. });
  7078. };
  7079. _proto._runSync = function _runSync(rule, options) {
  7080. if (options === void 0) {
  7081. options = {};
  7082. }
  7083. var root = this._root(rule, options);
  7084. var transform = this.func(root);
  7085. if (transform && typeof transform.then === "function") {
  7086. throw new Error("Selector processor returned a promise to a synchronous call.");
  7087. }
  7088. var string = undefined;
  7089. if (options.updateSelector && typeof rule !== "string") {
  7090. string = root.toString();
  7091. rule.selector = string;
  7092. }
  7093. return {
  7094. transform: transform,
  7095. root: root,
  7096. string: string
  7097. };
  7098. }
  7099. /**
  7100. * Process rule into a selector AST.
  7101. *
  7102. * @param rule {postcss.Rule | string} The css selector to be processed
  7103. * @param options The options for processing
  7104. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7105. */;
  7106. _proto.ast = function ast(rule, options) {
  7107. return this._run(rule, options).then(function (result) {
  7108. return result.root;
  7109. });
  7110. }
  7111. /**
  7112. * Process rule into a selector AST synchronously.
  7113. *
  7114. * @param rule {postcss.Rule | string} The css selector to be processed
  7115. * @param options The options for processing
  7116. * @returns {parser.Root} The AST of the selector after processing it.
  7117. */;
  7118. _proto.astSync = function astSync(rule, options) {
  7119. return this._runSync(rule, options).root;
  7120. }
  7121. /**
  7122. * Process a selector into a transformed value asynchronously
  7123. *
  7124. * @param rule {postcss.Rule | string} The css selector to be processed
  7125. * @param options The options for processing
  7126. * @returns {Promise<any>} The value returned by the processor.
  7127. */;
  7128. _proto.transform = function transform(rule, options) {
  7129. return this._run(rule, options).then(function (result) {
  7130. return result.transform;
  7131. });
  7132. }
  7133. /**
  7134. * Process a selector into a transformed value synchronously.
  7135. *
  7136. * @param rule {postcss.Rule | string} The css selector to be processed
  7137. * @param options The options for processing
  7138. * @returns {any} The value returned by the processor.
  7139. */;
  7140. _proto.transformSync = function transformSync(rule, options) {
  7141. return this._runSync(rule, options).transform;
  7142. }
  7143. /**
  7144. * Process a selector into a new selector string asynchronously.
  7145. *
  7146. * @param rule {postcss.Rule | string} The css selector to be processed
  7147. * @param options The options for processing
  7148. * @returns {string} the selector after processing.
  7149. */;
  7150. _proto.process = function process(rule, options) {
  7151. return this._run(rule, options).then(function (result) {
  7152. return result.string || result.root.toString();
  7153. });
  7154. }
  7155. /**
  7156. * Process a selector into a new selector string synchronously.
  7157. *
  7158. * @param rule {postcss.Rule | string} The css selector to be processed
  7159. * @param options The options for processing
  7160. * @returns {string} the selector after processing.
  7161. */;
  7162. _proto.processSync = function processSync(rule, options) {
  7163. var result = this._runSync(rule, options);
  7164. return result.string || result.root.toString();
  7165. };
  7166. return Processor;
  7167. }();
  7168. exports["default"] = Processor;
  7169. module.exports = exports.default;
  7170. } (processor, processor.exports));
  7171. var processorExports = processor.exports;
  7172. var selectors = {};
  7173. var constructors = {};
  7174. constructors.__esModule = true;
  7175. constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0;
  7176. var _attribute = _interopRequireDefault$4(attribute$1);
  7177. var _className = _interopRequireDefault$4(classNameExports);
  7178. var _combinator = _interopRequireDefault$4(combinatorExports);
  7179. var _comment = _interopRequireDefault$4(commentExports);
  7180. var _id = _interopRequireDefault$4(idExports);
  7181. var _nesting = _interopRequireDefault$4(nestingExports);
  7182. var _pseudo = _interopRequireDefault$4(pseudoExports);
  7183. var _root = _interopRequireDefault$4(rootExports);
  7184. var _selector = _interopRequireDefault$4(selectorExports);
  7185. var _string = _interopRequireDefault$4(stringExports);
  7186. var _tag = _interopRequireDefault$4(tagExports);
  7187. var _universal = _interopRequireDefault$4(universalExports);
  7188. function _interopRequireDefault$4(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7189. var attribute = function attribute(opts) {
  7190. return new _attribute["default"](opts);
  7191. };
  7192. constructors.attribute = attribute;
  7193. var className = function className(opts) {
  7194. return new _className["default"](opts);
  7195. };
  7196. constructors.className = className;
  7197. var combinator = function combinator(opts) {
  7198. return new _combinator["default"](opts);
  7199. };
  7200. constructors.combinator = combinator;
  7201. var comment = function comment(opts) {
  7202. return new _comment["default"](opts);
  7203. };
  7204. constructors.comment = comment;
  7205. var id = function id(opts) {
  7206. return new _id["default"](opts);
  7207. };
  7208. constructors.id = id;
  7209. var nesting = function nesting(opts) {
  7210. return new _nesting["default"](opts);
  7211. };
  7212. constructors.nesting = nesting;
  7213. var pseudo = function pseudo(opts) {
  7214. return new _pseudo["default"](opts);
  7215. };
  7216. constructors.pseudo = pseudo;
  7217. var root$1 = function root(opts) {
  7218. return new _root["default"](opts);
  7219. };
  7220. constructors.root = root$1;
  7221. var selector = function selector(opts) {
  7222. return new _selector["default"](opts);
  7223. };
  7224. constructors.selector = selector;
  7225. var string = function string(opts) {
  7226. return new _string["default"](opts);
  7227. };
  7228. constructors.string = string;
  7229. var tag = function tag(opts) {
  7230. return new _tag["default"](opts);
  7231. };
  7232. constructors.tag = tag;
  7233. var universal = function universal(opts) {
  7234. return new _universal["default"](opts);
  7235. };
  7236. constructors.universal = universal;
  7237. var guards = {};
  7238. guards.__esModule = true;
  7239. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  7240. guards.isContainer = isContainer;
  7241. guards.isIdentifier = void 0;
  7242. guards.isNamespace = isNamespace;
  7243. guards.isNesting = void 0;
  7244. guards.isNode = isNode;
  7245. guards.isPseudo = void 0;
  7246. guards.isPseudoClass = isPseudoClass;
  7247. guards.isPseudoElement = isPseudoElement;
  7248. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  7249. var _types = types$1;
  7250. var _IS_TYPE;
  7251. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
  7252. function isNode(node) {
  7253. return typeof node === "object" && IS_TYPE[node.type];
  7254. }
  7255. function isNodeType(type, node) {
  7256. return isNode(node) && node.type === type;
  7257. }
  7258. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7259. guards.isAttribute = isAttribute;
  7260. var isClassName = isNodeType.bind(null, _types.CLASS);
  7261. guards.isClassName = isClassName;
  7262. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7263. guards.isCombinator = isCombinator;
  7264. var isComment = isNodeType.bind(null, _types.COMMENT);
  7265. guards.isComment = isComment;
  7266. var isIdentifier = isNodeType.bind(null, _types.ID);
  7267. guards.isIdentifier = isIdentifier;
  7268. var isNesting = isNodeType.bind(null, _types.NESTING);
  7269. guards.isNesting = isNesting;
  7270. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7271. guards.isPseudo = isPseudo;
  7272. var isRoot = isNodeType.bind(null, _types.ROOT);
  7273. guards.isRoot = isRoot;
  7274. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7275. guards.isSelector = isSelector;
  7276. var isString = isNodeType.bind(null, _types.STRING);
  7277. guards.isString = isString;
  7278. var isTag = isNodeType.bind(null, _types.TAG);
  7279. guards.isTag = isTag;
  7280. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7281. guards.isUniversal = isUniversal;
  7282. function isPseudoElement(node) {
  7283. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line");
  7284. }
  7285. function isPseudoClass(node) {
  7286. return isPseudo(node) && !isPseudoElement(node);
  7287. }
  7288. function isContainer(node) {
  7289. return !!(isNode(node) && node.walk);
  7290. }
  7291. function isNamespace(node) {
  7292. return isAttribute(node) || isTag(node);
  7293. }
  7294. (function (exports) {
  7295. exports.__esModule = true;
  7296. var _types = types$1;
  7297. Object.keys(_types).forEach(function (key) {
  7298. if (key === "default" || key === "__esModule") return;
  7299. if (key in exports && exports[key] === _types[key]) return;
  7300. exports[key] = _types[key];
  7301. });
  7302. var _constructors = constructors;
  7303. Object.keys(_constructors).forEach(function (key) {
  7304. if (key === "default" || key === "__esModule") return;
  7305. if (key in exports && exports[key] === _constructors[key]) return;
  7306. exports[key] = _constructors[key];
  7307. });
  7308. var _guards = guards;
  7309. Object.keys(_guards).forEach(function (key) {
  7310. if (key === "default" || key === "__esModule") return;
  7311. if (key in exports && exports[key] === _guards[key]) return;
  7312. exports[key] = _guards[key];
  7313. });
  7314. } (selectors));
  7315. (function (module, exports) {
  7316. exports.__esModule = true;
  7317. exports["default"] = void 0;
  7318. var _processor = _interopRequireDefault(processorExports);
  7319. var selectors$1 = _interopRequireWildcard(selectors);
  7320. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  7321. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  7322. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7323. var parser = function parser(processor) {
  7324. return new _processor["default"](processor);
  7325. };
  7326. Object.assign(parser, selectors$1);
  7327. delete parser.__esModule;
  7328. var _default = parser;
  7329. exports["default"] = _default;
  7330. module.exports = exports.default;
  7331. } (dist, dist.exports));
  7332. var distExports = dist.exports;
  7333. var selectorParser$2 = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7334. const animationNameRE = /^(-\w+-)?animation-name$/;
  7335. const animationRE = /^(-\w+-)?animation$/;
  7336. const scopedPlugin = (id = "") => {
  7337. const keyframes = /* @__PURE__ */ Object.create(null);
  7338. const shortId = id.replace(/^data-v-/, "");
  7339. return {
  7340. postcssPlugin: "vue-sfc-scoped",
  7341. Rule(rule) {
  7342. processRule(id, rule);
  7343. },
  7344. AtRule(node) {
  7345. if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7346. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7347. }
  7348. },
  7349. OnceExit(root) {
  7350. if (Object.keys(keyframes).length) {
  7351. root.walkDecls((decl) => {
  7352. if (animationNameRE.test(decl.prop)) {
  7353. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7354. }
  7355. if (animationRE.test(decl.prop)) {
  7356. decl.value = decl.value.split(",").map((v) => {
  7357. const vals = v.trim().split(/\s+/);
  7358. const i = vals.findIndex((val) => keyframes[val]);
  7359. if (i !== -1) {
  7360. vals.splice(i, 1, keyframes[vals[i]]);
  7361. return vals.join(" ");
  7362. } else {
  7363. return v;
  7364. }
  7365. }).join(",");
  7366. }
  7367. });
  7368. }
  7369. }
  7370. };
  7371. };
  7372. const processedRules = /* @__PURE__ */ new WeakSet();
  7373. function processRule(id, rule) {
  7374. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) {
  7375. return;
  7376. }
  7377. processedRules.add(rule);
  7378. rule.selector = selectorParser$2((selectorRoot) => {
  7379. selectorRoot.each((selector) => {
  7380. rewriteSelector(id, selector, selectorRoot);
  7381. });
  7382. }).processSync(rule.selector);
  7383. }
  7384. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  7385. let node = null;
  7386. let shouldInject = true;
  7387. selector.each((n) => {
  7388. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7389. n.value = " ";
  7390. n.spaces.before = n.spaces.after = "";
  7391. warn(
  7392. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7393. );
  7394. return false;
  7395. }
  7396. if (n.type === "pseudo") {
  7397. const { value } = n;
  7398. if (value === ":deep" || value === "::v-deep") {
  7399. if (n.nodes.length) {
  7400. let last = n;
  7401. n.nodes[0].each((ss) => {
  7402. selector.insertAfter(last, ss);
  7403. last = ss;
  7404. });
  7405. const prev = selector.at(selector.index(n) - 1);
  7406. if (!prev || !isSpaceCombinator(prev)) {
  7407. selector.insertAfter(
  7408. n,
  7409. selectorParser$2.combinator({
  7410. value: " "
  7411. })
  7412. );
  7413. }
  7414. selector.removeChild(n);
  7415. } else {
  7416. warn(
  7417. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7418. );
  7419. const prev = selector.at(selector.index(n) - 1);
  7420. if (prev && isSpaceCombinator(prev)) {
  7421. selector.removeChild(prev);
  7422. }
  7423. selector.removeChild(n);
  7424. }
  7425. return false;
  7426. }
  7427. if (value === ":slotted" || value === "::v-slotted") {
  7428. rewriteSelector(
  7429. id,
  7430. n.nodes[0],
  7431. selectorRoot,
  7432. true
  7433. /* slotted */
  7434. );
  7435. let last = n;
  7436. n.nodes[0].each((ss) => {
  7437. selector.insertAfter(last, ss);
  7438. last = ss;
  7439. });
  7440. selector.removeChild(n);
  7441. shouldInject = false;
  7442. return false;
  7443. }
  7444. if (value === ":global" || value === "::v-global") {
  7445. selectorRoot.insertAfter(selector, n.nodes[0]);
  7446. selectorRoot.removeChild(selector);
  7447. return false;
  7448. }
  7449. }
  7450. if (n.type === "universal") {
  7451. const prev = selector.at(selector.index(n) - 1);
  7452. const next = selector.at(selector.index(n) + 1);
  7453. if (!prev) {
  7454. if (next) {
  7455. if (next.type === "combinator" && next.value === " ") {
  7456. selector.removeChild(next);
  7457. }
  7458. selector.removeChild(n);
  7459. return;
  7460. } else {
  7461. node = selectorParser$2.combinator({
  7462. value: ""
  7463. });
  7464. selector.insertBefore(n, node);
  7465. selector.removeChild(n);
  7466. return false;
  7467. }
  7468. }
  7469. if (node)
  7470. return;
  7471. }
  7472. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node) {
  7473. node = n;
  7474. }
  7475. });
  7476. if (node) {
  7477. const { type, value } = node;
  7478. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7479. node.nodes.forEach(
  7480. (value2) => rewriteSelector(id, value2, selectorRoot, slotted)
  7481. );
  7482. shouldInject = false;
  7483. }
  7484. }
  7485. if (node) {
  7486. node.spaces.after = "";
  7487. } else {
  7488. selector.first.spaces.before = "";
  7489. }
  7490. if (shouldInject) {
  7491. const idToAdd = slotted ? id + "-s" : id;
  7492. selector.insertAfter(
  7493. // If node is null it means we need to inject [id] at the start
  7494. // insertAfter can handle `null` here
  7495. node,
  7496. selectorParser$2.attribute({
  7497. attribute: idToAdd,
  7498. value: idToAdd,
  7499. raws: {},
  7500. quoteMark: `"`
  7501. })
  7502. );
  7503. }
  7504. }
  7505. function isSpaceCombinator(node) {
  7506. return node.type === "combinator" && /^\s+$/.test(node.value);
  7507. }
  7508. scopedPlugin.postcss = true;
  7509. var sourceMap$1 = {};
  7510. var sourceMapGenerator = {};
  7511. var base64Vlq = {};
  7512. var base64$1 = {};
  7513. /* -*- Mode: js; js-indent-level: 2; -*- */
  7514. /*
  7515. * Copyright 2011 Mozilla Foundation and contributors
  7516. * Licensed under the New BSD license. See LICENSE or:
  7517. * http://opensource.org/licenses/BSD-3-Clause
  7518. */
  7519. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7520. /**
  7521. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7522. */
  7523. base64$1.encode = function (number) {
  7524. if (0 <= number && number < intToCharMap.length) {
  7525. return intToCharMap[number];
  7526. }
  7527. throw new TypeError("Must be between 0 and 63: " + number);
  7528. };
  7529. /**
  7530. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7531. * failure.
  7532. */
  7533. base64$1.decode = function (charCode) {
  7534. var bigA = 65; // 'A'
  7535. var bigZ = 90; // 'Z'
  7536. var littleA = 97; // 'a'
  7537. var littleZ = 122; // 'z'
  7538. var zero = 48; // '0'
  7539. var nine = 57; // '9'
  7540. var plus = 43; // '+'
  7541. var slash = 47; // '/'
  7542. var littleOffset = 26;
  7543. var numberOffset = 52;
  7544. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7545. if (bigA <= charCode && charCode <= bigZ) {
  7546. return (charCode - bigA);
  7547. }
  7548. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7549. if (littleA <= charCode && charCode <= littleZ) {
  7550. return (charCode - littleA + littleOffset);
  7551. }
  7552. // 52 - 61: 0123456789
  7553. if (zero <= charCode && charCode <= nine) {
  7554. return (charCode - zero + numberOffset);
  7555. }
  7556. // 62: +
  7557. if (charCode == plus) {
  7558. return 62;
  7559. }
  7560. // 63: /
  7561. if (charCode == slash) {
  7562. return 63;
  7563. }
  7564. // Invalid base64 digit.
  7565. return -1;
  7566. };
  7567. /* -*- Mode: js; js-indent-level: 2; -*- */
  7568. /*
  7569. * Copyright 2011 Mozilla Foundation and contributors
  7570. * Licensed under the New BSD license. See LICENSE or:
  7571. * http://opensource.org/licenses/BSD-3-Clause
  7572. *
  7573. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7574. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7575. *
  7576. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7577. * Redistribution and use in source and binary forms, with or without
  7578. * modification, are permitted provided that the following conditions are
  7579. * met:
  7580. *
  7581. * * Redistributions of source code must retain the above copyright
  7582. * notice, this list of conditions and the following disclaimer.
  7583. * * Redistributions in binary form must reproduce the above
  7584. * copyright notice, this list of conditions and the following
  7585. * disclaimer in the documentation and/or other materials provided
  7586. * with the distribution.
  7587. * * Neither the name of Google Inc. nor the names of its
  7588. * contributors may be used to endorse or promote products derived
  7589. * from this software without specific prior written permission.
  7590. *
  7591. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7592. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7593. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7594. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7595. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7596. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7597. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7598. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7599. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7600. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7601. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7602. */
  7603. var base64 = base64$1;
  7604. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7605. // length quantities we use in the source map spec, the first bit is the sign,
  7606. // the next four bits are the actual value, and the 6th bit is the
  7607. // continuation bit. The continuation bit tells us whether there are more
  7608. // digits in this value following this digit.
  7609. //
  7610. // Continuation
  7611. // | Sign
  7612. // | |
  7613. // V V
  7614. // 101011
  7615. var VLQ_BASE_SHIFT = 5;
  7616. // binary: 100000
  7617. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7618. // binary: 011111
  7619. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7620. // binary: 100000
  7621. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7622. /**
  7623. * Converts from a two-complement value to a value where the sign bit is
  7624. * placed in the least significant bit. For example, as decimals:
  7625. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7626. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7627. */
  7628. function toVLQSigned(aValue) {
  7629. return aValue < 0
  7630. ? ((-aValue) << 1) + 1
  7631. : (aValue << 1) + 0;
  7632. }
  7633. /**
  7634. * Converts to a two-complement value from a value where the sign bit is
  7635. * placed in the least significant bit. For example, as decimals:
  7636. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7637. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7638. */
  7639. function fromVLQSigned(aValue) {
  7640. var isNegative = (aValue & 1) === 1;
  7641. var shifted = aValue >> 1;
  7642. return isNegative
  7643. ? -shifted
  7644. : shifted;
  7645. }
  7646. /**
  7647. * Returns the base 64 VLQ encoded value.
  7648. */
  7649. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7650. var encoded = "";
  7651. var digit;
  7652. var vlq = toVLQSigned(aValue);
  7653. do {
  7654. digit = vlq & VLQ_BASE_MASK;
  7655. vlq >>>= VLQ_BASE_SHIFT;
  7656. if (vlq > 0) {
  7657. // There are still more digits in this value, so we must make sure the
  7658. // continuation bit is marked.
  7659. digit |= VLQ_CONTINUATION_BIT;
  7660. }
  7661. encoded += base64.encode(digit);
  7662. } while (vlq > 0);
  7663. return encoded;
  7664. };
  7665. /**
  7666. * Decodes the next base 64 VLQ value from the given string and returns the
  7667. * value and the rest of the string via the out parameter.
  7668. */
  7669. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7670. var strLen = aStr.length;
  7671. var result = 0;
  7672. var shift = 0;
  7673. var continuation, digit;
  7674. do {
  7675. if (aIndex >= strLen) {
  7676. throw new Error("Expected more digits in base 64 VLQ value.");
  7677. }
  7678. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7679. if (digit === -1) {
  7680. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7681. }
  7682. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7683. digit &= VLQ_BASE_MASK;
  7684. result = result + (digit << shift);
  7685. shift += VLQ_BASE_SHIFT;
  7686. } while (continuation);
  7687. aOutParam.value = fromVLQSigned(result);
  7688. aOutParam.rest = aIndex;
  7689. };
  7690. var util$5 = {};
  7691. /* -*- Mode: js; js-indent-level: 2; -*- */
  7692. (function (exports) {
  7693. /*
  7694. * Copyright 2011 Mozilla Foundation and contributors
  7695. * Licensed under the New BSD license. See LICENSE or:
  7696. * http://opensource.org/licenses/BSD-3-Clause
  7697. */
  7698. /**
  7699. * This is a helper function for getting values from parameter/options
  7700. * objects.
  7701. *
  7702. * @param args The object we are extracting values from
  7703. * @param name The name of the property we are getting.
  7704. * @param defaultValue An optional value to return if the property is missing
  7705. * from the object. If this is not specified and the property is missing, an
  7706. * error will be thrown.
  7707. */
  7708. function getArg(aArgs, aName, aDefaultValue) {
  7709. if (aName in aArgs) {
  7710. return aArgs[aName];
  7711. } else if (arguments.length === 3) {
  7712. return aDefaultValue;
  7713. } else {
  7714. throw new Error('"' + aName + '" is a required argument.');
  7715. }
  7716. }
  7717. exports.getArg = getArg;
  7718. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7719. var dataUrlRegexp = /^data:.+\,.+$/;
  7720. function urlParse(aUrl) {
  7721. var match = aUrl.match(urlRegexp);
  7722. if (!match) {
  7723. return null;
  7724. }
  7725. return {
  7726. scheme: match[1],
  7727. auth: match[2],
  7728. host: match[3],
  7729. port: match[4],
  7730. path: match[5]
  7731. };
  7732. }
  7733. exports.urlParse = urlParse;
  7734. function urlGenerate(aParsedUrl) {
  7735. var url = '';
  7736. if (aParsedUrl.scheme) {
  7737. url += aParsedUrl.scheme + ':';
  7738. }
  7739. url += '//';
  7740. if (aParsedUrl.auth) {
  7741. url += aParsedUrl.auth + '@';
  7742. }
  7743. if (aParsedUrl.host) {
  7744. url += aParsedUrl.host;
  7745. }
  7746. if (aParsedUrl.port) {
  7747. url += ":" + aParsedUrl.port;
  7748. }
  7749. if (aParsedUrl.path) {
  7750. url += aParsedUrl.path;
  7751. }
  7752. return url;
  7753. }
  7754. exports.urlGenerate = urlGenerate;
  7755. /**
  7756. * Normalizes a path, or the path portion of a URL:
  7757. *
  7758. * - Replaces consecutive slashes with one slash.
  7759. * - Removes unnecessary '.' parts.
  7760. * - Removes unnecessary '<dir>/..' parts.
  7761. *
  7762. * Based on code in the Node.js 'path' core module.
  7763. *
  7764. * @param aPath The path or url to normalize.
  7765. */
  7766. function normalize(aPath) {
  7767. var path = aPath;
  7768. var url = urlParse(aPath);
  7769. if (url) {
  7770. if (!url.path) {
  7771. return aPath;
  7772. }
  7773. path = url.path;
  7774. }
  7775. var isAbsolute = exports.isAbsolute(path);
  7776. var parts = path.split(/\/+/);
  7777. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7778. part = parts[i];
  7779. if (part === '.') {
  7780. parts.splice(i, 1);
  7781. } else if (part === '..') {
  7782. up++;
  7783. } else if (up > 0) {
  7784. if (part === '') {
  7785. // The first part is blank if the path is absolute. Trying to go
  7786. // above the root is a no-op. Therefore we can remove all '..' parts
  7787. // directly after the root.
  7788. parts.splice(i + 1, up);
  7789. up = 0;
  7790. } else {
  7791. parts.splice(i, 2);
  7792. up--;
  7793. }
  7794. }
  7795. }
  7796. path = parts.join('/');
  7797. if (path === '') {
  7798. path = isAbsolute ? '/' : '.';
  7799. }
  7800. if (url) {
  7801. url.path = path;
  7802. return urlGenerate(url);
  7803. }
  7804. return path;
  7805. }
  7806. exports.normalize = normalize;
  7807. /**
  7808. * Joins two paths/URLs.
  7809. *
  7810. * @param aRoot The root path or URL.
  7811. * @param aPath The path or URL to be joined with the root.
  7812. *
  7813. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  7814. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  7815. * first.
  7816. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  7817. * is updated with the result and aRoot is returned. Otherwise the result
  7818. * is returned.
  7819. * - If aPath is absolute, the result is aPath.
  7820. * - Otherwise the two paths are joined with a slash.
  7821. * - Joining for example 'http://' and 'www.example.com' is also supported.
  7822. */
  7823. function join(aRoot, aPath) {
  7824. if (aRoot === "") {
  7825. aRoot = ".";
  7826. }
  7827. if (aPath === "") {
  7828. aPath = ".";
  7829. }
  7830. var aPathUrl = urlParse(aPath);
  7831. var aRootUrl = urlParse(aRoot);
  7832. if (aRootUrl) {
  7833. aRoot = aRootUrl.path || '/';
  7834. }
  7835. // `join(foo, '//www.example.org')`
  7836. if (aPathUrl && !aPathUrl.scheme) {
  7837. if (aRootUrl) {
  7838. aPathUrl.scheme = aRootUrl.scheme;
  7839. }
  7840. return urlGenerate(aPathUrl);
  7841. }
  7842. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  7843. return aPath;
  7844. }
  7845. // `join('http://', 'www.example.com')`
  7846. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  7847. aRootUrl.host = aPath;
  7848. return urlGenerate(aRootUrl);
  7849. }
  7850. var joined = aPath.charAt(0) === '/'
  7851. ? aPath
  7852. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  7853. if (aRootUrl) {
  7854. aRootUrl.path = joined;
  7855. return urlGenerate(aRootUrl);
  7856. }
  7857. return joined;
  7858. }
  7859. exports.join = join;
  7860. exports.isAbsolute = function (aPath) {
  7861. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  7862. };
  7863. /**
  7864. * Make a path relative to a URL or another path.
  7865. *
  7866. * @param aRoot The root path or URL.
  7867. * @param aPath The path or URL to be made relative to aRoot.
  7868. */
  7869. function relative(aRoot, aPath) {
  7870. if (aRoot === "") {
  7871. aRoot = ".";
  7872. }
  7873. aRoot = aRoot.replace(/\/$/, '');
  7874. // It is possible for the path to be above the root. In this case, simply
  7875. // checking whether the root is a prefix of the path won't work. Instead, we
  7876. // need to remove components from the root one by one, until either we find
  7877. // a prefix that fits, or we run out of components to remove.
  7878. var level = 0;
  7879. while (aPath.indexOf(aRoot + '/') !== 0) {
  7880. var index = aRoot.lastIndexOf("/");
  7881. if (index < 0) {
  7882. return aPath;
  7883. }
  7884. // If the only part of the root that is left is the scheme (i.e. http://,
  7885. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  7886. // have exhausted all components, so the path is not relative to the root.
  7887. aRoot = aRoot.slice(0, index);
  7888. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  7889. return aPath;
  7890. }
  7891. ++level;
  7892. }
  7893. // Make sure we add a "../" for each component we removed from the root.
  7894. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  7895. }
  7896. exports.relative = relative;
  7897. var supportsNullProto = (function () {
  7898. var obj = Object.create(null);
  7899. return !('__proto__' in obj);
  7900. }());
  7901. function identity (s) {
  7902. return s;
  7903. }
  7904. /**
  7905. * Because behavior goes wacky when you set `__proto__` on objects, we
  7906. * have to prefix all the strings in our set with an arbitrary character.
  7907. *
  7908. * See https://github.com/mozilla/source-map/pull/31 and
  7909. * https://github.com/mozilla/source-map/issues/30
  7910. *
  7911. * @param String aStr
  7912. */
  7913. function toSetString(aStr) {
  7914. if (isProtoString(aStr)) {
  7915. return '$' + aStr;
  7916. }
  7917. return aStr;
  7918. }
  7919. exports.toSetString = supportsNullProto ? identity : toSetString;
  7920. function fromSetString(aStr) {
  7921. if (isProtoString(aStr)) {
  7922. return aStr.slice(1);
  7923. }
  7924. return aStr;
  7925. }
  7926. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  7927. function isProtoString(s) {
  7928. if (!s) {
  7929. return false;
  7930. }
  7931. var length = s.length;
  7932. if (length < 9 /* "__proto__".length */) {
  7933. return false;
  7934. }
  7935. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  7936. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  7937. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  7938. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  7939. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  7940. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  7941. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  7942. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  7943. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  7944. return false;
  7945. }
  7946. for (var i = length - 10; i >= 0; i--) {
  7947. if (s.charCodeAt(i) !== 36 /* '$' */) {
  7948. return false;
  7949. }
  7950. }
  7951. return true;
  7952. }
  7953. /**
  7954. * Comparator between two mappings where the original positions are compared.
  7955. *
  7956. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  7957. * mappings with the same original source/line/column, but different generated
  7958. * line and column the same. Useful when searching for a mapping with a
  7959. * stubbed out mapping.
  7960. */
  7961. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  7962. var cmp = strcmp(mappingA.source, mappingB.source);
  7963. if (cmp !== 0) {
  7964. return cmp;
  7965. }
  7966. cmp = mappingA.originalLine - mappingB.originalLine;
  7967. if (cmp !== 0) {
  7968. return cmp;
  7969. }
  7970. cmp = mappingA.originalColumn - mappingB.originalColumn;
  7971. if (cmp !== 0 || onlyCompareOriginal) {
  7972. return cmp;
  7973. }
  7974. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  7975. if (cmp !== 0) {
  7976. return cmp;
  7977. }
  7978. cmp = mappingA.generatedLine - mappingB.generatedLine;
  7979. if (cmp !== 0) {
  7980. return cmp;
  7981. }
  7982. return strcmp(mappingA.name, mappingB.name);
  7983. }
  7984. exports.compareByOriginalPositions = compareByOriginalPositions;
  7985. /**
  7986. * Comparator between two mappings with deflated source and name indices where
  7987. * the generated positions are compared.
  7988. *
  7989. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  7990. * mappings with the same generated line and column, but different
  7991. * source/name/original line and column the same. Useful when searching for a
  7992. * mapping with a stubbed out mapping.
  7993. */
  7994. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  7995. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  7996. if (cmp !== 0) {
  7997. return cmp;
  7998. }
  7999. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8000. if (cmp !== 0 || onlyCompareGenerated) {
  8001. return cmp;
  8002. }
  8003. cmp = strcmp(mappingA.source, mappingB.source);
  8004. if (cmp !== 0) {
  8005. return cmp;
  8006. }
  8007. cmp = mappingA.originalLine - mappingB.originalLine;
  8008. if (cmp !== 0) {
  8009. return cmp;
  8010. }
  8011. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8012. if (cmp !== 0) {
  8013. return cmp;
  8014. }
  8015. return strcmp(mappingA.name, mappingB.name);
  8016. }
  8017. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8018. function strcmp(aStr1, aStr2) {
  8019. if (aStr1 === aStr2) {
  8020. return 0;
  8021. }
  8022. if (aStr1 === null) {
  8023. return 1; // aStr2 !== null
  8024. }
  8025. if (aStr2 === null) {
  8026. return -1; // aStr1 !== null
  8027. }
  8028. if (aStr1 > aStr2) {
  8029. return 1;
  8030. }
  8031. return -1;
  8032. }
  8033. /**
  8034. * Comparator between two mappings with inflated source and name strings where
  8035. * the generated positions are compared.
  8036. */
  8037. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8038. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8039. if (cmp !== 0) {
  8040. return cmp;
  8041. }
  8042. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8043. if (cmp !== 0) {
  8044. return cmp;
  8045. }
  8046. cmp = strcmp(mappingA.source, mappingB.source);
  8047. if (cmp !== 0) {
  8048. return cmp;
  8049. }
  8050. cmp = mappingA.originalLine - mappingB.originalLine;
  8051. if (cmp !== 0) {
  8052. return cmp;
  8053. }
  8054. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8055. if (cmp !== 0) {
  8056. return cmp;
  8057. }
  8058. return strcmp(mappingA.name, mappingB.name);
  8059. }
  8060. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8061. /**
  8062. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8063. * in the source maps specification), and then parse the string as
  8064. * JSON.
  8065. */
  8066. function parseSourceMapInput(str) {
  8067. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8068. }
  8069. exports.parseSourceMapInput = parseSourceMapInput;
  8070. /**
  8071. * Compute the URL of a source given the the source root, the source's
  8072. * URL, and the source map's URL.
  8073. */
  8074. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8075. sourceURL = sourceURL || '';
  8076. if (sourceRoot) {
  8077. // This follows what Chrome does.
  8078. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8079. sourceRoot += '/';
  8080. }
  8081. // The spec says:
  8082. // Line 4: An optional source root, useful for relocating source
  8083. // files on a server or removing repeated values in the
  8084. // “sources” entry. This value is prepended to the individual
  8085. // entries in the “source” field.
  8086. sourceURL = sourceRoot + sourceURL;
  8087. }
  8088. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8089. // a parameter. This mode is still somewhat supported, which is why
  8090. // this code block is conditional. However, it's preferable to pass
  8091. // the source map URL to SourceMapConsumer, so that this function
  8092. // can implement the source URL resolution algorithm as outlined in
  8093. // the spec. This block is basically the equivalent of:
  8094. // new URL(sourceURL, sourceMapURL).toString()
  8095. // ... except it avoids using URL, which wasn't available in the
  8096. // older releases of node still supported by this library.
  8097. //
  8098. // The spec says:
  8099. // If the sources are not absolute URLs after prepending of the
  8100. // “sourceRoot”, the sources are resolved relative to the
  8101. // SourceMap (like resolving script src in a html document).
  8102. if (sourceMapURL) {
  8103. var parsed = urlParse(sourceMapURL);
  8104. if (!parsed) {
  8105. throw new Error("sourceMapURL could not be parsed");
  8106. }
  8107. if (parsed.path) {
  8108. // Strip the last path component, but keep the "/".
  8109. var index = parsed.path.lastIndexOf('/');
  8110. if (index >= 0) {
  8111. parsed.path = parsed.path.substring(0, index + 1);
  8112. }
  8113. }
  8114. sourceURL = join(urlGenerate(parsed), sourceURL);
  8115. }
  8116. return normalize(sourceURL);
  8117. }
  8118. exports.computeSourceURL = computeSourceURL;
  8119. } (util$5));
  8120. var arraySet = {};
  8121. /* -*- Mode: js; js-indent-level: 2; -*- */
  8122. /*
  8123. * Copyright 2011 Mozilla Foundation and contributors
  8124. * Licensed under the New BSD license. See LICENSE or:
  8125. * http://opensource.org/licenses/BSD-3-Clause
  8126. */
  8127. var util$4 = util$5;
  8128. var has = Object.prototype.hasOwnProperty;
  8129. var hasNativeMap = typeof Map !== "undefined";
  8130. /**
  8131. * A data structure which is a combination of an array and a set. Adding a new
  8132. * member is O(1), testing for membership is O(1), and finding the index of an
  8133. * element is O(1). Removing elements from the set is not supported. Only
  8134. * strings are supported for membership.
  8135. */
  8136. function ArraySet$2() {
  8137. this._array = [];
  8138. this._set = hasNativeMap ? new Map() : Object.create(null);
  8139. }
  8140. /**
  8141. * Static method for creating ArraySet instances from an existing array.
  8142. */
  8143. ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8144. var set = new ArraySet$2();
  8145. for (var i = 0, len = aArray.length; i < len; i++) {
  8146. set.add(aArray[i], aAllowDuplicates);
  8147. }
  8148. return set;
  8149. };
  8150. /**
  8151. * Return how many unique items are in this ArraySet. If duplicates have been
  8152. * added, than those do not count towards the size.
  8153. *
  8154. * @returns Number
  8155. */
  8156. ArraySet$2.prototype.size = function ArraySet_size() {
  8157. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8158. };
  8159. /**
  8160. * Add the given string to this set.
  8161. *
  8162. * @param String aStr
  8163. */
  8164. ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8165. var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr);
  8166. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8167. var idx = this._array.length;
  8168. if (!isDuplicate || aAllowDuplicates) {
  8169. this._array.push(aStr);
  8170. }
  8171. if (!isDuplicate) {
  8172. if (hasNativeMap) {
  8173. this._set.set(aStr, idx);
  8174. } else {
  8175. this._set[sStr] = idx;
  8176. }
  8177. }
  8178. };
  8179. /**
  8180. * Is the given string a member of this set?
  8181. *
  8182. * @param String aStr
  8183. */
  8184. ArraySet$2.prototype.has = function ArraySet_has(aStr) {
  8185. if (hasNativeMap) {
  8186. return this._set.has(aStr);
  8187. } else {
  8188. var sStr = util$4.toSetString(aStr);
  8189. return has.call(this._set, sStr);
  8190. }
  8191. };
  8192. /**
  8193. * What is the index of the given string in the array?
  8194. *
  8195. * @param String aStr
  8196. */
  8197. ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8198. if (hasNativeMap) {
  8199. var idx = this._set.get(aStr);
  8200. if (idx >= 0) {
  8201. return idx;
  8202. }
  8203. } else {
  8204. var sStr = util$4.toSetString(aStr);
  8205. if (has.call(this._set, sStr)) {
  8206. return this._set[sStr];
  8207. }
  8208. }
  8209. throw new Error('"' + aStr + '" is not in the set.');
  8210. };
  8211. /**
  8212. * What is the element at the given index?
  8213. *
  8214. * @param Number aIdx
  8215. */
  8216. ArraySet$2.prototype.at = function ArraySet_at(aIdx) {
  8217. if (aIdx >= 0 && aIdx < this._array.length) {
  8218. return this._array[aIdx];
  8219. }
  8220. throw new Error('No element indexed by ' + aIdx);
  8221. };
  8222. /**
  8223. * Returns the array representation of this set (which has the proper indices
  8224. * indicated by indexOf). Note that this is a copy of the internal array used
  8225. * for storing the members so that no one can mess with internal state.
  8226. */
  8227. ArraySet$2.prototype.toArray = function ArraySet_toArray() {
  8228. return this._array.slice();
  8229. };
  8230. arraySet.ArraySet = ArraySet$2;
  8231. var mappingList = {};
  8232. /* -*- Mode: js; js-indent-level: 2; -*- */
  8233. /*
  8234. * Copyright 2014 Mozilla Foundation and contributors
  8235. * Licensed under the New BSD license. See LICENSE or:
  8236. * http://opensource.org/licenses/BSD-3-Clause
  8237. */
  8238. var util$3 = util$5;
  8239. /**
  8240. * Determine whether mappingB is after mappingA with respect to generated
  8241. * position.
  8242. */
  8243. function generatedPositionAfter(mappingA, mappingB) {
  8244. // Optimized for most common case
  8245. var lineA = mappingA.generatedLine;
  8246. var lineB = mappingB.generatedLine;
  8247. var columnA = mappingA.generatedColumn;
  8248. var columnB = mappingB.generatedColumn;
  8249. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8250. util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8251. }
  8252. /**
  8253. * A data structure to provide a sorted view of accumulated mappings in a
  8254. * performance conscious manner. It trades a neglibable overhead in general
  8255. * case for a large speedup in case of mappings being added in order.
  8256. */
  8257. function MappingList$1() {
  8258. this._array = [];
  8259. this._sorted = true;
  8260. // Serves as infimum
  8261. this._last = {generatedLine: -1, generatedColumn: 0};
  8262. }
  8263. /**
  8264. * Iterate through internal items. This method takes the same arguments that
  8265. * `Array.prototype.forEach` takes.
  8266. *
  8267. * NOTE: The order of the mappings is NOT guaranteed.
  8268. */
  8269. MappingList$1.prototype.unsortedForEach =
  8270. function MappingList_forEach(aCallback, aThisArg) {
  8271. this._array.forEach(aCallback, aThisArg);
  8272. };
  8273. /**
  8274. * Add the given source mapping.
  8275. *
  8276. * @param Object aMapping
  8277. */
  8278. MappingList$1.prototype.add = function MappingList_add(aMapping) {
  8279. if (generatedPositionAfter(this._last, aMapping)) {
  8280. this._last = aMapping;
  8281. this._array.push(aMapping);
  8282. } else {
  8283. this._sorted = false;
  8284. this._array.push(aMapping);
  8285. }
  8286. };
  8287. /**
  8288. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8289. * generated position.
  8290. *
  8291. * WARNING: This method returns internal data without copying, for
  8292. * performance. The return value must NOT be mutated, and should be treated as
  8293. * an immutable borrow. If you want to take ownership, you must make your own
  8294. * copy.
  8295. */
  8296. MappingList$1.prototype.toArray = function MappingList_toArray() {
  8297. if (!this._sorted) {
  8298. this._array.sort(util$3.compareByGeneratedPositionsInflated);
  8299. this._sorted = true;
  8300. }
  8301. return this._array;
  8302. };
  8303. mappingList.MappingList = MappingList$1;
  8304. /* -*- Mode: js; js-indent-level: 2; -*- */
  8305. /*
  8306. * Copyright 2011 Mozilla Foundation and contributors
  8307. * Licensed under the New BSD license. See LICENSE or:
  8308. * http://opensource.org/licenses/BSD-3-Clause
  8309. */
  8310. var base64VLQ$1 = base64Vlq;
  8311. var util$2 = util$5;
  8312. var ArraySet$1 = arraySet.ArraySet;
  8313. var MappingList = mappingList.MappingList;
  8314. /**
  8315. * An instance of the SourceMapGenerator represents a source map which is
  8316. * being built incrementally. You may pass an object with the following
  8317. * properties:
  8318. *
  8319. * - file: The filename of the generated source.
  8320. * - sourceRoot: A root for all relative URLs in this source map.
  8321. */
  8322. function SourceMapGenerator$2(aArgs) {
  8323. if (!aArgs) {
  8324. aArgs = {};
  8325. }
  8326. this._file = util$2.getArg(aArgs, 'file', null);
  8327. this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null);
  8328. this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false);
  8329. this._sources = new ArraySet$1();
  8330. this._names = new ArraySet$1();
  8331. this._mappings = new MappingList();
  8332. this._sourcesContents = null;
  8333. }
  8334. SourceMapGenerator$2.prototype._version = 3;
  8335. /**
  8336. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8337. *
  8338. * @param aSourceMapConsumer The SourceMap.
  8339. */
  8340. SourceMapGenerator$2.fromSourceMap =
  8341. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8342. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8343. var generator = new SourceMapGenerator$2({
  8344. file: aSourceMapConsumer.file,
  8345. sourceRoot: sourceRoot
  8346. });
  8347. aSourceMapConsumer.eachMapping(function (mapping) {
  8348. var newMapping = {
  8349. generated: {
  8350. line: mapping.generatedLine,
  8351. column: mapping.generatedColumn
  8352. }
  8353. };
  8354. if (mapping.source != null) {
  8355. newMapping.source = mapping.source;
  8356. if (sourceRoot != null) {
  8357. newMapping.source = util$2.relative(sourceRoot, newMapping.source);
  8358. }
  8359. newMapping.original = {
  8360. line: mapping.originalLine,
  8361. column: mapping.originalColumn
  8362. };
  8363. if (mapping.name != null) {
  8364. newMapping.name = mapping.name;
  8365. }
  8366. }
  8367. generator.addMapping(newMapping);
  8368. });
  8369. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8370. var sourceRelative = sourceFile;
  8371. if (sourceRoot !== null) {
  8372. sourceRelative = util$2.relative(sourceRoot, sourceFile);
  8373. }
  8374. if (!generator._sources.has(sourceRelative)) {
  8375. generator._sources.add(sourceRelative);
  8376. }
  8377. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8378. if (content != null) {
  8379. generator.setSourceContent(sourceFile, content);
  8380. }
  8381. });
  8382. return generator;
  8383. };
  8384. /**
  8385. * Add a single mapping from original source line and column to the generated
  8386. * source's line and column for this source map being created. The mapping
  8387. * object should have the following properties:
  8388. *
  8389. * - generated: An object with the generated line and column positions.
  8390. * - original: An object with the original line and column positions.
  8391. * - source: The original source file (relative to the sourceRoot).
  8392. * - name: An optional original token name for this mapping.
  8393. */
  8394. SourceMapGenerator$2.prototype.addMapping =
  8395. function SourceMapGenerator_addMapping(aArgs) {
  8396. var generated = util$2.getArg(aArgs, 'generated');
  8397. var original = util$2.getArg(aArgs, 'original', null);
  8398. var source = util$2.getArg(aArgs, 'source', null);
  8399. var name = util$2.getArg(aArgs, 'name', null);
  8400. if (!this._skipValidation) {
  8401. this._validateMapping(generated, original, source, name);
  8402. }
  8403. if (source != null) {
  8404. source = String(source);
  8405. if (!this._sources.has(source)) {
  8406. this._sources.add(source);
  8407. }
  8408. }
  8409. if (name != null) {
  8410. name = String(name);
  8411. if (!this._names.has(name)) {
  8412. this._names.add(name);
  8413. }
  8414. }
  8415. this._mappings.add({
  8416. generatedLine: generated.line,
  8417. generatedColumn: generated.column,
  8418. originalLine: original != null && original.line,
  8419. originalColumn: original != null && original.column,
  8420. source: source,
  8421. name: name
  8422. });
  8423. };
  8424. /**
  8425. * Set the source content for a source file.
  8426. */
  8427. SourceMapGenerator$2.prototype.setSourceContent =
  8428. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8429. var source = aSourceFile;
  8430. if (this._sourceRoot != null) {
  8431. source = util$2.relative(this._sourceRoot, source);
  8432. }
  8433. if (aSourceContent != null) {
  8434. // Add the source content to the _sourcesContents map.
  8435. // Create a new _sourcesContents map if the property is null.
  8436. if (!this._sourcesContents) {
  8437. this._sourcesContents = Object.create(null);
  8438. }
  8439. this._sourcesContents[util$2.toSetString(source)] = aSourceContent;
  8440. } else if (this._sourcesContents) {
  8441. // Remove the source file from the _sourcesContents map.
  8442. // If the _sourcesContents map is empty, set the property to null.
  8443. delete this._sourcesContents[util$2.toSetString(source)];
  8444. if (Object.keys(this._sourcesContents).length === 0) {
  8445. this._sourcesContents = null;
  8446. }
  8447. }
  8448. };
  8449. /**
  8450. * Applies the mappings of a sub-source-map for a specific source file to the
  8451. * source map being generated. Each mapping to the supplied source file is
  8452. * rewritten using the supplied source map. Note: The resolution for the
  8453. * resulting mappings is the minimium of this map and the supplied map.
  8454. *
  8455. * @param aSourceMapConsumer The source map to be applied.
  8456. * @param aSourceFile Optional. The filename of the source file.
  8457. * If omitted, SourceMapConsumer's file property will be used.
  8458. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8459. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8460. * This parameter is needed when the two source maps aren't in the same
  8461. * directory, and the source map to be applied contains relative source
  8462. * paths. If so, those relative source paths need to be rewritten
  8463. * relative to the SourceMapGenerator.
  8464. */
  8465. SourceMapGenerator$2.prototype.applySourceMap =
  8466. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8467. var sourceFile = aSourceFile;
  8468. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8469. if (aSourceFile == null) {
  8470. if (aSourceMapConsumer.file == null) {
  8471. throw new Error(
  8472. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8473. 'or the source map\'s "file" property. Both were omitted.'
  8474. );
  8475. }
  8476. sourceFile = aSourceMapConsumer.file;
  8477. }
  8478. var sourceRoot = this._sourceRoot;
  8479. // Make "sourceFile" relative if an absolute Url is passed.
  8480. if (sourceRoot != null) {
  8481. sourceFile = util$2.relative(sourceRoot, sourceFile);
  8482. }
  8483. // Applying the SourceMap can add and remove items from the sources and
  8484. // the names array.
  8485. var newSources = new ArraySet$1();
  8486. var newNames = new ArraySet$1();
  8487. // Find mappings for the "sourceFile"
  8488. this._mappings.unsortedForEach(function (mapping) {
  8489. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8490. // Check if it can be mapped by the source map, then update the mapping.
  8491. var original = aSourceMapConsumer.originalPositionFor({
  8492. line: mapping.originalLine,
  8493. column: mapping.originalColumn
  8494. });
  8495. if (original.source != null) {
  8496. // Copy mapping
  8497. mapping.source = original.source;
  8498. if (aSourceMapPath != null) {
  8499. mapping.source = util$2.join(aSourceMapPath, mapping.source);
  8500. }
  8501. if (sourceRoot != null) {
  8502. mapping.source = util$2.relative(sourceRoot, mapping.source);
  8503. }
  8504. mapping.originalLine = original.line;
  8505. mapping.originalColumn = original.column;
  8506. if (original.name != null) {
  8507. mapping.name = original.name;
  8508. }
  8509. }
  8510. }
  8511. var source = mapping.source;
  8512. if (source != null && !newSources.has(source)) {
  8513. newSources.add(source);
  8514. }
  8515. var name = mapping.name;
  8516. if (name != null && !newNames.has(name)) {
  8517. newNames.add(name);
  8518. }
  8519. }, this);
  8520. this._sources = newSources;
  8521. this._names = newNames;
  8522. // Copy sourcesContents of applied map.
  8523. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8524. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8525. if (content != null) {
  8526. if (aSourceMapPath != null) {
  8527. sourceFile = util$2.join(aSourceMapPath, sourceFile);
  8528. }
  8529. if (sourceRoot != null) {
  8530. sourceFile = util$2.relative(sourceRoot, sourceFile);
  8531. }
  8532. this.setSourceContent(sourceFile, content);
  8533. }
  8534. }, this);
  8535. };
  8536. /**
  8537. * A mapping can have one of the three levels of data:
  8538. *
  8539. * 1. Just the generated position.
  8540. * 2. The Generated position, original position, and original source.
  8541. * 3. Generated and original position, original source, as well as a name
  8542. * token.
  8543. *
  8544. * To maintain consistency, we validate that any new mapping being added falls
  8545. * in to one of these categories.
  8546. */
  8547. SourceMapGenerator$2.prototype._validateMapping =
  8548. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8549. aName) {
  8550. // When aOriginal is truthy but has empty values for .line and .column,
  8551. // it is most likely a programmer error. In this case we throw a very
  8552. // specific error message to try to guide them the right way.
  8553. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8554. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8555. throw new Error(
  8556. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8557. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8558. 'null for the original mapping instead of an object with empty or null values.'
  8559. );
  8560. }
  8561. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8562. && aGenerated.line > 0 && aGenerated.column >= 0
  8563. && !aOriginal && !aSource && !aName) {
  8564. // Case 1.
  8565. return;
  8566. }
  8567. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8568. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8569. && aGenerated.line > 0 && aGenerated.column >= 0
  8570. && aOriginal.line > 0 && aOriginal.column >= 0
  8571. && aSource) {
  8572. // Cases 2 and 3.
  8573. return;
  8574. }
  8575. else {
  8576. throw new Error('Invalid mapping: ' + JSON.stringify({
  8577. generated: aGenerated,
  8578. source: aSource,
  8579. original: aOriginal,
  8580. name: aName
  8581. }));
  8582. }
  8583. };
  8584. /**
  8585. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8586. * specified by the source map format.
  8587. */
  8588. SourceMapGenerator$2.prototype._serializeMappings =
  8589. function SourceMapGenerator_serializeMappings() {
  8590. var previousGeneratedColumn = 0;
  8591. var previousGeneratedLine = 1;
  8592. var previousOriginalColumn = 0;
  8593. var previousOriginalLine = 0;
  8594. var previousName = 0;
  8595. var previousSource = 0;
  8596. var result = '';
  8597. var next;
  8598. var mapping;
  8599. var nameIdx;
  8600. var sourceIdx;
  8601. var mappings = this._mappings.toArray();
  8602. for (var i = 0, len = mappings.length; i < len; i++) {
  8603. mapping = mappings[i];
  8604. next = '';
  8605. if (mapping.generatedLine !== previousGeneratedLine) {
  8606. previousGeneratedColumn = 0;
  8607. while (mapping.generatedLine !== previousGeneratedLine) {
  8608. next += ';';
  8609. previousGeneratedLine++;
  8610. }
  8611. }
  8612. else {
  8613. if (i > 0) {
  8614. if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8615. continue;
  8616. }
  8617. next += ',';
  8618. }
  8619. }
  8620. next += base64VLQ$1.encode(mapping.generatedColumn
  8621. - previousGeneratedColumn);
  8622. previousGeneratedColumn = mapping.generatedColumn;
  8623. if (mapping.source != null) {
  8624. sourceIdx = this._sources.indexOf(mapping.source);
  8625. next += base64VLQ$1.encode(sourceIdx - previousSource);
  8626. previousSource = sourceIdx;
  8627. // lines are stored 0-based in SourceMap spec version 3
  8628. next += base64VLQ$1.encode(mapping.originalLine - 1
  8629. - previousOriginalLine);
  8630. previousOriginalLine = mapping.originalLine - 1;
  8631. next += base64VLQ$1.encode(mapping.originalColumn
  8632. - previousOriginalColumn);
  8633. previousOriginalColumn = mapping.originalColumn;
  8634. if (mapping.name != null) {
  8635. nameIdx = this._names.indexOf(mapping.name);
  8636. next += base64VLQ$1.encode(nameIdx - previousName);
  8637. previousName = nameIdx;
  8638. }
  8639. }
  8640. result += next;
  8641. }
  8642. return result;
  8643. };
  8644. SourceMapGenerator$2.prototype._generateSourcesContent =
  8645. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8646. return aSources.map(function (source) {
  8647. if (!this._sourcesContents) {
  8648. return null;
  8649. }
  8650. if (aSourceRoot != null) {
  8651. source = util$2.relative(aSourceRoot, source);
  8652. }
  8653. var key = util$2.toSetString(source);
  8654. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8655. ? this._sourcesContents[key]
  8656. : null;
  8657. }, this);
  8658. };
  8659. /**
  8660. * Externalize the source map.
  8661. */
  8662. SourceMapGenerator$2.prototype.toJSON =
  8663. function SourceMapGenerator_toJSON() {
  8664. var map = {
  8665. version: this._version,
  8666. sources: this._sources.toArray(),
  8667. names: this._names.toArray(),
  8668. mappings: this._serializeMappings()
  8669. };
  8670. if (this._file != null) {
  8671. map.file = this._file;
  8672. }
  8673. if (this._sourceRoot != null) {
  8674. map.sourceRoot = this._sourceRoot;
  8675. }
  8676. if (this._sourcesContents) {
  8677. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8678. }
  8679. return map;
  8680. };
  8681. /**
  8682. * Render the source map being generated to a string.
  8683. */
  8684. SourceMapGenerator$2.prototype.toString =
  8685. function SourceMapGenerator_toString() {
  8686. return JSON.stringify(this.toJSON());
  8687. };
  8688. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$2;
  8689. var sourceMapConsumer = {};
  8690. var binarySearch$1 = {};
  8691. /* -*- Mode: js; js-indent-level: 2; -*- */
  8692. (function (exports) {
  8693. /*
  8694. * Copyright 2011 Mozilla Foundation and contributors
  8695. * Licensed under the New BSD license. See LICENSE or:
  8696. * http://opensource.org/licenses/BSD-3-Clause
  8697. */
  8698. exports.GREATEST_LOWER_BOUND = 1;
  8699. exports.LEAST_UPPER_BOUND = 2;
  8700. /**
  8701. * Recursive implementation of binary search.
  8702. *
  8703. * @param aLow Indices here and lower do not contain the needle.
  8704. * @param aHigh Indices here and higher do not contain the needle.
  8705. * @param aNeedle The element being searched for.
  8706. * @param aHaystack The non-empty array being searched.
  8707. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8708. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8709. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8710. * closest element that is smaller than or greater than the one we are
  8711. * searching for, respectively, if the exact element cannot be found.
  8712. */
  8713. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8714. // This function terminates when one of the following is true:
  8715. //
  8716. // 1. We find the exact element we are looking for.
  8717. //
  8718. // 2. We did not find the exact element, but we can return the index of
  8719. // the next-closest element.
  8720. //
  8721. // 3. We did not find the exact element, and there is no next-closest
  8722. // element than the one we are searching for, so we return -1.
  8723. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  8724. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  8725. if (cmp === 0) {
  8726. // Found the element we are looking for.
  8727. return mid;
  8728. }
  8729. else if (cmp > 0) {
  8730. // Our needle is greater than aHaystack[mid].
  8731. if (aHigh - mid > 1) {
  8732. // The element is in the upper half.
  8733. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  8734. }
  8735. // The exact needle element was not found in this haystack. Determine if
  8736. // we are in termination case (3) or (2) and return the appropriate thing.
  8737. if (aBias == exports.LEAST_UPPER_BOUND) {
  8738. return aHigh < aHaystack.length ? aHigh : -1;
  8739. } else {
  8740. return mid;
  8741. }
  8742. }
  8743. else {
  8744. // Our needle is less than aHaystack[mid].
  8745. if (mid - aLow > 1) {
  8746. // The element is in the lower half.
  8747. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  8748. }
  8749. // we are in termination case (3) or (2) and return the appropriate thing.
  8750. if (aBias == exports.LEAST_UPPER_BOUND) {
  8751. return mid;
  8752. } else {
  8753. return aLow < 0 ? -1 : aLow;
  8754. }
  8755. }
  8756. }
  8757. /**
  8758. * This is an implementation of binary search which will always try and return
  8759. * the index of the closest element if there is no exact hit. This is because
  8760. * mappings between original and generated line/col pairs are single points,
  8761. * and there is an implicit region between each of them, so a miss just means
  8762. * that you aren't on the very start of a region.
  8763. *
  8764. * @param aNeedle The element you are looking for.
  8765. * @param aHaystack The array that is being searched.
  8766. * @param aCompare A function which takes the needle and an element in the
  8767. * array and returns -1, 0, or 1 depending on whether the needle is less
  8768. * than, equal to, or greater than the element, respectively.
  8769. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8770. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8771. * closest element that is smaller than or greater than the one we are
  8772. * searching for, respectively, if the exact element cannot be found.
  8773. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  8774. */
  8775. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  8776. if (aHaystack.length === 0) {
  8777. return -1;
  8778. }
  8779. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  8780. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  8781. if (index < 0) {
  8782. return -1;
  8783. }
  8784. // We have found either the exact element, or the next-closest element than
  8785. // the one we are searching for. However, there may be more than one such
  8786. // element. Make sure we always return the smallest of these.
  8787. while (index - 1 >= 0) {
  8788. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  8789. break;
  8790. }
  8791. --index;
  8792. }
  8793. return index;
  8794. };
  8795. } (binarySearch$1));
  8796. var quickSort$1 = {};
  8797. /* -*- Mode: js; js-indent-level: 2; -*- */
  8798. /*
  8799. * Copyright 2011 Mozilla Foundation and contributors
  8800. * Licensed under the New BSD license. See LICENSE or:
  8801. * http://opensource.org/licenses/BSD-3-Clause
  8802. */
  8803. // It turns out that some (most?) JavaScript engines don't self-host
  8804. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  8805. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  8806. // custom comparator function, calling back and forth between the VM's C++ and
  8807. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  8808. // worse generated code for the comparator function than would be optimal. In
  8809. // fact, when sorting with a comparator, these costs outweigh the benefits of
  8810. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  8811. // a ~3500ms mean speed-up in `bench/bench.html`.
  8812. /**
  8813. * Swap the elements indexed by `x` and `y` in the array `ary`.
  8814. *
  8815. * @param {Array} ary
  8816. * The array.
  8817. * @param {Number} x
  8818. * The index of the first item.
  8819. * @param {Number} y
  8820. * The index of the second item.
  8821. */
  8822. function swap(ary, x, y) {
  8823. var temp = ary[x];
  8824. ary[x] = ary[y];
  8825. ary[y] = temp;
  8826. }
  8827. /**
  8828. * Returns a random integer within the range `low .. high` inclusive.
  8829. *
  8830. * @param {Number} low
  8831. * The lower bound on the range.
  8832. * @param {Number} high
  8833. * The upper bound on the range.
  8834. */
  8835. function randomIntInRange(low, high) {
  8836. return Math.round(low + (Math.random() * (high - low)));
  8837. }
  8838. /**
  8839. * The Quick Sort algorithm.
  8840. *
  8841. * @param {Array} ary
  8842. * An array to sort.
  8843. * @param {function} comparator
  8844. * Function to use to compare two items.
  8845. * @param {Number} p
  8846. * Start index of the array
  8847. * @param {Number} r
  8848. * End index of the array
  8849. */
  8850. function doQuickSort(ary, comparator, p, r) {
  8851. // If our lower bound is less than our upper bound, we (1) partition the
  8852. // array into two pieces and (2) recurse on each half. If it is not, this is
  8853. // the empty array and our base case.
  8854. if (p < r) {
  8855. // (1) Partitioning.
  8856. //
  8857. // The partitioning chooses a pivot between `p` and `r` and moves all
  8858. // elements that are less than or equal to the pivot to the before it, and
  8859. // all the elements that are greater than it after it. The effect is that
  8860. // once partition is done, the pivot is in the exact place it will be when
  8861. // the array is put in sorted order, and it will not need to be moved
  8862. // again. This runs in O(n) time.
  8863. // Always choose a random pivot so that an input array which is reverse
  8864. // sorted does not cause O(n^2) running time.
  8865. var pivotIndex = randomIntInRange(p, r);
  8866. var i = p - 1;
  8867. swap(ary, pivotIndex, r);
  8868. var pivot = ary[r];
  8869. // Immediately after `j` is incremented in this loop, the following hold
  8870. // true:
  8871. //
  8872. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  8873. //
  8874. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  8875. for (var j = p; j < r; j++) {
  8876. if (comparator(ary[j], pivot) <= 0) {
  8877. i += 1;
  8878. swap(ary, i, j);
  8879. }
  8880. }
  8881. swap(ary, i + 1, j);
  8882. var q = i + 1;
  8883. // (2) Recurse on each half.
  8884. doQuickSort(ary, comparator, p, q - 1);
  8885. doQuickSort(ary, comparator, q + 1, r);
  8886. }
  8887. }
  8888. /**
  8889. * Sort the given array in-place with the given comparator function.
  8890. *
  8891. * @param {Array} ary
  8892. * An array to sort.
  8893. * @param {function} comparator
  8894. * Function to use to compare two items.
  8895. */
  8896. quickSort$1.quickSort = function (ary, comparator) {
  8897. doQuickSort(ary, comparator, 0, ary.length - 1);
  8898. };
  8899. /* -*- Mode: js; js-indent-level: 2; -*- */
  8900. /*
  8901. * Copyright 2011 Mozilla Foundation and contributors
  8902. * Licensed under the New BSD license. See LICENSE or:
  8903. * http://opensource.org/licenses/BSD-3-Clause
  8904. */
  8905. var util$1 = util$5;
  8906. var binarySearch = binarySearch$1;
  8907. var ArraySet = arraySet.ArraySet;
  8908. var base64VLQ = base64Vlq;
  8909. var quickSort = quickSort$1.quickSort;
  8910. function SourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  8911. var sourceMap = aSourceMap;
  8912. if (typeof aSourceMap === 'string') {
  8913. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  8914. }
  8915. return sourceMap.sections != null
  8916. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  8917. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  8918. }
  8919. SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  8920. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  8921. };
  8922. /**
  8923. * The version of the source mapping spec that we are consuming.
  8924. */
  8925. SourceMapConsumer$1.prototype._version = 3;
  8926. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  8927. // parsed mapping coordinates from the source map's "mappings" attribute. They
  8928. // are lazily instantiated, accessed via the `_generatedMappings` and
  8929. // `_originalMappings` getters respectively, and we only parse the mappings
  8930. // and create these arrays once queried for a source location. We jump through
  8931. // these hoops because there can be many thousands of mappings, and parsing
  8932. // them is expensive, so we only want to do it if we must.
  8933. //
  8934. // Each object in the arrays is of the form:
  8935. //
  8936. // {
  8937. // generatedLine: The line number in the generated code,
  8938. // generatedColumn: The column number in the generated code,
  8939. // source: The path to the original source file that generated this
  8940. // chunk of code,
  8941. // originalLine: The line number in the original source that
  8942. // corresponds to this chunk of generated code,
  8943. // originalColumn: The column number in the original source that
  8944. // corresponds to this chunk of generated code,
  8945. // name: The name of the original symbol which generated this chunk of
  8946. // code.
  8947. // }
  8948. //
  8949. // All properties except for `generatedLine` and `generatedColumn` can be
  8950. // `null`.
  8951. //
  8952. // `_generatedMappings` is ordered by the generated positions.
  8953. //
  8954. // `_originalMappings` is ordered by the original positions.
  8955. SourceMapConsumer$1.prototype.__generatedMappings = null;
  8956. Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', {
  8957. configurable: true,
  8958. enumerable: true,
  8959. get: function () {
  8960. if (!this.__generatedMappings) {
  8961. this._parseMappings(this._mappings, this.sourceRoot);
  8962. }
  8963. return this.__generatedMappings;
  8964. }
  8965. });
  8966. SourceMapConsumer$1.prototype.__originalMappings = null;
  8967. Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', {
  8968. configurable: true,
  8969. enumerable: true,
  8970. get: function () {
  8971. if (!this.__originalMappings) {
  8972. this._parseMappings(this._mappings, this.sourceRoot);
  8973. }
  8974. return this.__originalMappings;
  8975. }
  8976. });
  8977. SourceMapConsumer$1.prototype._charIsMappingSeparator =
  8978. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  8979. var c = aStr.charAt(index);
  8980. return c === ";" || c === ",";
  8981. };
  8982. /**
  8983. * Parse the mappings in a string in to a data structure which we can easily
  8984. * query (the ordered arrays in the `this.__generatedMappings` and
  8985. * `this.__originalMappings` properties).
  8986. */
  8987. SourceMapConsumer$1.prototype._parseMappings =
  8988. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  8989. throw new Error("Subclasses must implement _parseMappings");
  8990. };
  8991. SourceMapConsumer$1.GENERATED_ORDER = 1;
  8992. SourceMapConsumer$1.ORIGINAL_ORDER = 2;
  8993. SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1;
  8994. SourceMapConsumer$1.LEAST_UPPER_BOUND = 2;
  8995. /**
  8996. * Iterate over each mapping between an original source/line/column and a
  8997. * generated line/column in this source map.
  8998. *
  8999. * @param Function aCallback
  9000. * The function that is called with each mapping.
  9001. * @param Object aContext
  9002. * Optional. If specified, this object will be the value of `this` every
  9003. * time that `aCallback` is called.
  9004. * @param aOrder
  9005. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9006. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9007. * iterate over the mappings sorted by the generated file's line/column
  9008. * order or the original's source/line/column order, respectively. Defaults to
  9009. * `SourceMapConsumer.GENERATED_ORDER`.
  9010. */
  9011. SourceMapConsumer$1.prototype.eachMapping =
  9012. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9013. var context = aContext || null;
  9014. var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;
  9015. var mappings;
  9016. switch (order) {
  9017. case SourceMapConsumer$1.GENERATED_ORDER:
  9018. mappings = this._generatedMappings;
  9019. break;
  9020. case SourceMapConsumer$1.ORIGINAL_ORDER:
  9021. mappings = this._originalMappings;
  9022. break;
  9023. default:
  9024. throw new Error("Unknown order of iteration.");
  9025. }
  9026. var sourceRoot = this.sourceRoot;
  9027. mappings.map(function (mapping) {
  9028. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9029. source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9030. return {
  9031. source: source,
  9032. generatedLine: mapping.generatedLine,
  9033. generatedColumn: mapping.generatedColumn,
  9034. originalLine: mapping.originalLine,
  9035. originalColumn: mapping.originalColumn,
  9036. name: mapping.name === null ? null : this._names.at(mapping.name)
  9037. };
  9038. }, this).forEach(aCallback, context);
  9039. };
  9040. /**
  9041. * Returns all generated line and column information for the original source,
  9042. * line, and column provided. If no column is provided, returns all mappings
  9043. * corresponding to a either the line we are searching for or the next
  9044. * closest line that has any mappings. Otherwise, returns all mappings
  9045. * corresponding to the given line and either the column we are searching for
  9046. * or the next closest column that has any offsets.
  9047. *
  9048. * The only argument is an object with the following properties:
  9049. *
  9050. * - source: The filename of the original source.
  9051. * - line: The line number in the original source. The line number is 1-based.
  9052. * - column: Optional. the column number in the original source.
  9053. * The column number is 0-based.
  9054. *
  9055. * and an array of objects is returned, each with the following properties:
  9056. *
  9057. * - line: The line number in the generated source, or null. The
  9058. * line number is 1-based.
  9059. * - column: The column number in the generated source, or null.
  9060. * The column number is 0-based.
  9061. */
  9062. SourceMapConsumer$1.prototype.allGeneratedPositionsFor =
  9063. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9064. var line = util$1.getArg(aArgs, 'line');
  9065. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9066. // returns the index of the closest mapping less than the needle. By
  9067. // setting needle.originalColumn to 0, we thus find the last mapping for
  9068. // the given line, provided such a mapping exists.
  9069. var needle = {
  9070. source: util$1.getArg(aArgs, 'source'),
  9071. originalLine: line,
  9072. originalColumn: util$1.getArg(aArgs, 'column', 0)
  9073. };
  9074. needle.source = this._findSourceIndex(needle.source);
  9075. if (needle.source < 0) {
  9076. return [];
  9077. }
  9078. var mappings = [];
  9079. var index = this._findMapping(needle,
  9080. this._originalMappings,
  9081. "originalLine",
  9082. "originalColumn",
  9083. util$1.compareByOriginalPositions,
  9084. binarySearch.LEAST_UPPER_BOUND);
  9085. if (index >= 0) {
  9086. var mapping = this._originalMappings[index];
  9087. if (aArgs.column === undefined) {
  9088. var originalLine = mapping.originalLine;
  9089. // Iterate until either we run out of mappings, or we run into
  9090. // a mapping for a different line than the one we found. Since
  9091. // mappings are sorted, this is guaranteed to find all mappings for
  9092. // the line we found.
  9093. while (mapping && mapping.originalLine === originalLine) {
  9094. mappings.push({
  9095. line: util$1.getArg(mapping, 'generatedLine', null),
  9096. column: util$1.getArg(mapping, 'generatedColumn', null),
  9097. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9098. });
  9099. mapping = this._originalMappings[++index];
  9100. }
  9101. } else {
  9102. var originalColumn = mapping.originalColumn;
  9103. // Iterate until either we run out of mappings, or we run into
  9104. // a mapping for a different line than the one we were searching for.
  9105. // Since mappings are sorted, this is guaranteed to find all mappings for
  9106. // the line we are searching for.
  9107. while (mapping &&
  9108. mapping.originalLine === line &&
  9109. mapping.originalColumn == originalColumn) {
  9110. mappings.push({
  9111. line: util$1.getArg(mapping, 'generatedLine', null),
  9112. column: util$1.getArg(mapping, 'generatedColumn', null),
  9113. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9114. });
  9115. mapping = this._originalMappings[++index];
  9116. }
  9117. }
  9118. }
  9119. return mappings;
  9120. };
  9121. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1;
  9122. /**
  9123. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9124. * query for information about the original file positions by giving it a file
  9125. * position in the generated source.
  9126. *
  9127. * The first parameter is the raw source map (either as a JSON string, or
  9128. * already parsed to an object). According to the spec, source maps have the
  9129. * following attributes:
  9130. *
  9131. * - version: Which version of the source map spec this map is following.
  9132. * - sources: An array of URLs to the original source files.
  9133. * - names: An array of identifiers which can be referrenced by individual mappings.
  9134. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9135. * - sourcesContent: Optional. An array of contents of the original source files.
  9136. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9137. * - file: Optional. The generated file this source map is associated with.
  9138. *
  9139. * Here is an example source map, taken from the source map spec[0]:
  9140. *
  9141. * {
  9142. * version : 3,
  9143. * file: "out.js",
  9144. * sourceRoot : "",
  9145. * sources: ["foo.js", "bar.js"],
  9146. * names: ["src", "maps", "are", "fun"],
  9147. * mappings: "AA,AB;;ABCDE;"
  9148. * }
  9149. *
  9150. * The second parameter, if given, is a string whose value is the URL
  9151. * at which the source map was found. This URL is used to compute the
  9152. * sources array.
  9153. *
  9154. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9155. */
  9156. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9157. var sourceMap = aSourceMap;
  9158. if (typeof aSourceMap === 'string') {
  9159. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  9160. }
  9161. var version = util$1.getArg(sourceMap, 'version');
  9162. var sources = util$1.getArg(sourceMap, 'sources');
  9163. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9164. // requires the array) to play nice here.
  9165. var names = util$1.getArg(sourceMap, 'names', []);
  9166. var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
  9167. var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
  9168. var mappings = util$1.getArg(sourceMap, 'mappings');
  9169. var file = util$1.getArg(sourceMap, 'file', null);
  9170. // Once again, Sass deviates from the spec and supplies the version as a
  9171. // string rather than a number, so we use loose equality checking here.
  9172. if (version != this._version) {
  9173. throw new Error('Unsupported version: ' + version);
  9174. }
  9175. if (sourceRoot) {
  9176. sourceRoot = util$1.normalize(sourceRoot);
  9177. }
  9178. sources = sources
  9179. .map(String)
  9180. // Some source maps produce relative source paths like "./foo.js" instead of
  9181. // "foo.js". Normalize these first so that future comparisons will succeed.
  9182. // See bugzil.la/1090768.
  9183. .map(util$1.normalize)
  9184. // Always ensure that absolute sources are internally stored relative to
  9185. // the source root, if the source root is absolute. Not doing this would
  9186. // be particularly problematic when the source root is a prefix of the
  9187. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9188. .map(function (source) {
  9189. return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
  9190. ? util$1.relative(sourceRoot, source)
  9191. : source;
  9192. });
  9193. // Pass `true` below to allow duplicate names and sources. While source maps
  9194. // are intended to be compressed and deduplicated, the TypeScript compiler
  9195. // sometimes generates source maps with duplicates in them. See Github issue
  9196. // #72 and bugzil.la/889492.
  9197. this._names = ArraySet.fromArray(names.map(String), true);
  9198. this._sources = ArraySet.fromArray(sources, true);
  9199. this._absoluteSources = this._sources.toArray().map(function (s) {
  9200. return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9201. });
  9202. this.sourceRoot = sourceRoot;
  9203. this.sourcesContent = sourcesContent;
  9204. this._mappings = mappings;
  9205. this._sourceMapURL = aSourceMapURL;
  9206. this.file = file;
  9207. }
  9208. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  9209. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1;
  9210. /**
  9211. * Utility function to find the index of a source. Returns -1 if not
  9212. * found.
  9213. */
  9214. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9215. var relativeSource = aSource;
  9216. if (this.sourceRoot != null) {
  9217. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  9218. }
  9219. if (this._sources.has(relativeSource)) {
  9220. return this._sources.indexOf(relativeSource);
  9221. }
  9222. // Maybe aSource is an absolute URL as returned by |sources|. In
  9223. // this case we can't simply undo the transform.
  9224. var i;
  9225. for (i = 0; i < this._absoluteSources.length; ++i) {
  9226. if (this._absoluteSources[i] == aSource) {
  9227. return i;
  9228. }
  9229. }
  9230. return -1;
  9231. };
  9232. /**
  9233. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9234. *
  9235. * @param SourceMapGenerator aSourceMap
  9236. * The source map that will be consumed.
  9237. * @param String aSourceMapURL
  9238. * The URL at which the source map can be found (optional)
  9239. * @returns BasicSourceMapConsumer
  9240. */
  9241. BasicSourceMapConsumer.fromSourceMap =
  9242. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9243. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9244. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9245. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9246. smc.sourceRoot = aSourceMap._sourceRoot;
  9247. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9248. smc.sourceRoot);
  9249. smc.file = aSourceMap._file;
  9250. smc._sourceMapURL = aSourceMapURL;
  9251. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9252. return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9253. });
  9254. // Because we are modifying the entries (by converting string sources and
  9255. // names to indices into the sources and names ArraySets), we have to make
  9256. // a copy of the entry or else bad things happen. Shared mutable state
  9257. // strikes again! See github issue #191.
  9258. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9259. var destGeneratedMappings = smc.__generatedMappings = [];
  9260. var destOriginalMappings = smc.__originalMappings = [];
  9261. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9262. var srcMapping = generatedMappings[i];
  9263. var destMapping = new Mapping;
  9264. destMapping.generatedLine = srcMapping.generatedLine;
  9265. destMapping.generatedColumn = srcMapping.generatedColumn;
  9266. if (srcMapping.source) {
  9267. destMapping.source = sources.indexOf(srcMapping.source);
  9268. destMapping.originalLine = srcMapping.originalLine;
  9269. destMapping.originalColumn = srcMapping.originalColumn;
  9270. if (srcMapping.name) {
  9271. destMapping.name = names.indexOf(srcMapping.name);
  9272. }
  9273. destOriginalMappings.push(destMapping);
  9274. }
  9275. destGeneratedMappings.push(destMapping);
  9276. }
  9277. quickSort(smc.__originalMappings, util$1.compareByOriginalPositions);
  9278. return smc;
  9279. };
  9280. /**
  9281. * The version of the source mapping spec that we are consuming.
  9282. */
  9283. BasicSourceMapConsumer.prototype._version = 3;
  9284. /**
  9285. * The list of original sources.
  9286. */
  9287. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9288. get: function () {
  9289. return this._absoluteSources.slice();
  9290. }
  9291. });
  9292. /**
  9293. * Provide the JIT with a nice shape / hidden class.
  9294. */
  9295. function Mapping() {
  9296. this.generatedLine = 0;
  9297. this.generatedColumn = 0;
  9298. this.source = null;
  9299. this.originalLine = null;
  9300. this.originalColumn = null;
  9301. this.name = null;
  9302. }
  9303. /**
  9304. * Parse the mappings in a string in to a data structure which we can easily
  9305. * query (the ordered arrays in the `this.__generatedMappings` and
  9306. * `this.__originalMappings` properties).
  9307. */
  9308. BasicSourceMapConsumer.prototype._parseMappings =
  9309. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9310. var generatedLine = 1;
  9311. var previousGeneratedColumn = 0;
  9312. var previousOriginalLine = 0;
  9313. var previousOriginalColumn = 0;
  9314. var previousSource = 0;
  9315. var previousName = 0;
  9316. var length = aStr.length;
  9317. var index = 0;
  9318. var cachedSegments = {};
  9319. var temp = {};
  9320. var originalMappings = [];
  9321. var generatedMappings = [];
  9322. var mapping, str, segment, end, value;
  9323. while (index < length) {
  9324. if (aStr.charAt(index) === ';') {
  9325. generatedLine++;
  9326. index++;
  9327. previousGeneratedColumn = 0;
  9328. }
  9329. else if (aStr.charAt(index) === ',') {
  9330. index++;
  9331. }
  9332. else {
  9333. mapping = new Mapping();
  9334. mapping.generatedLine = generatedLine;
  9335. // Because each offset is encoded relative to the previous one,
  9336. // many segments often have the same encoding. We can exploit this
  9337. // fact by caching the parsed variable length fields of each segment,
  9338. // allowing us to avoid a second parse if we encounter the same
  9339. // segment again.
  9340. for (end = index; end < length; end++) {
  9341. if (this._charIsMappingSeparator(aStr, end)) {
  9342. break;
  9343. }
  9344. }
  9345. str = aStr.slice(index, end);
  9346. segment = cachedSegments[str];
  9347. if (segment) {
  9348. index += str.length;
  9349. } else {
  9350. segment = [];
  9351. while (index < end) {
  9352. base64VLQ.decode(aStr, index, temp);
  9353. value = temp.value;
  9354. index = temp.rest;
  9355. segment.push(value);
  9356. }
  9357. if (segment.length === 2) {
  9358. throw new Error('Found a source, but no line and column');
  9359. }
  9360. if (segment.length === 3) {
  9361. throw new Error('Found a source and line, but no column');
  9362. }
  9363. cachedSegments[str] = segment;
  9364. }
  9365. // Generated column.
  9366. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9367. previousGeneratedColumn = mapping.generatedColumn;
  9368. if (segment.length > 1) {
  9369. // Original source.
  9370. mapping.source = previousSource + segment[1];
  9371. previousSource += segment[1];
  9372. // Original line.
  9373. mapping.originalLine = previousOriginalLine + segment[2];
  9374. previousOriginalLine = mapping.originalLine;
  9375. // Lines are stored 0-based
  9376. mapping.originalLine += 1;
  9377. // Original column.
  9378. mapping.originalColumn = previousOriginalColumn + segment[3];
  9379. previousOriginalColumn = mapping.originalColumn;
  9380. if (segment.length > 4) {
  9381. // Original name.
  9382. mapping.name = previousName + segment[4];
  9383. previousName += segment[4];
  9384. }
  9385. }
  9386. generatedMappings.push(mapping);
  9387. if (typeof mapping.originalLine === 'number') {
  9388. originalMappings.push(mapping);
  9389. }
  9390. }
  9391. }
  9392. quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  9393. this.__generatedMappings = generatedMappings;
  9394. quickSort(originalMappings, util$1.compareByOriginalPositions);
  9395. this.__originalMappings = originalMappings;
  9396. };
  9397. /**
  9398. * Find the mapping that best matches the hypothetical "needle" mapping that
  9399. * we are searching for in the given "haystack" of mappings.
  9400. */
  9401. BasicSourceMapConsumer.prototype._findMapping =
  9402. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9403. aColumnName, aComparator, aBias) {
  9404. // To return the position we are searching for, we must first find the
  9405. // mapping for the given position and then return the opposite position it
  9406. // points to. Because the mappings are sorted, we can use binary search to
  9407. // find the best mapping.
  9408. if (aNeedle[aLineName] <= 0) {
  9409. throw new TypeError('Line must be greater than or equal to 1, got '
  9410. + aNeedle[aLineName]);
  9411. }
  9412. if (aNeedle[aColumnName] < 0) {
  9413. throw new TypeError('Column must be greater than or equal to 0, got '
  9414. + aNeedle[aColumnName]);
  9415. }
  9416. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9417. };
  9418. /**
  9419. * Compute the last column for each generated mapping. The last column is
  9420. * inclusive.
  9421. */
  9422. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9423. function SourceMapConsumer_computeColumnSpans() {
  9424. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9425. var mapping = this._generatedMappings[index];
  9426. // Mappings do not contain a field for the last generated columnt. We
  9427. // can come up with an optimistic estimate, however, by assuming that
  9428. // mappings are contiguous (i.e. given two consecutive mappings, the
  9429. // first mapping ends where the second one starts).
  9430. if (index + 1 < this._generatedMappings.length) {
  9431. var nextMapping = this._generatedMappings[index + 1];
  9432. if (mapping.generatedLine === nextMapping.generatedLine) {
  9433. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9434. continue;
  9435. }
  9436. }
  9437. // The last mapping for each line spans the entire line.
  9438. mapping.lastGeneratedColumn = Infinity;
  9439. }
  9440. };
  9441. /**
  9442. * Returns the original source, line, and column information for the generated
  9443. * source's line and column positions provided. The only argument is an object
  9444. * with the following properties:
  9445. *
  9446. * - line: The line number in the generated source. The line number
  9447. * is 1-based.
  9448. * - column: The column number in the generated source. The column
  9449. * number is 0-based.
  9450. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9451. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9452. * closest element that is smaller than or greater than the one we are
  9453. * searching for, respectively, if the exact element cannot be found.
  9454. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9455. *
  9456. * and an object is returned with the following properties:
  9457. *
  9458. * - source: The original source file, or null.
  9459. * - line: The line number in the original source, or null. The
  9460. * line number is 1-based.
  9461. * - column: The column number in the original source, or null. The
  9462. * column number is 0-based.
  9463. * - name: The original identifier, or null.
  9464. */
  9465. BasicSourceMapConsumer.prototype.originalPositionFor =
  9466. function SourceMapConsumer_originalPositionFor(aArgs) {
  9467. var needle = {
  9468. generatedLine: util$1.getArg(aArgs, 'line'),
  9469. generatedColumn: util$1.getArg(aArgs, 'column')
  9470. };
  9471. var index = this._findMapping(
  9472. needle,
  9473. this._generatedMappings,
  9474. "generatedLine",
  9475. "generatedColumn",
  9476. util$1.compareByGeneratedPositionsDeflated,
  9477. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  9478. );
  9479. if (index >= 0) {
  9480. var mapping = this._generatedMappings[index];
  9481. if (mapping.generatedLine === needle.generatedLine) {
  9482. var source = util$1.getArg(mapping, 'source', null);
  9483. if (source !== null) {
  9484. source = this._sources.at(source);
  9485. source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9486. }
  9487. var name = util$1.getArg(mapping, 'name', null);
  9488. if (name !== null) {
  9489. name = this._names.at(name);
  9490. }
  9491. return {
  9492. source: source,
  9493. line: util$1.getArg(mapping, 'originalLine', null),
  9494. column: util$1.getArg(mapping, 'originalColumn', null),
  9495. name: name
  9496. };
  9497. }
  9498. }
  9499. return {
  9500. source: null,
  9501. line: null,
  9502. column: null,
  9503. name: null
  9504. };
  9505. };
  9506. /**
  9507. * Return true if we have the source content for every source in the source
  9508. * map, false otherwise.
  9509. */
  9510. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9511. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9512. if (!this.sourcesContent) {
  9513. return false;
  9514. }
  9515. return this.sourcesContent.length >= this._sources.size() &&
  9516. !this.sourcesContent.some(function (sc) { return sc == null; });
  9517. };
  9518. /**
  9519. * Returns the original source content. The only argument is the url of the
  9520. * original source file. Returns null if no original source content is
  9521. * available.
  9522. */
  9523. BasicSourceMapConsumer.prototype.sourceContentFor =
  9524. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9525. if (!this.sourcesContent) {
  9526. return null;
  9527. }
  9528. var index = this._findSourceIndex(aSource);
  9529. if (index >= 0) {
  9530. return this.sourcesContent[index];
  9531. }
  9532. var relativeSource = aSource;
  9533. if (this.sourceRoot != null) {
  9534. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  9535. }
  9536. var url;
  9537. if (this.sourceRoot != null
  9538. && (url = util$1.urlParse(this.sourceRoot))) {
  9539. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9540. // many users. We can help them out when they expect file:// URIs to
  9541. // behave like it would if they were running a local HTTP server. See
  9542. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9543. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9544. if (url.scheme == "file"
  9545. && this._sources.has(fileUriAbsPath)) {
  9546. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9547. }
  9548. if ((!url.path || url.path == "/")
  9549. && this._sources.has("/" + relativeSource)) {
  9550. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9551. }
  9552. }
  9553. // This function is used recursively from
  9554. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9555. // don't want to throw if we can't find the source - we just want to
  9556. // return null, so we provide a flag to exit gracefully.
  9557. if (nullOnMissing) {
  9558. return null;
  9559. }
  9560. else {
  9561. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9562. }
  9563. };
  9564. /**
  9565. * Returns the generated line and column information for the original source,
  9566. * line, and column positions provided. The only argument is an object with
  9567. * the following properties:
  9568. *
  9569. * - source: The filename of the original source.
  9570. * - line: The line number in the original source. The line number
  9571. * is 1-based.
  9572. * - column: The column number in the original source. The column
  9573. * number is 0-based.
  9574. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9575. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9576. * closest element that is smaller than or greater than the one we are
  9577. * searching for, respectively, if the exact element cannot be found.
  9578. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9579. *
  9580. * and an object is returned with the following properties:
  9581. *
  9582. * - line: The line number in the generated source, or null. The
  9583. * line number is 1-based.
  9584. * - column: The column number in the generated source, or null.
  9585. * The column number is 0-based.
  9586. */
  9587. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9588. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9589. var source = util$1.getArg(aArgs, 'source');
  9590. source = this._findSourceIndex(source);
  9591. if (source < 0) {
  9592. return {
  9593. line: null,
  9594. column: null,
  9595. lastColumn: null
  9596. };
  9597. }
  9598. var needle = {
  9599. source: source,
  9600. originalLine: util$1.getArg(aArgs, 'line'),
  9601. originalColumn: util$1.getArg(aArgs, 'column')
  9602. };
  9603. var index = this._findMapping(
  9604. needle,
  9605. this._originalMappings,
  9606. "originalLine",
  9607. "originalColumn",
  9608. util$1.compareByOriginalPositions,
  9609. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  9610. );
  9611. if (index >= 0) {
  9612. var mapping = this._originalMappings[index];
  9613. if (mapping.source === needle.source) {
  9614. return {
  9615. line: util$1.getArg(mapping, 'generatedLine', null),
  9616. column: util$1.getArg(mapping, 'generatedColumn', null),
  9617. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9618. };
  9619. }
  9620. }
  9621. return {
  9622. line: null,
  9623. column: null,
  9624. lastColumn: null
  9625. };
  9626. };
  9627. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9628. /**
  9629. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9630. * we can query for information. It differs from BasicSourceMapConsumer in
  9631. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9632. * input.
  9633. *
  9634. * The first parameter is a raw source map (either as a JSON string, or already
  9635. * parsed to an object). According to the spec for indexed source maps, they
  9636. * have the following attributes:
  9637. *
  9638. * - version: Which version of the source map spec this map is following.
  9639. * - file: Optional. The generated file this source map is associated with.
  9640. * - sections: A list of section definitions.
  9641. *
  9642. * Each value under the "sections" field has two fields:
  9643. * - offset: The offset into the original specified at which this section
  9644. * begins to apply, defined as an object with a "line" and "column"
  9645. * field.
  9646. * - map: A source map definition. This source map could also be indexed,
  9647. * but doesn't have to be.
  9648. *
  9649. * Instead of the "map" field, it's also possible to have a "url" field
  9650. * specifying a URL to retrieve a source map from, but that's currently
  9651. * unsupported.
  9652. *
  9653. * Here's an example source map, taken from the source map spec[0], but
  9654. * modified to omit a section which uses the "url" field.
  9655. *
  9656. * {
  9657. * version : 3,
  9658. * file: "app.js",
  9659. * sections: [{
  9660. * offset: {line:100, column:10},
  9661. * map: {
  9662. * version : 3,
  9663. * file: "section.js",
  9664. * sources: ["foo.js", "bar.js"],
  9665. * names: ["src", "maps", "are", "fun"],
  9666. * mappings: "AAAA,E;;ABCDE;"
  9667. * }
  9668. * }],
  9669. * }
  9670. *
  9671. * The second parameter, if given, is a string whose value is the URL
  9672. * at which the source map was found. This URL is used to compute the
  9673. * sources array.
  9674. *
  9675. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9676. */
  9677. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9678. var sourceMap = aSourceMap;
  9679. if (typeof aSourceMap === 'string') {
  9680. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  9681. }
  9682. var version = util$1.getArg(sourceMap, 'version');
  9683. var sections = util$1.getArg(sourceMap, 'sections');
  9684. if (version != this._version) {
  9685. throw new Error('Unsupported version: ' + version);
  9686. }
  9687. this._sources = new ArraySet();
  9688. this._names = new ArraySet();
  9689. var lastOffset = {
  9690. line: -1,
  9691. column: 0
  9692. };
  9693. this._sections = sections.map(function (s) {
  9694. if (s.url) {
  9695. // The url field will require support for asynchronicity.
  9696. // See https://github.com/mozilla/source-map/issues/16
  9697. throw new Error('Support for url field in sections not implemented.');
  9698. }
  9699. var offset = util$1.getArg(s, 'offset');
  9700. var offsetLine = util$1.getArg(offset, 'line');
  9701. var offsetColumn = util$1.getArg(offset, 'column');
  9702. if (offsetLine < lastOffset.line ||
  9703. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9704. throw new Error('Section offsets must be ordered and non-overlapping.');
  9705. }
  9706. lastOffset = offset;
  9707. return {
  9708. generatedOffset: {
  9709. // The offset fields are 0-based, but we use 1-based indices when
  9710. // encoding/decoding from VLQ.
  9711. generatedLine: offsetLine + 1,
  9712. generatedColumn: offsetColumn + 1
  9713. },
  9714. consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL)
  9715. }
  9716. });
  9717. }
  9718. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  9719. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1;
  9720. /**
  9721. * The version of the source mapping spec that we are consuming.
  9722. */
  9723. IndexedSourceMapConsumer.prototype._version = 3;
  9724. /**
  9725. * The list of original sources.
  9726. */
  9727. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  9728. get: function () {
  9729. var sources = [];
  9730. for (var i = 0; i < this._sections.length; i++) {
  9731. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  9732. sources.push(this._sections[i].consumer.sources[j]);
  9733. }
  9734. }
  9735. return sources;
  9736. }
  9737. });
  9738. /**
  9739. * Returns the original source, line, and column information for the generated
  9740. * source's line and column positions provided. The only argument is an object
  9741. * with the following properties:
  9742. *
  9743. * - line: The line number in the generated source. The line number
  9744. * is 1-based.
  9745. * - column: The column number in the generated source. The column
  9746. * number is 0-based.
  9747. *
  9748. * and an object is returned with the following properties:
  9749. *
  9750. * - source: The original source file, or null.
  9751. * - line: The line number in the original source, or null. The
  9752. * line number is 1-based.
  9753. * - column: The column number in the original source, or null. The
  9754. * column number is 0-based.
  9755. * - name: The original identifier, or null.
  9756. */
  9757. IndexedSourceMapConsumer.prototype.originalPositionFor =
  9758. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  9759. var needle = {
  9760. generatedLine: util$1.getArg(aArgs, 'line'),
  9761. generatedColumn: util$1.getArg(aArgs, 'column')
  9762. };
  9763. // Find the section containing the generated position we're trying to map
  9764. // to an original position.
  9765. var sectionIndex = binarySearch.search(needle, this._sections,
  9766. function(needle, section) {
  9767. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  9768. if (cmp) {
  9769. return cmp;
  9770. }
  9771. return (needle.generatedColumn -
  9772. section.generatedOffset.generatedColumn);
  9773. });
  9774. var section = this._sections[sectionIndex];
  9775. if (!section) {
  9776. return {
  9777. source: null,
  9778. line: null,
  9779. column: null,
  9780. name: null
  9781. };
  9782. }
  9783. return section.consumer.originalPositionFor({
  9784. line: needle.generatedLine -
  9785. (section.generatedOffset.generatedLine - 1),
  9786. column: needle.generatedColumn -
  9787. (section.generatedOffset.generatedLine === needle.generatedLine
  9788. ? section.generatedOffset.generatedColumn - 1
  9789. : 0),
  9790. bias: aArgs.bias
  9791. });
  9792. };
  9793. /**
  9794. * Return true if we have the source content for every source in the source
  9795. * map, false otherwise.
  9796. */
  9797. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  9798. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  9799. return this._sections.every(function (s) {
  9800. return s.consumer.hasContentsOfAllSources();
  9801. });
  9802. };
  9803. /**
  9804. * Returns the original source content. The only argument is the url of the
  9805. * original source file. Returns null if no original source content is
  9806. * available.
  9807. */
  9808. IndexedSourceMapConsumer.prototype.sourceContentFor =
  9809. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9810. for (var i = 0; i < this._sections.length; i++) {
  9811. var section = this._sections[i];
  9812. var content = section.consumer.sourceContentFor(aSource, true);
  9813. if (content) {
  9814. return content;
  9815. }
  9816. }
  9817. if (nullOnMissing) {
  9818. return null;
  9819. }
  9820. else {
  9821. throw new Error('"' + aSource + '" is not in the SourceMap.');
  9822. }
  9823. };
  9824. /**
  9825. * Returns the generated line and column information for the original source,
  9826. * line, and column positions provided. The only argument is an object with
  9827. * the following properties:
  9828. *
  9829. * - source: The filename of the original source.
  9830. * - line: The line number in the original source. The line number
  9831. * is 1-based.
  9832. * - column: The column number in the original source. The column
  9833. * number is 0-based.
  9834. *
  9835. * and an object is returned with the following properties:
  9836. *
  9837. * - line: The line number in the generated source, or null. The
  9838. * line number is 1-based.
  9839. * - column: The column number in the generated source, or null.
  9840. * The column number is 0-based.
  9841. */
  9842. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  9843. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  9844. for (var i = 0; i < this._sections.length; i++) {
  9845. var section = this._sections[i];
  9846. // Only consider this section if the requested source is in the list of
  9847. // sources of the consumer.
  9848. if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) {
  9849. continue;
  9850. }
  9851. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  9852. if (generatedPosition) {
  9853. var ret = {
  9854. line: generatedPosition.line +
  9855. (section.generatedOffset.generatedLine - 1),
  9856. column: generatedPosition.column +
  9857. (section.generatedOffset.generatedLine === generatedPosition.line
  9858. ? section.generatedOffset.generatedColumn - 1
  9859. : 0)
  9860. };
  9861. return ret;
  9862. }
  9863. }
  9864. return {
  9865. line: null,
  9866. column: null
  9867. };
  9868. };
  9869. /**
  9870. * Parse the mappings in a string in to a data structure which we can easily
  9871. * query (the ordered arrays in the `this.__generatedMappings` and
  9872. * `this.__originalMappings` properties).
  9873. */
  9874. IndexedSourceMapConsumer.prototype._parseMappings =
  9875. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9876. this.__generatedMappings = [];
  9877. this.__originalMappings = [];
  9878. for (var i = 0; i < this._sections.length; i++) {
  9879. var section = this._sections[i];
  9880. var sectionMappings = section.consumer._generatedMappings;
  9881. for (var j = 0; j < sectionMappings.length; j++) {
  9882. var mapping = sectionMappings[j];
  9883. var source = section.consumer._sources.at(mapping.source);
  9884. source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  9885. this._sources.add(source);
  9886. source = this._sources.indexOf(source);
  9887. var name = null;
  9888. if (mapping.name) {
  9889. name = section.consumer._names.at(mapping.name);
  9890. this._names.add(name);
  9891. name = this._names.indexOf(name);
  9892. }
  9893. // The mappings coming from the consumer for the section have
  9894. // generated positions relative to the start of the section, so we
  9895. // need to offset them to be relative to the start of the concatenated
  9896. // generated file.
  9897. var adjustedMapping = {
  9898. source: source,
  9899. generatedLine: mapping.generatedLine +
  9900. (section.generatedOffset.generatedLine - 1),
  9901. generatedColumn: mapping.generatedColumn +
  9902. (section.generatedOffset.generatedLine === mapping.generatedLine
  9903. ? section.generatedOffset.generatedColumn - 1
  9904. : 0),
  9905. originalLine: mapping.originalLine,
  9906. originalColumn: mapping.originalColumn,
  9907. name: name
  9908. };
  9909. this.__generatedMappings.push(adjustedMapping);
  9910. if (typeof adjustedMapping.originalLine === 'number') {
  9911. this.__originalMappings.push(adjustedMapping);
  9912. }
  9913. }
  9914. }
  9915. quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  9916. quickSort(this.__originalMappings, util$1.compareByOriginalPositions);
  9917. };
  9918. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  9919. var sourceNode = {};
  9920. /* -*- Mode: js; js-indent-level: 2; -*- */
  9921. /*
  9922. * Copyright 2011 Mozilla Foundation and contributors
  9923. * Licensed under the New BSD license. See LICENSE or:
  9924. * http://opensource.org/licenses/BSD-3-Clause
  9925. */
  9926. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  9927. var util = util$5;
  9928. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  9929. // operating systems these days (capturing the result).
  9930. var REGEX_NEWLINE = /(\r?\n)/;
  9931. // Newline character code for charCodeAt() comparisons
  9932. var NEWLINE_CODE = 10;
  9933. // Private symbol for identifying `SourceNode`s when multiple versions of
  9934. // the source-map library are loaded. This MUST NOT CHANGE across
  9935. // versions!
  9936. var isSourceNode = "$$$isSourceNode$$$";
  9937. /**
  9938. * SourceNodes provide a way to abstract over interpolating/concatenating
  9939. * snippets of generated JavaScript source code while maintaining the line and
  9940. * column information associated with the original source code.
  9941. *
  9942. * @param aLine The original line number.
  9943. * @param aColumn The original column number.
  9944. * @param aSource The original source's filename.
  9945. * @param aChunks Optional. An array of strings which are snippets of
  9946. * generated JS, or other SourceNodes.
  9947. * @param aName The original identifier.
  9948. */
  9949. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  9950. this.children = [];
  9951. this.sourceContents = {};
  9952. this.line = aLine == null ? null : aLine;
  9953. this.column = aColumn == null ? null : aColumn;
  9954. this.source = aSource == null ? null : aSource;
  9955. this.name = aName == null ? null : aName;
  9956. this[isSourceNode] = true;
  9957. if (aChunks != null) this.add(aChunks);
  9958. }
  9959. /**
  9960. * Creates a SourceNode from generated code and a SourceMapConsumer.
  9961. *
  9962. * @param aGeneratedCode The generated code
  9963. * @param aSourceMapConsumer The SourceMap for the generated code
  9964. * @param aRelativePath Optional. The path that relative sources in the
  9965. * SourceMapConsumer should be relative to.
  9966. */
  9967. SourceNode.fromStringWithSourceMap =
  9968. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  9969. // The SourceNode we want to fill with the generated code
  9970. // and the SourceMap
  9971. var node = new SourceNode();
  9972. // All even indices of this array are one line of the generated code,
  9973. // while all odd indices are the newlines between two adjacent lines
  9974. // (since `REGEX_NEWLINE` captures its match).
  9975. // Processed fragments are accessed by calling `shiftNextLine`.
  9976. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  9977. var remainingLinesIndex = 0;
  9978. var shiftNextLine = function() {
  9979. var lineContents = getNextLine();
  9980. // The last line of a file might not have a newline.
  9981. var newLine = getNextLine() || "";
  9982. return lineContents + newLine;
  9983. function getNextLine() {
  9984. return remainingLinesIndex < remainingLines.length ?
  9985. remainingLines[remainingLinesIndex++] : undefined;
  9986. }
  9987. };
  9988. // We need to remember the position of "remainingLines"
  9989. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  9990. // The generate SourceNodes we need a code range.
  9991. // To extract it current and last mapping is used.
  9992. // Here we store the last mapping.
  9993. var lastMapping = null;
  9994. aSourceMapConsumer.eachMapping(function (mapping) {
  9995. if (lastMapping !== null) {
  9996. // We add the code from "lastMapping" to "mapping":
  9997. // First check if there is a new line in between.
  9998. if (lastGeneratedLine < mapping.generatedLine) {
  9999. // Associate first line with "lastMapping"
  10000. addMappingWithCode(lastMapping, shiftNextLine());
  10001. lastGeneratedLine++;
  10002. lastGeneratedColumn = 0;
  10003. // The remaining code is added without mapping
  10004. } else {
  10005. // There is no new line in between.
  10006. // Associate the code between "lastGeneratedColumn" and
  10007. // "mapping.generatedColumn" with "lastMapping"
  10008. var nextLine = remainingLines[remainingLinesIndex] || '';
  10009. var code = nextLine.substr(0, mapping.generatedColumn -
  10010. lastGeneratedColumn);
  10011. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10012. lastGeneratedColumn);
  10013. lastGeneratedColumn = mapping.generatedColumn;
  10014. addMappingWithCode(lastMapping, code);
  10015. // No more remaining code, continue
  10016. lastMapping = mapping;
  10017. return;
  10018. }
  10019. }
  10020. // We add the generated code until the first mapping
  10021. // to the SourceNode without any mapping.
  10022. // Each line is added as separate string.
  10023. while (lastGeneratedLine < mapping.generatedLine) {
  10024. node.add(shiftNextLine());
  10025. lastGeneratedLine++;
  10026. }
  10027. if (lastGeneratedColumn < mapping.generatedColumn) {
  10028. var nextLine = remainingLines[remainingLinesIndex] || '';
  10029. node.add(nextLine.substr(0, mapping.generatedColumn));
  10030. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10031. lastGeneratedColumn = mapping.generatedColumn;
  10032. }
  10033. lastMapping = mapping;
  10034. }, this);
  10035. // We have processed all mappings.
  10036. if (remainingLinesIndex < remainingLines.length) {
  10037. if (lastMapping) {
  10038. // Associate the remaining code in the current line with "lastMapping"
  10039. addMappingWithCode(lastMapping, shiftNextLine());
  10040. }
  10041. // and add the remaining lines without any mapping
  10042. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10043. }
  10044. // Copy sourcesContent into SourceNode
  10045. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10046. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10047. if (content != null) {
  10048. if (aRelativePath != null) {
  10049. sourceFile = util.join(aRelativePath, sourceFile);
  10050. }
  10051. node.setSourceContent(sourceFile, content);
  10052. }
  10053. });
  10054. return node;
  10055. function addMappingWithCode(mapping, code) {
  10056. if (mapping === null || mapping.source === undefined) {
  10057. node.add(code);
  10058. } else {
  10059. var source = aRelativePath
  10060. ? util.join(aRelativePath, mapping.source)
  10061. : mapping.source;
  10062. node.add(new SourceNode(mapping.originalLine,
  10063. mapping.originalColumn,
  10064. source,
  10065. code,
  10066. mapping.name));
  10067. }
  10068. }
  10069. };
  10070. /**
  10071. * Add a chunk of generated JS to this source node.
  10072. *
  10073. * @param aChunk A string snippet of generated JS code, another instance of
  10074. * SourceNode, or an array where each member is one of those things.
  10075. */
  10076. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10077. if (Array.isArray(aChunk)) {
  10078. aChunk.forEach(function (chunk) {
  10079. this.add(chunk);
  10080. }, this);
  10081. }
  10082. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10083. if (aChunk) {
  10084. this.children.push(aChunk);
  10085. }
  10086. }
  10087. else {
  10088. throw new TypeError(
  10089. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10090. );
  10091. }
  10092. return this;
  10093. };
  10094. /**
  10095. * Add a chunk of generated JS to the beginning of this source node.
  10096. *
  10097. * @param aChunk A string snippet of generated JS code, another instance of
  10098. * SourceNode, or an array where each member is one of those things.
  10099. */
  10100. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10101. if (Array.isArray(aChunk)) {
  10102. for (var i = aChunk.length-1; i >= 0; i--) {
  10103. this.prepend(aChunk[i]);
  10104. }
  10105. }
  10106. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10107. this.children.unshift(aChunk);
  10108. }
  10109. else {
  10110. throw new TypeError(
  10111. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10112. );
  10113. }
  10114. return this;
  10115. };
  10116. /**
  10117. * Walk over the tree of JS snippets in this node and its children. The
  10118. * walking function is called once for each snippet of JS and is passed that
  10119. * snippet and the its original associated source's line/column location.
  10120. *
  10121. * @param aFn The traversal function.
  10122. */
  10123. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10124. var chunk;
  10125. for (var i = 0, len = this.children.length; i < len; i++) {
  10126. chunk = this.children[i];
  10127. if (chunk[isSourceNode]) {
  10128. chunk.walk(aFn);
  10129. }
  10130. else {
  10131. if (chunk !== '') {
  10132. aFn(chunk, { source: this.source,
  10133. line: this.line,
  10134. column: this.column,
  10135. name: this.name });
  10136. }
  10137. }
  10138. }
  10139. };
  10140. /**
  10141. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10142. * each of `this.children`.
  10143. *
  10144. * @param aSep The separator.
  10145. */
  10146. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10147. var newChildren;
  10148. var i;
  10149. var len = this.children.length;
  10150. if (len > 0) {
  10151. newChildren = [];
  10152. for (i = 0; i < len-1; i++) {
  10153. newChildren.push(this.children[i]);
  10154. newChildren.push(aSep);
  10155. }
  10156. newChildren.push(this.children[i]);
  10157. this.children = newChildren;
  10158. }
  10159. return this;
  10160. };
  10161. /**
  10162. * Call String.prototype.replace on the very right-most source snippet. Useful
  10163. * for trimming whitespace from the end of a source node, etc.
  10164. *
  10165. * @param aPattern The pattern to replace.
  10166. * @param aReplacement The thing to replace the pattern with.
  10167. */
  10168. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10169. var lastChild = this.children[this.children.length - 1];
  10170. if (lastChild[isSourceNode]) {
  10171. lastChild.replaceRight(aPattern, aReplacement);
  10172. }
  10173. else if (typeof lastChild === 'string') {
  10174. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10175. }
  10176. else {
  10177. this.children.push(''.replace(aPattern, aReplacement));
  10178. }
  10179. return this;
  10180. };
  10181. /**
  10182. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10183. * in the sourcesContent field.
  10184. *
  10185. * @param aSourceFile The filename of the source file
  10186. * @param aSourceContent The content of the source file
  10187. */
  10188. SourceNode.prototype.setSourceContent =
  10189. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10190. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10191. };
  10192. /**
  10193. * Walk over the tree of SourceNodes. The walking function is called for each
  10194. * source file content and is passed the filename and source content.
  10195. *
  10196. * @param aFn The traversal function.
  10197. */
  10198. SourceNode.prototype.walkSourceContents =
  10199. function SourceNode_walkSourceContents(aFn) {
  10200. for (var i = 0, len = this.children.length; i < len; i++) {
  10201. if (this.children[i][isSourceNode]) {
  10202. this.children[i].walkSourceContents(aFn);
  10203. }
  10204. }
  10205. var sources = Object.keys(this.sourceContents);
  10206. for (var i = 0, len = sources.length; i < len; i++) {
  10207. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10208. }
  10209. };
  10210. /**
  10211. * Return the string representation of this source node. Walks over the tree
  10212. * and concatenates all the various snippets together to one string.
  10213. */
  10214. SourceNode.prototype.toString = function SourceNode_toString() {
  10215. var str = "";
  10216. this.walk(function (chunk) {
  10217. str += chunk;
  10218. });
  10219. return str;
  10220. };
  10221. /**
  10222. * Returns the string representation of this source node along with a source
  10223. * map.
  10224. */
  10225. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10226. var generated = {
  10227. code: "",
  10228. line: 1,
  10229. column: 0
  10230. };
  10231. var map = new SourceMapGenerator$1(aArgs);
  10232. var sourceMappingActive = false;
  10233. var lastOriginalSource = null;
  10234. var lastOriginalLine = null;
  10235. var lastOriginalColumn = null;
  10236. var lastOriginalName = null;
  10237. this.walk(function (chunk, original) {
  10238. generated.code += chunk;
  10239. if (original.source !== null
  10240. && original.line !== null
  10241. && original.column !== null) {
  10242. if(lastOriginalSource !== original.source
  10243. || lastOriginalLine !== original.line
  10244. || lastOriginalColumn !== original.column
  10245. || lastOriginalName !== original.name) {
  10246. map.addMapping({
  10247. source: original.source,
  10248. original: {
  10249. line: original.line,
  10250. column: original.column
  10251. },
  10252. generated: {
  10253. line: generated.line,
  10254. column: generated.column
  10255. },
  10256. name: original.name
  10257. });
  10258. }
  10259. lastOriginalSource = original.source;
  10260. lastOriginalLine = original.line;
  10261. lastOriginalColumn = original.column;
  10262. lastOriginalName = original.name;
  10263. sourceMappingActive = true;
  10264. } else if (sourceMappingActive) {
  10265. map.addMapping({
  10266. generated: {
  10267. line: generated.line,
  10268. column: generated.column
  10269. }
  10270. });
  10271. lastOriginalSource = null;
  10272. sourceMappingActive = false;
  10273. }
  10274. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10275. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10276. generated.line++;
  10277. generated.column = 0;
  10278. // Mappings end at eol
  10279. if (idx + 1 === length) {
  10280. lastOriginalSource = null;
  10281. sourceMappingActive = false;
  10282. } else if (sourceMappingActive) {
  10283. map.addMapping({
  10284. source: original.source,
  10285. original: {
  10286. line: original.line,
  10287. column: original.column
  10288. },
  10289. generated: {
  10290. line: generated.line,
  10291. column: generated.column
  10292. },
  10293. name: original.name
  10294. });
  10295. }
  10296. } else {
  10297. generated.column++;
  10298. }
  10299. }
  10300. });
  10301. this.walkSourceContents(function (sourceFile, sourceContent) {
  10302. map.setSourceContent(sourceFile, sourceContent);
  10303. });
  10304. return { code: generated.code, map: map };
  10305. };
  10306. sourceNode.SourceNode = SourceNode;
  10307. /*
  10308. * Copyright 2009-2011 Mozilla Foundation and contributors
  10309. * Licensed under the New BSD license. See LICENSE.txt or:
  10310. * http://opensource.org/licenses/BSD-3-Clause
  10311. */
  10312. sourceMap$1.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
  10313. sourceMap$1.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer;
  10314. sourceMap$1.SourceNode = sourceNode.SourceNode;
  10315. var sourceMap = sourceMap$1;
  10316. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10317. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10318. var mergeSourceMap = merge;
  10319. /**
  10320. * Merge old source map and new source map and return merged.
  10321. * If old or new source map value is falsy, return another one as it is.
  10322. *
  10323. * @param {object|string} [oldMap] old source map object
  10324. * @param {object|string} [newmap] new source map object
  10325. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10326. */
  10327. function merge(oldMap, newMap) {
  10328. if (!oldMap) return newMap
  10329. if (!newMap) return oldMap
  10330. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10331. var newMapConsumer = new SourceMapConsumer(newMap);
  10332. var mergedMapGenerator = new SourceMapGenerator();
  10333. // iterate on new map and overwrite original position of new map with one of old map
  10334. newMapConsumer.eachMapping(function(m) {
  10335. // pass when `originalLine` is null.
  10336. // It occurs in case that the node does not have origin in original code.
  10337. if (m.originalLine == null) return
  10338. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10339. line: m.originalLine,
  10340. column: m.originalColumn
  10341. });
  10342. if (origPosInOldMap.source == null) return
  10343. mergedMapGenerator.addMapping({
  10344. original: {
  10345. line: origPosInOldMap.line,
  10346. column: origPosInOldMap.column
  10347. },
  10348. generated: {
  10349. line: m.generatedLine,
  10350. column: m.generatedColumn
  10351. },
  10352. source: origPosInOldMap.source,
  10353. name: origPosInOldMap.name
  10354. });
  10355. });
  10356. var consumers = [oldMapConsumer, newMapConsumer];
  10357. consumers.forEach(function(consumer) {
  10358. consumer.sources.forEach(function(sourceFile) {
  10359. mergedMapGenerator._sources.add(sourceFile);
  10360. var sourceContent = consumer.sourceContentFor(sourceFile);
  10361. if (sourceContent != null) {
  10362. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10363. }
  10364. });
  10365. });
  10366. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10367. mergedMapGenerator._file = oldMap.file;
  10368. return JSON.parse(mergedMapGenerator.toString())
  10369. }
  10370. var merge$1 = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMap);
  10371. const scss = (source, map, options, load = require) => {
  10372. const nodeSass = load("sass");
  10373. const finalOptions = {
  10374. ...options,
  10375. data: getSource(source, options.filename, options.additionalData),
  10376. file: options.filename,
  10377. outFile: options.filename,
  10378. sourceMap: !!map
  10379. };
  10380. try {
  10381. const result = nodeSass.renderSync(finalOptions);
  10382. const dependencies = result.stats.includedFiles;
  10383. if (map) {
  10384. return {
  10385. code: result.css.toString(),
  10386. map: merge$1(map, JSON.parse(result.map.toString())),
  10387. errors: [],
  10388. dependencies
  10389. };
  10390. }
  10391. return { code: result.css.toString(), errors: [], dependencies };
  10392. } catch (e) {
  10393. return { code: "", errors: [e], dependencies: [] };
  10394. }
  10395. };
  10396. const sass = (source, map, options, load) => scss(
  10397. source,
  10398. map,
  10399. {
  10400. ...options,
  10401. indentedSyntax: true
  10402. },
  10403. load
  10404. );
  10405. const less = (source, map, options, load = require) => {
  10406. const nodeLess = load("less");
  10407. let result;
  10408. let error = null;
  10409. nodeLess.render(
  10410. getSource(source, options.filename, options.additionalData),
  10411. { ...options, syncImport: true },
  10412. (err, output) => {
  10413. error = err;
  10414. result = output;
  10415. }
  10416. );
  10417. if (error)
  10418. return { code: "", errors: [error], dependencies: [] };
  10419. const dependencies = result.imports;
  10420. if (map) {
  10421. return {
  10422. code: result.css.toString(),
  10423. map: merge$1(map, result.map),
  10424. errors: [],
  10425. dependencies
  10426. };
  10427. }
  10428. return {
  10429. code: result.css.toString(),
  10430. errors: [],
  10431. dependencies
  10432. };
  10433. };
  10434. const styl = (source, map, options, load = require) => {
  10435. const nodeStylus = load("stylus");
  10436. try {
  10437. const ref = nodeStylus(source, options);
  10438. if (map)
  10439. ref.set("sourcemap", { inline: false, comment: false });
  10440. const result = ref.render();
  10441. const dependencies = ref.deps();
  10442. if (map) {
  10443. return {
  10444. code: result,
  10445. map: merge$1(map, ref.sourcemap),
  10446. errors: [],
  10447. dependencies
  10448. };
  10449. }
  10450. return { code: result, errors: [], dependencies };
  10451. } catch (e) {
  10452. return { code: "", errors: [e], dependencies: [] };
  10453. }
  10454. };
  10455. function getSource(source, filename, additionalData) {
  10456. if (!additionalData)
  10457. return source;
  10458. if (shared.isFunction(additionalData)) {
  10459. return additionalData(source, filename);
  10460. }
  10461. return additionalData + source;
  10462. }
  10463. const processors = {
  10464. less,
  10465. sass,
  10466. scss,
  10467. styl,
  10468. stylus: styl
  10469. };
  10470. var build = {exports: {}};
  10471. var fs = {};
  10472. Object.defineProperty(fs, "__esModule", {
  10473. value: true
  10474. });
  10475. fs.getFileSystem = getFileSystem;
  10476. fs.setFileSystem = setFileSystem;
  10477. let fileSystem = {
  10478. readFile: () => {
  10479. throw Error("readFile not implemented");
  10480. },
  10481. writeFile: () => {
  10482. throw Error("writeFile not implemented");
  10483. }
  10484. };
  10485. function setFileSystem(fs) {
  10486. fileSystem.readFile = fs.readFile;
  10487. fileSystem.writeFile = fs.writeFile;
  10488. }
  10489. function getFileSystem() {
  10490. return fileSystem;
  10491. }
  10492. var pluginFactory = {};
  10493. var unquote$1 = {};
  10494. Object.defineProperty(unquote$1, "__esModule", {
  10495. value: true
  10496. });
  10497. unquote$1.default = unquote;
  10498. // copied from https://github.com/lakenen/node-unquote
  10499. const reg = /['"]/;
  10500. function unquote(str) {
  10501. if (!str) {
  10502. return "";
  10503. }
  10504. if (reg.test(str.charAt(0))) {
  10505. str = str.substr(1);
  10506. }
  10507. if (reg.test(str.charAt(str.length - 1))) {
  10508. str = str.substr(0, str.length - 1);
  10509. }
  10510. return str;
  10511. }
  10512. var Parser$1 = {};
  10513. const matchValueName = /[$]?[\w-]+/g;
  10514. const replaceValueSymbols$2 = (value, replacements) => {
  10515. let matches;
  10516. while ((matches = matchValueName.exec(value))) {
  10517. const replacement = replacements[matches[0]];
  10518. if (replacement) {
  10519. value =
  10520. value.slice(0, matches.index) +
  10521. replacement +
  10522. value.slice(matchValueName.lastIndex);
  10523. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10524. }
  10525. }
  10526. return value;
  10527. };
  10528. var replaceValueSymbols_1 = replaceValueSymbols$2;
  10529. const replaceValueSymbols$1 = replaceValueSymbols_1;
  10530. const replaceSymbols$1 = (css, replacements) => {
  10531. css.walk((node) => {
  10532. if (node.type === "decl" && node.value) {
  10533. node.value = replaceValueSymbols$1(node.value.toString(), replacements);
  10534. } else if (node.type === "rule" && node.selector) {
  10535. node.selector = replaceValueSymbols$1(
  10536. node.selector.toString(),
  10537. replacements
  10538. );
  10539. } else if (node.type === "atrule" && node.params) {
  10540. node.params = replaceValueSymbols$1(node.params.toString(), replacements);
  10541. }
  10542. });
  10543. };
  10544. var replaceSymbols_1 = replaceSymbols$1;
  10545. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10546. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10547. const getDeclsObject = (rule) => {
  10548. const object = {};
  10549. rule.walkDecls((decl) => {
  10550. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10551. object[before + decl.prop] = decl.value;
  10552. });
  10553. return object;
  10554. };
  10555. /**
  10556. *
  10557. * @param {string} css
  10558. * @param {boolean} removeRules
  10559. * @param {'auto' | 'rule' | 'at-rule'} mode
  10560. */
  10561. const extractICSS$2 = (css, removeRules = true, mode = "auto") => {
  10562. const icssImports = {};
  10563. const icssExports = {};
  10564. function addImports(node, path) {
  10565. const unquoted = path.replace(/'|"/g, "");
  10566. icssImports[unquoted] = Object.assign(
  10567. icssImports[unquoted] || {},
  10568. getDeclsObject(node)
  10569. );
  10570. if (removeRules) {
  10571. node.remove();
  10572. }
  10573. }
  10574. function addExports(node) {
  10575. Object.assign(icssExports, getDeclsObject(node));
  10576. if (removeRules) {
  10577. node.remove();
  10578. }
  10579. }
  10580. css.each((node) => {
  10581. if (node.type === "rule" && mode !== "at-rule") {
  10582. if (node.selector.slice(0, 7) === ":import") {
  10583. const matches = importPattern.exec(node.selector);
  10584. if (matches) {
  10585. addImports(node, matches[1]);
  10586. }
  10587. }
  10588. if (node.selector === ":export") {
  10589. addExports(node);
  10590. }
  10591. }
  10592. if (node.type === "atrule" && mode !== "rule") {
  10593. if (node.name === "icss-import") {
  10594. const matches = balancedQuotes.exec(node.params);
  10595. if (matches) {
  10596. addImports(node, matches[1]);
  10597. }
  10598. }
  10599. if (node.name === "icss-export") {
  10600. addExports(node);
  10601. }
  10602. }
  10603. });
  10604. return { icssImports, icssExports };
  10605. };
  10606. var extractICSS_1 = extractICSS$2;
  10607. const createImports = (imports, postcss, mode = "rule") => {
  10608. return Object.keys(imports).map((path) => {
  10609. const aliases = imports[path];
  10610. const declarations = Object.keys(aliases).map((key) =>
  10611. postcss.decl({
  10612. prop: key,
  10613. value: aliases[key],
  10614. raws: { before: "\n " },
  10615. })
  10616. );
  10617. const hasDeclarations = declarations.length > 0;
  10618. const rule =
  10619. mode === "rule"
  10620. ? postcss.rule({
  10621. selector: `:import('${path}')`,
  10622. raws: { after: hasDeclarations ? "\n" : "" },
  10623. })
  10624. : postcss.atRule({
  10625. name: "icss-import",
  10626. params: `'${path}'`,
  10627. raws: { after: hasDeclarations ? "\n" : "" },
  10628. });
  10629. if (hasDeclarations) {
  10630. rule.append(declarations);
  10631. }
  10632. return rule;
  10633. });
  10634. };
  10635. const createExports = (exports, postcss, mode = "rule") => {
  10636. const declarations = Object.keys(exports).map((key) =>
  10637. postcss.decl({
  10638. prop: key,
  10639. value: exports[key],
  10640. raws: { before: "\n " },
  10641. })
  10642. );
  10643. if (declarations.length === 0) {
  10644. return [];
  10645. }
  10646. const rule =
  10647. mode === "rule"
  10648. ? postcss.rule({
  10649. selector: `:export`,
  10650. raws: { after: "\n" },
  10651. })
  10652. : postcss.atRule({
  10653. name: "icss-export",
  10654. raws: { after: "\n" },
  10655. });
  10656. rule.append(declarations);
  10657. return [rule];
  10658. };
  10659. const createICSSRules$1 = (imports, exports, postcss, mode) => [
  10660. ...createImports(imports, postcss, mode),
  10661. ...createExports(exports, postcss, mode),
  10662. ];
  10663. var createICSSRules_1 = createICSSRules$1;
  10664. const replaceValueSymbols = replaceValueSymbols_1;
  10665. const replaceSymbols = replaceSymbols_1;
  10666. const extractICSS$1 = extractICSS_1;
  10667. const createICSSRules = createICSSRules_1;
  10668. var src$4 = {
  10669. replaceValueSymbols,
  10670. replaceSymbols,
  10671. extractICSS: extractICSS$1,
  10672. createICSSRules,
  10673. };
  10674. Object.defineProperty(Parser$1, "__esModule", {
  10675. value: true
  10676. });
  10677. Parser$1.default = void 0;
  10678. var _icssUtils = src$4;
  10679. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  10680. const importRegexp = /^:import\((.+)\)$/;
  10681. class Parser {
  10682. constructor(pathFetcher, trace) {
  10683. this.pathFetcher = pathFetcher;
  10684. this.plugin = this.plugin.bind(this);
  10685. this.exportTokens = {};
  10686. this.translations = {};
  10687. this.trace = trace;
  10688. }
  10689. plugin() {
  10690. const parser = this;
  10691. return {
  10692. postcssPlugin: "css-modules-parser",
  10693. async OnceExit(css) {
  10694. await Promise.all(parser.fetchAllImports(css));
  10695. parser.linkImportedSymbols(css);
  10696. return parser.extractExports(css);
  10697. }
  10698. };
  10699. }
  10700. fetchAllImports(css) {
  10701. let imports = [];
  10702. css.each(node => {
  10703. if (node.type == "rule" && node.selector.match(importRegexp)) {
  10704. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  10705. }
  10706. });
  10707. return imports;
  10708. }
  10709. linkImportedSymbols(css) {
  10710. (0, _icssUtils.replaceSymbols)(css, this.translations);
  10711. }
  10712. extractExports(css) {
  10713. css.each(node => {
  10714. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  10715. });
  10716. }
  10717. handleExport(exportNode) {
  10718. exportNode.each(decl => {
  10719. if (decl.type == "decl") {
  10720. Object.keys(this.translations).forEach(translation => {
  10721. decl.value = decl.value.replace(translation, this.translations[translation]);
  10722. });
  10723. this.exportTokens[decl.prop] = decl.value;
  10724. }
  10725. });
  10726. exportNode.remove();
  10727. }
  10728. async fetchImport(importNode, relativeTo, depNr) {
  10729. const file = importNode.selector.match(importRegexp)[1];
  10730. const depTrace = this.trace + String.fromCharCode(depNr);
  10731. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  10732. try {
  10733. importNode.each(decl => {
  10734. if (decl.type == "decl") {
  10735. this.translations[decl.prop] = exports[decl.value];
  10736. }
  10737. });
  10738. importNode.remove();
  10739. } catch (err) {
  10740. console.log(err);
  10741. }
  10742. }
  10743. }
  10744. Parser$1.default = Parser;
  10745. var saveJSON$1 = {};
  10746. Object.defineProperty(saveJSON$1, "__esModule", {
  10747. value: true
  10748. });
  10749. saveJSON$1.default = saveJSON;
  10750. var _fs$2 = fs;
  10751. function saveJSON(cssFile, json) {
  10752. return new Promise((resolve, reject) => {
  10753. const {
  10754. writeFile
  10755. } = (0, _fs$2.getFileSystem)();
  10756. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  10757. });
  10758. }
  10759. var localsConvention = {};
  10760. /**
  10761. * lodash (Custom Build) <https://lodash.com/>
  10762. * Build: `lodash modularize exports="npm" -o ./`
  10763. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  10764. * Released under MIT license <https://lodash.com/license>
  10765. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  10766. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  10767. */
  10768. /** Used as references for various `Number` constants. */
  10769. var INFINITY = 1 / 0;
  10770. /** `Object#toString` result references. */
  10771. var symbolTag = '[object Symbol]';
  10772. /** Used to match words composed of alphanumeric characters. */
  10773. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  10774. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  10775. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  10776. /** Used to compose unicode character classes. */
  10777. var rsAstralRange = '\\ud800-\\udfff',
  10778. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  10779. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  10780. rsDingbatRange = '\\u2700-\\u27bf',
  10781. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  10782. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  10783. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  10784. rsPunctuationRange = '\\u2000-\\u206f',
  10785. rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
  10786. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  10787. rsVarRange = '\\ufe0e\\ufe0f',
  10788. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  10789. /** Used to compose unicode capture groups. */
  10790. var rsApos = "['\u2019]",
  10791. rsAstral = '[' + rsAstralRange + ']',
  10792. rsBreak = '[' + rsBreakRange + ']',
  10793. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  10794. rsDigits = '\\d+',
  10795. rsDingbat = '[' + rsDingbatRange + ']',
  10796. rsLower = '[' + rsLowerRange + ']',
  10797. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  10798. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  10799. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  10800. rsNonAstral = '[^' + rsAstralRange + ']',
  10801. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  10802. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  10803. rsUpper = '[' + rsUpperRange + ']',
  10804. rsZWJ = '\\u200d';
  10805. /** Used to compose unicode regexes. */
  10806. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  10807. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  10808. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  10809. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  10810. reOptMod = rsModifier + '?',
  10811. rsOptVar = '[' + rsVarRange + ']?',
  10812. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  10813. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  10814. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  10815. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  10816. /** Used to match apostrophes. */
  10817. var reApos = RegExp(rsApos, 'g');
  10818. /**
  10819. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  10820. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  10821. */
  10822. var reComboMark = RegExp(rsCombo, 'g');
  10823. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  10824. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  10825. /** Used to match complex or compound words. */
  10826. var reUnicodeWord = RegExp([
  10827. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  10828. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  10829. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  10830. rsUpper + '+' + rsOptUpperContr,
  10831. rsDigits,
  10832. rsEmoji
  10833. ].join('|'), 'g');
  10834. /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  10835. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  10836. /** Used to detect strings that need a more robust regexp to match words. */
  10837. var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
  10838. /** Used to map Latin Unicode letters to basic Latin letters. */
  10839. var deburredLetters = {
  10840. // Latin-1 Supplement block.
  10841. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  10842. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  10843. '\xc7': 'C', '\xe7': 'c',
  10844. '\xd0': 'D', '\xf0': 'd',
  10845. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  10846. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  10847. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  10848. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  10849. '\xd1': 'N', '\xf1': 'n',
  10850. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  10851. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  10852. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  10853. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  10854. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  10855. '\xc6': 'Ae', '\xe6': 'ae',
  10856. '\xde': 'Th', '\xfe': 'th',
  10857. '\xdf': 'ss',
  10858. // Latin Extended-A block.
  10859. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  10860. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  10861. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  10862. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  10863. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  10864. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  10865. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  10866. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  10867. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  10868. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  10869. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  10870. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  10871. '\u0134': 'J', '\u0135': 'j',
  10872. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  10873. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  10874. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  10875. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  10876. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  10877. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  10878. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  10879. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  10880. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  10881. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  10882. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  10883. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  10884. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  10885. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  10886. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  10887. '\u0174': 'W', '\u0175': 'w',
  10888. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  10889. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  10890. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  10891. '\u0132': 'IJ', '\u0133': 'ij',
  10892. '\u0152': 'Oe', '\u0153': 'oe',
  10893. '\u0149': "'n", '\u017f': 'ss'
  10894. };
  10895. /** Detect free variable `global` from Node.js. */
  10896. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  10897. /** Detect free variable `self`. */
  10898. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  10899. /** Used as a reference to the global object. */
  10900. var root = freeGlobal || freeSelf || Function('return this')();
  10901. /**
  10902. * A specialized version of `_.reduce` for arrays without support for
  10903. * iteratee shorthands.
  10904. *
  10905. * @private
  10906. * @param {Array} [array] The array to iterate over.
  10907. * @param {Function} iteratee The function invoked per iteration.
  10908. * @param {*} [accumulator] The initial value.
  10909. * @param {boolean} [initAccum] Specify using the first element of `array` as
  10910. * the initial value.
  10911. * @returns {*} Returns the accumulated value.
  10912. */
  10913. function arrayReduce(array, iteratee, accumulator, initAccum) {
  10914. var index = -1,
  10915. length = array ? array.length : 0;
  10916. if (initAccum && length) {
  10917. accumulator = array[++index];
  10918. }
  10919. while (++index < length) {
  10920. accumulator = iteratee(accumulator, array[index], index, array);
  10921. }
  10922. return accumulator;
  10923. }
  10924. /**
  10925. * Converts an ASCII `string` to an array.
  10926. *
  10927. * @private
  10928. * @param {string} string The string to convert.
  10929. * @returns {Array} Returns the converted array.
  10930. */
  10931. function asciiToArray(string) {
  10932. return string.split('');
  10933. }
  10934. /**
  10935. * Splits an ASCII `string` into an array of its words.
  10936. *
  10937. * @private
  10938. * @param {string} The string to inspect.
  10939. * @returns {Array} Returns the words of `string`.
  10940. */
  10941. function asciiWords(string) {
  10942. return string.match(reAsciiWord) || [];
  10943. }
  10944. /**
  10945. * The base implementation of `_.propertyOf` without support for deep paths.
  10946. *
  10947. * @private
  10948. * @param {Object} object The object to query.
  10949. * @returns {Function} Returns the new accessor function.
  10950. */
  10951. function basePropertyOf(object) {
  10952. return function(key) {
  10953. return object == null ? undefined : object[key];
  10954. };
  10955. }
  10956. /**
  10957. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  10958. * letters to basic Latin letters.
  10959. *
  10960. * @private
  10961. * @param {string} letter The matched letter to deburr.
  10962. * @returns {string} Returns the deburred letter.
  10963. */
  10964. var deburrLetter = basePropertyOf(deburredLetters);
  10965. /**
  10966. * Checks if `string` contains Unicode symbols.
  10967. *
  10968. * @private
  10969. * @param {string} string The string to inspect.
  10970. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  10971. */
  10972. function hasUnicode(string) {
  10973. return reHasUnicode.test(string);
  10974. }
  10975. /**
  10976. * Checks if `string` contains a word composed of Unicode symbols.
  10977. *
  10978. * @private
  10979. * @param {string} string The string to inspect.
  10980. * @returns {boolean} Returns `true` if a word is found, else `false`.
  10981. */
  10982. function hasUnicodeWord(string) {
  10983. return reHasUnicodeWord.test(string);
  10984. }
  10985. /**
  10986. * Converts `string` to an array.
  10987. *
  10988. * @private
  10989. * @param {string} string The string to convert.
  10990. * @returns {Array} Returns the converted array.
  10991. */
  10992. function stringToArray(string) {
  10993. return hasUnicode(string)
  10994. ? unicodeToArray(string)
  10995. : asciiToArray(string);
  10996. }
  10997. /**
  10998. * Converts a Unicode `string` to an array.
  10999. *
  11000. * @private
  11001. * @param {string} string The string to convert.
  11002. * @returns {Array} Returns the converted array.
  11003. */
  11004. function unicodeToArray(string) {
  11005. return string.match(reUnicode) || [];
  11006. }
  11007. /**
  11008. * Splits a Unicode `string` into an array of its words.
  11009. *
  11010. * @private
  11011. * @param {string} The string to inspect.
  11012. * @returns {Array} Returns the words of `string`.
  11013. */
  11014. function unicodeWords(string) {
  11015. return string.match(reUnicodeWord) || [];
  11016. }
  11017. /** Used for built-in method references. */
  11018. var objectProto = Object.prototype;
  11019. /**
  11020. * Used to resolve the
  11021. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11022. * of values.
  11023. */
  11024. var objectToString = objectProto.toString;
  11025. /** Built-in value references. */
  11026. var Symbol$1 = root.Symbol;
  11027. /** Used to convert symbols to primitives and strings. */
  11028. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
  11029. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11030. /**
  11031. * The base implementation of `_.slice` without an iteratee call guard.
  11032. *
  11033. * @private
  11034. * @param {Array} array The array to slice.
  11035. * @param {number} [start=0] The start position.
  11036. * @param {number} [end=array.length] The end position.
  11037. * @returns {Array} Returns the slice of `array`.
  11038. */
  11039. function baseSlice(array, start, end) {
  11040. var index = -1,
  11041. length = array.length;
  11042. if (start < 0) {
  11043. start = -start > length ? 0 : (length + start);
  11044. }
  11045. end = end > length ? length : end;
  11046. if (end < 0) {
  11047. end += length;
  11048. }
  11049. length = start > end ? 0 : ((end - start) >>> 0);
  11050. start >>>= 0;
  11051. var result = Array(length);
  11052. while (++index < length) {
  11053. result[index] = array[index + start];
  11054. }
  11055. return result;
  11056. }
  11057. /**
  11058. * The base implementation of `_.toString` which doesn't convert nullish
  11059. * values to empty strings.
  11060. *
  11061. * @private
  11062. * @param {*} value The value to process.
  11063. * @returns {string} Returns the string.
  11064. */
  11065. function baseToString(value) {
  11066. // Exit early for strings to avoid a performance hit in some environments.
  11067. if (typeof value == 'string') {
  11068. return value;
  11069. }
  11070. if (isSymbol(value)) {
  11071. return symbolToString ? symbolToString.call(value) : '';
  11072. }
  11073. var result = (value + '');
  11074. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  11075. }
  11076. /**
  11077. * Casts `array` to a slice if it's needed.
  11078. *
  11079. * @private
  11080. * @param {Array} array The array to inspect.
  11081. * @param {number} start The start position.
  11082. * @param {number} [end=array.length] The end position.
  11083. * @returns {Array} Returns the cast slice.
  11084. */
  11085. function castSlice(array, start, end) {
  11086. var length = array.length;
  11087. end = end === undefined ? length : end;
  11088. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11089. }
  11090. /**
  11091. * Creates a function like `_.lowerFirst`.
  11092. *
  11093. * @private
  11094. * @param {string} methodName The name of the `String` case method to use.
  11095. * @returns {Function} Returns the new case function.
  11096. */
  11097. function createCaseFirst(methodName) {
  11098. return function(string) {
  11099. string = toString(string);
  11100. var strSymbols = hasUnicode(string)
  11101. ? stringToArray(string)
  11102. : undefined;
  11103. var chr = strSymbols
  11104. ? strSymbols[0]
  11105. : string.charAt(0);
  11106. var trailing = strSymbols
  11107. ? castSlice(strSymbols, 1).join('')
  11108. : string.slice(1);
  11109. return chr[methodName]() + trailing;
  11110. };
  11111. }
  11112. /**
  11113. * Creates a function like `_.camelCase`.
  11114. *
  11115. * @private
  11116. * @param {Function} callback The function to combine each word.
  11117. * @returns {Function} Returns the new compounder function.
  11118. */
  11119. function createCompounder(callback) {
  11120. return function(string) {
  11121. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11122. };
  11123. }
  11124. /**
  11125. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11126. * and has a `typeof` result of "object".
  11127. *
  11128. * @static
  11129. * @memberOf _
  11130. * @since 4.0.0
  11131. * @category Lang
  11132. * @param {*} value The value to check.
  11133. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11134. * @example
  11135. *
  11136. * _.isObjectLike({});
  11137. * // => true
  11138. *
  11139. * _.isObjectLike([1, 2, 3]);
  11140. * // => true
  11141. *
  11142. * _.isObjectLike(_.noop);
  11143. * // => false
  11144. *
  11145. * _.isObjectLike(null);
  11146. * // => false
  11147. */
  11148. function isObjectLike(value) {
  11149. return !!value && typeof value == 'object';
  11150. }
  11151. /**
  11152. * Checks if `value` is classified as a `Symbol` primitive or object.
  11153. *
  11154. * @static
  11155. * @memberOf _
  11156. * @since 4.0.0
  11157. * @category Lang
  11158. * @param {*} value The value to check.
  11159. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11160. * @example
  11161. *
  11162. * _.isSymbol(Symbol.iterator);
  11163. * // => true
  11164. *
  11165. * _.isSymbol('abc');
  11166. * // => false
  11167. */
  11168. function isSymbol(value) {
  11169. return typeof value == 'symbol' ||
  11170. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11171. }
  11172. /**
  11173. * Converts `value` to a string. An empty string is returned for `null`
  11174. * and `undefined` values. The sign of `-0` is preserved.
  11175. *
  11176. * @static
  11177. * @memberOf _
  11178. * @since 4.0.0
  11179. * @category Lang
  11180. * @param {*} value The value to process.
  11181. * @returns {string} Returns the string.
  11182. * @example
  11183. *
  11184. * _.toString(null);
  11185. * // => ''
  11186. *
  11187. * _.toString(-0);
  11188. * // => '-0'
  11189. *
  11190. * _.toString([1, 2, 3]);
  11191. * // => '1,2,3'
  11192. */
  11193. function toString(value) {
  11194. return value == null ? '' : baseToString(value);
  11195. }
  11196. /**
  11197. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11198. *
  11199. * @static
  11200. * @memberOf _
  11201. * @since 3.0.0
  11202. * @category String
  11203. * @param {string} [string=''] The string to convert.
  11204. * @returns {string} Returns the camel cased string.
  11205. * @example
  11206. *
  11207. * _.camelCase('Foo Bar');
  11208. * // => 'fooBar'
  11209. *
  11210. * _.camelCase('--foo-bar--');
  11211. * // => 'fooBar'
  11212. *
  11213. * _.camelCase('__FOO_BAR__');
  11214. * // => 'fooBar'
  11215. */
  11216. var camelCase = createCompounder(function(result, word, index) {
  11217. word = word.toLowerCase();
  11218. return result + (index ? capitalize(word) : word);
  11219. });
  11220. /**
  11221. * Converts the first character of `string` to upper case and the remaining
  11222. * to lower case.
  11223. *
  11224. * @static
  11225. * @memberOf _
  11226. * @since 3.0.0
  11227. * @category String
  11228. * @param {string} [string=''] The string to capitalize.
  11229. * @returns {string} Returns the capitalized string.
  11230. * @example
  11231. *
  11232. * _.capitalize('FRED');
  11233. * // => 'Fred'
  11234. */
  11235. function capitalize(string) {
  11236. return upperFirst(toString(string).toLowerCase());
  11237. }
  11238. /**
  11239. * Deburrs `string` by converting
  11240. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11241. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11242. * letters to basic Latin letters and removing
  11243. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11244. *
  11245. * @static
  11246. * @memberOf _
  11247. * @since 3.0.0
  11248. * @category String
  11249. * @param {string} [string=''] The string to deburr.
  11250. * @returns {string} Returns the deburred string.
  11251. * @example
  11252. *
  11253. * _.deburr('déjà vu');
  11254. * // => 'deja vu'
  11255. */
  11256. function deburr(string) {
  11257. string = toString(string);
  11258. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11259. }
  11260. /**
  11261. * Converts the first character of `string` to upper case.
  11262. *
  11263. * @static
  11264. * @memberOf _
  11265. * @since 4.0.0
  11266. * @category String
  11267. * @param {string} [string=''] The string to convert.
  11268. * @returns {string} Returns the converted string.
  11269. * @example
  11270. *
  11271. * _.upperFirst('fred');
  11272. * // => 'Fred'
  11273. *
  11274. * _.upperFirst('FRED');
  11275. * // => 'FRED'
  11276. */
  11277. var upperFirst = createCaseFirst('toUpperCase');
  11278. /**
  11279. * Splits `string` into an array of its words.
  11280. *
  11281. * @static
  11282. * @memberOf _
  11283. * @since 3.0.0
  11284. * @category String
  11285. * @param {string} [string=''] The string to inspect.
  11286. * @param {RegExp|string} [pattern] The pattern to match words.
  11287. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11288. * @returns {Array} Returns the words of `string`.
  11289. * @example
  11290. *
  11291. * _.words('fred, barney, & pebbles');
  11292. * // => ['fred', 'barney', 'pebbles']
  11293. *
  11294. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11295. * // => ['fred', 'barney', '&', 'pebbles']
  11296. */
  11297. function words(string, pattern, guard) {
  11298. string = toString(string);
  11299. pattern = guard ? undefined : pattern;
  11300. if (pattern === undefined) {
  11301. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11302. }
  11303. return string.match(pattern) || [];
  11304. }
  11305. var lodash_camelcase = camelCase;
  11306. Object.defineProperty(localsConvention, "__esModule", {
  11307. value: true
  11308. });
  11309. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11310. var _lodash = _interopRequireDefault$3(lodash_camelcase);
  11311. function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11312. function dashesCamelCase(string) {
  11313. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11314. }
  11315. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11316. const isFunc = typeof localsConvention === "function";
  11317. return (tokens, [className, value]) => {
  11318. if (isFunc) {
  11319. const convention = localsConvention(className, value, inputFile);
  11320. tokens[convention] = value;
  11321. return tokens;
  11322. }
  11323. switch (localsConvention) {
  11324. case "camelCase":
  11325. tokens[className] = value;
  11326. tokens[(0, _lodash.default)(className)] = value;
  11327. break;
  11328. case "camelCaseOnly":
  11329. tokens[(0, _lodash.default)(className)] = value;
  11330. break;
  11331. case "dashes":
  11332. tokens[className] = value;
  11333. tokens[dashesCamelCase(className)] = value;
  11334. break;
  11335. case "dashesOnly":
  11336. tokens[dashesCamelCase(className)] = value;
  11337. break;
  11338. }
  11339. return tokens;
  11340. };
  11341. }
  11342. var FileSystemLoader$1 = {};
  11343. Object.defineProperty(FileSystemLoader$1, "__esModule", {
  11344. value: true
  11345. });
  11346. FileSystemLoader$1.default = void 0;
  11347. var _postcss$1 = _interopRequireDefault$2(require$$0$1);
  11348. var _path = _interopRequireDefault$2(path$3);
  11349. var _Parser$1 = _interopRequireDefault$2(Parser$1);
  11350. var _fs$1 = fs;
  11351. function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11352. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11353. class Core {
  11354. constructor(plugins) {
  11355. this.plugins = plugins || Core.defaultPlugins;
  11356. }
  11357. async load(sourceString, sourcePath, trace, pathFetcher) {
  11358. const parser = new _Parser$1.default(pathFetcher, trace);
  11359. const plugins = this.plugins.concat([parser.plugin()]);
  11360. const result = await (0, _postcss$1.default)(plugins).process(sourceString, {
  11361. from: sourcePath
  11362. });
  11363. return {
  11364. injectableSource: result.css,
  11365. exportTokens: parser.exportTokens
  11366. };
  11367. }
  11368. } // Sorts dependencies in the following way:
  11369. // AAA comes before AA and A
  11370. // AB comes after AA and before A
  11371. // All Bs come after all As
  11372. // This ensures that the files are always returned in the following order:
  11373. // - In the order they were required, except
  11374. // - After all their dependencies
  11375. const traceKeySorter = (a, b) => {
  11376. if (a.length < b.length) {
  11377. return a < b.substring(0, a.length) ? -1 : 1;
  11378. }
  11379. if (a.length > b.length) {
  11380. return a.substring(0, b.length) <= b ? -1 : 1;
  11381. }
  11382. return a < b ? -1 : 1;
  11383. };
  11384. class FileSystemLoader {
  11385. constructor(root, plugins, fileResolve) {
  11386. if (root === "/" && process.platform === "win32") {
  11387. const cwdDrive = process.cwd().slice(0, 3);
  11388. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11389. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11390. }
  11391. root = cwdDrive;
  11392. }
  11393. this.root = root;
  11394. this.fileResolve = fileResolve;
  11395. this.sources = {};
  11396. this.traces = {};
  11397. this.importNr = 0;
  11398. this.core = new Core(plugins);
  11399. this.tokensByFile = {};
  11400. this.fs = (0, _fs$1.getFileSystem)();
  11401. }
  11402. async fetch(_newPath, relativeTo, _trace) {
  11403. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11404. const trace = _trace || String.fromCharCode(this.importNr++);
  11405. const useFileResolve = typeof this.fileResolve === "function";
  11406. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11407. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11408. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11409. }
  11410. const relativeDir = _path.default.dirname(relativeTo);
  11411. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11412. let fileRelativePath = fileResolvedPath || _path.default.resolve(_path.default.resolve(this.root, relativeDir), newPath); // if the path is not relative or absolute, try to resolve it in node_modules
  11413. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11414. try {
  11415. fileRelativePath = require.resolve(newPath);
  11416. } catch (e) {// noop
  11417. }
  11418. }
  11419. const tokens = this.tokensByFile[fileRelativePath];
  11420. if (tokens) return tokens;
  11421. return new Promise((resolve, reject) => {
  11422. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11423. if (err) reject(err);
  11424. const {
  11425. injectableSource,
  11426. exportTokens
  11427. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11428. this.sources[fileRelativePath] = injectableSource;
  11429. this.traces[trace] = fileRelativePath;
  11430. this.tokensByFile[fileRelativePath] = exportTokens;
  11431. resolve(exportTokens);
  11432. });
  11433. });
  11434. }
  11435. get finalSource() {
  11436. const traces = this.traces;
  11437. const sources = this.sources;
  11438. let written = new Set();
  11439. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11440. const filename = traces[key];
  11441. if (written.has(filename)) {
  11442. return null;
  11443. }
  11444. written.add(filename);
  11445. return sources[filename];
  11446. }).join("");
  11447. }
  11448. }
  11449. FileSystemLoader$1.default = FileSystemLoader;
  11450. var scoping = {};
  11451. var src$3 = {exports: {}};
  11452. const PERMANENT_MARKER = 2;
  11453. const TEMPORARY_MARKER = 1;
  11454. function createError(node, graph) {
  11455. const er = new Error("Nondeterministic import's order");
  11456. const related = graph[node];
  11457. const relatedNode = related.find(
  11458. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11459. );
  11460. er.nodes = [node, relatedNode];
  11461. return er;
  11462. }
  11463. function walkGraph(node, graph, state, result, strict) {
  11464. if (state[node] === PERMANENT_MARKER) {
  11465. return;
  11466. }
  11467. if (state[node] === TEMPORARY_MARKER) {
  11468. if (strict) {
  11469. return createError(node, graph);
  11470. }
  11471. return;
  11472. }
  11473. state[node] = TEMPORARY_MARKER;
  11474. const children = graph[node];
  11475. const length = children.length;
  11476. for (let i = 0; i < length; ++i) {
  11477. const error = walkGraph(children[i], graph, state, result, strict);
  11478. if (error instanceof Error) {
  11479. return error;
  11480. }
  11481. }
  11482. state[node] = PERMANENT_MARKER;
  11483. result.push(node);
  11484. }
  11485. function topologicalSort$1(graph, strict) {
  11486. const result = [];
  11487. const state = {};
  11488. const nodes = Object.keys(graph);
  11489. const length = nodes.length;
  11490. for (let i = 0; i < length; ++i) {
  11491. const er = walkGraph(nodes[i], graph, state, result, strict);
  11492. if (er instanceof Error) {
  11493. return er;
  11494. }
  11495. }
  11496. return result;
  11497. }
  11498. var topologicalSort_1 = topologicalSort$1;
  11499. const topologicalSort = topologicalSort_1;
  11500. const matchImports$1 = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11501. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11502. const VISITED_MARKER = 1;
  11503. /**
  11504. * :import('G') {}
  11505. *
  11506. * Rule
  11507. * composes: ... from 'A'
  11508. * composes: ... from 'B'
  11509. * Rule
  11510. * composes: ... from 'A'
  11511. * composes: ... from 'A'
  11512. * composes: ... from 'C'
  11513. *
  11514. * Results in:
  11515. *
  11516. * graph: {
  11517. * G: [],
  11518. * A: [],
  11519. * B: ['A'],
  11520. * C: ['A'],
  11521. * }
  11522. */
  11523. function addImportToGraph(importId, parentId, graph, visited) {
  11524. const siblingsId = parentId + "_" + "siblings";
  11525. const visitedId = parentId + "_" + importId;
  11526. if (visited[visitedId] !== VISITED_MARKER) {
  11527. if (!Array.isArray(visited[siblingsId])) {
  11528. visited[siblingsId] = [];
  11529. }
  11530. const siblings = visited[siblingsId];
  11531. if (Array.isArray(graph[importId])) {
  11532. graph[importId] = graph[importId].concat(siblings);
  11533. } else {
  11534. graph[importId] = siblings.slice();
  11535. }
  11536. visited[visitedId] = VISITED_MARKER;
  11537. siblings.push(importId);
  11538. }
  11539. }
  11540. src$3.exports = (options = {}) => {
  11541. let importIndex = 0;
  11542. const createImportedName =
  11543. typeof options.createImportedName !== "function"
  11544. ? (importName /*, path*/) =>
  11545. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11546. : options.createImportedName;
  11547. const failOnWrongOrder = options.failOnWrongOrder;
  11548. return {
  11549. postcssPlugin: "postcss-modules-extract-imports",
  11550. prepare() {
  11551. const graph = {};
  11552. const visited = {};
  11553. const existingImports = {};
  11554. const importDecls = {};
  11555. const imports = {};
  11556. return {
  11557. Once(root, postcss) {
  11558. // Check the existing imports order and save refs
  11559. root.walkRules((rule) => {
  11560. const matches = icssImport.exec(rule.selector);
  11561. if (matches) {
  11562. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11563. const importPath = doubleQuotePath || singleQuotePath;
  11564. addImportToGraph(importPath, "root", graph, visited);
  11565. existingImports[importPath] = rule;
  11566. }
  11567. });
  11568. root.walkDecls(/^composes$/, (declaration) => {
  11569. const matches = declaration.value.match(matchImports$1);
  11570. if (!matches) {
  11571. return;
  11572. }
  11573. let tmpSymbols;
  11574. let [
  11575. ,
  11576. /*match*/ symbols,
  11577. doubleQuotePath,
  11578. singleQuotePath,
  11579. global,
  11580. ] = matches;
  11581. if (global) {
  11582. // Composing globals simply means changing these classes to wrap them in global(name)
  11583. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  11584. } else {
  11585. const importPath = doubleQuotePath || singleQuotePath;
  11586. let parent = declaration.parent;
  11587. let parentIndexes = "";
  11588. while (parent.type !== "root") {
  11589. parentIndexes =
  11590. parent.parent.index(parent) + "_" + parentIndexes;
  11591. parent = parent.parent;
  11592. }
  11593. const { selector } = declaration.parent;
  11594. const parentRule = `_${parentIndexes}${selector}`;
  11595. addImportToGraph(importPath, parentRule, graph, visited);
  11596. importDecls[importPath] = declaration;
  11597. imports[importPath] = imports[importPath] || {};
  11598. tmpSymbols = symbols.split(/\s+/).map((s) => {
  11599. if (!imports[importPath][s]) {
  11600. imports[importPath][s] = createImportedName(s, importPath);
  11601. }
  11602. return imports[importPath][s];
  11603. });
  11604. }
  11605. declaration.value = tmpSymbols.join(" ");
  11606. });
  11607. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  11608. if (importsOrder instanceof Error) {
  11609. const importPath = importsOrder.nodes.find((importPath) =>
  11610. // eslint-disable-next-line no-prototype-builtins
  11611. importDecls.hasOwnProperty(importPath)
  11612. );
  11613. const decl = importDecls[importPath];
  11614. throw decl.error(
  11615. "Failed to resolve order of composed modules " +
  11616. importsOrder.nodes
  11617. .map((importPath) => "`" + importPath + "`")
  11618. .join(", ") +
  11619. ".",
  11620. {
  11621. plugin: "postcss-modules-extract-imports",
  11622. word: "composes",
  11623. }
  11624. );
  11625. }
  11626. let lastImportRule;
  11627. importsOrder.forEach((path) => {
  11628. const importedSymbols = imports[path];
  11629. let rule = existingImports[path];
  11630. if (!rule && importedSymbols) {
  11631. rule = postcss.rule({
  11632. selector: `:import("${path}")`,
  11633. raws: { after: "\n" },
  11634. });
  11635. if (lastImportRule) {
  11636. root.insertAfter(lastImportRule, rule);
  11637. } else {
  11638. root.prepend(rule);
  11639. }
  11640. }
  11641. lastImportRule = rule;
  11642. if (!importedSymbols) {
  11643. return;
  11644. }
  11645. Object.keys(importedSymbols).forEach((importedSymbol) => {
  11646. rule.append(
  11647. postcss.decl({
  11648. value: importedSymbol,
  11649. prop: importedSymbols[importedSymbol],
  11650. raws: { before: "\n " },
  11651. })
  11652. );
  11653. });
  11654. });
  11655. },
  11656. };
  11657. },
  11658. };
  11659. };
  11660. src$3.exports.postcss = true;
  11661. var srcExports$2 = src$3.exports;
  11662. var wasmHash = {exports: {}};
  11663. /*
  11664. MIT License http://www.opensource.org/licenses/mit-license.php
  11665. Author Tobias Koppers @sokra
  11666. */
  11667. var hasRequiredWasmHash;
  11668. function requireWasmHash () {
  11669. if (hasRequiredWasmHash) return wasmHash.exports;
  11670. hasRequiredWasmHash = 1;
  11671. // 65536 is the size of a wasm memory page
  11672. // 64 is the maximum chunk size for every possible wasm hash implementation
  11673. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  11674. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  11675. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
  11676. class WasmHash {
  11677. /**
  11678. * @param {WebAssembly.Instance} instance wasm instance
  11679. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  11680. * @param {number} chunkSize size of data chunks passed to wasm
  11681. * @param {number} digestSize size of digest returned by wasm
  11682. */
  11683. constructor(instance, instancesPool, chunkSize, digestSize) {
  11684. const exports = /** @type {any} */ (instance.exports);
  11685. exports.init();
  11686. this.exports = exports;
  11687. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  11688. this.buffered = 0;
  11689. this.instancesPool = instancesPool;
  11690. this.chunkSize = chunkSize;
  11691. this.digestSize = digestSize;
  11692. }
  11693. reset() {
  11694. this.buffered = 0;
  11695. this.exports.init();
  11696. }
  11697. /**
  11698. * @param {Buffer | string} data data
  11699. * @param {BufferEncoding=} encoding encoding
  11700. * @returns {this} itself
  11701. */
  11702. update(data, encoding) {
  11703. if (typeof data === "string") {
  11704. while (data.length > MAX_SHORT_STRING) {
  11705. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  11706. data = data.slice(MAX_SHORT_STRING);
  11707. }
  11708. this._updateWithShortString(data, encoding);
  11709. return this;
  11710. }
  11711. this._updateWithBuffer(data);
  11712. return this;
  11713. }
  11714. /**
  11715. * @param {string} data data
  11716. * @param {BufferEncoding=} encoding encoding
  11717. * @returns {void}
  11718. */
  11719. _updateWithShortString(data, encoding) {
  11720. const { exports, buffered, mem, chunkSize } = this;
  11721. let endPos;
  11722. if (data.length < 70) {
  11723. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  11724. endPos = buffered;
  11725. for (let i = 0; i < data.length; i++) {
  11726. const cc = data.charCodeAt(i);
  11727. if (cc < 0x80) {
  11728. mem[endPos++] = cc;
  11729. } else if (cc < 0x800) {
  11730. mem[endPos] = (cc >> 6) | 0xc0;
  11731. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  11732. endPos += 2;
  11733. } else {
  11734. // bail-out for weird chars
  11735. endPos += mem.write(data.slice(i), endPos, encoding);
  11736. break;
  11737. }
  11738. }
  11739. } else if (encoding === "latin1") {
  11740. endPos = buffered;
  11741. for (let i = 0; i < data.length; i++) {
  11742. const cc = data.charCodeAt(i);
  11743. mem[endPos++] = cc;
  11744. }
  11745. } else {
  11746. endPos = buffered + mem.write(data, buffered, encoding);
  11747. }
  11748. } else {
  11749. endPos = buffered + mem.write(data, buffered, encoding);
  11750. }
  11751. if (endPos < chunkSize) {
  11752. this.buffered = endPos;
  11753. } else {
  11754. const l = endPos & ~(this.chunkSize - 1);
  11755. exports.update(l);
  11756. const newBuffered = endPos - l;
  11757. this.buffered = newBuffered;
  11758. if (newBuffered > 0) {
  11759. mem.copyWithin(0, l, endPos);
  11760. }
  11761. }
  11762. }
  11763. /**
  11764. * @param {Buffer} data data
  11765. * @returns {void}
  11766. */
  11767. _updateWithBuffer(data) {
  11768. const { exports, buffered, mem } = this;
  11769. const length = data.length;
  11770. if (buffered + length < this.chunkSize) {
  11771. data.copy(mem, buffered, 0, length);
  11772. this.buffered += length;
  11773. } else {
  11774. const l = (buffered + length) & ~(this.chunkSize - 1);
  11775. if (l > 65536) {
  11776. let i = 65536 - buffered;
  11777. data.copy(mem, buffered, 0, i);
  11778. exports.update(65536);
  11779. const stop = l - buffered - 65536;
  11780. while (i < stop) {
  11781. data.copy(mem, 0, i, i + 65536);
  11782. exports.update(65536);
  11783. i += 65536;
  11784. }
  11785. data.copy(mem, 0, i, l - buffered);
  11786. exports.update(l - buffered - i);
  11787. } else {
  11788. data.copy(mem, buffered, 0, l - buffered);
  11789. exports.update(l);
  11790. }
  11791. const newBuffered = length + buffered - l;
  11792. this.buffered = newBuffered;
  11793. if (newBuffered > 0) {
  11794. data.copy(mem, 0, length - newBuffered, length);
  11795. }
  11796. }
  11797. }
  11798. digest(type) {
  11799. const { exports, buffered, mem, digestSize } = this;
  11800. exports.final(buffered);
  11801. this.instancesPool.push(this);
  11802. const hex = mem.toString("latin1", 0, digestSize);
  11803. if (type === "hex") {
  11804. return hex;
  11805. }
  11806. if (type === "binary" || !type) {
  11807. return Buffer.from(hex, "hex");
  11808. }
  11809. return Buffer.from(hex, "hex").toString(type);
  11810. }
  11811. }
  11812. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  11813. if (instancesPool.length > 0) {
  11814. const old = instancesPool.pop();
  11815. old.reset();
  11816. return old;
  11817. } else {
  11818. return new WasmHash(
  11819. new WebAssembly.Instance(wasmModule),
  11820. instancesPool,
  11821. chunkSize,
  11822. digestSize
  11823. );
  11824. }
  11825. };
  11826. wasmHash.exports = create;
  11827. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  11828. return wasmHash.exports;
  11829. }
  11830. /*
  11831. MIT License http://www.opensource.org/licenses/mit-license.php
  11832. Author Tobias Koppers @sokra
  11833. */
  11834. var xxhash64_1;
  11835. var hasRequiredXxhash64;
  11836. function requireXxhash64 () {
  11837. if (hasRequiredXxhash64) return xxhash64_1;
  11838. hasRequiredXxhash64 = 1;
  11839. const create = requireWasmHash();
  11840. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  11841. const xxhash64 = new WebAssembly.Module(
  11842. Buffer.from(
  11843. // 1173 bytes
  11844. "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrUIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqwYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEACfyACIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCECIAFBBGoLIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAiACQh2IhUL5893xmfaZqxZ+IgIgAkIgiIUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL",
  11845. "base64"
  11846. )
  11847. );
  11848. //#endregion
  11849. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  11850. return xxhash64_1;
  11851. }
  11852. var BatchedHash_1;
  11853. var hasRequiredBatchedHash;
  11854. function requireBatchedHash () {
  11855. if (hasRequiredBatchedHash) return BatchedHash_1;
  11856. hasRequiredBatchedHash = 1;
  11857. const MAX_SHORT_STRING = requireWasmHash().MAX_SHORT_STRING;
  11858. class BatchedHash {
  11859. constructor(hash) {
  11860. this.string = undefined;
  11861. this.encoding = undefined;
  11862. this.hash = hash;
  11863. }
  11864. /**
  11865. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  11866. * @param {string|Buffer} data data
  11867. * @param {string=} inputEncoding data encoding
  11868. * @returns {this} updated hash
  11869. */
  11870. update(data, inputEncoding) {
  11871. if (this.string !== undefined) {
  11872. if (
  11873. typeof data === "string" &&
  11874. inputEncoding === this.encoding &&
  11875. this.string.length + data.length < MAX_SHORT_STRING
  11876. ) {
  11877. this.string += data;
  11878. return this;
  11879. }
  11880. this.hash.update(this.string, this.encoding);
  11881. this.string = undefined;
  11882. }
  11883. if (typeof data === "string") {
  11884. if (
  11885. data.length < MAX_SHORT_STRING &&
  11886. // base64 encoding is not valid since it may contain padding chars
  11887. (!inputEncoding || !inputEncoding.startsWith("ba"))
  11888. ) {
  11889. this.string = data;
  11890. this.encoding = inputEncoding;
  11891. } else {
  11892. this.hash.update(data, inputEncoding);
  11893. }
  11894. } else {
  11895. this.hash.update(data);
  11896. }
  11897. return this;
  11898. }
  11899. /**
  11900. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  11901. * @param {string=} encoding encoding of the return value
  11902. * @returns {string|Buffer} digest
  11903. */
  11904. digest(encoding) {
  11905. if (this.string !== undefined) {
  11906. this.hash.update(this.string, this.encoding);
  11907. }
  11908. return this.hash.digest(encoding);
  11909. }
  11910. }
  11911. BatchedHash_1 = BatchedHash;
  11912. return BatchedHash_1;
  11913. }
  11914. /*
  11915. MIT License http://www.opensource.org/licenses/mit-license.php
  11916. Author Tobias Koppers @sokra
  11917. */
  11918. var md4_1;
  11919. var hasRequiredMd4;
  11920. function requireMd4 () {
  11921. if (hasRequiredMd4) return md4_1;
  11922. hasRequiredMd4 = 1;
  11923. const create = requireWasmHash();
  11924. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  11925. const md4 = new WebAssembly.Module(
  11926. Buffer.from(
  11927. // 2150 bytes
  11928. "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqFEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvMCgEYfyMBIQojAiEGIwMhByMEIQgDQCAAIAVLBEAgBSgCCCINIAcgBiAFKAIEIgsgCCAHIAUoAgAiDCAKIAggBiAHIAhzcXNqakEDdyIDIAYgB3Nxc2pqQQd3IgEgAyAGc3FzampBC3chAiAFKAIUIg8gASACIAUoAhAiCSADIAEgBSgCDCIOIAYgAyACIAEgA3Nxc2pqQRN3IgQgASACc3FzampBA3ciAyACIARzcXNqakEHdyEBIAUoAiAiEiADIAEgBSgCHCIRIAQgAyAFKAIYIhAgAiAEIAEgAyAEc3FzampBC3ciAiABIANzcXNqakETdyIEIAEgAnNxc2pqQQN3IQMgBSgCLCIVIAQgAyAFKAIoIhQgAiAEIAUoAiQiEyABIAIgAyACIARzcXNqakEHdyIBIAMgBHNxc2pqQQt3IgIgASADc3FzampBE3chBCAPIBAgCSAVIBQgEyAFKAI4IhYgAiAEIAUoAjQiFyABIAIgBSgCMCIYIAMgASAEIAEgAnNxc2pqQQN3IgEgAiAEc3FzampBB3ciAiABIARzcXNqakELdyIDIAkgAiAMIAEgBSgCPCIJIAQgASADIAEgAnNxc2pqQRN3IgEgAiADcnEgAiADcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyaiASakGZ84nUBWpBCXciAyAPIAQgCyACIBggASADIAIgBHJxIAIgBHFyampBmfOJ1AVqQQ13IgEgAyAEcnEgAyAEcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyampBmfOJ1AVqQQl3IgMgECAEIAIgFyABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmogDWpBmfOJ1AVqQQN3IgIgASADcnEgASADcXJqakGZ84nUBWpBBXciBCABIAJycSABIAJxcmpqQZnzidQFakEJdyIDIBEgBCAOIAIgFiABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmpqQZnzidQFakEDdyICIAEgA3JxIAEgA3FyampBmfOJ1AVqQQV3IgQgASACcnEgASACcXJqakGZ84nUBWpBCXciAyAMIAIgAyAJIAEgAyACIARycSACIARxcmpqQZnzidQFakENdyIBcyAEc2pqQaHX5/YGakEDdyICIAQgASACcyADc2ogEmpBodfn9gZqQQl3IgRzIAFzampBodfn9gZqQQt3IgMgAiADIBggASADIARzIAJzampBodfn9gZqQQ93IgFzIARzaiANakGh1+f2BmpBA3ciAiAUIAQgASACcyADc2pqQaHX5/YGakEJdyIEcyABc2pqQaHX5/YGakELdyIDIAsgAiADIBYgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgIgEyAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3chAyAKIA4gAiADIBcgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgJqIQogBiAJIAEgESADIAIgFSAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3ciAyAEcyACc2pqQaHX5/YGakEPd2ohBiADIAdqIQcgBCAIaiEIIAVBQGshBQwBCwsgCiQBIAYkAiAHJAMgCCQECw0AIAAQASMAIABqJAAL/wQCA38BfiMAIABqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=",
  11929. "base64"
  11930. )
  11931. );
  11932. //#endregion
  11933. md4_1 = create.bind(null, md4, [], 64, 32);
  11934. return md4_1;
  11935. }
  11936. var BulkUpdateDecorator_1;
  11937. var hasRequiredBulkUpdateDecorator;
  11938. function requireBulkUpdateDecorator () {
  11939. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  11940. hasRequiredBulkUpdateDecorator = 1;
  11941. const BULK_SIZE = 2000;
  11942. // We are using an object instead of a Map as this will stay static during the runtime
  11943. // so access to it can be optimized by v8
  11944. const digestCaches = {};
  11945. class BulkUpdateDecorator {
  11946. /**
  11947. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  11948. * @param {string=} hashKey key for caching
  11949. */
  11950. constructor(hashOrFactory, hashKey) {
  11951. this.hashKey = hashKey;
  11952. if (typeof hashOrFactory === "function") {
  11953. this.hashFactory = hashOrFactory;
  11954. this.hash = undefined;
  11955. } else {
  11956. this.hashFactory = undefined;
  11957. this.hash = hashOrFactory;
  11958. }
  11959. this.buffer = "";
  11960. }
  11961. /**
  11962. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  11963. * @param {string|Buffer} data data
  11964. * @param {string=} inputEncoding data encoding
  11965. * @returns {this} updated hash
  11966. */
  11967. update(data, inputEncoding) {
  11968. if (
  11969. inputEncoding !== undefined ||
  11970. typeof data !== "string" ||
  11971. data.length > BULK_SIZE
  11972. ) {
  11973. if (this.hash === undefined) {
  11974. this.hash = this.hashFactory();
  11975. }
  11976. if (this.buffer.length > 0) {
  11977. this.hash.update(this.buffer);
  11978. this.buffer = "";
  11979. }
  11980. this.hash.update(data, inputEncoding);
  11981. } else {
  11982. this.buffer += data;
  11983. if (this.buffer.length > BULK_SIZE) {
  11984. if (this.hash === undefined) {
  11985. this.hash = this.hashFactory();
  11986. }
  11987. this.hash.update(this.buffer);
  11988. this.buffer = "";
  11989. }
  11990. }
  11991. return this;
  11992. }
  11993. /**
  11994. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  11995. * @param {string=} encoding encoding of the return value
  11996. * @returns {string|Buffer} digest
  11997. */
  11998. digest(encoding) {
  11999. let digestCache;
  12000. const buffer = this.buffer;
  12001. if (this.hash === undefined) {
  12002. // short data for hash, we can use caching
  12003. const cacheKey = `${this.hashKey}-${encoding}`;
  12004. digestCache = digestCaches[cacheKey];
  12005. if (digestCache === undefined) {
  12006. digestCache = digestCaches[cacheKey] = new Map();
  12007. }
  12008. const cacheEntry = digestCache.get(buffer);
  12009. if (cacheEntry !== undefined) {
  12010. return cacheEntry;
  12011. }
  12012. this.hash = this.hashFactory();
  12013. }
  12014. if (buffer.length > 0) {
  12015. this.hash.update(buffer);
  12016. }
  12017. const digestResult = this.hash.digest(encoding);
  12018. if (digestCache !== undefined) {
  12019. digestCache.set(buffer, digestResult);
  12020. }
  12021. return digestResult;
  12022. }
  12023. }
  12024. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12025. return BulkUpdateDecorator_1;
  12026. }
  12027. const baseEncodeTables = {
  12028. 26: "abcdefghijklmnopqrstuvwxyz",
  12029. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12030. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12031. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12032. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12033. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12034. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12035. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12036. };
  12037. /**
  12038. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12039. * @param {number} divisor The divisor
  12040. * @return {number} Modulo (remainder) of the division
  12041. */
  12042. function divmod32(uint32Array, divisor) {
  12043. let carry = 0;
  12044. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12045. const value = carry * 0x100000000 + uint32Array[i];
  12046. carry = value % divisor;
  12047. uint32Array[i] = Math.floor(value / divisor);
  12048. }
  12049. return carry;
  12050. }
  12051. function encodeBufferToBase(buffer, base, length) {
  12052. const encodeTable = baseEncodeTables[base];
  12053. if (!encodeTable) {
  12054. throw new Error("Unknown encoding base" + base);
  12055. }
  12056. // Input bits are only enough to generate this many characters
  12057. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12058. length = Math.min(length, limit);
  12059. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12060. // Fewer numbers in the array means faster math.
  12061. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12062. // Make sure the input buffer data is copied and is not mutated by reference.
  12063. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12064. buffer.copy(Buffer.from(uint32Array.buffer));
  12065. let output = "";
  12066. for (let i = 0; i < length; i++) {
  12067. output = encodeTable[divmod32(uint32Array, base)] + output;
  12068. }
  12069. return output;
  12070. }
  12071. let crypto = undefined;
  12072. let createXXHash64 = undefined;
  12073. let createMd4 = undefined;
  12074. let BatchedHash = undefined;
  12075. let BulkUpdateDecorator = undefined;
  12076. function getHashDigest$1(buffer, algorithm, digestType, maxLength) {
  12077. algorithm = algorithm || "xxhash64";
  12078. maxLength = maxLength || 9999;
  12079. let hash;
  12080. if (algorithm === "xxhash64") {
  12081. if (createXXHash64 === undefined) {
  12082. createXXHash64 = requireXxhash64();
  12083. if (BatchedHash === undefined) {
  12084. BatchedHash = requireBatchedHash();
  12085. }
  12086. }
  12087. hash = new BatchedHash(createXXHash64());
  12088. } else if (algorithm === "md4") {
  12089. if (createMd4 === undefined) {
  12090. createMd4 = requireMd4();
  12091. if (BatchedHash === undefined) {
  12092. BatchedHash = requireBatchedHash();
  12093. }
  12094. }
  12095. hash = new BatchedHash(createMd4());
  12096. } else if (algorithm === "native-md4") {
  12097. if (typeof crypto === "undefined") {
  12098. crypto = require("crypto");
  12099. if (BulkUpdateDecorator === undefined) {
  12100. BulkUpdateDecorator = requireBulkUpdateDecorator();
  12101. }
  12102. }
  12103. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12104. } else {
  12105. if (typeof crypto === "undefined") {
  12106. crypto = require("crypto");
  12107. if (BulkUpdateDecorator === undefined) {
  12108. BulkUpdateDecorator = requireBulkUpdateDecorator();
  12109. }
  12110. }
  12111. hash = new BulkUpdateDecorator(
  12112. () => crypto.createHash(algorithm),
  12113. algorithm
  12114. );
  12115. }
  12116. hash.update(buffer);
  12117. if (
  12118. digestType === "base26" ||
  12119. digestType === "base32" ||
  12120. digestType === "base36" ||
  12121. digestType === "base49" ||
  12122. digestType === "base52" ||
  12123. digestType === "base58" ||
  12124. digestType === "base62"
  12125. ) {
  12126. return encodeBufferToBase(hash.digest(), digestType.substr(4), maxLength);
  12127. } else {
  12128. return hash.digest(digestType || "hex").substr(0, maxLength);
  12129. }
  12130. }
  12131. var getHashDigest_1 = getHashDigest$1;
  12132. const path$2 = path$3;
  12133. const getHashDigest = getHashDigest_1;
  12134. function interpolateName$1(loaderContext, name, options = {}) {
  12135. let filename;
  12136. const hasQuery =
  12137. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12138. if (typeof name === "function") {
  12139. filename = name(
  12140. loaderContext.resourcePath,
  12141. hasQuery ? loaderContext.resourceQuery : undefined
  12142. );
  12143. } else {
  12144. filename = name || "[hash].[ext]";
  12145. }
  12146. const context = options.context;
  12147. const content = options.content;
  12148. const regExp = options.regExp;
  12149. let ext = "bin";
  12150. let basename = "file";
  12151. let directory = "";
  12152. let folder = "";
  12153. let query = "";
  12154. if (loaderContext.resourcePath) {
  12155. const parsed = path$2.parse(loaderContext.resourcePath);
  12156. let resourcePath = loaderContext.resourcePath;
  12157. if (parsed.ext) {
  12158. ext = parsed.ext.substr(1);
  12159. }
  12160. if (parsed.dir) {
  12161. basename = parsed.name;
  12162. resourcePath = parsed.dir + path$2.sep;
  12163. }
  12164. if (typeof context !== "undefined") {
  12165. directory = path$2
  12166. .relative(context, resourcePath + "_")
  12167. .replace(/\\/g, "/")
  12168. .replace(/\.\.(\/)?/g, "_$1");
  12169. directory = directory.substr(0, directory.length - 1);
  12170. } else {
  12171. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12172. }
  12173. if (directory.length === 1) {
  12174. directory = "";
  12175. } else if (directory.length > 1) {
  12176. folder = path$2.basename(directory);
  12177. }
  12178. }
  12179. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12180. query = loaderContext.resourceQuery;
  12181. const hashIdx = query.indexOf("#");
  12182. if (hashIdx >= 0) {
  12183. query = query.substr(0, hashIdx);
  12184. }
  12185. }
  12186. let url = filename;
  12187. if (content) {
  12188. // Match hash template
  12189. url = url
  12190. // `hash` and `contenthash` are same in `loader-utils` context
  12191. // let's keep `hash` for backward compatibility
  12192. .replace(
  12193. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi,
  12194. (all, hashType, digestType, maxLength) =>
  12195. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12196. );
  12197. }
  12198. url = url
  12199. .replace(/\[ext\]/gi, () => ext)
  12200. .replace(/\[name\]/gi, () => basename)
  12201. .replace(/\[path\]/gi, () => directory)
  12202. .replace(/\[folder\]/gi, () => folder)
  12203. .replace(/\[query\]/gi, () => query);
  12204. if (regExp && loaderContext.resourcePath) {
  12205. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12206. match &&
  12207. match.forEach((matched, i) => {
  12208. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12209. });
  12210. }
  12211. if (
  12212. typeof loaderContext.options === "object" &&
  12213. typeof loaderContext.options.customInterpolateName === "function"
  12214. ) {
  12215. url = loaderContext.options.customInterpolateName.call(
  12216. loaderContext,
  12217. url,
  12218. name,
  12219. options
  12220. );
  12221. }
  12222. return url;
  12223. }
  12224. var interpolateName_1 = interpolateName$1;
  12225. var interpolateName = interpolateName_1;
  12226. var path$1 = path$3;
  12227. /**
  12228. * @param {string} pattern
  12229. * @param {object} options
  12230. * @param {string} options.context
  12231. * @param {string} options.hashPrefix
  12232. * @return {function}
  12233. */
  12234. var genericNames = function createGenerator(pattern, options) {
  12235. options = options || {};
  12236. var context =
  12237. options && typeof options.context === "string"
  12238. ? options.context
  12239. : process.cwd();
  12240. var hashPrefix =
  12241. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12242. /**
  12243. * @param {string} localName Usually a class name
  12244. * @param {string} filepath Absolute path
  12245. * @return {string}
  12246. */
  12247. return function generate(localName, filepath) {
  12248. var name = pattern.replace(/\[local\]/gi, localName);
  12249. var loaderContext = {
  12250. resourcePath: filepath,
  12251. };
  12252. var loaderOptions = {
  12253. content:
  12254. hashPrefix +
  12255. path$1.relative(context, filepath).replace(/\\/g, "/") +
  12256. "\x00" +
  12257. localName,
  12258. context: context,
  12259. };
  12260. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12261. return genericName
  12262. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12263. .replace(/^((-?[0-9])|--)/, "_$1");
  12264. };
  12265. };
  12266. var src$2 = {exports: {}};
  12267. var openParentheses = "(".charCodeAt(0);
  12268. var closeParentheses = ")".charCodeAt(0);
  12269. var singleQuote = "'".charCodeAt(0);
  12270. var doubleQuote = '"'.charCodeAt(0);
  12271. var backslash = "\\".charCodeAt(0);
  12272. var slash = "/".charCodeAt(0);
  12273. var comma = ",".charCodeAt(0);
  12274. var colon = ":".charCodeAt(0);
  12275. var star$2 = "*".charCodeAt(0);
  12276. var uLower = "u".charCodeAt(0);
  12277. var uUpper = "U".charCodeAt(0);
  12278. var plus = "+".charCodeAt(0);
  12279. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  12280. var parse$1 = function(input) {
  12281. var tokens = [];
  12282. var value = input;
  12283. var next,
  12284. quote,
  12285. prev,
  12286. token,
  12287. escape,
  12288. escapePos,
  12289. whitespacePos,
  12290. parenthesesOpenPos;
  12291. var pos = 0;
  12292. var code = value.charCodeAt(pos);
  12293. var max = value.length;
  12294. var stack = [{ nodes: tokens }];
  12295. var balanced = 0;
  12296. var parent;
  12297. var name = "";
  12298. var before = "";
  12299. var after = "";
  12300. while (pos < max) {
  12301. // Whitespaces
  12302. if (code <= 32) {
  12303. next = pos;
  12304. do {
  12305. next += 1;
  12306. code = value.charCodeAt(next);
  12307. } while (code <= 32);
  12308. token = value.slice(pos, next);
  12309. prev = tokens[tokens.length - 1];
  12310. if (code === closeParentheses && balanced) {
  12311. after = token;
  12312. } else if (prev && prev.type === "div") {
  12313. prev.after = token;
  12314. prev.sourceEndIndex += token.length;
  12315. } else if (
  12316. code === comma ||
  12317. code === colon ||
  12318. (code === slash &&
  12319. value.charCodeAt(next + 1) !== star$2 &&
  12320. (!parent ||
  12321. (parent && parent.type === "function" && parent.value !== "calc")))
  12322. ) {
  12323. before = token;
  12324. } else {
  12325. tokens.push({
  12326. type: "space",
  12327. sourceIndex: pos,
  12328. sourceEndIndex: next,
  12329. value: token
  12330. });
  12331. }
  12332. pos = next;
  12333. // Quotes
  12334. } else if (code === singleQuote || code === doubleQuote) {
  12335. next = pos;
  12336. quote = code === singleQuote ? "'" : '"';
  12337. token = {
  12338. type: "string",
  12339. sourceIndex: pos,
  12340. quote: quote
  12341. };
  12342. do {
  12343. escape = false;
  12344. next = value.indexOf(quote, next + 1);
  12345. if (~next) {
  12346. escapePos = next;
  12347. while (value.charCodeAt(escapePos - 1) === backslash) {
  12348. escapePos -= 1;
  12349. escape = !escape;
  12350. }
  12351. } else {
  12352. value += quote;
  12353. next = value.length - 1;
  12354. token.unclosed = true;
  12355. }
  12356. } while (escape);
  12357. token.value = value.slice(pos + 1, next);
  12358. token.sourceEndIndex = token.unclosed ? next : next + 1;
  12359. tokens.push(token);
  12360. pos = next + 1;
  12361. code = value.charCodeAt(pos);
  12362. // Comments
  12363. } else if (code === slash && value.charCodeAt(pos + 1) === star$2) {
  12364. next = value.indexOf("*/", pos);
  12365. token = {
  12366. type: "comment",
  12367. sourceIndex: pos,
  12368. sourceEndIndex: next + 2
  12369. };
  12370. if (next === -1) {
  12371. token.unclosed = true;
  12372. next = value.length;
  12373. token.sourceEndIndex = next;
  12374. }
  12375. token.value = value.slice(pos + 2, next);
  12376. tokens.push(token);
  12377. pos = next + 2;
  12378. code = value.charCodeAt(pos);
  12379. // Operation within calc
  12380. } else if (
  12381. (code === slash || code === star$2) &&
  12382. parent &&
  12383. parent.type === "function" &&
  12384. parent.value === "calc"
  12385. ) {
  12386. token = value[pos];
  12387. tokens.push({
  12388. type: "word",
  12389. sourceIndex: pos - before.length,
  12390. sourceEndIndex: pos + token.length,
  12391. value: token
  12392. });
  12393. pos += 1;
  12394. code = value.charCodeAt(pos);
  12395. // Dividers
  12396. } else if (code === slash || code === comma || code === colon) {
  12397. token = value[pos];
  12398. tokens.push({
  12399. type: "div",
  12400. sourceIndex: pos - before.length,
  12401. sourceEndIndex: pos + token.length,
  12402. value: token,
  12403. before: before,
  12404. after: ""
  12405. });
  12406. before = "";
  12407. pos += 1;
  12408. code = value.charCodeAt(pos);
  12409. // Open parentheses
  12410. } else if (openParentheses === code) {
  12411. // Whitespaces after open parentheses
  12412. next = pos;
  12413. do {
  12414. next += 1;
  12415. code = value.charCodeAt(next);
  12416. } while (code <= 32);
  12417. parenthesesOpenPos = pos;
  12418. token = {
  12419. type: "function",
  12420. sourceIndex: pos - name.length,
  12421. value: name,
  12422. before: value.slice(parenthesesOpenPos + 1, next)
  12423. };
  12424. pos = next;
  12425. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  12426. next -= 1;
  12427. do {
  12428. escape = false;
  12429. next = value.indexOf(")", next + 1);
  12430. if (~next) {
  12431. escapePos = next;
  12432. while (value.charCodeAt(escapePos - 1) === backslash) {
  12433. escapePos -= 1;
  12434. escape = !escape;
  12435. }
  12436. } else {
  12437. value += ")";
  12438. next = value.length - 1;
  12439. token.unclosed = true;
  12440. }
  12441. } while (escape);
  12442. // Whitespaces before closed
  12443. whitespacePos = next;
  12444. do {
  12445. whitespacePos -= 1;
  12446. code = value.charCodeAt(whitespacePos);
  12447. } while (code <= 32);
  12448. if (parenthesesOpenPos < whitespacePos) {
  12449. if (pos !== whitespacePos + 1) {
  12450. token.nodes = [
  12451. {
  12452. type: "word",
  12453. sourceIndex: pos,
  12454. sourceEndIndex: whitespacePos + 1,
  12455. value: value.slice(pos, whitespacePos + 1)
  12456. }
  12457. ];
  12458. } else {
  12459. token.nodes = [];
  12460. }
  12461. if (token.unclosed && whitespacePos + 1 !== next) {
  12462. token.after = "";
  12463. token.nodes.push({
  12464. type: "space",
  12465. sourceIndex: whitespacePos + 1,
  12466. sourceEndIndex: next,
  12467. value: value.slice(whitespacePos + 1, next)
  12468. });
  12469. } else {
  12470. token.after = value.slice(whitespacePos + 1, next);
  12471. token.sourceEndIndex = next;
  12472. }
  12473. } else {
  12474. token.after = "";
  12475. token.nodes = [];
  12476. }
  12477. pos = next + 1;
  12478. token.sourceEndIndex = token.unclosed ? next : pos;
  12479. code = value.charCodeAt(pos);
  12480. tokens.push(token);
  12481. } else {
  12482. balanced += 1;
  12483. token.after = "";
  12484. token.sourceEndIndex = pos + 1;
  12485. tokens.push(token);
  12486. stack.push(token);
  12487. tokens = token.nodes = [];
  12488. parent = token;
  12489. }
  12490. name = "";
  12491. // Close parentheses
  12492. } else if (closeParentheses === code && balanced) {
  12493. pos += 1;
  12494. code = value.charCodeAt(pos);
  12495. parent.after = after;
  12496. parent.sourceEndIndex += after.length;
  12497. after = "";
  12498. balanced -= 1;
  12499. stack[stack.length - 1].sourceEndIndex = pos;
  12500. stack.pop();
  12501. parent = stack[balanced];
  12502. tokens = parent.nodes;
  12503. // Words
  12504. } else {
  12505. next = pos;
  12506. do {
  12507. if (code === backslash) {
  12508. next += 1;
  12509. }
  12510. next += 1;
  12511. code = value.charCodeAt(next);
  12512. } while (
  12513. next < max &&
  12514. !(
  12515. code <= 32 ||
  12516. code === singleQuote ||
  12517. code === doubleQuote ||
  12518. code === comma ||
  12519. code === colon ||
  12520. code === slash ||
  12521. code === openParentheses ||
  12522. (code === star$2 &&
  12523. parent &&
  12524. parent.type === "function" &&
  12525. parent.value === "calc") ||
  12526. (code === slash &&
  12527. parent.type === "function" &&
  12528. parent.value === "calc") ||
  12529. (code === closeParentheses && balanced)
  12530. )
  12531. );
  12532. token = value.slice(pos, next);
  12533. if (openParentheses === code) {
  12534. name = token;
  12535. } else if (
  12536. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  12537. plus === token.charCodeAt(1) &&
  12538. isUnicodeRange.test(token.slice(2))
  12539. ) {
  12540. tokens.push({
  12541. type: "unicode-range",
  12542. sourceIndex: pos,
  12543. sourceEndIndex: next,
  12544. value: token
  12545. });
  12546. } else {
  12547. tokens.push({
  12548. type: "word",
  12549. sourceIndex: pos,
  12550. sourceEndIndex: next,
  12551. value: token
  12552. });
  12553. }
  12554. pos = next;
  12555. }
  12556. }
  12557. for (pos = stack.length - 1; pos; pos -= 1) {
  12558. stack[pos].unclosed = true;
  12559. stack[pos].sourceEndIndex = value.length;
  12560. }
  12561. return stack[0].nodes;
  12562. };
  12563. var walk$2 = function walk(nodes, cb, bubble) {
  12564. var i, max, node, result;
  12565. for (i = 0, max = nodes.length; i < max; i += 1) {
  12566. node = nodes[i];
  12567. if (!bubble) {
  12568. result = cb(node, i, nodes);
  12569. }
  12570. if (
  12571. result !== false &&
  12572. node.type === "function" &&
  12573. Array.isArray(node.nodes)
  12574. ) {
  12575. walk(node.nodes, cb, bubble);
  12576. }
  12577. if (bubble) {
  12578. cb(node, i, nodes);
  12579. }
  12580. }
  12581. };
  12582. function stringifyNode(node, custom) {
  12583. var type = node.type;
  12584. var value = node.value;
  12585. var buf;
  12586. var customResult;
  12587. if (custom && (customResult = custom(node)) !== undefined) {
  12588. return customResult;
  12589. } else if (type === "word" || type === "space") {
  12590. return value;
  12591. } else if (type === "string") {
  12592. buf = node.quote || "";
  12593. return buf + value + (node.unclosed ? "" : buf);
  12594. } else if (type === "comment") {
  12595. return "/*" + value + (node.unclosed ? "" : "*/");
  12596. } else if (type === "div") {
  12597. return (node.before || "") + value + (node.after || "");
  12598. } else if (Array.isArray(node.nodes)) {
  12599. buf = stringify$1(node.nodes, custom);
  12600. if (type !== "function") {
  12601. return buf;
  12602. }
  12603. return (
  12604. value +
  12605. "(" +
  12606. (node.before || "") +
  12607. buf +
  12608. (node.after || "") +
  12609. (node.unclosed ? "" : ")")
  12610. );
  12611. }
  12612. return value;
  12613. }
  12614. function stringify$1(nodes, custom) {
  12615. var result, i;
  12616. if (Array.isArray(nodes)) {
  12617. result = "";
  12618. for (i = nodes.length - 1; ~i; i -= 1) {
  12619. result = stringifyNode(nodes[i], custom) + result;
  12620. }
  12621. return result;
  12622. }
  12623. return stringifyNode(nodes, custom);
  12624. }
  12625. var stringify_1 = stringify$1;
  12626. var unit;
  12627. var hasRequiredUnit;
  12628. function requireUnit () {
  12629. if (hasRequiredUnit) return unit;
  12630. hasRequiredUnit = 1;
  12631. var minus = "-".charCodeAt(0);
  12632. var plus = "+".charCodeAt(0);
  12633. var dot = ".".charCodeAt(0);
  12634. var exp = "e".charCodeAt(0);
  12635. var EXP = "E".charCodeAt(0);
  12636. // Check if three code points would start a number
  12637. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  12638. function likeNumber(value) {
  12639. var code = value.charCodeAt(0);
  12640. var nextCode;
  12641. if (code === plus || code === minus) {
  12642. nextCode = value.charCodeAt(1);
  12643. if (nextCode >= 48 && nextCode <= 57) {
  12644. return true;
  12645. }
  12646. var nextNextCode = value.charCodeAt(2);
  12647. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  12648. return true;
  12649. }
  12650. return false;
  12651. }
  12652. if (code === dot) {
  12653. nextCode = value.charCodeAt(1);
  12654. if (nextCode >= 48 && nextCode <= 57) {
  12655. return true;
  12656. }
  12657. return false;
  12658. }
  12659. if (code >= 48 && code <= 57) {
  12660. return true;
  12661. }
  12662. return false;
  12663. }
  12664. // Consume a number
  12665. // https://www.w3.org/TR/css-syntax-3/#consume-number
  12666. unit = function(value) {
  12667. var pos = 0;
  12668. var length = value.length;
  12669. var code;
  12670. var nextCode;
  12671. var nextNextCode;
  12672. if (length === 0 || !likeNumber(value)) {
  12673. return false;
  12674. }
  12675. code = value.charCodeAt(pos);
  12676. if (code === plus || code === minus) {
  12677. pos++;
  12678. }
  12679. while (pos < length) {
  12680. code = value.charCodeAt(pos);
  12681. if (code < 48 || code > 57) {
  12682. break;
  12683. }
  12684. pos += 1;
  12685. }
  12686. code = value.charCodeAt(pos);
  12687. nextCode = value.charCodeAt(pos + 1);
  12688. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  12689. pos += 2;
  12690. while (pos < length) {
  12691. code = value.charCodeAt(pos);
  12692. if (code < 48 || code > 57) {
  12693. break;
  12694. }
  12695. pos += 1;
  12696. }
  12697. }
  12698. code = value.charCodeAt(pos);
  12699. nextCode = value.charCodeAt(pos + 1);
  12700. nextNextCode = value.charCodeAt(pos + 2);
  12701. if (
  12702. (code === exp || code === EXP) &&
  12703. ((nextCode >= 48 && nextCode <= 57) ||
  12704. ((nextCode === plus || nextCode === minus) &&
  12705. nextNextCode >= 48 &&
  12706. nextNextCode <= 57))
  12707. ) {
  12708. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  12709. while (pos < length) {
  12710. code = value.charCodeAt(pos);
  12711. if (code < 48 || code > 57) {
  12712. break;
  12713. }
  12714. pos += 1;
  12715. }
  12716. }
  12717. return {
  12718. number: value.slice(0, pos),
  12719. unit: value.slice(pos)
  12720. };
  12721. };
  12722. return unit;
  12723. }
  12724. var parse = parse$1;
  12725. var walk$1 = walk$2;
  12726. var stringify = stringify_1;
  12727. function ValueParser(value) {
  12728. if (this instanceof ValueParser) {
  12729. this.nodes = parse(value);
  12730. return this;
  12731. }
  12732. return new ValueParser(value);
  12733. }
  12734. ValueParser.prototype.toString = function() {
  12735. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  12736. };
  12737. ValueParser.prototype.walk = function(cb, bubble) {
  12738. walk$1(this.nodes, cb, bubble);
  12739. return this;
  12740. };
  12741. ValueParser.unit = requireUnit();
  12742. ValueParser.walk = walk$1;
  12743. ValueParser.stringify = stringify;
  12744. var lib = ValueParser;
  12745. const selectorParser$1 = distExports;
  12746. const valueParser = lib;
  12747. const { extractICSS } = src$4;
  12748. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  12749. function normalizeNodeArray(nodes) {
  12750. const array = [];
  12751. nodes.forEach((x) => {
  12752. if (Array.isArray(x)) {
  12753. normalizeNodeArray(x).forEach((item) => {
  12754. array.push(item);
  12755. });
  12756. } else if (x) {
  12757. array.push(x);
  12758. }
  12759. });
  12760. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  12761. array.pop();
  12762. }
  12763. return array;
  12764. }
  12765. function localizeNode(rule, mode, localAliasMap) {
  12766. const transform = (node, context) => {
  12767. if (context.ignoreNextSpacing && !isSpacing(node)) {
  12768. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  12769. }
  12770. if (context.enforceNoSpacing && isSpacing(node)) {
  12771. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  12772. }
  12773. let newNodes;
  12774. switch (node.type) {
  12775. case "root": {
  12776. let resultingGlobal;
  12777. context.hasPureGlobals = false;
  12778. newNodes = node.nodes.map((n) => {
  12779. const nContext = {
  12780. global: context.global,
  12781. lastWasSpacing: true,
  12782. hasLocals: false,
  12783. explicit: false,
  12784. };
  12785. n = transform(n, nContext);
  12786. if (typeof resultingGlobal === "undefined") {
  12787. resultingGlobal = nContext.global;
  12788. } else if (resultingGlobal !== nContext.global) {
  12789. throw new Error(
  12790. 'Inconsistent rule global/local result in rule "' +
  12791. node +
  12792. '" (multiple selectors must result in the same mode for the rule)'
  12793. );
  12794. }
  12795. if (!nContext.hasLocals) {
  12796. context.hasPureGlobals = true;
  12797. }
  12798. return n;
  12799. });
  12800. context.global = resultingGlobal;
  12801. node.nodes = normalizeNodeArray(newNodes);
  12802. break;
  12803. }
  12804. case "selector": {
  12805. newNodes = node.map((childNode) => transform(childNode, context));
  12806. node = node.clone();
  12807. node.nodes = normalizeNodeArray(newNodes);
  12808. break;
  12809. }
  12810. case "combinator": {
  12811. if (isSpacing(node)) {
  12812. if (context.ignoreNextSpacing) {
  12813. context.ignoreNextSpacing = false;
  12814. context.lastWasSpacing = false;
  12815. context.enforceNoSpacing = false;
  12816. return null;
  12817. }
  12818. context.lastWasSpacing = true;
  12819. return node;
  12820. }
  12821. break;
  12822. }
  12823. case "pseudo": {
  12824. let childContext;
  12825. const isNested = !!node.length;
  12826. const isScoped = node.value === ":local" || node.value === ":global";
  12827. const isImportExport =
  12828. node.value === ":import" || node.value === ":export";
  12829. if (isImportExport) {
  12830. context.hasLocals = true;
  12831. // :local(.foo)
  12832. } else if (isNested) {
  12833. if (isScoped) {
  12834. if (node.nodes.length === 0) {
  12835. throw new Error(`${node.value}() can't be empty`);
  12836. }
  12837. if (context.inside) {
  12838. throw new Error(
  12839. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  12840. );
  12841. }
  12842. childContext = {
  12843. global: node.value === ":global",
  12844. inside: node.value,
  12845. hasLocals: false,
  12846. explicit: true,
  12847. };
  12848. newNodes = node
  12849. .map((childNode) => transform(childNode, childContext))
  12850. .reduce((acc, next) => acc.concat(next.nodes), []);
  12851. if (newNodes.length) {
  12852. const { before, after } = node.spaces;
  12853. const first = newNodes[0];
  12854. const last = newNodes[newNodes.length - 1];
  12855. first.spaces = { before, after: first.spaces.after };
  12856. last.spaces = { before: last.spaces.before, after };
  12857. }
  12858. node = newNodes;
  12859. break;
  12860. } else {
  12861. childContext = {
  12862. global: context.global,
  12863. inside: context.inside,
  12864. lastWasSpacing: true,
  12865. hasLocals: false,
  12866. explicit: context.explicit,
  12867. };
  12868. newNodes = node.map((childNode) => {
  12869. const newContext = {
  12870. ...childContext,
  12871. enforceNoSpacing: false,
  12872. };
  12873. const result = transform(childNode, newContext);
  12874. childContext.global = newContext.global;
  12875. childContext.hasLocals = newContext.hasLocals;
  12876. return result;
  12877. });
  12878. node = node.clone();
  12879. node.nodes = normalizeNodeArray(newNodes);
  12880. if (childContext.hasLocals) {
  12881. context.hasLocals = true;
  12882. }
  12883. }
  12884. break;
  12885. //:local .foo .bar
  12886. } else if (isScoped) {
  12887. if (context.inside) {
  12888. throw new Error(
  12889. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  12890. );
  12891. }
  12892. const addBackSpacing = !!node.spaces.before;
  12893. context.ignoreNextSpacing = context.lastWasSpacing
  12894. ? node.value
  12895. : false;
  12896. context.enforceNoSpacing = context.lastWasSpacing
  12897. ? false
  12898. : node.value;
  12899. context.global = node.value === ":global";
  12900. context.explicit = true;
  12901. // because this node has spacing that is lost when we remove it
  12902. // we make up for it by adding an extra combinator in since adding
  12903. // spacing on the parent selector doesn't work
  12904. return addBackSpacing
  12905. ? selectorParser$1.combinator({ value: " " })
  12906. : null;
  12907. }
  12908. break;
  12909. }
  12910. case "id":
  12911. case "class": {
  12912. if (!node.value) {
  12913. throw new Error("Invalid class or id selector syntax");
  12914. }
  12915. if (context.global) {
  12916. break;
  12917. }
  12918. const isImportedValue = localAliasMap.has(node.value);
  12919. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  12920. if (!isImportedValue || isImportedWithExplicitScope) {
  12921. const innerNode = node.clone();
  12922. innerNode.spaces = { before: "", after: "" };
  12923. node = selectorParser$1.pseudo({
  12924. value: ":local",
  12925. nodes: [innerNode],
  12926. spaces: node.spaces,
  12927. });
  12928. context.hasLocals = true;
  12929. }
  12930. break;
  12931. }
  12932. }
  12933. context.lastWasSpacing = false;
  12934. context.ignoreNextSpacing = false;
  12935. context.enforceNoSpacing = false;
  12936. return node;
  12937. };
  12938. const rootContext = {
  12939. global: mode === "global",
  12940. hasPureGlobals: false,
  12941. };
  12942. rootContext.selector = selectorParser$1((root) => {
  12943. transform(root, rootContext);
  12944. }).processSync(rule, { updateSelector: false, lossless: true });
  12945. return rootContext;
  12946. }
  12947. function localizeDeclNode(node, context) {
  12948. switch (node.type) {
  12949. case "word":
  12950. if (context.localizeNextItem) {
  12951. if (!context.localAliasMap.has(node.value)) {
  12952. node.value = ":local(" + node.value + ")";
  12953. context.localizeNextItem = false;
  12954. }
  12955. }
  12956. break;
  12957. case "function":
  12958. if (
  12959. context.options &&
  12960. context.options.rewriteUrl &&
  12961. node.value.toLowerCase() === "url"
  12962. ) {
  12963. node.nodes.map((nestedNode) => {
  12964. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  12965. return;
  12966. }
  12967. let newUrl = context.options.rewriteUrl(
  12968. context.global,
  12969. nestedNode.value
  12970. );
  12971. switch (nestedNode.type) {
  12972. case "string":
  12973. if (nestedNode.quote === "'") {
  12974. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  12975. }
  12976. if (nestedNode.quote === '"') {
  12977. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  12978. }
  12979. break;
  12980. case "word":
  12981. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  12982. break;
  12983. }
  12984. nestedNode.value = newUrl;
  12985. });
  12986. }
  12987. break;
  12988. }
  12989. return node;
  12990. }
  12991. // `none` is special value, other is global values
  12992. const specialKeywords = [
  12993. "none",
  12994. "inherit",
  12995. "initial",
  12996. "revert",
  12997. "revert-layer",
  12998. "unset",
  12999. ];
  13000. function localizeDeclarationValues(localize, declaration, context) {
  13001. const valueNodes = valueParser(declaration.value);
  13002. valueNodes.walk((node, index, nodes) => {
  13003. if (
  13004. node.type === "function" &&
  13005. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  13006. ) {
  13007. return false;
  13008. }
  13009. if (
  13010. node.type === "word" &&
  13011. specialKeywords.includes(node.value.toLowerCase())
  13012. ) {
  13013. return;
  13014. }
  13015. const subContext = {
  13016. options: context.options,
  13017. global: context.global,
  13018. localizeNextItem: localize && !context.global,
  13019. localAliasMap: context.localAliasMap,
  13020. };
  13021. nodes[index] = localizeDeclNode(node, subContext);
  13022. });
  13023. declaration.value = valueNodes.toString();
  13024. }
  13025. function localizeDeclaration(declaration, context) {
  13026. const isAnimation = /animation$/i.test(declaration.prop);
  13027. if (isAnimation) {
  13028. // letter
  13029. // An uppercase letter or a lowercase letter.
  13030. //
  13031. // ident-start code point
  13032. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  13033. //
  13034. // ident code point
  13035. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  13036. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  13037. const validIdent =
  13038. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-)((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  13039. /*
  13040. The spec defines some keywords that you can use to describe properties such as the timing
  13041. function. These are still valid animation names, so as long as there is a property that accepts
  13042. a keyword, it is given priority. Only when all the properties that can take a keyword are
  13043. exhausted can the animation name be set to the keyword. I.e.
  13044. animation: infinite infinite;
  13045. The animation will repeat an infinite number of times from the first argument, and will have an
  13046. animation name of infinite from the second.
  13047. */
  13048. const animationKeywords = {
  13049. // animation-direction
  13050. $normal: 1,
  13051. $reverse: 1,
  13052. $alternate: 1,
  13053. "$alternate-reverse": 1,
  13054. // animation-fill-mode
  13055. $forwards: 1,
  13056. $backwards: 1,
  13057. $both: 1,
  13058. // animation-iteration-count
  13059. $infinite: 1,
  13060. // animation-play-state
  13061. $paused: 1,
  13062. $running: 1,
  13063. // animation-timing-function
  13064. $ease: 1,
  13065. "$ease-in": 1,
  13066. "$ease-out": 1,
  13067. "$ease-in-out": 1,
  13068. $linear: 1,
  13069. "$step-end": 1,
  13070. "$step-start": 1,
  13071. // Special
  13072. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  13073. // Global values
  13074. $initial: Infinity,
  13075. $inherit: Infinity,
  13076. $unset: Infinity,
  13077. $revert: Infinity,
  13078. "$revert-layer": Infinity,
  13079. };
  13080. let parsedAnimationKeywords = {};
  13081. const valueNodes = valueParser(declaration.value).walk((node) => {
  13082. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  13083. if (node.type === "div") {
  13084. parsedAnimationKeywords = {};
  13085. return;
  13086. }
  13087. // Do not handle nested functions
  13088. else if (node.type === "function") {
  13089. return false;
  13090. }
  13091. // Ignore all except word
  13092. else if (node.type !== "word") {
  13093. return;
  13094. }
  13095. const value = node.type === "word" ? node.value.toLowerCase() : null;
  13096. let shouldParseAnimationName = false;
  13097. if (value && validIdent.test(value)) {
  13098. if ("$" + value in animationKeywords) {
  13099. parsedAnimationKeywords["$" + value] =
  13100. "$" + value in parsedAnimationKeywords
  13101. ? parsedAnimationKeywords["$" + value] + 1
  13102. : 0;
  13103. shouldParseAnimationName =
  13104. parsedAnimationKeywords["$" + value] >=
  13105. animationKeywords["$" + value];
  13106. } else {
  13107. shouldParseAnimationName = true;
  13108. }
  13109. }
  13110. const subContext = {
  13111. options: context.options,
  13112. global: context.global,
  13113. localizeNextItem: shouldParseAnimationName && !context.global,
  13114. localAliasMap: context.localAliasMap,
  13115. };
  13116. return localizeDeclNode(node, subContext);
  13117. });
  13118. declaration.value = valueNodes.toString();
  13119. return;
  13120. }
  13121. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  13122. if (isAnimationName) {
  13123. return localizeDeclarationValues(true, declaration, context);
  13124. }
  13125. const hasUrl = /url\(/i.test(declaration.value);
  13126. if (hasUrl) {
  13127. return localizeDeclarationValues(false, declaration, context);
  13128. }
  13129. }
  13130. src$2.exports = (options = {}) => {
  13131. if (
  13132. options &&
  13133. options.mode &&
  13134. options.mode !== "global" &&
  13135. options.mode !== "local" &&
  13136. options.mode !== "pure"
  13137. ) {
  13138. throw new Error(
  13139. 'options.mode must be either "global", "local" or "pure" (default "local")'
  13140. );
  13141. }
  13142. const pureMode = options && options.mode === "pure";
  13143. const globalMode = options && options.mode === "global";
  13144. return {
  13145. postcssPlugin: "postcss-modules-local-by-default",
  13146. prepare() {
  13147. const localAliasMap = new Map();
  13148. return {
  13149. Once(root) {
  13150. const { icssImports } = extractICSS(root, false);
  13151. Object.keys(icssImports).forEach((key) => {
  13152. Object.keys(icssImports[key]).forEach((prop) => {
  13153. localAliasMap.set(prop, icssImports[key][prop]);
  13154. });
  13155. });
  13156. root.walkAtRules((atRule) => {
  13157. if (/keyframes$/i.test(atRule.name)) {
  13158. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  13159. atRule.params
  13160. );
  13161. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  13162. atRule.params
  13163. );
  13164. let globalKeyframes = globalMode;
  13165. if (globalMatch) {
  13166. if (pureMode) {
  13167. throw atRule.error(
  13168. "@keyframes :global(...) is not allowed in pure mode"
  13169. );
  13170. }
  13171. atRule.params = globalMatch[1];
  13172. globalKeyframes = true;
  13173. } else if (localMatch) {
  13174. atRule.params = localMatch[0];
  13175. globalKeyframes = false;
  13176. } else if (!globalMode) {
  13177. if (atRule.params && !localAliasMap.has(atRule.params)) {
  13178. atRule.params = ":local(" + atRule.params + ")";
  13179. }
  13180. }
  13181. atRule.walkDecls((declaration) => {
  13182. localizeDeclaration(declaration, {
  13183. localAliasMap,
  13184. options: options,
  13185. global: globalKeyframes,
  13186. });
  13187. });
  13188. } else if (atRule.nodes) {
  13189. atRule.nodes.forEach((declaration) => {
  13190. if (declaration.type === "decl") {
  13191. localizeDeclaration(declaration, {
  13192. localAliasMap,
  13193. options: options,
  13194. global: globalMode,
  13195. });
  13196. }
  13197. });
  13198. }
  13199. });
  13200. root.walkRules((rule) => {
  13201. if (
  13202. rule.parent &&
  13203. rule.parent.type === "atrule" &&
  13204. /keyframes$/i.test(rule.parent.name)
  13205. ) {
  13206. // ignore keyframe rules
  13207. return;
  13208. }
  13209. const context = localizeNode(rule, options.mode, localAliasMap);
  13210. context.options = options;
  13211. context.localAliasMap = localAliasMap;
  13212. if (pureMode && context.hasPureGlobals) {
  13213. throw rule.error(
  13214. 'Selector "' +
  13215. rule.selector +
  13216. '" is not pure ' +
  13217. "(pure selectors must contain at least one local class or id)"
  13218. );
  13219. }
  13220. rule.selector = context.selector;
  13221. // Less-syntax mixins parse as rules with no nodes
  13222. if (rule.nodes) {
  13223. rule.nodes.forEach((declaration) =>
  13224. localizeDeclaration(declaration, context)
  13225. );
  13226. }
  13227. });
  13228. },
  13229. };
  13230. },
  13231. };
  13232. };
  13233. src$2.exports.postcss = true;
  13234. var srcExports$1 = src$2.exports;
  13235. const selectorParser = distExports;
  13236. const hasOwnProperty = Object.prototype.hasOwnProperty;
  13237. function getSingleLocalNamesForComposes(root) {
  13238. return root.nodes.map((node) => {
  13239. if (node.type !== "selector" || node.nodes.length !== 1) {
  13240. throw new Error(
  13241. `composition is only allowed when selector is single :local class name not in "${root}"`
  13242. );
  13243. }
  13244. node = node.nodes[0];
  13245. if (
  13246. node.type !== "pseudo" ||
  13247. node.value !== ":local" ||
  13248. node.nodes.length !== 1
  13249. ) {
  13250. throw new Error(
  13251. 'composition is only allowed when selector is single :local class name not in "' +
  13252. root +
  13253. '", "' +
  13254. node +
  13255. '" is weird'
  13256. );
  13257. }
  13258. node = node.first;
  13259. if (node.type !== "selector" || node.length !== 1) {
  13260. throw new Error(
  13261. 'composition is only allowed when selector is single :local class name not in "' +
  13262. root +
  13263. '", "' +
  13264. node +
  13265. '" is weird'
  13266. );
  13267. }
  13268. node = node.first;
  13269. if (node.type !== "class") {
  13270. // 'id' is not possible, because you can't compose ids
  13271. throw new Error(
  13272. 'composition is only allowed when selector is single :local class name not in "' +
  13273. root +
  13274. '", "' +
  13275. node +
  13276. '" is weird'
  13277. );
  13278. }
  13279. return node.value;
  13280. });
  13281. }
  13282. const whitespace = "[\\x20\\t\\r\\n\\f]";
  13283. const unescapeRegExp = new RegExp(
  13284. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  13285. "ig"
  13286. );
  13287. function unescape$1(str) {
  13288. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  13289. const high = "0x" + escaped - 0x10000;
  13290. // NaN means non-codepoint
  13291. // Workaround erroneous numeric interpretation of +"0x"
  13292. return high !== high || escapedWhitespace
  13293. ? escaped
  13294. : high < 0
  13295. ? // BMP codepoint
  13296. String.fromCharCode(high + 0x10000)
  13297. : // Supplemental Plane codepoint (surrogate pair)
  13298. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  13299. });
  13300. }
  13301. const plugin = (options = {}) => {
  13302. const generateScopedName =
  13303. (options && options.generateScopedName) || plugin.generateScopedName;
  13304. const generateExportEntry =
  13305. (options && options.generateExportEntry) || plugin.generateExportEntry;
  13306. const exportGlobals = options && options.exportGlobals;
  13307. return {
  13308. postcssPlugin: "postcss-modules-scope",
  13309. Once(root, { rule }) {
  13310. const exports = Object.create(null);
  13311. function exportScopedName(name, rawName) {
  13312. const scopedName = generateScopedName(
  13313. rawName ? rawName : name,
  13314. root.source.input.from,
  13315. root.source.input.css
  13316. );
  13317. const exportEntry = generateExportEntry(
  13318. rawName ? rawName : name,
  13319. scopedName,
  13320. root.source.input.from,
  13321. root.source.input.css
  13322. );
  13323. const { key, value } = exportEntry;
  13324. exports[key] = exports[key] || [];
  13325. if (exports[key].indexOf(value) < 0) {
  13326. exports[key].push(value);
  13327. }
  13328. return scopedName;
  13329. }
  13330. function localizeNode(node) {
  13331. switch (node.type) {
  13332. case "selector":
  13333. node.nodes = node.map(localizeNode);
  13334. return node;
  13335. case "class":
  13336. return selectorParser.className({
  13337. value: exportScopedName(
  13338. node.value,
  13339. node.raws && node.raws.value ? node.raws.value : null
  13340. ),
  13341. });
  13342. case "id": {
  13343. return selectorParser.id({
  13344. value: exportScopedName(
  13345. node.value,
  13346. node.raws && node.raws.value ? node.raws.value : null
  13347. ),
  13348. });
  13349. }
  13350. }
  13351. throw new Error(
  13352. `${node.type} ("${node}") is not allowed in a :local block`
  13353. );
  13354. }
  13355. function traverseNode(node) {
  13356. switch (node.type) {
  13357. case "pseudo":
  13358. if (node.value === ":local") {
  13359. if (node.nodes.length !== 1) {
  13360. throw new Error('Unexpected comma (",") in :local block');
  13361. }
  13362. const selector = localizeNode(node.first, node.spaces);
  13363. // move the spaces that were around the psuedo selector to the first
  13364. // non-container node
  13365. selector.first.spaces = node.spaces;
  13366. const nextNode = node.next();
  13367. if (
  13368. nextNode &&
  13369. nextNode.type === "combinator" &&
  13370. nextNode.value === " " &&
  13371. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  13372. ) {
  13373. selector.last.spaces.after = " ";
  13374. }
  13375. node.replaceWith(selector);
  13376. return;
  13377. }
  13378. /* falls through */
  13379. case "root":
  13380. case "selector": {
  13381. node.each(traverseNode);
  13382. break;
  13383. }
  13384. case "id":
  13385. case "class":
  13386. if (exportGlobals) {
  13387. exports[node.value] = [node.value];
  13388. }
  13389. break;
  13390. }
  13391. return node;
  13392. }
  13393. // Find any :import and remember imported names
  13394. const importedNames = {};
  13395. root.walkRules(/^:import\(.+\)$/, (rule) => {
  13396. rule.walkDecls((decl) => {
  13397. importedNames[decl.prop] = true;
  13398. });
  13399. });
  13400. // Find any :local selectors
  13401. root.walkRules((rule) => {
  13402. let parsedSelector = selectorParser().astSync(rule);
  13403. rule.selector = traverseNode(parsedSelector.clone()).toString();
  13404. rule.walkDecls(/composes|compose-with/i, (decl) => {
  13405. const localNames = getSingleLocalNamesForComposes(parsedSelector);
  13406. const classes = decl.value.split(/\s+/);
  13407. classes.forEach((className) => {
  13408. const global = /^global\(([^)]+)\)$/.exec(className);
  13409. if (global) {
  13410. localNames.forEach((exportedName) => {
  13411. exports[exportedName].push(global[1]);
  13412. });
  13413. } else if (hasOwnProperty.call(importedNames, className)) {
  13414. localNames.forEach((exportedName) => {
  13415. exports[exportedName].push(className);
  13416. });
  13417. } else if (hasOwnProperty.call(exports, className)) {
  13418. localNames.forEach((exportedName) => {
  13419. exports[className].forEach((item) => {
  13420. exports[exportedName].push(item);
  13421. });
  13422. });
  13423. } else {
  13424. throw decl.error(
  13425. `referenced class name "${className}" in ${decl.prop} not found`
  13426. );
  13427. }
  13428. });
  13429. decl.remove();
  13430. });
  13431. // Find any :local values
  13432. rule.walkDecls((decl) => {
  13433. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  13434. return;
  13435. }
  13436. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  13437. tokens = tokens.map((token, idx) => {
  13438. if (idx === 0 || tokens[idx - 1] === ",") {
  13439. let result = token;
  13440. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  13441. if (localMatch) {
  13442. const input = localMatch.input;
  13443. const matchPattern = localMatch[0];
  13444. const matchVal = localMatch[1];
  13445. const newVal = exportScopedName(matchVal);
  13446. result = input.replace(matchPattern, newVal);
  13447. } else {
  13448. return token;
  13449. }
  13450. return result;
  13451. } else {
  13452. return token;
  13453. }
  13454. });
  13455. decl.value = tokens.join("");
  13456. });
  13457. });
  13458. // Find any :local keyframes
  13459. root.walkAtRules(/keyframes$/i, (atRule) => {
  13460. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  13461. if (!localMatch) {
  13462. return;
  13463. }
  13464. atRule.params = exportScopedName(localMatch[1]);
  13465. });
  13466. // If we found any :locals, insert an :export rule
  13467. const exportedNames = Object.keys(exports);
  13468. if (exportedNames.length > 0) {
  13469. const exportRule = rule({ selector: ":export" });
  13470. exportedNames.forEach((exportedName) =>
  13471. exportRule.append({
  13472. prop: exportedName,
  13473. value: exports[exportedName].join(" "),
  13474. raws: { before: "\n " },
  13475. })
  13476. );
  13477. root.append(exportRule);
  13478. }
  13479. },
  13480. };
  13481. };
  13482. plugin.postcss = true;
  13483. plugin.generateScopedName = function (name, path) {
  13484. const sanitisedPath = path
  13485. .replace(/\.[^./\\]+$/, "")
  13486. .replace(/[\W_]+/g, "_")
  13487. .replace(/^_|_$/g, "");
  13488. return `_${sanitisedPath}__${name}`.trim();
  13489. };
  13490. plugin.generateExportEntry = function (name, scopedName) {
  13491. return {
  13492. key: unescape$1(name),
  13493. value: unescape$1(scopedName),
  13494. };
  13495. };
  13496. var src$1 = plugin;
  13497. function hash(str) {
  13498. var hash = 5381,
  13499. i = str.length;
  13500. while(i) {
  13501. hash = (hash * 33) ^ str.charCodeAt(--i);
  13502. }
  13503. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  13504. * integers. Since we want the results to be always positive, convert the
  13505. * signed int to an unsigned by doing an unsigned bitshift. */
  13506. return hash >>> 0;
  13507. }
  13508. var stringHash = hash;
  13509. var src = {exports: {}};
  13510. const ICSSUtils = src$4;
  13511. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  13512. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  13513. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  13514. src.exports = (options) => {
  13515. let importIndex = 0;
  13516. const createImportedName =
  13517. (options && options.createImportedName) ||
  13518. ((importName /*, path*/) =>
  13519. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  13520. return {
  13521. postcssPlugin: "postcss-modules-values",
  13522. prepare(result) {
  13523. const importAliases = [];
  13524. const definitions = {};
  13525. return {
  13526. Once(root, postcss) {
  13527. root.walkAtRules(/value/i, (atRule) => {
  13528. const matches = atRule.params.match(matchImports);
  13529. if (matches) {
  13530. let [, /*match*/ aliases, path] = matches;
  13531. // We can use constants for path names
  13532. if (definitions[path]) {
  13533. path = definitions[path];
  13534. }
  13535. const imports = aliases
  13536. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  13537. .split(/\s*,\s*/)
  13538. .map((alias) => {
  13539. const tokens = matchImport.exec(alias);
  13540. if (tokens) {
  13541. const [, /*match*/ theirName, myName = theirName] = tokens;
  13542. const importedName = createImportedName(myName);
  13543. definitions[myName] = importedName;
  13544. return { theirName, importedName };
  13545. } else {
  13546. throw new Error(`@import statement "${alias}" is invalid!`);
  13547. }
  13548. });
  13549. importAliases.push({ path, imports });
  13550. atRule.remove();
  13551. return;
  13552. }
  13553. if (atRule.params.indexOf("@value") !== -1) {
  13554. result.warn("Invalid value definition: " + atRule.params);
  13555. }
  13556. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  13557. matchValueDefinition
  13558. );
  13559. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  13560. if (normalizedValue.length === 0) {
  13561. result.warn("Invalid value definition: " + atRule.params);
  13562. atRule.remove();
  13563. return;
  13564. }
  13565. let isOnlySpace = /^\s+$/.test(normalizedValue);
  13566. if (!isOnlySpace) {
  13567. value = value.trim();
  13568. }
  13569. // Add to the definitions, knowing that values can refer to each other
  13570. definitions[key] = ICSSUtils.replaceValueSymbols(
  13571. value,
  13572. definitions
  13573. );
  13574. atRule.remove();
  13575. });
  13576. /* If we have no definitions, don't continue */
  13577. if (!Object.keys(definitions).length) {
  13578. return;
  13579. }
  13580. /* Perform replacements */
  13581. ICSSUtils.replaceSymbols(root, definitions);
  13582. /* We want to export anything defined by now, but don't add it to the CSS yet or it well get picked up by the replacement stuff */
  13583. const exportDeclarations = Object.keys(definitions).map((key) =>
  13584. postcss.decl({
  13585. value: definitions[key],
  13586. prop: key,
  13587. raws: { before: "\n " },
  13588. })
  13589. );
  13590. /* Add export rules if any */
  13591. if (exportDeclarations.length > 0) {
  13592. const exportRule = postcss.rule({
  13593. selector: ":export",
  13594. raws: { after: "\n" },
  13595. });
  13596. exportRule.append(exportDeclarations);
  13597. root.prepend(exportRule);
  13598. }
  13599. /* Add import rules */
  13600. importAliases.reverse().forEach(({ path, imports }) => {
  13601. const importRule = postcss.rule({
  13602. selector: `:import(${path})`,
  13603. raws: { after: "\n" },
  13604. });
  13605. imports.forEach(({ theirName, importedName }) => {
  13606. importRule.append({
  13607. value: theirName,
  13608. prop: importedName,
  13609. raws: { before: "\n " },
  13610. });
  13611. });
  13612. root.prepend(importRule);
  13613. });
  13614. },
  13615. };
  13616. },
  13617. };
  13618. };
  13619. src.exports.postcss = true;
  13620. var srcExports = src.exports;
  13621. Object.defineProperty(scoping, "__esModule", {
  13622. value: true
  13623. });
  13624. scoping.behaviours = void 0;
  13625. scoping.getDefaultPlugins = getDefaultPlugins;
  13626. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  13627. scoping.getScopedNameGenerator = getScopedNameGenerator;
  13628. var _postcssModulesExtractImports = _interopRequireDefault$1(srcExports$2);
  13629. var _genericNames = _interopRequireDefault$1(genericNames);
  13630. var _postcssModulesLocalByDefault = _interopRequireDefault$1(srcExports$1);
  13631. var _postcssModulesScope = _interopRequireDefault$1(src$1);
  13632. var _stringHash = _interopRequireDefault$1(stringHash);
  13633. var _postcssModulesValues = _interopRequireDefault$1(srcExports);
  13634. function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13635. const behaviours = {
  13636. LOCAL: "local",
  13637. GLOBAL: "global"
  13638. };
  13639. scoping.behaviours = behaviours;
  13640. function getDefaultPlugins({
  13641. behaviour,
  13642. generateScopedName,
  13643. exportGlobals
  13644. }) {
  13645. const scope = (0, _postcssModulesScope.default)({
  13646. generateScopedName,
  13647. exportGlobals
  13648. });
  13649. const plugins = {
  13650. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  13651. mode: "local"
  13652. }), _postcssModulesExtractImports.default, scope],
  13653. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  13654. mode: "global"
  13655. }), _postcssModulesExtractImports.default, scope]
  13656. };
  13657. return plugins[behaviour];
  13658. }
  13659. function isValidBehaviour(behaviour) {
  13660. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  13661. }
  13662. function getDefaultScopeBehaviour(scopeBehaviour) {
  13663. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  13664. }
  13665. function generateScopedNameDefault(name, filename, css) {
  13666. const i = css.indexOf(`.${name}`);
  13667. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  13668. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  13669. return `_${name}_${hash}_${lineNumber}`;
  13670. }
  13671. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  13672. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  13673. if (typeof scopedNameGenerator === "function") {
  13674. return scopedNameGenerator;
  13675. }
  13676. return (0, _genericNames.default)(scopedNameGenerator, {
  13677. context: process.cwd(),
  13678. hashPrefix: hashPrefix
  13679. });
  13680. }
  13681. Object.defineProperty(pluginFactory, "__esModule", {
  13682. value: true
  13683. });
  13684. pluginFactory.makePlugin = makePlugin;
  13685. var _postcss = _interopRequireDefault(require$$0$1);
  13686. var _unquote = _interopRequireDefault(unquote$1);
  13687. var _Parser = _interopRequireDefault(Parser$1);
  13688. var _saveJSON = _interopRequireDefault(saveJSON$1);
  13689. var _localsConvention = localsConvention;
  13690. var _FileSystemLoader = _interopRequireDefault(FileSystemLoader$1);
  13691. var _scoping = scoping;
  13692. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13693. const PLUGIN_NAME = "postcss-modules";
  13694. function isGlobalModule(globalModules, inputFile) {
  13695. return globalModules.some(regex => inputFile.match(regex));
  13696. }
  13697. function getDefaultPluginsList(opts, inputFile) {
  13698. const globalModulesList = opts.globalModulePaths || null;
  13699. const exportGlobals = opts.exportGlobals || false;
  13700. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  13701. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  13702. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  13703. return (0, _scoping.getDefaultPlugins)({
  13704. behaviour: _scoping.behaviours.GLOBAL,
  13705. generateScopedName,
  13706. exportGlobals
  13707. });
  13708. }
  13709. return (0, _scoping.getDefaultPlugins)({
  13710. behaviour: defaultBehaviour,
  13711. generateScopedName,
  13712. exportGlobals
  13713. });
  13714. }
  13715. function getLoader(opts, plugins) {
  13716. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  13717. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  13718. }
  13719. function isOurPlugin(plugin) {
  13720. return plugin.postcssPlugin === PLUGIN_NAME;
  13721. }
  13722. function makePlugin(opts) {
  13723. return {
  13724. postcssPlugin: PLUGIN_NAME,
  13725. async OnceExit(css, {
  13726. result
  13727. }) {
  13728. const getJSON = opts.getJSON || _saveJSON.default;
  13729. const inputFile = css.source.input.file;
  13730. const pluginList = getDefaultPluginsList(opts, inputFile);
  13731. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  13732. if (resultPluginIndex === -1) {
  13733. throw new Error("Plugin missing from options.");
  13734. }
  13735. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  13736. const loaderPlugins = [...earlierPlugins, ...pluginList];
  13737. const loader = getLoader(opts, loaderPlugins);
  13738. const fetcher = async (file, relativeTo, depTrace) => {
  13739. const unquoteFile = (0, _unquote.default)(file);
  13740. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  13741. };
  13742. const parser = new _Parser.default(fetcher);
  13743. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  13744. from: inputFile
  13745. });
  13746. const out = loader.finalSource;
  13747. if (out) css.prepend(out);
  13748. if (opts.localsConvention) {
  13749. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  13750. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  13751. }
  13752. result.messages.push({
  13753. type: "export",
  13754. plugin: "postcss-modules",
  13755. exportTokens: parser.exportTokens
  13756. }); // getJSON may return a promise
  13757. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  13758. }
  13759. };
  13760. }
  13761. var _fs = require$$0;
  13762. var _fs2 = fs;
  13763. var _pluginFactory = pluginFactory;
  13764. (0, _fs2.setFileSystem)({
  13765. readFile: _fs.readFile,
  13766. writeFile: _fs.writeFile
  13767. });
  13768. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  13769. build.exports.postcss = true;
  13770. var buildExports = build.exports;
  13771. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  13772. function compileStyle(options) {
  13773. return doCompileStyle({
  13774. ...options,
  13775. isAsync: false
  13776. });
  13777. }
  13778. function compileStyleAsync(options) {
  13779. return doCompileStyle({
  13780. ...options,
  13781. isAsync: true
  13782. });
  13783. }
  13784. function doCompileStyle(options) {
  13785. const {
  13786. filename,
  13787. id,
  13788. scoped = false,
  13789. trim = true,
  13790. isProd = false,
  13791. modules = false,
  13792. modulesOptions = {},
  13793. preprocessLang,
  13794. postcssOptions,
  13795. postcssPlugins
  13796. } = options;
  13797. const preprocessor = preprocessLang && processors[preprocessLang];
  13798. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  13799. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  13800. const source = preProcessedSource ? preProcessedSource.code : options.source;
  13801. const shortId = id.replace(/^data-v-/, "");
  13802. const longId = `data-v-${shortId}`;
  13803. const plugins = (postcssPlugins || []).slice();
  13804. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  13805. if (trim) {
  13806. plugins.push(trimPlugin());
  13807. }
  13808. if (scoped) {
  13809. plugins.push(scopedPlugin(longId));
  13810. }
  13811. let cssModules;
  13812. if (modules) {
  13813. if (!options.isAsync) {
  13814. throw new Error(
  13815. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  13816. );
  13817. }
  13818. plugins.push(
  13819. postcssModules({
  13820. ...modulesOptions,
  13821. getJSON: (_cssFileName, json) => {
  13822. cssModules = json;
  13823. }
  13824. })
  13825. );
  13826. }
  13827. const postCSSOptions = {
  13828. ...postcssOptions,
  13829. to: filename,
  13830. from: filename
  13831. };
  13832. if (map) {
  13833. postCSSOptions.map = {
  13834. inline: false,
  13835. annotation: false,
  13836. prev: map
  13837. };
  13838. }
  13839. let result;
  13840. let code;
  13841. let outMap;
  13842. const dependencies = new Set(
  13843. preProcessedSource ? preProcessedSource.dependencies : []
  13844. );
  13845. dependencies.delete(filename);
  13846. const errors = [];
  13847. if (preProcessedSource && preProcessedSource.errors.length) {
  13848. errors.push(...preProcessedSource.errors);
  13849. }
  13850. const recordPlainCssDependencies = (messages) => {
  13851. messages.forEach((msg) => {
  13852. if (msg.type === "dependency") {
  13853. dependencies.add(msg.file);
  13854. }
  13855. });
  13856. return dependencies;
  13857. };
  13858. try {
  13859. result = require$$0$1(plugins).process(source, postCSSOptions);
  13860. if (options.isAsync) {
  13861. return result.then((result2) => ({
  13862. code: result2.css || "",
  13863. map: result2.map && result2.map.toJSON(),
  13864. errors,
  13865. modules: cssModules,
  13866. rawResult: result2,
  13867. dependencies: recordPlainCssDependencies(result2.messages)
  13868. })).catch((error) => ({
  13869. code: "",
  13870. map: void 0,
  13871. errors: [...errors, error],
  13872. rawResult: void 0,
  13873. dependencies
  13874. }));
  13875. }
  13876. recordPlainCssDependencies(result.messages);
  13877. code = result.css;
  13878. outMap = result.map;
  13879. } catch (e) {
  13880. errors.push(e);
  13881. }
  13882. return {
  13883. code: code || ``,
  13884. map: outMap && outMap.toJSON(),
  13885. errors,
  13886. rawResult: result,
  13887. dependencies
  13888. };
  13889. }
  13890. function preprocess(options, preprocessor) {
  13891. return preprocessor(
  13892. options.source,
  13893. options.inMap || options.map,
  13894. {
  13895. filename: options.filename,
  13896. ...options.preprocessOptions
  13897. },
  13898. options.preprocessCustomRequire
  13899. );
  13900. }
  13901. function analyzeScriptBindings(ast) {
  13902. for (const node of ast) {
  13903. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  13904. return analyzeBindingsFromOptions(node.declaration);
  13905. }
  13906. }
  13907. return {};
  13908. }
  13909. function analyzeBindingsFromOptions(node) {
  13910. const bindings = {};
  13911. Object.defineProperty(bindings, "__isScriptSetup", {
  13912. enumerable: false,
  13913. value: false
  13914. });
  13915. for (const property of node.properties) {
  13916. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  13917. if (property.key.name === "props") {
  13918. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  13919. bindings[key] = "props";
  13920. }
  13921. } else if (property.key.name === "inject") {
  13922. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  13923. bindings[key] = "options";
  13924. }
  13925. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  13926. for (const key of getObjectExpressionKeys(property.value)) {
  13927. bindings[key] = "options";
  13928. }
  13929. }
  13930. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  13931. for (const bodyItem of property.body.body) {
  13932. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  13933. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  13934. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  13935. }
  13936. }
  13937. }
  13938. }
  13939. }
  13940. return bindings;
  13941. }
  13942. function getObjectExpressionKeys(node) {
  13943. const keys = [];
  13944. for (const prop of node.properties) {
  13945. if (prop.type === "SpreadElement")
  13946. continue;
  13947. const key = resolveObjectKey(prop.key, prop.computed);
  13948. if (key)
  13949. keys.push(String(key));
  13950. }
  13951. return keys;
  13952. }
  13953. function getArrayExpressionKeys(node) {
  13954. const keys = [];
  13955. for (const element of node.elements) {
  13956. if (element && element.type === "StringLiteral") {
  13957. keys.push(element.value);
  13958. }
  13959. }
  13960. return keys;
  13961. }
  13962. function getObjectOrArrayExpressionKeys(value) {
  13963. if (value.type === "ArrayExpression") {
  13964. return getArrayExpressionKeys(value);
  13965. }
  13966. if (value.type === "ObjectExpression") {
  13967. return getObjectExpressionKeys(value);
  13968. }
  13969. return [];
  13970. }
  13971. var _a, _b;
  13972. class ScriptCompileContext {
  13973. constructor(descriptor, options) {
  13974. this.descriptor = descriptor;
  13975. this.options = options;
  13976. this.isCE = false;
  13977. this.source = this.descriptor.source;
  13978. this.filename = this.descriptor.filename;
  13979. this.s = new MagicString(this.source);
  13980. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  13981. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  13982. this.userImports = /* @__PURE__ */ Object.create(null);
  13983. // macros presence check
  13984. this.hasDefinePropsCall = false;
  13985. this.hasDefineEmitCall = false;
  13986. this.hasDefineExposeCall = false;
  13987. this.hasDefaultExportName = false;
  13988. this.hasDefaultExportRender = false;
  13989. this.hasDefineOptionsCall = false;
  13990. this.hasDefineSlotsCall = false;
  13991. this.hasDefineModelCall = false;
  13992. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  13993. // defineModel
  13994. this.modelDecls = /* @__PURE__ */ Object.create(null);
  13995. // codegen
  13996. this.bindingMetadata = {};
  13997. this.helperImports = /* @__PURE__ */ new Set();
  13998. const { script, scriptSetup } = descriptor;
  13999. const scriptLang = script && script.lang;
  14000. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  14001. this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx";
  14002. this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx";
  14003. const customElement = options.customElement;
  14004. const filename = this.descriptor.filename;
  14005. if (customElement) {
  14006. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  14007. }
  14008. const plugins = resolveParserPlugins(
  14009. scriptLang || scriptSetupLang,
  14010. options.babelParserPlugins
  14011. );
  14012. function parse(input, offset) {
  14013. try {
  14014. return parser$1.parse(input, {
  14015. plugins,
  14016. sourceType: "module"
  14017. }).program;
  14018. } catch (e) {
  14019. e.message = `[vue/compiler-sfc] ${e.message}
  14020. ${descriptor.filename}
  14021. ${shared.generateCodeFrame(
  14022. descriptor.source,
  14023. e.pos + offset,
  14024. e.pos + offset + 1
  14025. )}`;
  14026. throw e;
  14027. }
  14028. }
  14029. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  14030. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  14031. }
  14032. helper(key) {
  14033. this.helperImports.add(key);
  14034. return `_${key}`;
  14035. }
  14036. getString(node, scriptSetup = true) {
  14037. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  14038. return block.content.slice(node.start, node.end);
  14039. }
  14040. error(msg, node, scope) {
  14041. const offset = scope ? scope.offset : this.startOffset;
  14042. throw new Error(
  14043. `[@vue/compiler-sfc] ${msg}
  14044. ${(scope || this.descriptor).filename}
  14045. ${shared.generateCodeFrame(
  14046. (scope || this.descriptor).source,
  14047. node.start + offset,
  14048. node.end + offset
  14049. )}`
  14050. );
  14051. }
  14052. }
  14053. function resolveParserPlugins(lang, userPlugins, dts = false) {
  14054. const plugins = [];
  14055. if (!userPlugins || !userPlugins.some(
  14056. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  14057. )) {
  14058. plugins.push("importAttributes");
  14059. }
  14060. if (lang === "jsx" || lang === "tsx") {
  14061. plugins.push("jsx");
  14062. } else if (userPlugins) {
  14063. userPlugins = userPlugins.filter((p) => p !== "jsx");
  14064. }
  14065. if (lang === "ts" || lang === "tsx") {
  14066. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  14067. if (!userPlugins || !userPlugins.includes("decorators")) {
  14068. plugins.push("decorators-legacy");
  14069. }
  14070. }
  14071. if (userPlugins) {
  14072. plugins.push(...userPlugins);
  14073. }
  14074. return plugins;
  14075. }
  14076. function rewriteDefault(input, as, parserPlugins) {
  14077. const ast = parser$1.parse(input, {
  14078. sourceType: "module",
  14079. plugins: resolveParserPlugins("js", parserPlugins)
  14080. }).program.body;
  14081. const s = new MagicString(input);
  14082. rewriteDefaultAST(ast, s, as);
  14083. return s.toString();
  14084. }
  14085. function rewriteDefaultAST(ast, s, as) {
  14086. if (!hasDefaultExport(ast)) {
  14087. s.append(`
  14088. const ${as} = {}`);
  14089. return;
  14090. }
  14091. ast.forEach((node) => {
  14092. if (node.type === "ExportDefaultDeclaration") {
  14093. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  14094. let start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  14095. s.overwrite(start, node.declaration.id.start, ` class `);
  14096. s.append(`
  14097. const ${as} = ${node.declaration.id.name}`);
  14098. } else {
  14099. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  14100. }
  14101. } else if (node.type === "ExportNamedDeclaration") {
  14102. for (const specifier of node.specifiers) {
  14103. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  14104. if (node.source) {
  14105. if (specifier.local.name === "default") {
  14106. s.prepend(
  14107. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  14108. `
  14109. );
  14110. const end2 = specifierEnd(s, specifier.local.end, node.end);
  14111. s.remove(specifier.start, end2);
  14112. s.append(`
  14113. const ${as} = __VUE_DEFAULT__`);
  14114. continue;
  14115. } else {
  14116. s.prepend(
  14117. `import { ${s.slice(
  14118. specifier.local.start,
  14119. specifier.local.end
  14120. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  14121. `
  14122. );
  14123. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  14124. s.remove(specifier.start, end2);
  14125. s.append(`
  14126. const ${as} = __VUE_DEFAULT__`);
  14127. continue;
  14128. }
  14129. }
  14130. const end = specifierEnd(s, specifier.end, node.end);
  14131. s.remove(specifier.start, end);
  14132. s.append(`
  14133. const ${as} = ${specifier.local.name}`);
  14134. }
  14135. }
  14136. }
  14137. });
  14138. }
  14139. function hasDefaultExport(ast) {
  14140. for (const stmt of ast) {
  14141. if (stmt.type === "ExportDefaultDeclaration") {
  14142. return true;
  14143. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  14144. (spec) => spec.exported.name === "default"
  14145. )) {
  14146. return true;
  14147. }
  14148. }
  14149. return false;
  14150. }
  14151. function specifierEnd(s, end, nodeEnd) {
  14152. let hasCommas = false;
  14153. let oldEnd = end;
  14154. while (end < nodeEnd) {
  14155. if (/\s/.test(s.slice(end, end + 1))) {
  14156. end++;
  14157. } else if (s.slice(end, end + 1) === ",") {
  14158. end++;
  14159. hasCommas = true;
  14160. break;
  14161. } else if (s.slice(end, end + 1) === "}") {
  14162. break;
  14163. }
  14164. }
  14165. return hasCommas ? end : oldEnd;
  14166. }
  14167. const normalScriptDefaultVar = `__default__`;
  14168. function processNormalScript(ctx, scopeId) {
  14169. var _a;
  14170. const script = ctx.descriptor.script;
  14171. if (script.lang && !ctx.isJS && !ctx.isTS) {
  14172. return script;
  14173. }
  14174. try {
  14175. let content = script.content;
  14176. let map = script.map;
  14177. const scriptAst = ctx.scriptAst;
  14178. const bindings = analyzeScriptBindings(scriptAst.body);
  14179. const { cssVars } = ctx.descriptor;
  14180. const { genDefaultAs, isProd } = ctx.options;
  14181. if (cssVars.length || genDefaultAs) {
  14182. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  14183. const s = new MagicString(content);
  14184. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  14185. content = s.toString();
  14186. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  14187. content += genNormalScriptCssVarsCode(
  14188. cssVars,
  14189. bindings,
  14190. scopeId,
  14191. !!isProd,
  14192. defaultVar
  14193. );
  14194. }
  14195. if (!genDefaultAs) {
  14196. content += `
  14197. export default ${defaultVar}`;
  14198. }
  14199. }
  14200. return {
  14201. ...script,
  14202. content,
  14203. map,
  14204. bindings,
  14205. scriptAst: scriptAst.body
  14206. };
  14207. } catch (e) {
  14208. return script;
  14209. }
  14210. }
  14211. var balancedMatch = balanced$1;
  14212. function balanced$1(a, b, str) {
  14213. if (a instanceof RegExp) a = maybeMatch(a, str);
  14214. if (b instanceof RegExp) b = maybeMatch(b, str);
  14215. var r = range(a, b, str);
  14216. return r && {
  14217. start: r[0],
  14218. end: r[1],
  14219. pre: str.slice(0, r[0]),
  14220. body: str.slice(r[0] + a.length, r[1]),
  14221. post: str.slice(r[1] + b.length)
  14222. };
  14223. }
  14224. function maybeMatch(reg, str) {
  14225. var m = str.match(reg);
  14226. return m ? m[0] : null;
  14227. }
  14228. balanced$1.range = range;
  14229. function range(a, b, str) {
  14230. var begs, beg, left, right, result;
  14231. var ai = str.indexOf(a);
  14232. var bi = str.indexOf(b, ai + 1);
  14233. var i = ai;
  14234. if (ai >= 0 && bi > 0) {
  14235. if(a===b) {
  14236. return [ai, bi];
  14237. }
  14238. begs = [];
  14239. left = str.length;
  14240. while (i >= 0 && !result) {
  14241. if (i == ai) {
  14242. begs.push(i);
  14243. ai = str.indexOf(a, i + 1);
  14244. } else if (begs.length == 1) {
  14245. result = [ begs.pop(), bi ];
  14246. } else {
  14247. beg = begs.pop();
  14248. if (beg < left) {
  14249. left = beg;
  14250. right = bi;
  14251. }
  14252. bi = str.indexOf(b, i + 1);
  14253. }
  14254. i = ai < bi && ai >= 0 ? ai : bi;
  14255. }
  14256. if (begs.length) {
  14257. result = [ left, right ];
  14258. }
  14259. }
  14260. return result;
  14261. }
  14262. var balanced = balancedMatch;
  14263. var braceExpansion = expandTop;
  14264. var escSlash = '\0SLASH'+Math.random()+'\0';
  14265. var escOpen = '\0OPEN'+Math.random()+'\0';
  14266. var escClose = '\0CLOSE'+Math.random()+'\0';
  14267. var escComma = '\0COMMA'+Math.random()+'\0';
  14268. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  14269. function numeric(str) {
  14270. return parseInt(str, 10) == str
  14271. ? parseInt(str, 10)
  14272. : str.charCodeAt(0);
  14273. }
  14274. function escapeBraces(str) {
  14275. return str.split('\\\\').join(escSlash)
  14276. .split('\\{').join(escOpen)
  14277. .split('\\}').join(escClose)
  14278. .split('\\,').join(escComma)
  14279. .split('\\.').join(escPeriod);
  14280. }
  14281. function unescapeBraces(str) {
  14282. return str.split(escSlash).join('\\')
  14283. .split(escOpen).join('{')
  14284. .split(escClose).join('}')
  14285. .split(escComma).join(',')
  14286. .split(escPeriod).join('.');
  14287. }
  14288. // Basically just str.split(","), but handling cases
  14289. // where we have nested braced sections, which should be
  14290. // treated as individual members, like {a,{b,c},d}
  14291. function parseCommaParts(str) {
  14292. if (!str)
  14293. return [''];
  14294. var parts = [];
  14295. var m = balanced('{', '}', str);
  14296. if (!m)
  14297. return str.split(',');
  14298. var pre = m.pre;
  14299. var body = m.body;
  14300. var post = m.post;
  14301. var p = pre.split(',');
  14302. p[p.length-1] += '{' + body + '}';
  14303. var postParts = parseCommaParts(post);
  14304. if (post.length) {
  14305. p[p.length-1] += postParts.shift();
  14306. p.push.apply(p, postParts);
  14307. }
  14308. parts.push.apply(parts, p);
  14309. return parts;
  14310. }
  14311. function expandTop(str) {
  14312. if (!str)
  14313. return [];
  14314. // I don't know why Bash 4.3 does this, but it does.
  14315. // Anything starting with {} will have the first two bytes preserved
  14316. // but *only* at the top level, so {},a}b will not expand to anything,
  14317. // but a{},b}c will be expanded to [a}c,abc].
  14318. // One could argue that this is a bug in Bash, but since the goal of
  14319. // this module is to match Bash's rules, we escape a leading {}
  14320. if (str.substr(0, 2) === '{}') {
  14321. str = '\\{\\}' + str.substr(2);
  14322. }
  14323. return expand(escapeBraces(str), true).map(unescapeBraces);
  14324. }
  14325. function embrace(str) {
  14326. return '{' + str + '}';
  14327. }
  14328. function isPadded(el) {
  14329. return /^-?0\d/.test(el);
  14330. }
  14331. function lte(i, y) {
  14332. return i <= y;
  14333. }
  14334. function gte(i, y) {
  14335. return i >= y;
  14336. }
  14337. function expand(str, isTop) {
  14338. var expansions = [];
  14339. var m = balanced('{', '}', str);
  14340. if (!m) return [str];
  14341. // no need to expand pre, since it is guaranteed to be free of brace-sets
  14342. var pre = m.pre;
  14343. var post = m.post.length
  14344. ? expand(m.post, false)
  14345. : [''];
  14346. if (/\$$/.test(m.pre)) {
  14347. for (var k = 0; k < post.length; k++) {
  14348. var expansion = pre+ '{' + m.body + '}' + post[k];
  14349. expansions.push(expansion);
  14350. }
  14351. } else {
  14352. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  14353. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  14354. var isSequence = isNumericSequence || isAlphaSequence;
  14355. var isOptions = m.body.indexOf(',') >= 0;
  14356. if (!isSequence && !isOptions) {
  14357. // {a},b}
  14358. if (m.post.match(/,.*\}/)) {
  14359. str = m.pre + '{' + m.body + escClose + m.post;
  14360. return expand(str);
  14361. }
  14362. return [str];
  14363. }
  14364. var n;
  14365. if (isSequence) {
  14366. n = m.body.split(/\.\./);
  14367. } else {
  14368. n = parseCommaParts(m.body);
  14369. if (n.length === 1) {
  14370. // x{{a,b}}y ==> x{a}y x{b}y
  14371. n = expand(n[0], false).map(embrace);
  14372. if (n.length === 1) {
  14373. return post.map(function(p) {
  14374. return m.pre + n[0] + p;
  14375. });
  14376. }
  14377. }
  14378. }
  14379. // at this point, n is the parts, and we know it's not a comma set
  14380. // with a single entry.
  14381. var N;
  14382. if (isSequence) {
  14383. var x = numeric(n[0]);
  14384. var y = numeric(n[1]);
  14385. var width = Math.max(n[0].length, n[1].length);
  14386. var incr = n.length == 3
  14387. ? Math.abs(numeric(n[2]))
  14388. : 1;
  14389. var test = lte;
  14390. var reverse = y < x;
  14391. if (reverse) {
  14392. incr *= -1;
  14393. test = gte;
  14394. }
  14395. var pad = n.some(isPadded);
  14396. N = [];
  14397. for (var i = x; test(i, y); i += incr) {
  14398. var c;
  14399. if (isAlphaSequence) {
  14400. c = String.fromCharCode(i);
  14401. if (c === '\\')
  14402. c = '';
  14403. } else {
  14404. c = String(i);
  14405. if (pad) {
  14406. var need = width - c.length;
  14407. if (need > 0) {
  14408. var z = new Array(need + 1).join('0');
  14409. if (i < 0)
  14410. c = '-' + z + c.slice(1);
  14411. else
  14412. c = z + c;
  14413. }
  14414. }
  14415. }
  14416. N.push(c);
  14417. }
  14418. } else {
  14419. N = [];
  14420. for (var j = 0; j < n.length; j++) {
  14421. N.push.apply(N, expand(n[j], false));
  14422. }
  14423. }
  14424. for (var j = 0; j < N.length; j++) {
  14425. for (var k = 0; k < post.length; k++) {
  14426. var expansion = pre + N[j] + post[k];
  14427. if (!isTop || isSequence || expansion)
  14428. expansions.push(expansion);
  14429. }
  14430. }
  14431. }
  14432. return expansions;
  14433. }
  14434. var expand$1 = /*@__PURE__*/getDefaultExportFromCjs(braceExpansion);
  14435. const MAX_PATTERN_LENGTH = 1024 * 64;
  14436. const assertValidPattern = (pattern) => {
  14437. if (typeof pattern !== 'string') {
  14438. throw new TypeError('invalid pattern');
  14439. }
  14440. if (pattern.length > MAX_PATTERN_LENGTH) {
  14441. throw new TypeError('pattern is too long');
  14442. }
  14443. };
  14444. // translate the various posix character classes into unicode properties
  14445. // this works across all unicode locales
  14446. // { <posix class>: [<translation>, /u flag required, negated]
  14447. const posixClasses = {
  14448. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  14449. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  14450. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  14451. '[:blank:]': ['\\p{Zs}\\t', true],
  14452. '[:cntrl:]': ['\\p{Cc}', true],
  14453. '[:digit:]': ['\\p{Nd}', true],
  14454. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  14455. '[:lower:]': ['\\p{Ll}', true],
  14456. '[:print:]': ['\\p{C}', true],
  14457. '[:punct:]': ['\\p{P}', true],
  14458. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  14459. '[:upper:]': ['\\p{Lu}', true],
  14460. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  14461. '[:xdigit:]': ['A-Fa-f0-9', false],
  14462. };
  14463. // only need to escape a few things inside of brace expressions
  14464. // escapes: [ \ ] -
  14465. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  14466. // escape all regexp magic characters
  14467. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  14468. // everything has already been escaped, we just have to join
  14469. const rangesToString = (ranges) => ranges.join('');
  14470. // takes a glob string at a posix brace expression, and returns
  14471. // an equivalent regular expression source, and boolean indicating
  14472. // whether the /u flag needs to be applied, and the number of chars
  14473. // consumed to parse the character class.
  14474. // This also removes out of order ranges, and returns ($.) if the
  14475. // entire class just no good.
  14476. const parseClass = (glob, position) => {
  14477. const pos = position;
  14478. /* c8 ignore start */
  14479. if (glob.charAt(pos) !== '[') {
  14480. throw new Error('not in a brace expression');
  14481. }
  14482. /* c8 ignore stop */
  14483. const ranges = [];
  14484. const negs = [];
  14485. let i = pos + 1;
  14486. let sawStart = false;
  14487. let uflag = false;
  14488. let escaping = false;
  14489. let negate = false;
  14490. let endPos = pos;
  14491. let rangeStart = '';
  14492. WHILE: while (i < glob.length) {
  14493. const c = glob.charAt(i);
  14494. if ((c === '!' || c === '^') && i === pos + 1) {
  14495. negate = true;
  14496. i++;
  14497. continue;
  14498. }
  14499. if (c === ']' && sawStart && !escaping) {
  14500. endPos = i + 1;
  14501. break;
  14502. }
  14503. sawStart = true;
  14504. if (c === '\\') {
  14505. if (!escaping) {
  14506. escaping = true;
  14507. i++;
  14508. continue;
  14509. }
  14510. // escaped \ char, fall through and treat like normal char
  14511. }
  14512. if (c === '[' && !escaping) {
  14513. // either a posix class, a collation equivalent, or just a [
  14514. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  14515. if (glob.startsWith(cls, i)) {
  14516. // invalid, [a-[] is fine, but not [a-[:alpha]]
  14517. if (rangeStart) {
  14518. return ['$.', false, glob.length - pos, true];
  14519. }
  14520. i += cls.length;
  14521. if (neg)
  14522. negs.push(unip);
  14523. else
  14524. ranges.push(unip);
  14525. uflag = uflag || u;
  14526. continue WHILE;
  14527. }
  14528. }
  14529. }
  14530. // now it's just a normal character, effectively
  14531. escaping = false;
  14532. if (rangeStart) {
  14533. // throw this range away if it's not valid, but others
  14534. // can still match.
  14535. if (c > rangeStart) {
  14536. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  14537. }
  14538. else if (c === rangeStart) {
  14539. ranges.push(braceEscape(c));
  14540. }
  14541. rangeStart = '';
  14542. i++;
  14543. continue;
  14544. }
  14545. // now might be the start of a range.
  14546. // can be either c-d or c-] or c<more...>] or c] at this point
  14547. if (glob.startsWith('-]', i + 1)) {
  14548. ranges.push(braceEscape(c + '-'));
  14549. i += 2;
  14550. continue;
  14551. }
  14552. if (glob.startsWith('-', i + 1)) {
  14553. rangeStart = c;
  14554. i += 2;
  14555. continue;
  14556. }
  14557. // not the start of a range, just a single character
  14558. ranges.push(braceEscape(c));
  14559. i++;
  14560. }
  14561. if (endPos < i) {
  14562. // didn't see the end of the class, not a valid class,
  14563. // but might still be valid as a literal match.
  14564. return ['', false, 0, false];
  14565. }
  14566. // if we got no ranges and no negates, then we have a range that
  14567. // cannot possibly match anything, and that poisons the whole glob
  14568. if (!ranges.length && !negs.length) {
  14569. return ['$.', false, glob.length - pos, true];
  14570. }
  14571. // if we got one positive range, and it's a single character, then that's
  14572. // not actually a magic pattern, it's just that one literal character.
  14573. // we should not treat that as "magic", we should just return the literal
  14574. // character. [_] is a perfectly valid way to escape glob magic chars.
  14575. if (negs.length === 0 &&
  14576. ranges.length === 1 &&
  14577. /^\\?.$/.test(ranges[0]) &&
  14578. !negate) {
  14579. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  14580. return [regexpEscape(r), false, endPos - pos, false];
  14581. }
  14582. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  14583. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  14584. const comb = ranges.length && negs.length
  14585. ? '(' + sranges + '|' + snegs + ')'
  14586. : ranges.length
  14587. ? sranges
  14588. : snegs;
  14589. return [comb, uflag, endPos - pos, true];
  14590. };
  14591. /**
  14592. * Un-escape a string that has been escaped with {@link escape}.
  14593. *
  14594. * If the {@link windowsPathsNoEscape} option is used, then square-brace
  14595. * escapes are removed, but not backslash escapes. For example, it will turn
  14596. * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
  14597. * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
  14598. *
  14599. * When `windowsPathsNoEscape` is not set, then both brace escapes and
  14600. * backslash escapes are removed.
  14601. *
  14602. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  14603. * or unescaped.
  14604. */
  14605. const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
  14606. return windowsPathsNoEscape
  14607. ? s.replace(/\[([^\/\\])\]/g, '$1')
  14608. : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
  14609. };
  14610. // parse a single path portion
  14611. const types = new Set(['!', '?', '+', '*', '@']);
  14612. const isExtglobType = (c) => types.has(c);
  14613. // Patterns that get prepended to bind to the start of either the
  14614. // entire string, or just a single path portion, to prevent dots
  14615. // and/or traversal patterns, when needed.
  14616. // Exts don't need the ^ or / bit, because the root binds that already.
  14617. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  14618. const startNoDot = '(?!\\.)';
  14619. // characters that indicate a start of pattern needs the "no dots" bit,
  14620. // because a dot *might* be matched. ( is not in the list, because in
  14621. // the case of a child extglob, it will handle the prevention itself.
  14622. const addPatternStart = new Set(['[', '.']);
  14623. // cases where traversal is A-OK, no dot prevention needed
  14624. const justDots = new Set(['..', '.']);
  14625. const reSpecials = new Set('().*{}+?[]^$\\!');
  14626. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  14627. // any single thing other than /
  14628. const qmark$1 = '[^/]';
  14629. // * => any number of characters
  14630. const star$1 = qmark$1 + '*?';
  14631. // use + when we need to ensure that *something* matches, because the * is
  14632. // the only thing in the path portion.
  14633. const starNoEmpty = qmark$1 + '+?';
  14634. // remove the \ chars that we added if we end up doing a nonmagic compare
  14635. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  14636. class AST {
  14637. type;
  14638. #root;
  14639. #hasMagic;
  14640. #uflag = false;
  14641. #parts = [];
  14642. #parent;
  14643. #parentIndex;
  14644. #negs;
  14645. #filledNegs = false;
  14646. #options;
  14647. #toString;
  14648. // set to true if it's an extglob with no children
  14649. // (which really means one child of '')
  14650. #emptyExt = false;
  14651. constructor(type, parent, options = {}) {
  14652. this.type = type;
  14653. // extglobs are inherently magical
  14654. if (type)
  14655. this.#hasMagic = true;
  14656. this.#parent = parent;
  14657. this.#root = this.#parent ? this.#parent.#root : this;
  14658. this.#options = this.#root === this ? options : this.#root.#options;
  14659. this.#negs = this.#root === this ? [] : this.#root.#negs;
  14660. if (type === '!' && !this.#root.#filledNegs)
  14661. this.#negs.push(this);
  14662. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  14663. }
  14664. get hasMagic() {
  14665. /* c8 ignore start */
  14666. if (this.#hasMagic !== undefined)
  14667. return this.#hasMagic;
  14668. /* c8 ignore stop */
  14669. for (const p of this.#parts) {
  14670. if (typeof p === 'string')
  14671. continue;
  14672. if (p.type || p.hasMagic)
  14673. return (this.#hasMagic = true);
  14674. }
  14675. // note: will be undefined until we generate the regexp src and find out
  14676. return this.#hasMagic;
  14677. }
  14678. // reconstructs the pattern
  14679. toString() {
  14680. if (this.#toString !== undefined)
  14681. return this.#toString;
  14682. if (!this.type) {
  14683. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  14684. }
  14685. else {
  14686. return (this.#toString =
  14687. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  14688. }
  14689. }
  14690. #fillNegs() {
  14691. /* c8 ignore start */
  14692. if (this !== this.#root)
  14693. throw new Error('should only call on root');
  14694. if (this.#filledNegs)
  14695. return this;
  14696. /* c8 ignore stop */
  14697. // call toString() once to fill this out
  14698. this.toString();
  14699. this.#filledNegs = true;
  14700. let n;
  14701. while ((n = this.#negs.pop())) {
  14702. if (n.type !== '!')
  14703. continue;
  14704. // walk up the tree, appending everthing that comes AFTER parentIndex
  14705. let p = n;
  14706. let pp = p.#parent;
  14707. while (pp) {
  14708. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  14709. for (const part of n.#parts) {
  14710. /* c8 ignore start */
  14711. if (typeof part === 'string') {
  14712. throw new Error('string part in extglob AST??');
  14713. }
  14714. /* c8 ignore stop */
  14715. part.copyIn(pp.#parts[i]);
  14716. }
  14717. }
  14718. p = pp;
  14719. pp = p.#parent;
  14720. }
  14721. }
  14722. return this;
  14723. }
  14724. push(...parts) {
  14725. for (const p of parts) {
  14726. if (p === '')
  14727. continue;
  14728. /* c8 ignore start */
  14729. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  14730. throw new Error('invalid part: ' + p);
  14731. }
  14732. /* c8 ignore stop */
  14733. this.#parts.push(p);
  14734. }
  14735. }
  14736. toJSON() {
  14737. const ret = this.type === null
  14738. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  14739. : [this.type, ...this.#parts.map(p => p.toJSON())];
  14740. if (this.isStart() && !this.type)
  14741. ret.unshift([]);
  14742. if (this.isEnd() &&
  14743. (this === this.#root ||
  14744. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  14745. ret.push({});
  14746. }
  14747. return ret;
  14748. }
  14749. isStart() {
  14750. if (this.#root === this)
  14751. return true;
  14752. // if (this.type) return !!this.#parent?.isStart()
  14753. if (!this.#parent?.isStart())
  14754. return false;
  14755. if (this.#parentIndex === 0)
  14756. return true;
  14757. // if everything AHEAD of this is a negation, then it's still the "start"
  14758. const p = this.#parent;
  14759. for (let i = 0; i < this.#parentIndex; i++) {
  14760. const pp = p.#parts[i];
  14761. if (!(pp instanceof AST && pp.type === '!')) {
  14762. return false;
  14763. }
  14764. }
  14765. return true;
  14766. }
  14767. isEnd() {
  14768. if (this.#root === this)
  14769. return true;
  14770. if (this.#parent?.type === '!')
  14771. return true;
  14772. if (!this.#parent?.isEnd())
  14773. return false;
  14774. if (!this.type)
  14775. return this.#parent?.isEnd();
  14776. // if not root, it'll always have a parent
  14777. /* c8 ignore start */
  14778. const pl = this.#parent ? this.#parent.#parts.length : 0;
  14779. /* c8 ignore stop */
  14780. return this.#parentIndex === pl - 1;
  14781. }
  14782. copyIn(part) {
  14783. if (typeof part === 'string')
  14784. this.push(part);
  14785. else
  14786. this.push(part.clone(this));
  14787. }
  14788. clone(parent) {
  14789. const c = new AST(this.type, parent);
  14790. for (const p of this.#parts) {
  14791. c.copyIn(p);
  14792. }
  14793. return c;
  14794. }
  14795. static #parseAST(str, ast, pos, opt) {
  14796. let escaping = false;
  14797. let inBrace = false;
  14798. let braceStart = -1;
  14799. let braceNeg = false;
  14800. if (ast.type === null) {
  14801. // outside of a extglob, append until we find a start
  14802. let i = pos;
  14803. let acc = '';
  14804. while (i < str.length) {
  14805. const c = str.charAt(i++);
  14806. // still accumulate escapes at this point, but we do ignore
  14807. // starts that are escaped
  14808. if (escaping || c === '\\') {
  14809. escaping = !escaping;
  14810. acc += c;
  14811. continue;
  14812. }
  14813. if (inBrace) {
  14814. if (i === braceStart + 1) {
  14815. if (c === '^' || c === '!') {
  14816. braceNeg = true;
  14817. }
  14818. }
  14819. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  14820. inBrace = false;
  14821. }
  14822. acc += c;
  14823. continue;
  14824. }
  14825. else if (c === '[') {
  14826. inBrace = true;
  14827. braceStart = i;
  14828. braceNeg = false;
  14829. acc += c;
  14830. continue;
  14831. }
  14832. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  14833. ast.push(acc);
  14834. acc = '';
  14835. const ext = new AST(c, ast);
  14836. i = AST.#parseAST(str, ext, i, opt);
  14837. ast.push(ext);
  14838. continue;
  14839. }
  14840. acc += c;
  14841. }
  14842. ast.push(acc);
  14843. return i;
  14844. }
  14845. // some kind of extglob, pos is at the (
  14846. // find the next | or )
  14847. let i = pos + 1;
  14848. let part = new AST(null, ast);
  14849. const parts = [];
  14850. let acc = '';
  14851. while (i < str.length) {
  14852. const c = str.charAt(i++);
  14853. // still accumulate escapes at this point, but we do ignore
  14854. // starts that are escaped
  14855. if (escaping || c === '\\') {
  14856. escaping = !escaping;
  14857. acc += c;
  14858. continue;
  14859. }
  14860. if (inBrace) {
  14861. if (i === braceStart + 1) {
  14862. if (c === '^' || c === '!') {
  14863. braceNeg = true;
  14864. }
  14865. }
  14866. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  14867. inBrace = false;
  14868. }
  14869. acc += c;
  14870. continue;
  14871. }
  14872. else if (c === '[') {
  14873. inBrace = true;
  14874. braceStart = i;
  14875. braceNeg = false;
  14876. acc += c;
  14877. continue;
  14878. }
  14879. if (isExtglobType(c) && str.charAt(i) === '(') {
  14880. part.push(acc);
  14881. acc = '';
  14882. const ext = new AST(c, part);
  14883. part.push(ext);
  14884. i = AST.#parseAST(str, ext, i, opt);
  14885. continue;
  14886. }
  14887. if (c === '|') {
  14888. part.push(acc);
  14889. acc = '';
  14890. parts.push(part);
  14891. part = new AST(null, ast);
  14892. continue;
  14893. }
  14894. if (c === ')') {
  14895. if (acc === '' && ast.#parts.length === 0) {
  14896. ast.#emptyExt = true;
  14897. }
  14898. part.push(acc);
  14899. acc = '';
  14900. ast.push(...parts, part);
  14901. return i;
  14902. }
  14903. acc += c;
  14904. }
  14905. // unfinished extglob
  14906. // if we got here, it was a malformed extglob! not an extglob, but
  14907. // maybe something else in there.
  14908. ast.type = null;
  14909. ast.#hasMagic = undefined;
  14910. ast.#parts = [str.substring(pos - 1)];
  14911. return i;
  14912. }
  14913. static fromGlob(pattern, options = {}) {
  14914. const ast = new AST(null, undefined, options);
  14915. AST.#parseAST(pattern, ast, 0, options);
  14916. return ast;
  14917. }
  14918. // returns the regular expression if there's magic, or the unescaped
  14919. // string if not.
  14920. toMMPattern() {
  14921. // should only be called on root
  14922. /* c8 ignore start */
  14923. if (this !== this.#root)
  14924. return this.#root.toMMPattern();
  14925. /* c8 ignore stop */
  14926. const glob = this.toString();
  14927. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  14928. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  14929. // still need a regular expression if we have to case-insensitively
  14930. // match capital/lowercase characters.
  14931. const anyMagic = hasMagic ||
  14932. this.#hasMagic ||
  14933. (this.#options.nocase &&
  14934. !this.#options.nocaseMagicOnly &&
  14935. glob.toUpperCase() !== glob.toLowerCase());
  14936. if (!anyMagic) {
  14937. return body;
  14938. }
  14939. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  14940. return Object.assign(new RegExp(`^${re}$`, flags), {
  14941. _src: re,
  14942. _glob: glob,
  14943. });
  14944. }
  14945. get options() {
  14946. return this.#options;
  14947. }
  14948. // returns the string match, the regexp source, whether there's magic
  14949. // in the regexp (so a regular expression is required) and whether or
  14950. // not the uflag is needed for the regular expression (for posix classes)
  14951. // TODO: instead of injecting the start/end at this point, just return
  14952. // the BODY of the regexp, along with the start/end portions suitable
  14953. // for binding the start/end in either a joined full-path makeRe context
  14954. // (where we bind to (^|/), or a standalone matchPart context (where
  14955. // we bind to ^, and not /). Otherwise slashes get duped!
  14956. //
  14957. // In part-matching mode, the start is:
  14958. // - if not isStart: nothing
  14959. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  14960. // - if dots allowed or not possible: ^
  14961. // - if dots possible and not allowed: ^(?!\.)
  14962. // end is:
  14963. // - if not isEnd(): nothing
  14964. // - else: $
  14965. //
  14966. // In full-path matching mode, we put the slash at the START of the
  14967. // pattern, so start is:
  14968. // - if first pattern: same as part-matching mode
  14969. // - if not isStart(): nothing
  14970. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  14971. // - if dots allowed or not possible: /
  14972. // - if dots possible and not allowed: /(?!\.)
  14973. // end is:
  14974. // - if last pattern, same as part-matching mode
  14975. // - else nothing
  14976. //
  14977. // Always put the (?:$|/) on negated tails, though, because that has to be
  14978. // there to bind the end of the negated pattern portion, and it's easier to
  14979. // just stick it in now rather than try to inject it later in the middle of
  14980. // the pattern.
  14981. //
  14982. // We can just always return the same end, and leave it up to the caller
  14983. // to know whether it's going to be used joined or in parts.
  14984. // And, if the start is adjusted slightly, can do the same there:
  14985. // - if not isStart: nothing
  14986. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  14987. // - if dots allowed or not possible: (?:/|^)
  14988. // - if dots possible and not allowed: (?:/|^)(?!\.)
  14989. //
  14990. // But it's better to have a simpler binding without a conditional, for
  14991. // performance, so probably better to return both start options.
  14992. //
  14993. // Then the caller just ignores the end if it's not the first pattern,
  14994. // and the start always gets applied.
  14995. //
  14996. // But that's always going to be $ if it's the ending pattern, or nothing,
  14997. // so the caller can just attach $ at the end of the pattern when building.
  14998. //
  14999. // So the todo is:
  15000. // - better detect what kind of start is needed
  15001. // - return both flavors of starting pattern
  15002. // - attach $ at the end of the pattern when creating the actual RegExp
  15003. //
  15004. // Ah, but wait, no, that all only applies to the root when the first pattern
  15005. // is not an extglob. If the first pattern IS an extglob, then we need all
  15006. // that dot prevention biz to live in the extglob portions, because eg
  15007. // +(*|.x*) can match .xy but not .yx.
  15008. //
  15009. // So, return the two flavors if it's #root and the first child is not an
  15010. // AST, otherwise leave it to the child AST to handle it, and there,
  15011. // use the (?:^|/) style of start binding.
  15012. //
  15013. // Even simplified further:
  15014. // - Since the start for a join is eg /(?!\.) and the start for a part
  15015. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  15016. // or start or whatever) and prepend ^ or / at the Regexp construction.
  15017. toRegExpSource(allowDot) {
  15018. const dot = allowDot ?? !!this.#options.dot;
  15019. if (this.#root === this)
  15020. this.#fillNegs();
  15021. if (!this.type) {
  15022. const noEmpty = this.isStart() && this.isEnd();
  15023. const src = this.#parts
  15024. .map(p => {
  15025. const [re, _, hasMagic, uflag] = typeof p === 'string'
  15026. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  15027. : p.toRegExpSource(allowDot);
  15028. this.#hasMagic = this.#hasMagic || hasMagic;
  15029. this.#uflag = this.#uflag || uflag;
  15030. return re;
  15031. })
  15032. .join('');
  15033. let start = '';
  15034. if (this.isStart()) {
  15035. if (typeof this.#parts[0] === 'string') {
  15036. // this is the string that will match the start of the pattern,
  15037. // so we need to protect against dots and such.
  15038. // '.' and '..' cannot match unless the pattern is that exactly,
  15039. // even if it starts with . or dot:true is set.
  15040. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  15041. if (!dotTravAllowed) {
  15042. const aps = addPatternStart;
  15043. // check if we have a possibility of matching . or ..,
  15044. // and prevent that.
  15045. const needNoTrav =
  15046. // dots are allowed, and the pattern starts with [ or .
  15047. (dot && aps.has(src.charAt(0))) ||
  15048. // the pattern starts with \., and then [ or .
  15049. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  15050. // the pattern starts with \.\., and then [ or .
  15051. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  15052. // no need to prevent dots if it can't match a dot, or if a
  15053. // sub-pattern will be preventing it anyway.
  15054. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  15055. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  15056. }
  15057. }
  15058. }
  15059. // append the "end of path portion" pattern to negation tails
  15060. let end = '';
  15061. if (this.isEnd() &&
  15062. this.#root.#filledNegs &&
  15063. this.#parent?.type === '!') {
  15064. end = '(?:$|\\/)';
  15065. }
  15066. const final = start + src + end;
  15067. return [
  15068. final,
  15069. unescape(src),
  15070. (this.#hasMagic = !!this.#hasMagic),
  15071. this.#uflag,
  15072. ];
  15073. }
  15074. // We need to calculate the body *twice* if it's a repeat pattern
  15075. // at the start, once in nodot mode, then again in dot mode, so a
  15076. // pattern like *(?) can match 'x.y'
  15077. const repeated = this.type === '*' || this.type === '+';
  15078. // some kind of extglob
  15079. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  15080. let body = this.#partsToRegExp(dot);
  15081. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  15082. // invalid extglob, has to at least be *something* present, if it's
  15083. // the entire path portion.
  15084. const s = this.toString();
  15085. this.#parts = [s];
  15086. this.type = null;
  15087. this.#hasMagic = undefined;
  15088. return [s, unescape(this.toString()), false, false];
  15089. }
  15090. // XXX abstract out this map method
  15091. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
  15092. ? ''
  15093. : this.#partsToRegExp(true);
  15094. if (bodyDotAllowed === body) {
  15095. bodyDotAllowed = '';
  15096. }
  15097. if (bodyDotAllowed) {
  15098. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  15099. }
  15100. // an empty !() is exactly equivalent to a starNoEmpty
  15101. let final = '';
  15102. if (this.type === '!' && this.#emptyExt) {
  15103. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  15104. }
  15105. else {
  15106. const close = this.type === '!'
  15107. ? // !() must match something,but !(x) can match ''
  15108. '))' +
  15109. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  15110. star$1 +
  15111. ')'
  15112. : this.type === '@'
  15113. ? ')'
  15114. : this.type === '?'
  15115. ? ')?'
  15116. : this.type === '+' && bodyDotAllowed
  15117. ? ')'
  15118. : this.type === '*' && bodyDotAllowed
  15119. ? `)?`
  15120. : `)${this.type}`;
  15121. final = start + body + close;
  15122. }
  15123. return [
  15124. final,
  15125. unescape(body),
  15126. (this.#hasMagic = !!this.#hasMagic),
  15127. this.#uflag,
  15128. ];
  15129. }
  15130. #partsToRegExp(dot) {
  15131. return this.#parts
  15132. .map(p => {
  15133. // extglob ASTs should only contain parent ASTs
  15134. /* c8 ignore start */
  15135. if (typeof p === 'string') {
  15136. throw new Error('string type in extglob ast??');
  15137. }
  15138. /* c8 ignore stop */
  15139. // can ignore hasMagic, because extglobs are already always magic
  15140. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  15141. this.#uflag = this.#uflag || uflag;
  15142. return re;
  15143. })
  15144. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  15145. .join('|');
  15146. }
  15147. static #parseGlob(glob, hasMagic, noEmpty = false) {
  15148. let escaping = false;
  15149. let re = '';
  15150. let uflag = false;
  15151. for (let i = 0; i < glob.length; i++) {
  15152. const c = glob.charAt(i);
  15153. if (escaping) {
  15154. escaping = false;
  15155. re += (reSpecials.has(c) ? '\\' : '') + c;
  15156. continue;
  15157. }
  15158. if (c === '\\') {
  15159. if (i === glob.length - 1) {
  15160. re += '\\\\';
  15161. }
  15162. else {
  15163. escaping = true;
  15164. }
  15165. continue;
  15166. }
  15167. if (c === '[') {
  15168. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  15169. if (consumed) {
  15170. re += src;
  15171. uflag = uflag || needUflag;
  15172. i += consumed - 1;
  15173. hasMagic = hasMagic || magic;
  15174. continue;
  15175. }
  15176. }
  15177. if (c === '*') {
  15178. if (noEmpty && glob === '*')
  15179. re += starNoEmpty;
  15180. else
  15181. re += star$1;
  15182. hasMagic = true;
  15183. continue;
  15184. }
  15185. if (c === '?') {
  15186. re += qmark$1;
  15187. hasMagic = true;
  15188. continue;
  15189. }
  15190. re += regExpEscape$1(c);
  15191. }
  15192. return [re, unescape(glob), !!hasMagic, uflag];
  15193. }
  15194. }
  15195. /**
  15196. * Escape all magic characters in a glob pattern.
  15197. *
  15198. * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
  15199. * option is used, then characters are escaped by wrapping in `[]`, because
  15200. * a magic character wrapped in a character class can only be satisfied by
  15201. * that exact character. In this mode, `\` is _not_ escaped, because it is
  15202. * not interpreted as a magic character, but instead as a path separator.
  15203. */
  15204. const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
  15205. // don't need to escape +@! because we escape the parens
  15206. // that make those magic, and escaping ! as [!] isn't valid,
  15207. // because [!]] is a valid glob class meaning not ']'.
  15208. return windowsPathsNoEscape
  15209. ? s.replace(/[?*()[\]]/g, '[$&]')
  15210. : s.replace(/[?*()[\]\\]/g, '\\$&');
  15211. };
  15212. const minimatch = (p, pattern, options = {}) => {
  15213. assertValidPattern(pattern);
  15214. // shortcut: comments match nothing.
  15215. if (!options.nocomment && pattern.charAt(0) === '#') {
  15216. return false;
  15217. }
  15218. return new Minimatch(pattern, options).match(p);
  15219. };
  15220. // Optimized checking for the most common glob patterns.
  15221. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  15222. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  15223. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  15224. const starDotExtTestNocase = (ext) => {
  15225. ext = ext.toLowerCase();
  15226. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  15227. };
  15228. const starDotExtTestNocaseDot = (ext) => {
  15229. ext = ext.toLowerCase();
  15230. return (f) => f.toLowerCase().endsWith(ext);
  15231. };
  15232. const starDotStarRE = /^\*+\.\*+$/;
  15233. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  15234. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  15235. const dotStarRE = /^\.\*+$/;
  15236. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  15237. const starRE = /^\*+$/;
  15238. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  15239. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  15240. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  15241. const qmarksTestNocase = ([$0, ext = '']) => {
  15242. const noext = qmarksTestNoExt([$0]);
  15243. if (!ext)
  15244. return noext;
  15245. ext = ext.toLowerCase();
  15246. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  15247. };
  15248. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  15249. const noext = qmarksTestNoExtDot([$0]);
  15250. if (!ext)
  15251. return noext;
  15252. ext = ext.toLowerCase();
  15253. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  15254. };
  15255. const qmarksTestDot = ([$0, ext = '']) => {
  15256. const noext = qmarksTestNoExtDot([$0]);
  15257. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  15258. };
  15259. const qmarksTest = ([$0, ext = '']) => {
  15260. const noext = qmarksTestNoExt([$0]);
  15261. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  15262. };
  15263. const qmarksTestNoExt = ([$0]) => {
  15264. const len = $0.length;
  15265. return (f) => f.length === len && !f.startsWith('.');
  15266. };
  15267. const qmarksTestNoExtDot = ([$0]) => {
  15268. const len = $0.length;
  15269. return (f) => f.length === len && f !== '.' && f !== '..';
  15270. };
  15271. /* c8 ignore start */
  15272. const defaultPlatform = (typeof process === 'object' && process
  15273. ? (typeof process.env === 'object' &&
  15274. process.env &&
  15275. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  15276. process.platform
  15277. : 'posix');
  15278. const path = {
  15279. win32: { sep: '\\' },
  15280. posix: { sep: '/' },
  15281. };
  15282. /* c8 ignore stop */
  15283. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  15284. minimatch.sep = sep;
  15285. const GLOBSTAR = Symbol('globstar **');
  15286. minimatch.GLOBSTAR = GLOBSTAR;
  15287. // any single thing other than /
  15288. // don't need to escape / when using new RegExp()
  15289. const qmark = '[^/]';
  15290. // * => any number of characters
  15291. const star = qmark + '*?';
  15292. // ** when dots are allowed. Anything goes, except .. and .
  15293. // not (^ or / followed by one or two dots followed by $ or /),
  15294. // followed by anything, any number of times.
  15295. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  15296. // not a ^ or / followed by a dot,
  15297. // followed by anything, any number of times.
  15298. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  15299. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  15300. minimatch.filter = filter;
  15301. const ext = (a, b = {}) => Object.assign({}, a, b);
  15302. const defaults = (def) => {
  15303. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  15304. return minimatch;
  15305. }
  15306. const orig = minimatch;
  15307. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  15308. return Object.assign(m, {
  15309. Minimatch: class Minimatch extends orig.Minimatch {
  15310. constructor(pattern, options = {}) {
  15311. super(pattern, ext(def, options));
  15312. }
  15313. static defaults(options) {
  15314. return orig.defaults(ext(def, options)).Minimatch;
  15315. }
  15316. },
  15317. AST: class AST extends orig.AST {
  15318. /* c8 ignore start */
  15319. constructor(type, parent, options = {}) {
  15320. super(type, parent, ext(def, options));
  15321. }
  15322. /* c8 ignore stop */
  15323. static fromGlob(pattern, options = {}) {
  15324. return orig.AST.fromGlob(pattern, ext(def, options));
  15325. }
  15326. },
  15327. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  15328. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  15329. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  15330. defaults: (options) => orig.defaults(ext(def, options)),
  15331. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  15332. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  15333. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  15334. sep: orig.sep,
  15335. GLOBSTAR: GLOBSTAR,
  15336. });
  15337. };
  15338. minimatch.defaults = defaults;
  15339. // Brace expansion:
  15340. // a{b,c}d -> abd acd
  15341. // a{b,}c -> abc ac
  15342. // a{0..3}d -> a0d a1d a2d a3d
  15343. // a{b,c{d,e}f}g -> abg acdfg acefg
  15344. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  15345. //
  15346. // Invalid sets are not expanded.
  15347. // a{2..}b -> a{2..}b
  15348. // a{b}c -> a{b}c
  15349. const braceExpand = (pattern, options = {}) => {
  15350. assertValidPattern(pattern);
  15351. // Thanks to Yeting Li <https://github.com/yetingli> for
  15352. // improving this regexp to avoid a ReDOS vulnerability.
  15353. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  15354. // shortcut. no need to expand.
  15355. return [pattern];
  15356. }
  15357. return expand$1(pattern);
  15358. };
  15359. minimatch.braceExpand = braceExpand;
  15360. // parse a component of the expanded set.
  15361. // At this point, no pattern may contain "/" in it
  15362. // so we're going to return a 2d array, where each entry is the full
  15363. // pattern, split on '/', and then turned into a regular expression.
  15364. // A regexp is made at the end which joins each array with an
  15365. // escaped /, and another full one which joins each regexp with |.
  15366. //
  15367. // Following the lead of Bash 4.1, note that "**" only has special meaning
  15368. // when it is the *only* thing in a path portion. Otherwise, any series
  15369. // of * is equivalent to a single *. Globstar behavior is enabled by
  15370. // default, and can be disabled by setting options.noglobstar.
  15371. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  15372. minimatch.makeRe = makeRe;
  15373. const match = (list, pattern, options = {}) => {
  15374. const mm = new Minimatch(pattern, options);
  15375. list = list.filter(f => mm.match(f));
  15376. if (mm.options.nonull && !list.length) {
  15377. list.push(pattern);
  15378. }
  15379. return list;
  15380. };
  15381. minimatch.match = match;
  15382. // replace stuff like \* with *
  15383. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  15384. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  15385. class Minimatch {
  15386. options;
  15387. set;
  15388. pattern;
  15389. windowsPathsNoEscape;
  15390. nonegate;
  15391. negate;
  15392. comment;
  15393. empty;
  15394. preserveMultipleSlashes;
  15395. partial;
  15396. globSet;
  15397. globParts;
  15398. nocase;
  15399. isWindows;
  15400. platform;
  15401. windowsNoMagicRoot;
  15402. regexp;
  15403. constructor(pattern, options = {}) {
  15404. assertValidPattern(pattern);
  15405. options = options || {};
  15406. this.options = options;
  15407. this.pattern = pattern;
  15408. this.platform = options.platform || defaultPlatform;
  15409. this.isWindows = this.platform === 'win32';
  15410. this.windowsPathsNoEscape =
  15411. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  15412. if (this.windowsPathsNoEscape) {
  15413. this.pattern = this.pattern.replace(/\\/g, '/');
  15414. }
  15415. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  15416. this.regexp = null;
  15417. this.negate = false;
  15418. this.nonegate = !!options.nonegate;
  15419. this.comment = false;
  15420. this.empty = false;
  15421. this.partial = !!options.partial;
  15422. this.nocase = !!this.options.nocase;
  15423. this.windowsNoMagicRoot =
  15424. options.windowsNoMagicRoot !== undefined
  15425. ? options.windowsNoMagicRoot
  15426. : !!(this.isWindows && this.nocase);
  15427. this.globSet = [];
  15428. this.globParts = [];
  15429. this.set = [];
  15430. // make the set of regexps etc.
  15431. this.make();
  15432. }
  15433. hasMagic() {
  15434. if (this.options.magicalBraces && this.set.length > 1) {
  15435. return true;
  15436. }
  15437. for (const pattern of this.set) {
  15438. for (const part of pattern) {
  15439. if (typeof part !== 'string')
  15440. return true;
  15441. }
  15442. }
  15443. return false;
  15444. }
  15445. debug(..._) { }
  15446. make() {
  15447. const pattern = this.pattern;
  15448. const options = this.options;
  15449. // empty patterns and comments match nothing.
  15450. if (!options.nocomment && pattern.charAt(0) === '#') {
  15451. this.comment = true;
  15452. return;
  15453. }
  15454. if (!pattern) {
  15455. this.empty = true;
  15456. return;
  15457. }
  15458. // step 1: figure out negation, etc.
  15459. this.parseNegate();
  15460. // step 2: expand braces
  15461. this.globSet = [...new Set(this.braceExpand())];
  15462. if (options.debug) {
  15463. this.debug = (...args) => console.error(...args);
  15464. }
  15465. this.debug(this.pattern, this.globSet);
  15466. // step 3: now we have a set, so turn each one into a series of
  15467. // path-portion matching patterns.
  15468. // These will be regexps, except in the case of "**", which is
  15469. // set to the GLOBSTAR object for globstar behavior,
  15470. // and will not contain any / characters
  15471. //
  15472. // First, we preprocess to make the glob pattern sets a bit simpler
  15473. // and deduped. There are some perf-killing patterns that can cause
  15474. // problems with a glob walk, but we can simplify them down a bit.
  15475. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  15476. this.globParts = this.preprocess(rawGlobParts);
  15477. this.debug(this.pattern, this.globParts);
  15478. // glob --> regexps
  15479. let set = this.globParts.map((s, _, __) => {
  15480. if (this.isWindows && this.windowsNoMagicRoot) {
  15481. // check if it's a drive or unc path.
  15482. const isUNC = s[0] === '' &&
  15483. s[1] === '' &&
  15484. (s[2] === '?' || !globMagic.test(s[2])) &&
  15485. !globMagic.test(s[3]);
  15486. const isDrive = /^[a-z]:/i.test(s[0]);
  15487. if (isUNC) {
  15488. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  15489. }
  15490. else if (isDrive) {
  15491. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  15492. }
  15493. }
  15494. return s.map(ss => this.parse(ss));
  15495. });
  15496. this.debug(this.pattern, set);
  15497. // filter out everything that didn't compile properly.
  15498. this.set = set.filter(s => s.indexOf(false) === -1);
  15499. // do not treat the ? in UNC paths as magic
  15500. if (this.isWindows) {
  15501. for (let i = 0; i < this.set.length; i++) {
  15502. const p = this.set[i];
  15503. if (p[0] === '' &&
  15504. p[1] === '' &&
  15505. this.globParts[i][2] === '?' &&
  15506. typeof p[3] === 'string' &&
  15507. /^[a-z]:$/i.test(p[3])) {
  15508. p[2] = '?';
  15509. }
  15510. }
  15511. }
  15512. this.debug(this.pattern, this.set);
  15513. }
  15514. // various transforms to equivalent pattern sets that are
  15515. // faster to process in a filesystem walk. The goal is to
  15516. // eliminate what we can, and push all ** patterns as far
  15517. // to the right as possible, even if it increases the number
  15518. // of patterns that we have to process.
  15519. preprocess(globParts) {
  15520. // if we're not in globstar mode, then turn all ** into *
  15521. if (this.options.noglobstar) {
  15522. for (let i = 0; i < globParts.length; i++) {
  15523. for (let j = 0; j < globParts[i].length; j++) {
  15524. if (globParts[i][j] === '**') {
  15525. globParts[i][j] = '*';
  15526. }
  15527. }
  15528. }
  15529. }
  15530. const { optimizationLevel = 1 } = this.options;
  15531. if (optimizationLevel >= 2) {
  15532. // aggressive optimization for the purpose of fs walking
  15533. globParts = this.firstPhasePreProcess(globParts);
  15534. globParts = this.secondPhasePreProcess(globParts);
  15535. }
  15536. else if (optimizationLevel >= 1) {
  15537. // just basic optimizations to remove some .. parts
  15538. globParts = this.levelOneOptimize(globParts);
  15539. }
  15540. else {
  15541. // just collapse multiple ** portions into one
  15542. globParts = this.adjascentGlobstarOptimize(globParts);
  15543. }
  15544. return globParts;
  15545. }
  15546. // just get rid of adjascent ** portions
  15547. adjascentGlobstarOptimize(globParts) {
  15548. return globParts.map(parts => {
  15549. let gs = -1;
  15550. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  15551. let i = gs;
  15552. while (parts[i + 1] === '**') {
  15553. i++;
  15554. }
  15555. if (i !== gs) {
  15556. parts.splice(gs, i - gs);
  15557. }
  15558. }
  15559. return parts;
  15560. });
  15561. }
  15562. // get rid of adjascent ** and resolve .. portions
  15563. levelOneOptimize(globParts) {
  15564. return globParts.map(parts => {
  15565. parts = parts.reduce((set, part) => {
  15566. const prev = set[set.length - 1];
  15567. if (part === '**' && prev === '**') {
  15568. return set;
  15569. }
  15570. if (part === '..') {
  15571. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  15572. set.pop();
  15573. return set;
  15574. }
  15575. }
  15576. set.push(part);
  15577. return set;
  15578. }, []);
  15579. return parts.length === 0 ? [''] : parts;
  15580. });
  15581. }
  15582. levelTwoFileOptimize(parts) {
  15583. if (!Array.isArray(parts)) {
  15584. parts = this.slashSplit(parts);
  15585. }
  15586. let didSomething = false;
  15587. do {
  15588. didSomething = false;
  15589. // <pre>/<e>/<rest> -> <pre>/<rest>
  15590. if (!this.preserveMultipleSlashes) {
  15591. for (let i = 1; i < parts.length - 1; i++) {
  15592. const p = parts[i];
  15593. // don't squeeze out UNC patterns
  15594. if (i === 1 && p === '' && parts[0] === '')
  15595. continue;
  15596. if (p === '.' || p === '') {
  15597. didSomething = true;
  15598. parts.splice(i, 1);
  15599. i--;
  15600. }
  15601. }
  15602. if (parts[0] === '.' &&
  15603. parts.length === 2 &&
  15604. (parts[1] === '.' || parts[1] === '')) {
  15605. didSomething = true;
  15606. parts.pop();
  15607. }
  15608. }
  15609. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15610. let dd = 0;
  15611. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  15612. const p = parts[dd - 1];
  15613. if (p && p !== '.' && p !== '..' && p !== '**') {
  15614. didSomething = true;
  15615. parts.splice(dd - 1, 2);
  15616. dd -= 2;
  15617. }
  15618. }
  15619. } while (didSomething);
  15620. return parts.length === 0 ? [''] : parts;
  15621. }
  15622. // First phase: single-pattern processing
  15623. // <pre> is 1 or more portions
  15624. // <rest> is 1 or more portions
  15625. // <p> is any portion other than ., .., '', or **
  15626. // <e> is . or ''
  15627. //
  15628. // **/.. is *brutal* for filesystem walking performance, because
  15629. // it effectively resets the recursive walk each time it occurs,
  15630. // and ** cannot be reduced out by a .. pattern part like a regexp
  15631. // or most strings (other than .., ., and '') can be.
  15632. //
  15633. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  15634. // <pre>/<e>/<rest> -> <pre>/<rest>
  15635. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15636. // **/**/<rest> -> **/<rest>
  15637. //
  15638. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  15639. // this WOULD be allowed if ** did follow symlinks, or * didn't
  15640. firstPhasePreProcess(globParts) {
  15641. let didSomething = false;
  15642. do {
  15643. didSomething = false;
  15644. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  15645. for (let parts of globParts) {
  15646. let gs = -1;
  15647. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  15648. let gss = gs;
  15649. while (parts[gss + 1] === '**') {
  15650. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  15651. gss++;
  15652. }
  15653. // eg, if gs is 2 and gss is 4, that means we have 3 **
  15654. // parts, and can remove 2 of them.
  15655. if (gss > gs) {
  15656. parts.splice(gs + 1, gss - gs);
  15657. }
  15658. let next = parts[gs + 1];
  15659. const p = parts[gs + 2];
  15660. const p2 = parts[gs + 3];
  15661. if (next !== '..')
  15662. continue;
  15663. if (!p ||
  15664. p === '.' ||
  15665. p === '..' ||
  15666. !p2 ||
  15667. p2 === '.' ||
  15668. p2 === '..') {
  15669. continue;
  15670. }
  15671. didSomething = true;
  15672. // edit parts in place, and push the new one
  15673. parts.splice(gs, 1);
  15674. const other = parts.slice(0);
  15675. other[gs] = '**';
  15676. globParts.push(other);
  15677. gs--;
  15678. }
  15679. // <pre>/<e>/<rest> -> <pre>/<rest>
  15680. if (!this.preserveMultipleSlashes) {
  15681. for (let i = 1; i < parts.length - 1; i++) {
  15682. const p = parts[i];
  15683. // don't squeeze out UNC patterns
  15684. if (i === 1 && p === '' && parts[0] === '')
  15685. continue;
  15686. if (p === '.' || p === '') {
  15687. didSomething = true;
  15688. parts.splice(i, 1);
  15689. i--;
  15690. }
  15691. }
  15692. if (parts[0] === '.' &&
  15693. parts.length === 2 &&
  15694. (parts[1] === '.' || parts[1] === '')) {
  15695. didSomething = true;
  15696. parts.pop();
  15697. }
  15698. }
  15699. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15700. let dd = 0;
  15701. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  15702. const p = parts[dd - 1];
  15703. if (p && p !== '.' && p !== '..' && p !== '**') {
  15704. didSomething = true;
  15705. const needDot = dd === 1 && parts[dd + 1] === '**';
  15706. const splin = needDot ? ['.'] : [];
  15707. parts.splice(dd - 1, 2, ...splin);
  15708. if (parts.length === 0)
  15709. parts.push('');
  15710. dd -= 2;
  15711. }
  15712. }
  15713. }
  15714. } while (didSomething);
  15715. return globParts;
  15716. }
  15717. // second phase: multi-pattern dedupes
  15718. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  15719. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  15720. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  15721. //
  15722. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  15723. // ^-- not valid because ** doens't follow symlinks
  15724. secondPhasePreProcess(globParts) {
  15725. for (let i = 0; i < globParts.length - 1; i++) {
  15726. for (let j = i + 1; j < globParts.length; j++) {
  15727. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  15728. if (!matched)
  15729. continue;
  15730. globParts[i] = matched;
  15731. globParts[j] = [];
  15732. }
  15733. }
  15734. return globParts.filter(gs => gs.length);
  15735. }
  15736. partsMatch(a, b, emptyGSMatch = false) {
  15737. let ai = 0;
  15738. let bi = 0;
  15739. let result = [];
  15740. let which = '';
  15741. while (ai < a.length && bi < b.length) {
  15742. if (a[ai] === b[bi]) {
  15743. result.push(which === 'b' ? b[bi] : a[ai]);
  15744. ai++;
  15745. bi++;
  15746. }
  15747. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  15748. result.push(a[ai]);
  15749. ai++;
  15750. }
  15751. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  15752. result.push(b[bi]);
  15753. bi++;
  15754. }
  15755. else if (a[ai] === '*' &&
  15756. b[bi] &&
  15757. (this.options.dot || !b[bi].startsWith('.')) &&
  15758. b[bi] !== '**') {
  15759. if (which === 'b')
  15760. return false;
  15761. which = 'a';
  15762. result.push(a[ai]);
  15763. ai++;
  15764. bi++;
  15765. }
  15766. else if (b[bi] === '*' &&
  15767. a[ai] &&
  15768. (this.options.dot || !a[ai].startsWith('.')) &&
  15769. a[ai] !== '**') {
  15770. if (which === 'a')
  15771. return false;
  15772. which = 'b';
  15773. result.push(b[bi]);
  15774. ai++;
  15775. bi++;
  15776. }
  15777. else {
  15778. return false;
  15779. }
  15780. }
  15781. // if we fall out of the loop, it means they two are identical
  15782. // as long as their lengths match
  15783. return a.length === b.length && result;
  15784. }
  15785. parseNegate() {
  15786. if (this.nonegate)
  15787. return;
  15788. const pattern = this.pattern;
  15789. let negate = false;
  15790. let negateOffset = 0;
  15791. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  15792. negate = !negate;
  15793. negateOffset++;
  15794. }
  15795. if (negateOffset)
  15796. this.pattern = pattern.slice(negateOffset);
  15797. this.negate = negate;
  15798. }
  15799. // set partial to true to test if, for example,
  15800. // "/a/b" matches the start of "/*/b/*/d"
  15801. // Partial means, if you run out of file before you run
  15802. // out of pattern, then that's fine, as long as all
  15803. // the parts match.
  15804. matchOne(file, pattern, partial = false) {
  15805. const options = this.options;
  15806. // UNC paths like //?/X:/... can match X:/... and vice versa
  15807. // Drive letters in absolute drive or unc paths are always compared
  15808. // case-insensitively.
  15809. if (this.isWindows) {
  15810. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  15811. const fileUNC = !fileDrive &&
  15812. file[0] === '' &&
  15813. file[1] === '' &&
  15814. file[2] === '?' &&
  15815. /^[a-z]:$/i.test(file[3]);
  15816. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  15817. const patternUNC = !patternDrive &&
  15818. pattern[0] === '' &&
  15819. pattern[1] === '' &&
  15820. pattern[2] === '?' &&
  15821. typeof pattern[3] === 'string' &&
  15822. /^[a-z]:$/i.test(pattern[3]);
  15823. const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
  15824. const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
  15825. if (typeof fdi === 'number' && typeof pdi === 'number') {
  15826. const [fd, pd] = [file[fdi], pattern[pdi]];
  15827. if (fd.toLowerCase() === pd.toLowerCase()) {
  15828. pattern[pdi] = fd;
  15829. if (pdi > fdi) {
  15830. pattern = pattern.slice(pdi);
  15831. }
  15832. else if (fdi > pdi) {
  15833. file = file.slice(fdi);
  15834. }
  15835. }
  15836. }
  15837. }
  15838. // resolve and reduce . and .. portions in the file as well.
  15839. // dont' need to do the second phase, because it's only one string[]
  15840. const { optimizationLevel = 1 } = this.options;
  15841. if (optimizationLevel >= 2) {
  15842. file = this.levelTwoFileOptimize(file);
  15843. }
  15844. this.debug('matchOne', this, { file, pattern });
  15845. this.debug('matchOne', file.length, pattern.length);
  15846. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  15847. this.debug('matchOne loop');
  15848. var p = pattern[pi];
  15849. var f = file[fi];
  15850. this.debug(pattern, p, f);
  15851. // should be impossible.
  15852. // some invalid regexp stuff in the set.
  15853. /* c8 ignore start */
  15854. if (p === false) {
  15855. return false;
  15856. }
  15857. /* c8 ignore stop */
  15858. if (p === GLOBSTAR) {
  15859. this.debug('GLOBSTAR', [pattern, p, f]);
  15860. // "**"
  15861. // a/**/b/**/c would match the following:
  15862. // a/b/x/y/z/c
  15863. // a/x/y/z/b/c
  15864. // a/b/x/b/x/c
  15865. // a/b/c
  15866. // To do this, take the rest of the pattern after
  15867. // the **, and see if it would match the file remainder.
  15868. // If so, return success.
  15869. // If not, the ** "swallows" a segment, and try again.
  15870. // This is recursively awful.
  15871. //
  15872. // a/**/b/**/c matching a/b/x/y/z/c
  15873. // - a matches a
  15874. // - doublestar
  15875. // - matchOne(b/x/y/z/c, b/**/c)
  15876. // - b matches b
  15877. // - doublestar
  15878. // - matchOne(x/y/z/c, c) -> no
  15879. // - matchOne(y/z/c, c) -> no
  15880. // - matchOne(z/c, c) -> no
  15881. // - matchOne(c, c) yes, hit
  15882. var fr = fi;
  15883. var pr = pi + 1;
  15884. if (pr === pl) {
  15885. this.debug('** at the end');
  15886. // a ** at the end will just swallow the rest.
  15887. // We have found a match.
  15888. // however, it will not swallow /.x, unless
  15889. // options.dot is set.
  15890. // . and .. are *never* matched by **, for explosively
  15891. // exponential reasons.
  15892. for (; fi < fl; fi++) {
  15893. if (file[fi] === '.' ||
  15894. file[fi] === '..' ||
  15895. (!options.dot && file[fi].charAt(0) === '.'))
  15896. return false;
  15897. }
  15898. return true;
  15899. }
  15900. // ok, let's see if we can swallow whatever we can.
  15901. while (fr < fl) {
  15902. var swallowee = file[fr];
  15903. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  15904. // XXX remove this slice. Just pass the start index.
  15905. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  15906. this.debug('globstar found match!', fr, fl, swallowee);
  15907. // found a match.
  15908. return true;
  15909. }
  15910. else {
  15911. // can't swallow "." or ".." ever.
  15912. // can only swallow ".foo" when explicitly asked.
  15913. if (swallowee === '.' ||
  15914. swallowee === '..' ||
  15915. (!options.dot && swallowee.charAt(0) === '.')) {
  15916. this.debug('dot detected!', file, fr, pattern, pr);
  15917. break;
  15918. }
  15919. // ** swallows a segment, and continue.
  15920. this.debug('globstar swallow a segment, and continue');
  15921. fr++;
  15922. }
  15923. }
  15924. // no match was found.
  15925. // However, in partial mode, we can't say this is necessarily over.
  15926. /* c8 ignore start */
  15927. if (partial) {
  15928. // ran out of file
  15929. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  15930. if (fr === fl) {
  15931. return true;
  15932. }
  15933. }
  15934. /* c8 ignore stop */
  15935. return false;
  15936. }
  15937. // something other than **
  15938. // non-magic patterns just have to match exactly
  15939. // patterns with magic have been turned into regexps.
  15940. let hit;
  15941. if (typeof p === 'string') {
  15942. hit = f === p;
  15943. this.debug('string match', p, f, hit);
  15944. }
  15945. else {
  15946. hit = p.test(f);
  15947. this.debug('pattern match', p, f, hit);
  15948. }
  15949. if (!hit)
  15950. return false;
  15951. }
  15952. // Note: ending in / means that we'll get a final ""
  15953. // at the end of the pattern. This can only match a
  15954. // corresponding "" at the end of the file.
  15955. // If the file ends in /, then it can only match a
  15956. // a pattern that ends in /, unless the pattern just
  15957. // doesn't have any more for it. But, a/b/ should *not*
  15958. // match "a/b/*", even though "" matches against the
  15959. // [^/]*? pattern, except in partial mode, where it might
  15960. // simply not be reached yet.
  15961. // However, a/b/ should still satisfy a/*
  15962. // now either we fell off the end of the pattern, or we're done.
  15963. if (fi === fl && pi === pl) {
  15964. // ran out of pattern and filename at the same time.
  15965. // an exact hit!
  15966. return true;
  15967. }
  15968. else if (fi === fl) {
  15969. // ran out of file, but still had pattern left.
  15970. // this is ok if we're doing the match as part of
  15971. // a glob fs traversal.
  15972. return partial;
  15973. }
  15974. else if (pi === pl) {
  15975. // ran out of pattern, still have file left.
  15976. // this is only acceptable if we're on the very last
  15977. // empty segment of a file with a trailing slash.
  15978. // a/* should match a/b/
  15979. return fi === fl - 1 && file[fi] === '';
  15980. /* c8 ignore start */
  15981. }
  15982. else {
  15983. // should be unreachable.
  15984. throw new Error('wtf?');
  15985. }
  15986. /* c8 ignore stop */
  15987. }
  15988. braceExpand() {
  15989. return braceExpand(this.pattern, this.options);
  15990. }
  15991. parse(pattern) {
  15992. assertValidPattern(pattern);
  15993. const options = this.options;
  15994. // shortcuts
  15995. if (pattern === '**')
  15996. return GLOBSTAR;
  15997. if (pattern === '')
  15998. return '';
  15999. // far and away, the most common glob pattern parts are
  16000. // *, *.*, and *.<ext> Add a fast check method for those.
  16001. let m;
  16002. let fastTest = null;
  16003. if ((m = pattern.match(starRE))) {
  16004. fastTest = options.dot ? starTestDot : starTest;
  16005. }
  16006. else if ((m = pattern.match(starDotExtRE))) {
  16007. fastTest = (options.nocase
  16008. ? options.dot
  16009. ? starDotExtTestNocaseDot
  16010. : starDotExtTestNocase
  16011. : options.dot
  16012. ? starDotExtTestDot
  16013. : starDotExtTest)(m[1]);
  16014. }
  16015. else if ((m = pattern.match(qmarksRE))) {
  16016. fastTest = (options.nocase
  16017. ? options.dot
  16018. ? qmarksTestNocaseDot
  16019. : qmarksTestNocase
  16020. : options.dot
  16021. ? qmarksTestDot
  16022. : qmarksTest)(m);
  16023. }
  16024. else if ((m = pattern.match(starDotStarRE))) {
  16025. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  16026. }
  16027. else if ((m = pattern.match(dotStarRE))) {
  16028. fastTest = dotStarTest;
  16029. }
  16030. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  16031. if (fastTest && typeof re === 'object') {
  16032. // Avoids overriding in frozen environments
  16033. Reflect.defineProperty(re, 'test', { value: fastTest });
  16034. }
  16035. return re;
  16036. }
  16037. makeRe() {
  16038. if (this.regexp || this.regexp === false)
  16039. return this.regexp;
  16040. // at this point, this.set is a 2d array of partial
  16041. // pattern strings, or "**".
  16042. //
  16043. // It's better to use .match(). This function shouldn't
  16044. // be used, really, but it's pretty convenient sometimes,
  16045. // when you just want to work with a regex.
  16046. const set = this.set;
  16047. if (!set.length) {
  16048. this.regexp = false;
  16049. return this.regexp;
  16050. }
  16051. const options = this.options;
  16052. const twoStar = options.noglobstar
  16053. ? star
  16054. : options.dot
  16055. ? twoStarDot
  16056. : twoStarNoDot;
  16057. const flags = new Set(options.nocase ? ['i'] : []);
  16058. // regexpify non-globstar patterns
  16059. // if ** is only item, then we just do one twoStar
  16060. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  16061. // if ** is last, append (\/twoStar|) to previous
  16062. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  16063. // then filter out GLOBSTAR symbols
  16064. let re = set
  16065. .map(pattern => {
  16066. const pp = pattern.map(p => {
  16067. if (p instanceof RegExp) {
  16068. for (const f of p.flags.split(''))
  16069. flags.add(f);
  16070. }
  16071. return typeof p === 'string'
  16072. ? regExpEscape(p)
  16073. : p === GLOBSTAR
  16074. ? GLOBSTAR
  16075. : p._src;
  16076. });
  16077. pp.forEach((p, i) => {
  16078. const next = pp[i + 1];
  16079. const prev = pp[i - 1];
  16080. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  16081. return;
  16082. }
  16083. if (prev === undefined) {
  16084. if (next !== undefined && next !== GLOBSTAR) {
  16085. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  16086. }
  16087. else {
  16088. pp[i] = twoStar;
  16089. }
  16090. }
  16091. else if (next === undefined) {
  16092. pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
  16093. }
  16094. else if (next !== GLOBSTAR) {
  16095. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  16096. pp[i + 1] = GLOBSTAR;
  16097. }
  16098. });
  16099. return pp.filter(p => p !== GLOBSTAR).join('/');
  16100. })
  16101. .join('|');
  16102. // need to wrap in parens if we had more than one thing with |,
  16103. // otherwise only the first will be anchored to ^ and the last to $
  16104. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  16105. // must match entire pattern
  16106. // ending in a * or ** will make it less strict.
  16107. re = '^' + open + re + close + '$';
  16108. // can match anything, as long as it's not this.
  16109. if (this.negate)
  16110. re = '^(?!' + re + ').+$';
  16111. try {
  16112. this.regexp = new RegExp(re, [...flags].join(''));
  16113. /* c8 ignore start */
  16114. }
  16115. catch (ex) {
  16116. // should be impossible
  16117. this.regexp = false;
  16118. }
  16119. /* c8 ignore stop */
  16120. return this.regexp;
  16121. }
  16122. slashSplit(p) {
  16123. // if p starts with // on windows, we preserve that
  16124. // so that UNC paths aren't broken. Otherwise, any number of
  16125. // / characters are coalesced into one, unless
  16126. // preserveMultipleSlashes is set to true.
  16127. if (this.preserveMultipleSlashes) {
  16128. return p.split('/');
  16129. }
  16130. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  16131. // add an extra '' for the one we lose
  16132. return ['', ...p.split(/\/+/)];
  16133. }
  16134. else {
  16135. return p.split(/\/+/);
  16136. }
  16137. }
  16138. match(f, partial = this.partial) {
  16139. this.debug('match', f, this.pattern);
  16140. // short-circuit in the case of busted things.
  16141. // comments, etc.
  16142. if (this.comment) {
  16143. return false;
  16144. }
  16145. if (this.empty) {
  16146. return f === '';
  16147. }
  16148. if (f === '/' && partial) {
  16149. return true;
  16150. }
  16151. const options = this.options;
  16152. // windows: need to use /, not \
  16153. if (this.isWindows) {
  16154. f = f.split('\\').join('/');
  16155. }
  16156. // treat the test path as a set of pathparts.
  16157. const ff = this.slashSplit(f);
  16158. this.debug(this.pattern, 'split', ff);
  16159. // just ONE of the pattern sets in this.set needs to match
  16160. // in order for it to be valid. If negating, then just one
  16161. // match means that we have failed.
  16162. // Either way, return on the first hit.
  16163. const set = this.set;
  16164. this.debug(this.pattern, 'set', set);
  16165. // Find the basename of the path by looking for the last non-empty segment
  16166. let filename = ff[ff.length - 1];
  16167. if (!filename) {
  16168. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  16169. filename = ff[i];
  16170. }
  16171. }
  16172. for (let i = 0; i < set.length; i++) {
  16173. const pattern = set[i];
  16174. let file = ff;
  16175. if (options.matchBase && pattern.length === 1) {
  16176. file = [filename];
  16177. }
  16178. const hit = this.matchOne(file, pattern, partial);
  16179. if (hit) {
  16180. if (options.flipNegate) {
  16181. return true;
  16182. }
  16183. return !this.negate;
  16184. }
  16185. }
  16186. // didn't get any hits. this is success if it's a negative
  16187. // pattern, failure otherwise.
  16188. if (options.flipNegate) {
  16189. return false;
  16190. }
  16191. return this.negate;
  16192. }
  16193. static defaults(def) {
  16194. return minimatch.defaults(def).Minimatch;
  16195. }
  16196. }
  16197. /* c8 ignore stop */
  16198. minimatch.AST = AST;
  16199. minimatch.Minimatch = Minimatch;
  16200. minimatch.escape = escape;
  16201. minimatch.unescape = unescape;
  16202. class TypeScope {
  16203. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  16204. this.filename = filename;
  16205. this.source = source;
  16206. this.offset = offset;
  16207. this.imports = imports;
  16208. this.types = types;
  16209. this.declares = declares;
  16210. this.isGenericScope = false;
  16211. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  16212. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  16213. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  16214. }
  16215. }
  16216. function resolveTypeElements(ctx, node, scope, typeParameters) {
  16217. const canCache = !typeParameters;
  16218. if (canCache && node._resolvedElements) {
  16219. return node._resolvedElements;
  16220. }
  16221. const resolved = innerResolveTypeElements(
  16222. ctx,
  16223. node,
  16224. node._ownerScope || scope || ctxToScope(ctx),
  16225. typeParameters
  16226. );
  16227. return canCache ? node._resolvedElements = resolved : resolved;
  16228. }
  16229. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  16230. var _a, _b;
  16231. switch (node.type) {
  16232. case "TSTypeLiteral":
  16233. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  16234. case "TSInterfaceDeclaration":
  16235. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  16236. case "TSTypeAliasDeclaration":
  16237. case "TSParenthesizedType":
  16238. return resolveTypeElements(
  16239. ctx,
  16240. node.typeAnnotation,
  16241. scope,
  16242. typeParameters
  16243. );
  16244. case "TSFunctionType": {
  16245. return { props: {}, calls: [node] };
  16246. }
  16247. case "TSUnionType":
  16248. case "TSIntersectionType":
  16249. return mergeElements(
  16250. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  16251. node.type
  16252. );
  16253. case "TSMappedType":
  16254. return resolveMappedType(ctx, node, scope);
  16255. case "TSIndexedAccessType": {
  16256. const types = resolveIndexType(ctx, node, scope);
  16257. return mergeElements(
  16258. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  16259. "TSUnionType"
  16260. );
  16261. }
  16262. case "TSExpressionWithTypeArguments":
  16263. case "TSTypeReference": {
  16264. const typeName = getReferenceName(node);
  16265. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  16266. return resolveExtractPropTypes(
  16267. resolveTypeElements(
  16268. ctx,
  16269. node.typeParameters.params[0],
  16270. scope,
  16271. typeParameters
  16272. ),
  16273. scope
  16274. );
  16275. }
  16276. const resolved = resolveTypeReference(ctx, node, scope);
  16277. if (resolved) {
  16278. let typeParams;
  16279. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  16280. typeParams = /* @__PURE__ */ Object.create(null);
  16281. resolved.typeParameters.params.forEach((p, i) => {
  16282. let param = typeParameters && typeParameters[p.name];
  16283. if (!param)
  16284. param = node.typeParameters.params[i];
  16285. typeParams[p.name] = param;
  16286. });
  16287. }
  16288. return resolveTypeElements(
  16289. ctx,
  16290. resolved,
  16291. resolved._ownerScope,
  16292. typeParams
  16293. );
  16294. } else {
  16295. if (typeof typeName === "string") {
  16296. if (typeParameters && typeParameters[typeName]) {
  16297. return resolveTypeElements(
  16298. ctx,
  16299. typeParameters[typeName],
  16300. scope,
  16301. typeParameters
  16302. );
  16303. }
  16304. if (
  16305. // @ts-expect-error
  16306. SupportedBuiltinsSet.has(typeName)
  16307. ) {
  16308. return resolveBuiltin(
  16309. ctx,
  16310. node,
  16311. typeName,
  16312. scope,
  16313. typeParameters
  16314. );
  16315. } else if (typeName === "ReturnType" && node.typeParameters) {
  16316. const ret = resolveReturnType(
  16317. ctx,
  16318. node.typeParameters.params[0],
  16319. scope
  16320. );
  16321. if (ret) {
  16322. return resolveTypeElements(ctx, ret, scope);
  16323. }
  16324. }
  16325. }
  16326. return ctx.error(
  16327. `Unresolvable type reference or unsupported built-in utility type`,
  16328. node,
  16329. scope
  16330. );
  16331. }
  16332. }
  16333. case "TSImportType": {
  16334. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  16335. return resolveExtractPropTypes(
  16336. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  16337. scope
  16338. );
  16339. }
  16340. const sourceScope = importSourceToScope(
  16341. ctx,
  16342. node.argument,
  16343. scope,
  16344. node.argument.value
  16345. );
  16346. const resolved = resolveTypeReference(ctx, node, sourceScope);
  16347. if (resolved) {
  16348. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  16349. }
  16350. break;
  16351. }
  16352. case "TSTypeQuery":
  16353. {
  16354. const resolved = resolveTypeReference(ctx, node, scope);
  16355. if (resolved) {
  16356. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  16357. }
  16358. }
  16359. break;
  16360. }
  16361. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  16362. }
  16363. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  16364. const res = { props: {} };
  16365. for (const e of elements) {
  16366. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  16367. if (typeParameters) {
  16368. scope = createChildScope(scope);
  16369. scope.isGenericScope = true;
  16370. Object.assign(scope.types, typeParameters);
  16371. }
  16372. e._ownerScope = scope;
  16373. const name = getId(e.key);
  16374. if (name && !e.computed) {
  16375. res.props[name] = e;
  16376. } else if (e.key.type === "TemplateLiteral") {
  16377. for (const key of resolveTemplateKeys(ctx, e.key, scope)) {
  16378. res.props[key] = e;
  16379. }
  16380. } else {
  16381. ctx.error(
  16382. `Unsupported computed key in type referenced by a macro`,
  16383. e.key,
  16384. scope
  16385. );
  16386. }
  16387. } else if (e.type === "TSCallSignatureDeclaration") {
  16388. (res.calls || (res.calls = [])).push(e);
  16389. }
  16390. }
  16391. return res;
  16392. }
  16393. function mergeElements(maps, type) {
  16394. if (maps.length === 1)
  16395. return maps[0];
  16396. const res = { props: {} };
  16397. const { props: baseProps } = res;
  16398. for (const { props, calls } of maps) {
  16399. for (const key in props) {
  16400. if (!shared.hasOwn(baseProps, key)) {
  16401. baseProps[key] = props[key];
  16402. } else {
  16403. baseProps[key] = createProperty(
  16404. baseProps[key].key,
  16405. {
  16406. type,
  16407. // @ts-expect-error
  16408. types: [baseProps[key], props[key]]
  16409. },
  16410. baseProps[key]._ownerScope,
  16411. baseProps[key].optional || props[key].optional
  16412. );
  16413. }
  16414. }
  16415. if (calls) {
  16416. (res.calls || (res.calls = [])).push(...calls);
  16417. }
  16418. }
  16419. return res;
  16420. }
  16421. function createProperty(key, typeAnnotation, scope, optional) {
  16422. return {
  16423. type: "TSPropertySignature",
  16424. key,
  16425. kind: "get",
  16426. optional,
  16427. typeAnnotation: {
  16428. type: "TSTypeAnnotation",
  16429. typeAnnotation
  16430. },
  16431. _ownerScope: scope
  16432. };
  16433. }
  16434. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  16435. const base = typeElementsToMap(
  16436. ctx,
  16437. node.body.body,
  16438. node._ownerScope,
  16439. typeParameters
  16440. );
  16441. if (node.extends) {
  16442. for (const ext of node.extends) {
  16443. if (ext.leadingComments && ext.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  16444. continue;
  16445. }
  16446. try {
  16447. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  16448. for (const key in props) {
  16449. if (!shared.hasOwn(base.props, key)) {
  16450. base.props[key] = props[key];
  16451. }
  16452. }
  16453. if (calls) {
  16454. ;
  16455. (base.calls || (base.calls = [])).push(...calls);
  16456. }
  16457. } catch (e) {
  16458. ctx.error(
  16459. `Failed to resolve extends base type.
  16460. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  16461. interface Props extends /* @vue-ignore */ Base {}
  16462. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  16463. ext
  16464. );
  16465. }
  16466. }
  16467. }
  16468. return base;
  16469. }
  16470. function resolveMappedType(ctx, node, scope) {
  16471. const res = { props: {} };
  16472. const keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  16473. for (const key of keys) {
  16474. res.props[key] = createProperty(
  16475. {
  16476. type: "Identifier",
  16477. name: key
  16478. },
  16479. node.typeAnnotation,
  16480. scope,
  16481. !!node.optional
  16482. );
  16483. }
  16484. return res;
  16485. }
  16486. function resolveIndexType(ctx, node, scope) {
  16487. var _a, _b;
  16488. if (node.indexType.type === "TSNumberKeyword") {
  16489. return resolveArrayElementType(ctx, node.objectType, scope);
  16490. }
  16491. const { indexType, objectType } = node;
  16492. const types = [];
  16493. let keys;
  16494. let resolved;
  16495. if (indexType.type === "TSStringKeyword") {
  16496. resolved = resolveTypeElements(ctx, objectType, scope);
  16497. keys = Object.keys(resolved.props);
  16498. } else {
  16499. keys = resolveStringType(ctx, indexType, scope);
  16500. resolved = resolveTypeElements(ctx, objectType, scope);
  16501. }
  16502. for (const key of keys) {
  16503. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  16504. if (targetType) {
  16505. targetType._ownerScope = resolved.props[key]._ownerScope;
  16506. types.push(targetType);
  16507. }
  16508. }
  16509. return types;
  16510. }
  16511. function resolveArrayElementType(ctx, node, scope) {
  16512. if (node.type === "TSArrayType") {
  16513. return [node.elementType];
  16514. }
  16515. if (node.type === "TSTupleType") {
  16516. return node.elementTypes.map(
  16517. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  16518. );
  16519. }
  16520. if (node.type === "TSTypeReference") {
  16521. if (getReferenceName(node) === "Array" && node.typeParameters) {
  16522. return node.typeParameters.params;
  16523. } else {
  16524. const resolved = resolveTypeReference(ctx, node, scope);
  16525. if (resolved) {
  16526. return resolveArrayElementType(ctx, resolved, scope);
  16527. }
  16528. }
  16529. }
  16530. return ctx.error(
  16531. "Failed to resolve element type from target type",
  16532. node,
  16533. scope
  16534. );
  16535. }
  16536. function resolveStringType(ctx, node, scope) {
  16537. switch (node.type) {
  16538. case "StringLiteral":
  16539. return [node.value];
  16540. case "TSLiteralType":
  16541. return resolveStringType(ctx, node.literal, scope);
  16542. case "TSUnionType":
  16543. return node.types.map((t) => resolveStringType(ctx, t, scope)).flat();
  16544. case "TemplateLiteral": {
  16545. return resolveTemplateKeys(ctx, node, scope);
  16546. }
  16547. case "TSTypeReference": {
  16548. const resolved = resolveTypeReference(ctx, node, scope);
  16549. if (resolved) {
  16550. return resolveStringType(ctx, resolved, scope);
  16551. }
  16552. if (node.typeName.type === "Identifier") {
  16553. const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope);
  16554. switch (node.typeName.name) {
  16555. case "Extract":
  16556. return getParam(1);
  16557. case "Exclude": {
  16558. const excluded = getParam(1);
  16559. return getParam().filter((s) => !excluded.includes(s));
  16560. }
  16561. case "Uppercase":
  16562. return getParam().map((s) => s.toUpperCase());
  16563. case "Lowercase":
  16564. return getParam().map((s) => s.toLowerCase());
  16565. case "Capitalize":
  16566. return getParam().map(shared.capitalize);
  16567. case "Uncapitalize":
  16568. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  16569. default:
  16570. ctx.error(
  16571. "Unsupported type when resolving index type",
  16572. node.typeName,
  16573. scope
  16574. );
  16575. }
  16576. }
  16577. }
  16578. }
  16579. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  16580. }
  16581. function resolveTemplateKeys(ctx, node, scope) {
  16582. if (!node.expressions.length) {
  16583. return [node.quasis[0].value.raw];
  16584. }
  16585. const res = [];
  16586. const e = node.expressions[0];
  16587. const q = node.quasis[0];
  16588. const leading = q ? q.value.raw : ``;
  16589. const resolved = resolveStringType(ctx, e, scope);
  16590. const restResolved = resolveTemplateKeys(
  16591. ctx,
  16592. {
  16593. ...node,
  16594. expressions: node.expressions.slice(1),
  16595. quasis: q ? node.quasis.slice(1) : node.quasis
  16596. },
  16597. scope
  16598. );
  16599. for (const r of resolved) {
  16600. for (const rr of restResolved) {
  16601. res.push(leading + r + rr);
  16602. }
  16603. }
  16604. return res;
  16605. }
  16606. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  16607. "Partial",
  16608. "Required",
  16609. "Readonly",
  16610. "Pick",
  16611. "Omit"
  16612. ]);
  16613. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  16614. const t = resolveTypeElements(
  16615. ctx,
  16616. node.typeParameters.params[0],
  16617. scope,
  16618. typeParameters
  16619. );
  16620. switch (name) {
  16621. case "Partial": {
  16622. const res2 = { props: {}, calls: t.calls };
  16623. Object.keys(t.props).forEach((key) => {
  16624. res2.props[key] = { ...t.props[key], optional: true };
  16625. });
  16626. return res2;
  16627. }
  16628. case "Required": {
  16629. const res2 = { props: {}, calls: t.calls };
  16630. Object.keys(t.props).forEach((key) => {
  16631. res2.props[key] = { ...t.props[key], optional: false };
  16632. });
  16633. return res2;
  16634. }
  16635. case "Readonly":
  16636. return t;
  16637. case "Pick": {
  16638. const picked = resolveStringType(
  16639. ctx,
  16640. node.typeParameters.params[1],
  16641. scope
  16642. );
  16643. const res2 = { props: {}, calls: t.calls };
  16644. for (const key of picked) {
  16645. res2.props[key] = t.props[key];
  16646. }
  16647. return res2;
  16648. }
  16649. case "Omit":
  16650. const omitted = resolveStringType(
  16651. ctx,
  16652. node.typeParameters.params[1],
  16653. scope
  16654. );
  16655. const res = { props: {}, calls: t.calls };
  16656. for (const key in t.props) {
  16657. if (!omitted.includes(key)) {
  16658. res.props[key] = t.props[key];
  16659. }
  16660. }
  16661. return res;
  16662. }
  16663. }
  16664. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  16665. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  16666. if (canCache && node._resolvedReference) {
  16667. return node._resolvedReference;
  16668. }
  16669. const resolved = innerResolveTypeReference(
  16670. ctx,
  16671. scope || ctxToScope(ctx),
  16672. name || getReferenceName(node),
  16673. node,
  16674. onlyExported
  16675. );
  16676. return canCache ? node._resolvedReference = resolved : resolved;
  16677. }
  16678. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  16679. if (typeof name === "string") {
  16680. if (scope.imports[name]) {
  16681. return resolveTypeFromImport(ctx, node, name, scope);
  16682. } else {
  16683. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  16684. if (lookupSource[name]) {
  16685. return lookupSource[name];
  16686. } else {
  16687. const globalScopes = resolveGlobalScope(ctx);
  16688. if (globalScopes) {
  16689. for (const s of globalScopes) {
  16690. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  16691. if (src[name]) {
  16692. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  16693. return src[name];
  16694. }
  16695. }
  16696. }
  16697. }
  16698. }
  16699. } else {
  16700. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  16701. if (ns) {
  16702. if (ns.type !== "TSModuleDeclaration") {
  16703. ns = ns._ns;
  16704. }
  16705. if (ns) {
  16706. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  16707. return innerResolveTypeReference(
  16708. ctx,
  16709. childScope,
  16710. name.length > 2 ? name.slice(1) : name[name.length - 1],
  16711. node,
  16712. !ns.declare
  16713. );
  16714. }
  16715. }
  16716. }
  16717. }
  16718. function getReferenceName(node) {
  16719. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  16720. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  16721. return ref.name;
  16722. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  16723. return qualifiedNameToPath(ref);
  16724. } else {
  16725. return "default";
  16726. }
  16727. }
  16728. function qualifiedNameToPath(node) {
  16729. if (node.type === "Identifier") {
  16730. return [node.name];
  16731. } else {
  16732. return [...qualifiedNameToPath(node.left), node.right.name];
  16733. }
  16734. }
  16735. function resolveGlobalScope(ctx) {
  16736. if (ctx.options.globalTypeFiles) {
  16737. const fs = resolveFS(ctx);
  16738. if (!fs) {
  16739. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  16740. }
  16741. return ctx.options.globalTypeFiles.map(
  16742. (file) => fileToScope(ctx, normalizePath(file), true)
  16743. );
  16744. }
  16745. }
  16746. let ts;
  16747. let loadTS;
  16748. function registerTS(_loadTS) {
  16749. loadTS = () => {
  16750. try {
  16751. return _loadTS();
  16752. } catch (err) {
  16753. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  16754. throw new Error(
  16755. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.'
  16756. );
  16757. } else {
  16758. throw new Error(
  16759. "Failed to load TypeScript for resolving imported types."
  16760. );
  16761. }
  16762. }
  16763. };
  16764. }
  16765. function resolveFS(ctx) {
  16766. if (ctx.fs) {
  16767. return ctx.fs;
  16768. }
  16769. if (!ts && loadTS) {
  16770. ts = loadTS();
  16771. }
  16772. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  16773. if (!fs) {
  16774. return;
  16775. }
  16776. return ctx.fs = {
  16777. fileExists(file) {
  16778. if (file.endsWith(".vue.ts")) {
  16779. file = file.replace(/\.ts$/, "");
  16780. }
  16781. return fs.fileExists(file);
  16782. },
  16783. readFile(file) {
  16784. if (file.endsWith(".vue.ts")) {
  16785. file = file.replace(/\.ts$/, "");
  16786. }
  16787. return fs.readFile(file);
  16788. },
  16789. realpath: fs.realpath
  16790. };
  16791. }
  16792. function resolveTypeFromImport(ctx, node, name, scope) {
  16793. const { source, imported } = scope.imports[name];
  16794. const sourceScope = importSourceToScope(ctx, node, scope, source);
  16795. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  16796. }
  16797. function importSourceToScope(ctx, node, scope, source) {
  16798. let fs;
  16799. try {
  16800. fs = resolveFS(ctx);
  16801. } catch (err) {
  16802. return ctx.error(err.message, node, scope);
  16803. }
  16804. if (!fs) {
  16805. return ctx.error(
  16806. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  16807. node,
  16808. scope
  16809. );
  16810. }
  16811. let resolved = scope.resolvedImportSources[source];
  16812. if (!resolved) {
  16813. if (source.startsWith("..")) {
  16814. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$3.join : joinPaths;
  16815. const filename = osSpecificJoinFn(path$3.dirname(scope.filename), source);
  16816. resolved = resolveExt(filename, fs);
  16817. } else if (source.startsWith(".")) {
  16818. const filename = joinPaths(path$3.dirname(scope.filename), source);
  16819. resolved = resolveExt(filename, fs);
  16820. } else {
  16821. if (!ts) {
  16822. if (loadTS)
  16823. ts = loadTS();
  16824. if (!ts) {
  16825. return ctx.error(
  16826. `Failed to resolve import source ${JSON.stringify(source)}. typescript is required as a peer dep for vue in order to support resolving types from module imports.`,
  16827. node,
  16828. scope
  16829. );
  16830. }
  16831. }
  16832. resolved = resolveWithTS(scope.filename, source, ts, fs);
  16833. }
  16834. if (resolved) {
  16835. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  16836. }
  16837. }
  16838. if (resolved) {
  16839. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  16840. return fileToScope(ctx, resolved);
  16841. } else {
  16842. return ctx.error(
  16843. `Failed to resolve import source ${JSON.stringify(source)}.`,
  16844. node,
  16845. scope
  16846. );
  16847. }
  16848. }
  16849. function resolveExt(filename, fs) {
  16850. filename = filename.replace(/\.js$/, "");
  16851. const tryResolve = (filename2) => {
  16852. if (fs.fileExists(filename2))
  16853. return filename2;
  16854. };
  16855. return tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  16856. }
  16857. const tsConfigCache = createCache();
  16858. const tsConfigRefMap = /* @__PURE__ */ new Map();
  16859. function resolveWithTS(containingFile, source, ts2, fs) {
  16860. var _a, _b;
  16861. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  16862. let tsCompilerOptions;
  16863. let tsResolveCache;
  16864. if (configPath) {
  16865. let configs;
  16866. const normalizedConfigPath = normalizePath(configPath);
  16867. const cached = tsConfigCache.get(normalizedConfigPath);
  16868. if (!cached) {
  16869. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  16870. tsConfigCache.set(normalizedConfigPath, configs);
  16871. } else {
  16872. configs = cached;
  16873. }
  16874. let matchedConfig;
  16875. if (configs.length === 1) {
  16876. matchedConfig = configs[0];
  16877. } else {
  16878. for (const c of configs) {
  16879. const base = normalizePath(
  16880. c.config.options.pathsBasePath || path$3.dirname(c.config.options.configFilePath)
  16881. );
  16882. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  16883. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  16884. if (!included && (!base || containingFile.startsWith(base)) || included.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  16885. if (excluded && excluded.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  16886. continue;
  16887. }
  16888. matchedConfig = c;
  16889. break;
  16890. }
  16891. }
  16892. if (!matchedConfig) {
  16893. matchedConfig = configs[configs.length - 1];
  16894. }
  16895. }
  16896. tsCompilerOptions = matchedConfig.config.options;
  16897. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  16898. process__namespace.cwd(),
  16899. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  16900. tsCompilerOptions
  16901. ));
  16902. } else {
  16903. tsCompilerOptions = {};
  16904. }
  16905. const res = ts2.resolveModuleName(
  16906. source,
  16907. containingFile,
  16908. tsCompilerOptions,
  16909. fs,
  16910. tsResolveCache
  16911. );
  16912. if (res.resolvedModule) {
  16913. let filename = res.resolvedModule.resolvedFileName;
  16914. if (filename.endsWith(".vue.ts")) {
  16915. filename = filename.replace(/\.ts$/, "");
  16916. }
  16917. return fs.realpath ? fs.realpath(filename) : filename;
  16918. }
  16919. }
  16920. function loadTSConfig(configPath, ts2, fs) {
  16921. const parseConfigHost = ts2.sys;
  16922. const config = ts2.parseJsonConfigFileContent(
  16923. ts2.readConfigFile(configPath, fs.readFile).config,
  16924. parseConfigHost,
  16925. path$3.dirname(configPath),
  16926. void 0,
  16927. configPath
  16928. );
  16929. const res = [config];
  16930. if (config.projectReferences) {
  16931. for (const ref of config.projectReferences) {
  16932. tsConfigRefMap.set(ref.path, configPath);
  16933. res.unshift(...loadTSConfig(ref.path, ts2, fs));
  16934. }
  16935. }
  16936. return res;
  16937. }
  16938. const fileToScopeCache = createCache();
  16939. function invalidateTypeCache(filename) {
  16940. filename = normalizePath(filename);
  16941. fileToScopeCache.delete(filename);
  16942. tsConfigCache.delete(filename);
  16943. const affectedConfig = tsConfigRefMap.get(filename);
  16944. if (affectedConfig)
  16945. tsConfigCache.delete(affectedConfig);
  16946. }
  16947. function fileToScope(ctx, filename, asGlobal = false) {
  16948. const cached = fileToScopeCache.get(filename);
  16949. if (cached) {
  16950. return cached;
  16951. }
  16952. const fs = resolveFS(ctx);
  16953. const source = fs.readFile(filename) || "";
  16954. const body = parseFile(filename, source, ctx.options.babelParserPlugins);
  16955. const scope = new TypeScope(filename, source, 0, recordImports(body));
  16956. recordTypes(ctx, body, scope, asGlobal);
  16957. fileToScopeCache.set(filename, scope);
  16958. return scope;
  16959. }
  16960. function parseFile(filename, content, parserPlugins) {
  16961. const ext = path$3.extname(filename);
  16962. if (ext === ".ts" || ext === ".tsx") {
  16963. return parser$1.parse(content, {
  16964. plugins: resolveParserPlugins(
  16965. ext.slice(1),
  16966. parserPlugins,
  16967. filename.endsWith(".d.ts")
  16968. ),
  16969. sourceType: "module"
  16970. }).program.body;
  16971. } else if (ext === ".vue") {
  16972. const {
  16973. descriptor: { script, scriptSetup }
  16974. } = parse$2(content);
  16975. if (!script && !scriptSetup) {
  16976. return [];
  16977. }
  16978. const scriptOffset = script ? script.loc.start.offset : Infinity;
  16979. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  16980. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  16981. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  16982. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  16983. if (secondBlock) {
  16984. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  16985. }
  16986. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  16987. return parser$1.parse(scriptContent, {
  16988. plugins: resolveParserPlugins(lang, parserPlugins),
  16989. sourceType: "module"
  16990. }).program.body;
  16991. }
  16992. return [];
  16993. }
  16994. function ctxToScope(ctx) {
  16995. if (ctx.scope) {
  16996. return ctx.scope;
  16997. }
  16998. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  16999. const scope = new TypeScope(
  17000. ctx.filename,
  17001. ctx.source,
  17002. "startOffset" in ctx ? ctx.startOffset : 0,
  17003. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  17004. );
  17005. recordTypes(ctx, body, scope);
  17006. return ctx.scope = scope;
  17007. }
  17008. function moduleDeclToScope(ctx, node, parentScope) {
  17009. if (node._resolvedChildScope) {
  17010. return node._resolvedChildScope;
  17011. }
  17012. const scope = createChildScope(parentScope);
  17013. if (node.body.type === "TSModuleDeclaration") {
  17014. const decl = node.body;
  17015. decl._ownerScope = scope;
  17016. const id = getId(decl.id);
  17017. scope.types[id] = scope.exportedTypes[id] = decl;
  17018. } else {
  17019. recordTypes(ctx, node.body.body, scope);
  17020. }
  17021. return node._resolvedChildScope = scope;
  17022. }
  17023. function createChildScope(parentScope) {
  17024. return new TypeScope(
  17025. parentScope.filename,
  17026. parentScope.source,
  17027. parentScope.offset,
  17028. Object.create(parentScope.imports),
  17029. Object.create(parentScope.types),
  17030. Object.create(parentScope.declares)
  17031. );
  17032. }
  17033. const importExportRE = /^Import|^Export/;
  17034. function recordTypes(ctx, body, scope, asGlobal = false) {
  17035. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  17036. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  17037. for (const stmt of body) {
  17038. if (asGlobal) {
  17039. if (isAmbient) {
  17040. if (stmt.declare) {
  17041. recordType(stmt, types, declares);
  17042. }
  17043. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  17044. for (const s of stmt.body.body) {
  17045. recordType(s, types, declares);
  17046. }
  17047. }
  17048. } else {
  17049. recordType(stmt, types, declares);
  17050. }
  17051. }
  17052. if (!asGlobal) {
  17053. for (const stmt of body) {
  17054. if (stmt.type === "ExportNamedDeclaration") {
  17055. if (stmt.declaration) {
  17056. recordType(stmt.declaration, types, declares);
  17057. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  17058. } else {
  17059. for (const spec of stmt.specifiers) {
  17060. if (spec.type === "ExportSpecifier") {
  17061. const local = spec.local.name;
  17062. const exported = getId(spec.exported);
  17063. if (stmt.source) {
  17064. imports[exported] = {
  17065. source: stmt.source.value,
  17066. imported: local
  17067. };
  17068. exportedTypes[exported] = {
  17069. type: "TSTypeReference",
  17070. typeName: {
  17071. type: "Identifier",
  17072. name: local
  17073. },
  17074. _ownerScope: scope
  17075. };
  17076. } else if (types[local]) {
  17077. exportedTypes[exported] = types[local];
  17078. }
  17079. }
  17080. }
  17081. }
  17082. } else if (stmt.type === "ExportAllDeclaration") {
  17083. const sourceScope = importSourceToScope(
  17084. ctx,
  17085. stmt.source,
  17086. scope,
  17087. stmt.source.value
  17088. );
  17089. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  17090. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  17091. if (stmt.declaration.type !== "Identifier") {
  17092. recordType(stmt.declaration, types, declares, "default");
  17093. recordType(
  17094. stmt.declaration,
  17095. exportedTypes,
  17096. exportedDeclares,
  17097. "default"
  17098. );
  17099. } else if (types[stmt.declaration.name]) {
  17100. exportedTypes["default"] = types[stmt.declaration.name];
  17101. }
  17102. }
  17103. }
  17104. }
  17105. for (const key of Object.keys(types)) {
  17106. const node = types[key];
  17107. node._ownerScope = scope;
  17108. if (node._ns)
  17109. node._ns._ownerScope = scope;
  17110. }
  17111. for (const key of Object.keys(declares)) {
  17112. declares[key]._ownerScope = scope;
  17113. }
  17114. }
  17115. function recordType(node, types, declares, overwriteId) {
  17116. switch (node.type) {
  17117. case "TSInterfaceDeclaration":
  17118. case "TSEnumDeclaration":
  17119. case "TSModuleDeclaration": {
  17120. const id = overwriteId || getId(node.id);
  17121. let existing = types[id];
  17122. if (existing) {
  17123. if (node.type === "TSModuleDeclaration") {
  17124. if (existing.type === "TSModuleDeclaration") {
  17125. mergeNamespaces(existing, node);
  17126. } else {
  17127. attachNamespace(existing, node);
  17128. }
  17129. break;
  17130. }
  17131. if (existing.type === "TSModuleDeclaration") {
  17132. types[id] = node;
  17133. attachNamespace(node, existing);
  17134. break;
  17135. }
  17136. if (existing.type !== node.type) {
  17137. break;
  17138. }
  17139. if (node.type === "TSInterfaceDeclaration") {
  17140. existing.body.body.push(...node.body.body);
  17141. } else {
  17142. existing.members.push(...node.members);
  17143. }
  17144. } else {
  17145. types[id] = node;
  17146. }
  17147. break;
  17148. }
  17149. case "ClassDeclaration":
  17150. if (overwriteId || node.id)
  17151. types[overwriteId || getId(node.id)] = node;
  17152. break;
  17153. case "TSTypeAliasDeclaration":
  17154. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  17155. break;
  17156. case "TSDeclareFunction":
  17157. if (node.id)
  17158. declares[node.id.name] = node;
  17159. break;
  17160. case "VariableDeclaration": {
  17161. if (node.declare) {
  17162. for (const decl of node.declarations) {
  17163. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  17164. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  17165. }
  17166. }
  17167. }
  17168. break;
  17169. }
  17170. }
  17171. }
  17172. function mergeNamespaces(to, from) {
  17173. const toBody = to.body;
  17174. const fromBody = from.body;
  17175. if (toBody.type === "TSModuleDeclaration") {
  17176. if (fromBody.type === "TSModuleDeclaration") {
  17177. mergeNamespaces(toBody, fromBody);
  17178. } else {
  17179. fromBody.body.push({
  17180. type: "ExportNamedDeclaration",
  17181. declaration: toBody,
  17182. exportKind: "type",
  17183. specifiers: []
  17184. });
  17185. }
  17186. } else if (fromBody.type === "TSModuleDeclaration") {
  17187. toBody.body.push({
  17188. type: "ExportNamedDeclaration",
  17189. declaration: fromBody,
  17190. exportKind: "type",
  17191. specifiers: []
  17192. });
  17193. } else {
  17194. toBody.body.push(...fromBody.body);
  17195. }
  17196. }
  17197. function attachNamespace(to, ns) {
  17198. if (!to._ns) {
  17199. to._ns = ns;
  17200. } else {
  17201. mergeNamespaces(to._ns, ns);
  17202. }
  17203. }
  17204. function recordImports(body) {
  17205. const imports = /* @__PURE__ */ Object.create(null);
  17206. for (const s of body) {
  17207. recordImport(s, imports);
  17208. }
  17209. return imports;
  17210. }
  17211. function recordImport(node, imports) {
  17212. if (node.type !== "ImportDeclaration") {
  17213. return;
  17214. }
  17215. for (const s of node.specifiers) {
  17216. imports[s.local.name] = {
  17217. imported: getImportedName(s),
  17218. source: node.source.value
  17219. };
  17220. }
  17221. }
  17222. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx)) {
  17223. try {
  17224. switch (node.type) {
  17225. case "TSStringKeyword":
  17226. return ["String"];
  17227. case "TSNumberKeyword":
  17228. return ["Number"];
  17229. case "TSBooleanKeyword":
  17230. return ["Boolean"];
  17231. case "TSObjectKeyword":
  17232. return ["Object"];
  17233. case "TSNullKeyword":
  17234. return ["null"];
  17235. case "TSTypeLiteral":
  17236. case "TSInterfaceDeclaration": {
  17237. const types = /* @__PURE__ */ new Set();
  17238. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  17239. for (const m of members) {
  17240. if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  17241. types.add("Function");
  17242. } else {
  17243. types.add("Object");
  17244. }
  17245. }
  17246. return types.size ? Array.from(types) : ["Object"];
  17247. }
  17248. case "TSPropertySignature":
  17249. if (node.typeAnnotation) {
  17250. return inferRuntimeType(
  17251. ctx,
  17252. node.typeAnnotation.typeAnnotation,
  17253. scope
  17254. );
  17255. }
  17256. break;
  17257. case "TSMethodSignature":
  17258. case "TSFunctionType":
  17259. return ["Function"];
  17260. case "TSArrayType":
  17261. case "TSTupleType":
  17262. return ["Array"];
  17263. case "TSLiteralType":
  17264. switch (node.literal.type) {
  17265. case "StringLiteral":
  17266. return ["String"];
  17267. case "BooleanLiteral":
  17268. return ["Boolean"];
  17269. case "NumericLiteral":
  17270. case "BigIntLiteral":
  17271. return ["Number"];
  17272. default:
  17273. return [UNKNOWN_TYPE];
  17274. }
  17275. case "TSTypeReference": {
  17276. const resolved = resolveTypeReference(ctx, node, scope);
  17277. if (resolved) {
  17278. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  17279. }
  17280. if (node.typeName.type === "Identifier") {
  17281. switch (node.typeName.name) {
  17282. case "Array":
  17283. case "Function":
  17284. case "Object":
  17285. case "Set":
  17286. case "Map":
  17287. case "WeakSet":
  17288. case "WeakMap":
  17289. case "Date":
  17290. case "Promise":
  17291. case "Error":
  17292. return [node.typeName.name];
  17293. case "Partial":
  17294. case "Required":
  17295. case "Readonly":
  17296. case "Record":
  17297. case "Pick":
  17298. case "Omit":
  17299. case "InstanceType":
  17300. return ["Object"];
  17301. case "Uppercase":
  17302. case "Lowercase":
  17303. case "Capitalize":
  17304. case "Uncapitalize":
  17305. return ["String"];
  17306. case "Parameters":
  17307. case "ConstructorParameters":
  17308. return ["Array"];
  17309. case "NonNullable":
  17310. if (node.typeParameters && node.typeParameters.params[0]) {
  17311. return inferRuntimeType(
  17312. ctx,
  17313. node.typeParameters.params[0],
  17314. scope
  17315. ).filter((t) => t !== "null");
  17316. }
  17317. break;
  17318. case "Extract":
  17319. if (node.typeParameters && node.typeParameters.params[1]) {
  17320. return inferRuntimeType(
  17321. ctx,
  17322. node.typeParameters.params[1],
  17323. scope
  17324. );
  17325. }
  17326. break;
  17327. case "Exclude":
  17328. case "OmitThisParameter":
  17329. if (node.typeParameters && node.typeParameters.params[0]) {
  17330. return inferRuntimeType(
  17331. ctx,
  17332. node.typeParameters.params[0],
  17333. scope
  17334. );
  17335. }
  17336. break;
  17337. }
  17338. }
  17339. break;
  17340. }
  17341. case "TSParenthesizedType":
  17342. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  17343. case "TSUnionType":
  17344. return flattenTypes(ctx, node.types, scope);
  17345. case "TSIntersectionType": {
  17346. return flattenTypes(ctx, node.types, scope).filter(
  17347. (t) => t !== UNKNOWN_TYPE
  17348. );
  17349. }
  17350. case "TSEnumDeclaration":
  17351. return inferEnumType(node);
  17352. case "TSSymbolKeyword":
  17353. return ["Symbol"];
  17354. case "TSIndexedAccessType": {
  17355. const types = resolveIndexType(ctx, node, scope);
  17356. return flattenTypes(ctx, types, scope);
  17357. }
  17358. case "ClassDeclaration":
  17359. return ["Object"];
  17360. case "TSImportType": {
  17361. const sourceScope = importSourceToScope(
  17362. ctx,
  17363. node.argument,
  17364. scope,
  17365. node.argument.value
  17366. );
  17367. const resolved = resolveTypeReference(ctx, node, sourceScope);
  17368. if (resolved) {
  17369. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  17370. }
  17371. break;
  17372. }
  17373. case "TSTypeQuery": {
  17374. const id = node.exprName;
  17375. if (id.type === "Identifier") {
  17376. const matched = scope.declares[id.name];
  17377. if (matched) {
  17378. return inferRuntimeType(ctx, matched, matched._ownerScope);
  17379. }
  17380. }
  17381. break;
  17382. }
  17383. }
  17384. } catch (e) {
  17385. }
  17386. return [UNKNOWN_TYPE];
  17387. }
  17388. function flattenTypes(ctx, types, scope) {
  17389. if (types.length === 1) {
  17390. return inferRuntimeType(ctx, types[0], scope);
  17391. }
  17392. return [
  17393. ...new Set(
  17394. [].concat(
  17395. ...types.map((t) => inferRuntimeType(ctx, t, scope))
  17396. )
  17397. )
  17398. ];
  17399. }
  17400. function inferEnumType(node) {
  17401. const types = /* @__PURE__ */ new Set();
  17402. for (const m of node.members) {
  17403. if (m.initializer) {
  17404. switch (m.initializer.type) {
  17405. case "StringLiteral":
  17406. types.add("String");
  17407. break;
  17408. case "NumericLiteral":
  17409. types.add("Number");
  17410. break;
  17411. }
  17412. }
  17413. }
  17414. return types.size ? [...types] : ["Number"];
  17415. }
  17416. function resolveExtractPropTypes({ props }, scope) {
  17417. const res = { props: {} };
  17418. for (const key in props) {
  17419. const raw = props[key];
  17420. res.props[key] = reverseInferType(
  17421. raw.key,
  17422. raw.typeAnnotation.typeAnnotation,
  17423. scope
  17424. );
  17425. }
  17426. return res;
  17427. }
  17428. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  17429. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  17430. const typeType = findStaticPropertyType(node, "type");
  17431. if (typeType) {
  17432. const requiredType = findStaticPropertyType(node, "required");
  17433. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  17434. return reverseInferType(key, typeType, scope, optional2, false);
  17435. }
  17436. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  17437. if (node.typeName.name.endsWith("Constructor")) {
  17438. return createProperty(
  17439. key,
  17440. ctorToType(node.typeName.name),
  17441. scope,
  17442. optional
  17443. );
  17444. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  17445. return createProperty(key, node.typeParameters.params[0], scope, optional);
  17446. }
  17447. }
  17448. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  17449. for (const t of node.typeParameters.params) {
  17450. const inferred = reverseInferType(key, t, scope, optional);
  17451. if (inferred)
  17452. return inferred;
  17453. }
  17454. }
  17455. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  17456. }
  17457. function ctorToType(ctorType) {
  17458. const ctor = ctorType.slice(0, -11);
  17459. switch (ctor) {
  17460. case "String":
  17461. case "Number":
  17462. case "Boolean":
  17463. return { type: `TS${ctor}Keyword` };
  17464. case "Array":
  17465. case "Function":
  17466. case "Object":
  17467. case "Set":
  17468. case "Map":
  17469. case "WeakSet":
  17470. case "WeakMap":
  17471. case "Date":
  17472. case "Promise":
  17473. return {
  17474. type: "TSTypeReference",
  17475. typeName: { type: "Identifier", name: ctor }
  17476. };
  17477. }
  17478. return { type: `TSNullKeyword` };
  17479. }
  17480. function findStaticPropertyType(node, key) {
  17481. const prop = node.members.find(
  17482. (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation
  17483. );
  17484. return prop && prop.typeAnnotation.typeAnnotation;
  17485. }
  17486. function resolveReturnType(ctx, arg, scope) {
  17487. var _a;
  17488. let resolved = arg;
  17489. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  17490. resolved = resolveTypeReference(ctx, arg, scope);
  17491. }
  17492. if (!resolved)
  17493. return;
  17494. if (resolved.type === "TSFunctionType") {
  17495. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  17496. }
  17497. if (resolved.type === "TSDeclareFunction") {
  17498. return resolved.returnType;
  17499. }
  17500. }
  17501. function resolveUnionType(ctx, node, scope) {
  17502. if (node.type === "TSTypeReference") {
  17503. const resolved = resolveTypeReference(ctx, node, scope);
  17504. if (resolved)
  17505. node = resolved;
  17506. }
  17507. let types;
  17508. if (node.type === "TSUnionType") {
  17509. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  17510. } else {
  17511. types = [node];
  17512. }
  17513. return types;
  17514. }
  17515. const DEFINE_MODEL = "defineModel";
  17516. function processDefineModel(ctx, node, declId) {
  17517. if (!isCallOf(node, DEFINE_MODEL)) {
  17518. return false;
  17519. }
  17520. ctx.hasDefineModelCall = true;
  17521. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  17522. let modelName;
  17523. let options;
  17524. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  17525. const hasName = arg0 && arg0.type === "StringLiteral";
  17526. if (hasName) {
  17527. modelName = arg0.value;
  17528. options = node.arguments[1];
  17529. } else {
  17530. modelName = "modelValue";
  17531. options = arg0;
  17532. }
  17533. if (ctx.modelDecls[modelName]) {
  17534. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  17535. }
  17536. let optionsString = options && ctx.getString(options);
  17537. let optionsRemoved = !options;
  17538. const runtimeOptionNodes = [];
  17539. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  17540. let removed = 0;
  17541. for (let i = options.properties.length - 1; i >= 0; i--) {
  17542. const p = options.properties[i];
  17543. const next = options.properties[i + 1];
  17544. const start = p.start;
  17545. const end = next ? next.start : options.end - 1;
  17546. if ((p.type === "ObjectProperty" || p.type === "ObjectMethod") && (p.key.type === "Identifier" && (p.key.name === "get" || p.key.name === "set") || p.key.type === "StringLiteral" && (p.key.value === "get" || p.key.value === "set"))) {
  17547. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  17548. } else {
  17549. removed++;
  17550. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  17551. runtimeOptionNodes.push(p);
  17552. }
  17553. }
  17554. if (removed === options.properties.length) {
  17555. optionsRemoved = true;
  17556. ctx.s.remove(
  17557. ctx.startOffset + (hasName ? arg0.end : options.start),
  17558. ctx.startOffset + options.end
  17559. );
  17560. }
  17561. }
  17562. ctx.modelDecls[modelName] = {
  17563. type,
  17564. options: optionsString,
  17565. runtimeOptionNodes,
  17566. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  17567. };
  17568. ctx.bindingMetadata[modelName] = "props";
  17569. ctx.s.overwrite(
  17570. ctx.startOffset + node.callee.start,
  17571. ctx.startOffset + node.callee.end,
  17572. ctx.helper("useModel")
  17573. );
  17574. ctx.s.appendLeft(
  17575. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  17576. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  17577. );
  17578. return true;
  17579. }
  17580. function genModelProps(ctx) {
  17581. if (!ctx.hasDefineModelCall)
  17582. return;
  17583. const isProd = !!ctx.options.isProd;
  17584. let modelPropsDecl = "";
  17585. for (const [name, { type, options }] of Object.entries(ctx.modelDecls)) {
  17586. let skipCheck = false;
  17587. let runtimeTypes = type && inferRuntimeType(ctx, type);
  17588. if (runtimeTypes) {
  17589. const hasBoolean = runtimeTypes.includes("Boolean");
  17590. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  17591. if (isProd || hasUnknownType) {
  17592. runtimeTypes = runtimeTypes.filter(
  17593. (t) => t === "Boolean" || hasBoolean && t === "String" || t === "Function" && options
  17594. );
  17595. skipCheck = !isProd && hasUnknownType && runtimeTypes.length > 0;
  17596. }
  17597. }
  17598. let runtimeType = runtimeTypes && runtimeTypes.length > 0 && toRuntimeTypeString(runtimeTypes) || void 0;
  17599. const codegenOptions = concatStrings([
  17600. runtimeType && `type: ${runtimeType}`,
  17601. skipCheck && "skipCheck: true"
  17602. ]);
  17603. let decl;
  17604. if (runtimeType && options) {
  17605. decl = ctx.isTS ? `{ ${codegenOptions}, ...${options} }` : `Object.assign({ ${codegenOptions} }, ${options})`;
  17606. } else {
  17607. decl = options || (runtimeType ? `{ ${codegenOptions} }` : "{}");
  17608. }
  17609. modelPropsDecl += `
  17610. ${JSON.stringify(name)}: ${decl},`;
  17611. const modifierPropName = JSON.stringify(
  17612. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  17613. );
  17614. modelPropsDecl += `
  17615. ${modifierPropName}: {},`;
  17616. }
  17617. return `{${modelPropsDecl}
  17618. }`;
  17619. }
  17620. const DEFINE_PROPS = "defineProps";
  17621. const WITH_DEFAULTS = "withDefaults";
  17622. function processDefineProps(ctx, node, declId) {
  17623. if (!isCallOf(node, DEFINE_PROPS)) {
  17624. return processWithDefaults(ctx, node, declId);
  17625. }
  17626. if (ctx.hasDefinePropsCall) {
  17627. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  17628. }
  17629. ctx.hasDefinePropsCall = true;
  17630. ctx.propsRuntimeDecl = node.arguments[0];
  17631. if (ctx.propsRuntimeDecl) {
  17632. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  17633. if (!(key in ctx.bindingMetadata)) {
  17634. ctx.bindingMetadata[key] = "props";
  17635. }
  17636. }
  17637. }
  17638. if (node.typeParameters) {
  17639. if (ctx.propsRuntimeDecl) {
  17640. ctx.error(
  17641. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  17642. node
  17643. );
  17644. }
  17645. ctx.propsTypeDecl = node.typeParameters.params[0];
  17646. }
  17647. if (declId && declId.type === "ObjectPattern") {
  17648. processPropsDestructure(ctx, declId);
  17649. }
  17650. ctx.propsCall = node;
  17651. ctx.propsDecl = declId;
  17652. return true;
  17653. }
  17654. function processWithDefaults(ctx, node, declId) {
  17655. if (!isCallOf(node, WITH_DEFAULTS)) {
  17656. return false;
  17657. }
  17658. if (!processDefineProps(ctx, node.arguments[0], declId)) {
  17659. ctx.error(
  17660. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  17661. node.arguments[0] || node
  17662. );
  17663. }
  17664. if (ctx.propsRuntimeDecl) {
  17665. ctx.error(
  17666. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  17667. node
  17668. );
  17669. }
  17670. if (ctx.propsDestructureDecl) {
  17671. ctx.error(
  17672. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  17673. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`,
  17674. node.callee
  17675. );
  17676. }
  17677. ctx.propsRuntimeDefaults = node.arguments[1];
  17678. if (!ctx.propsRuntimeDefaults) {
  17679. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  17680. }
  17681. ctx.propsCall = node;
  17682. return true;
  17683. }
  17684. function genRuntimeProps(ctx) {
  17685. let propsDecls;
  17686. if (ctx.propsRuntimeDecl) {
  17687. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  17688. if (ctx.propsDestructureDecl) {
  17689. const defaults = [];
  17690. for (const key in ctx.propsDestructuredBindings) {
  17691. const d = genDestructuredDefaultValue(ctx, key);
  17692. const finalKey = getEscapedPropName(key);
  17693. if (d)
  17694. defaults.push(
  17695. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  17696. );
  17697. }
  17698. if (defaults.length) {
  17699. propsDecls = `/*#__PURE__*/${ctx.helper(
  17700. `mergeDefaults`
  17701. )}(${propsDecls}, {
  17702. ${defaults.join(",\n ")}
  17703. })`;
  17704. }
  17705. }
  17706. } else if (ctx.propsTypeDecl) {
  17707. propsDecls = extractRuntimeProps(ctx);
  17708. }
  17709. const modelsDecls = genModelProps(ctx);
  17710. if (propsDecls && modelsDecls) {
  17711. return `/*#__PURE__*/${ctx.helper(
  17712. "mergeModels"
  17713. )}(${propsDecls}, ${modelsDecls})`;
  17714. } else {
  17715. return modelsDecls || propsDecls;
  17716. }
  17717. }
  17718. function extractRuntimeProps(ctx) {
  17719. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  17720. if (!props.length) {
  17721. return;
  17722. }
  17723. const propStrings = [];
  17724. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  17725. for (const prop of props) {
  17726. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  17727. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  17728. ctx.bindingMetadata[prop.key] = "props";
  17729. }
  17730. }
  17731. let propsDecls = `{
  17732. ${propStrings.join(",\n ")}
  17733. }`;
  17734. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  17735. propsDecls = `/*#__PURE__*/${ctx.helper(
  17736. "mergeDefaults"
  17737. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  17738. }
  17739. return propsDecls;
  17740. }
  17741. function resolveRuntimePropsFromType(ctx, node) {
  17742. const props = [];
  17743. const elements = resolveTypeElements(ctx, node);
  17744. for (const key in elements.props) {
  17745. const e = elements.props[key];
  17746. let type = inferRuntimeType(ctx, e);
  17747. let skipCheck = false;
  17748. if (type.includes(UNKNOWN_TYPE)) {
  17749. if (type.includes("Boolean") || type.includes("Function")) {
  17750. type = type.filter((t) => t !== UNKNOWN_TYPE);
  17751. skipCheck = true;
  17752. } else {
  17753. type = ["null"];
  17754. }
  17755. }
  17756. props.push({
  17757. key,
  17758. required: !e.optional,
  17759. type: type || [`null`],
  17760. skipCheck
  17761. });
  17762. }
  17763. return props;
  17764. }
  17765. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  17766. let defaultString;
  17767. const destructured = genDestructuredDefaultValue(ctx, key, type);
  17768. if (destructured) {
  17769. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  17770. } else if (hasStaticDefaults) {
  17771. const prop = ctx.propsRuntimeDefaults.properties.find(
  17772. (node) => {
  17773. if (node.type === "SpreadElement")
  17774. return false;
  17775. return resolveObjectKey(node.key, node.computed) === key;
  17776. }
  17777. );
  17778. if (prop) {
  17779. if (prop.type === "ObjectProperty") {
  17780. defaultString = `default: ${ctx.getString(prop.value)}`;
  17781. } else {
  17782. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  17783. }
  17784. }
  17785. }
  17786. const finalKey = getEscapedPropName(key);
  17787. if (!ctx.options.isProd) {
  17788. return `${finalKey}: { ${concatStrings([
  17789. `type: ${toRuntimeTypeString(type)}`,
  17790. `required: ${required}`,
  17791. skipCheck && "skipCheck: true",
  17792. defaultString
  17793. ])} }`;
  17794. } else if (type.some(
  17795. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  17796. )) {
  17797. return `${finalKey}: { ${concatStrings([
  17798. `type: ${toRuntimeTypeString(type)}`,
  17799. defaultString
  17800. ])} }`;
  17801. } else {
  17802. if (ctx.isCE) {
  17803. if (defaultString) {
  17804. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  17805. type
  17806. )} }`}`;
  17807. } else {
  17808. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  17809. }
  17810. }
  17811. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  17812. }
  17813. }
  17814. function hasStaticWithDefaults(ctx) {
  17815. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  17816. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  17817. ));
  17818. }
  17819. function genDestructuredDefaultValue(ctx, key, inferredType) {
  17820. const destructured = ctx.propsDestructuredBindings[key];
  17821. const defaultVal = destructured && destructured.default;
  17822. if (defaultVal) {
  17823. const value = ctx.getString(defaultVal);
  17824. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  17825. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  17826. const valueType = inferValueType(unwrapped);
  17827. if (valueType && !inferredType.includes(valueType)) {
  17828. ctx.error(
  17829. `Default value of prop "${key}" does not match declared type.`,
  17830. unwrapped
  17831. );
  17832. }
  17833. }
  17834. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  17835. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  17836. return {
  17837. valueString: needFactoryWrap ? `() => (${value})` : value,
  17838. needSkipFactory
  17839. };
  17840. }
  17841. }
  17842. function inferValueType(node) {
  17843. switch (node.type) {
  17844. case "StringLiteral":
  17845. return "String";
  17846. case "NumericLiteral":
  17847. return "Number";
  17848. case "BooleanLiteral":
  17849. return "Boolean";
  17850. case "ObjectExpression":
  17851. return "Object";
  17852. case "ArrayExpression":
  17853. return "Array";
  17854. case "FunctionExpression":
  17855. case "ArrowFunctionExpression":
  17856. return "Function";
  17857. }
  17858. }
  17859. function processPropsDestructure(ctx, declId) {
  17860. if (!ctx.options.propsDestructure) {
  17861. return;
  17862. }
  17863. warnOnce(
  17864. `This project is using reactive props destructure, which is an experimental feature. It may receive breaking changes or be removed in the future, so use at your own risk.
  17865. To stay updated, follow the RFC at https://github.com/vuejs/rfcs/discussions/502.`
  17866. );
  17867. ctx.propsDestructureDecl = declId;
  17868. const registerBinding = (key, local, defaultValue) => {
  17869. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  17870. if (local !== key) {
  17871. ctx.bindingMetadata[local] = "props-aliased";
  17872. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  17873. }
  17874. };
  17875. for (const prop of declId.properties) {
  17876. if (prop.type === "ObjectProperty") {
  17877. const propKey = resolveObjectKey(prop.key, prop.computed);
  17878. if (!propKey) {
  17879. ctx.error(
  17880. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  17881. prop.key
  17882. );
  17883. }
  17884. if (prop.value.type === "AssignmentPattern") {
  17885. const { left, right } = prop.value;
  17886. if (left.type !== "Identifier") {
  17887. ctx.error(
  17888. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  17889. left
  17890. );
  17891. }
  17892. registerBinding(propKey, left.name, right);
  17893. } else if (prop.value.type === "Identifier") {
  17894. registerBinding(propKey, prop.value.name);
  17895. } else {
  17896. ctx.error(
  17897. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  17898. prop.value
  17899. );
  17900. }
  17901. } else {
  17902. ctx.propsDestructureRestId = prop.argument.name;
  17903. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  17904. }
  17905. }
  17906. }
  17907. function transformDestructuredProps(ctx, vueImportAliases) {
  17908. if (!ctx.options.propsDestructure) {
  17909. return;
  17910. }
  17911. const rootScope = {};
  17912. const scopeStack = [rootScope];
  17913. let currentScope = rootScope;
  17914. const excludedIds = /* @__PURE__ */ new WeakSet();
  17915. const parentStack = [];
  17916. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  17917. for (const key in ctx.propsDestructuredBindings) {
  17918. const { local } = ctx.propsDestructuredBindings[key];
  17919. rootScope[local] = true;
  17920. propsLocalToPublicMap[local] = key;
  17921. }
  17922. function pushScope() {
  17923. scopeStack.push(currentScope = Object.create(currentScope));
  17924. }
  17925. function popScope() {
  17926. scopeStack.pop();
  17927. currentScope = scopeStack[scopeStack.length - 1] || null;
  17928. }
  17929. function registerLocalBinding(id) {
  17930. excludedIds.add(id);
  17931. if (currentScope) {
  17932. currentScope[id.name] = false;
  17933. } else {
  17934. ctx.error(
  17935. "registerBinding called without active scope, something is wrong.",
  17936. id
  17937. );
  17938. }
  17939. }
  17940. function walkScope(node, isRoot = false) {
  17941. for (const stmt of node.body) {
  17942. if (stmt.type === "VariableDeclaration") {
  17943. walkVariableDeclaration(stmt, isRoot);
  17944. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  17945. if (stmt.declare || !stmt.id)
  17946. continue;
  17947. registerLocalBinding(stmt.id);
  17948. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  17949. walkVariableDeclaration(stmt.left);
  17950. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  17951. walkVariableDeclaration(stmt.declaration, isRoot);
  17952. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  17953. walkVariableDeclaration(stmt.body, isRoot);
  17954. }
  17955. }
  17956. }
  17957. function walkVariableDeclaration(stmt, isRoot = false) {
  17958. if (stmt.declare) {
  17959. return;
  17960. }
  17961. for (const decl of stmt.declarations) {
  17962. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  17963. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  17964. if (isDefineProps) {
  17965. excludedIds.add(id);
  17966. } else {
  17967. registerLocalBinding(id);
  17968. }
  17969. }
  17970. }
  17971. }
  17972. function rewriteId(id, parent, parentStack2) {
  17973. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  17974. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  17975. }
  17976. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  17977. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  17978. ctx.s.appendLeft(
  17979. id.end + ctx.startOffset,
  17980. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  17981. );
  17982. }
  17983. } else {
  17984. ctx.s.overwrite(
  17985. id.start + ctx.startOffset,
  17986. id.end + ctx.startOffset,
  17987. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  17988. );
  17989. }
  17990. }
  17991. function checkUsage(node, method, alias = method) {
  17992. if (isCallOf(node, alias)) {
  17993. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  17994. if (arg.type === "Identifier" && currentScope[arg.name]) {
  17995. ctx.error(
  17996. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  17997. arg
  17998. );
  17999. }
  18000. }
  18001. }
  18002. const ast = ctx.scriptSetupAst;
  18003. walkScope(ast, true);
  18004. estreeWalker.walk(ast, {
  18005. enter(node, parent) {
  18006. parent && parentStack.push(parent);
  18007. if (parent && parent.type.startsWith("TS") && parent.type !== "TSAsExpression" && parent.type !== "TSNonNullExpression" && parent.type !== "TSTypeAssertion") {
  18008. return this.skip();
  18009. }
  18010. checkUsage(node, "watch", vueImportAliases.watch);
  18011. checkUsage(node, "toRef", vueImportAliases.toRef);
  18012. if (CompilerDOM.isFunctionType(node)) {
  18013. pushScope();
  18014. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  18015. if (node.body.type === "BlockStatement") {
  18016. walkScope(node.body);
  18017. }
  18018. return;
  18019. }
  18020. if (node.type === "CatchClause") {
  18021. pushScope();
  18022. if (node.param && node.param.type === "Identifier") {
  18023. registerLocalBinding(node.param);
  18024. }
  18025. walkScope(node.body);
  18026. return;
  18027. }
  18028. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  18029. pushScope();
  18030. walkScope(node);
  18031. return;
  18032. }
  18033. if (node.type === "Identifier") {
  18034. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  18035. if (currentScope[node.name]) {
  18036. rewriteId(node, parent, parentStack);
  18037. }
  18038. }
  18039. }
  18040. },
  18041. leave(node, parent) {
  18042. parent && parentStack.pop();
  18043. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node)) {
  18044. popScope();
  18045. }
  18046. }
  18047. });
  18048. }
  18049. const DEFINE_EMITS = "defineEmits";
  18050. function processDefineEmits(ctx, node, declId) {
  18051. if (!isCallOf(node, DEFINE_EMITS)) {
  18052. return false;
  18053. }
  18054. if (ctx.hasDefineEmitCall) {
  18055. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  18056. }
  18057. ctx.hasDefineEmitCall = true;
  18058. ctx.emitsRuntimeDecl = node.arguments[0];
  18059. if (node.typeParameters) {
  18060. if (ctx.emitsRuntimeDecl) {
  18061. ctx.error(
  18062. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  18063. node
  18064. );
  18065. }
  18066. ctx.emitsTypeDecl = node.typeParameters.params[0];
  18067. }
  18068. ctx.emitDecl = declId;
  18069. return true;
  18070. }
  18071. function genRuntimeEmits(ctx) {
  18072. let emitsDecl = "";
  18073. if (ctx.emitsRuntimeDecl) {
  18074. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  18075. } else if (ctx.emitsTypeDecl) {
  18076. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  18077. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  18078. }
  18079. if (ctx.hasDefineModelCall) {
  18080. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  18081. emitsDecl = emitsDecl ? `/*#__PURE__*/${ctx.helper(
  18082. "mergeModels"
  18083. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  18084. }
  18085. return emitsDecl;
  18086. }
  18087. function extractRuntimeEmits(ctx) {
  18088. const emits = /* @__PURE__ */ new Set();
  18089. const node = ctx.emitsTypeDecl;
  18090. if (node.type === "TSFunctionType") {
  18091. extractEventNames(ctx, node.parameters[0], emits);
  18092. return emits;
  18093. }
  18094. const { props, calls } = resolveTypeElements(ctx, node);
  18095. let hasProperty = false;
  18096. for (const key in props) {
  18097. emits.add(key);
  18098. hasProperty = true;
  18099. }
  18100. if (calls) {
  18101. if (hasProperty) {
  18102. ctx.error(
  18103. `defineEmits() type cannot mixed call signature and property syntax.`,
  18104. node
  18105. );
  18106. }
  18107. for (const call of calls) {
  18108. extractEventNames(ctx, call.parameters[0], emits);
  18109. }
  18110. }
  18111. return emits;
  18112. }
  18113. function extractEventNames(ctx, eventName, emits) {
  18114. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  18115. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  18116. for (const type of types) {
  18117. if (type.type === "TSLiteralType") {
  18118. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  18119. emits.add(String(type.literal.value));
  18120. }
  18121. }
  18122. }
  18123. }
  18124. }
  18125. const DEFINE_EXPOSE = "defineExpose";
  18126. function processDefineExpose(ctx, node) {
  18127. if (isCallOf(node, DEFINE_EXPOSE)) {
  18128. if (ctx.hasDefineExposeCall) {
  18129. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  18130. }
  18131. ctx.hasDefineExposeCall = true;
  18132. return true;
  18133. }
  18134. return false;
  18135. }
  18136. const DEFINE_SLOTS = "defineSlots";
  18137. function processDefineSlots(ctx, node, declId) {
  18138. if (!isCallOf(node, DEFINE_SLOTS)) {
  18139. return false;
  18140. }
  18141. if (ctx.hasDefineSlotsCall) {
  18142. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  18143. }
  18144. ctx.hasDefineSlotsCall = true;
  18145. if (node.arguments.length > 0) {
  18146. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  18147. }
  18148. if (declId) {
  18149. ctx.s.overwrite(
  18150. ctx.startOffset + node.start,
  18151. ctx.startOffset + node.end,
  18152. `${ctx.helper("useSlots")}()`
  18153. );
  18154. }
  18155. return true;
  18156. }
  18157. const DEFINE_OPTIONS = "defineOptions";
  18158. function processDefineOptions(ctx, node) {
  18159. if (!isCallOf(node, DEFINE_OPTIONS)) {
  18160. return false;
  18161. }
  18162. if (ctx.hasDefineOptionsCall) {
  18163. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  18164. }
  18165. if (node.typeParameters) {
  18166. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  18167. }
  18168. if (!node.arguments[0])
  18169. return true;
  18170. ctx.hasDefineOptionsCall = true;
  18171. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  18172. let propsOption = void 0;
  18173. let emitsOption = void 0;
  18174. let exposeOption = void 0;
  18175. let slotsOption = void 0;
  18176. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  18177. for (const prop of ctx.optionsRuntimeDecl.properties) {
  18178. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  18179. if (prop.key.name === "props")
  18180. propsOption = prop;
  18181. if (prop.key.name === "emits")
  18182. emitsOption = prop;
  18183. if (prop.key.name === "expose")
  18184. exposeOption = prop;
  18185. if (prop.key.name === "slots")
  18186. slotsOption = prop;
  18187. }
  18188. }
  18189. }
  18190. if (propsOption) {
  18191. ctx.error(
  18192. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  18193. propsOption
  18194. );
  18195. }
  18196. if (emitsOption) {
  18197. ctx.error(
  18198. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  18199. emitsOption
  18200. );
  18201. }
  18202. if (exposeOption) {
  18203. ctx.error(
  18204. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  18205. exposeOption
  18206. );
  18207. }
  18208. if (slotsOption) {
  18209. ctx.error(
  18210. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  18211. slotsOption
  18212. );
  18213. }
  18214. return true;
  18215. }
  18216. function processAwait(ctx, node, needSemi, isStatement) {
  18217. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  18218. const startOffset = ctx.startOffset;
  18219. const argumentStr = ctx.descriptor.source.slice(
  18220. argumentStart + startOffset,
  18221. node.argument.end + startOffset
  18222. );
  18223. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  18224. ctx.s.overwrite(
  18225. node.start + startOffset,
  18226. argumentStart + startOffset,
  18227. `${needSemi ? `;` : ``}(
  18228. ([__temp,__restore] = ${ctx.helper(
  18229. `withAsyncContext`
  18230. )}(${containsNestedAwait ? `async ` : ``}() => `
  18231. );
  18232. ctx.s.appendLeft(
  18233. node.end + startOffset,
  18234. `)),
  18235. ${isStatement ? `` : `__temp = `}await __temp,
  18236. __restore()${isStatement ? `` : `,
  18237. __temp`}
  18238. )`
  18239. );
  18240. }
  18241. function compileScript(sfc, options) {
  18242. var _a, _b, _c;
  18243. if (!options.id) {
  18244. warnOnce(
  18245. `compileScript now requires passing the \`id\` option.
  18246. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  18247. );
  18248. }
  18249. const ctx = new ScriptCompileContext(sfc, options);
  18250. const { script, scriptSetup, source, filename } = sfc;
  18251. const hoistStatic = options.hoistStatic !== false && !script;
  18252. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  18253. const scriptLang = script && script.lang;
  18254. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  18255. if (!scriptSetup) {
  18256. if (!script) {
  18257. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  18258. }
  18259. return processNormalScript(ctx, scopeId);
  18260. }
  18261. if (script && scriptLang !== scriptSetupLang) {
  18262. throw new Error(
  18263. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  18264. );
  18265. }
  18266. if (scriptSetupLang && !ctx.isJS && !ctx.isTS) {
  18267. return scriptSetup;
  18268. }
  18269. const scriptBindings = /* @__PURE__ */ Object.create(null);
  18270. const setupBindings = /* @__PURE__ */ Object.create(null);
  18271. let defaultExport;
  18272. let hasAwait = false;
  18273. let hasInlinedSsrRenderFn = false;
  18274. const startOffset = ctx.startOffset;
  18275. const endOffset = ctx.endOffset;
  18276. const scriptStartOffset = script && script.loc.start.offset;
  18277. const scriptEndOffset = script && script.loc.end.offset;
  18278. function hoistNode(node) {
  18279. const start = node.start + startOffset;
  18280. let end = node.end + startOffset;
  18281. if (node.trailingComments && node.trailingComments.length > 0) {
  18282. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  18283. end = lastCommentNode.end + startOffset;
  18284. }
  18285. while (end <= source.length) {
  18286. if (!/\s/.test(source.charAt(end))) {
  18287. break;
  18288. }
  18289. end++;
  18290. }
  18291. ctx.s.move(start, end, 0);
  18292. }
  18293. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  18294. let isUsedInTemplate = needTemplateUsageCheck;
  18295. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  18296. isUsedInTemplate = isImportUsed(local, sfc);
  18297. }
  18298. ctx.userImports[local] = {
  18299. isType,
  18300. imported,
  18301. local,
  18302. source: source2,
  18303. isFromSetup,
  18304. isUsedInTemplate
  18305. };
  18306. }
  18307. function checkInvalidScopeReference(node, method) {
  18308. if (!node)
  18309. return;
  18310. CompilerDOM.walkIdentifiers(node, (id) => {
  18311. const binding = setupBindings[id.name];
  18312. if (binding && binding !== "literal-const") {
  18313. ctx.error(
  18314. `\`${method}()\` in <script setup> cannot reference locally declared variables because it will be hoisted outside of the setup() function. If your component options require initialization in the module scope, use a separate normal <script> to export the options instead.`,
  18315. id
  18316. );
  18317. }
  18318. });
  18319. }
  18320. const scriptAst = ctx.scriptAst;
  18321. const scriptSetupAst = ctx.scriptSetupAst;
  18322. if (scriptAst) {
  18323. for (const node of scriptAst.body) {
  18324. if (node.type === "ImportDeclaration") {
  18325. for (const specifier of node.specifiers) {
  18326. const imported = getImportedName(specifier);
  18327. registerUserImport(
  18328. node.source.value,
  18329. specifier.local.name,
  18330. imported,
  18331. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  18332. false,
  18333. !options.inlineTemplate
  18334. );
  18335. }
  18336. }
  18337. }
  18338. }
  18339. for (const node of scriptSetupAst.body) {
  18340. if (node.type === "ImportDeclaration") {
  18341. hoistNode(node);
  18342. let removed = 0;
  18343. const removeSpecifier = (i) => {
  18344. const removeLeft = i > removed;
  18345. removed++;
  18346. const current = node.specifiers[i];
  18347. const next = node.specifiers[i + 1];
  18348. ctx.s.remove(
  18349. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  18350. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  18351. );
  18352. };
  18353. for (let i = 0; i < node.specifiers.length; i++) {
  18354. const specifier = node.specifiers[i];
  18355. const local = specifier.local.name;
  18356. const imported = getImportedName(specifier);
  18357. const source2 = node.source.value;
  18358. const existing = ctx.userImports[local];
  18359. if (source2 === "vue" && (imported === DEFINE_PROPS || imported === DEFINE_EMITS || imported === DEFINE_EXPOSE)) {
  18360. warnOnce(
  18361. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  18362. );
  18363. removeSpecifier(i);
  18364. } else if (existing) {
  18365. if (existing.source === source2 && existing.imported === imported) {
  18366. removeSpecifier(i);
  18367. } else {
  18368. ctx.error(
  18369. `different imports aliased to same local name.`,
  18370. specifier
  18371. );
  18372. }
  18373. } else {
  18374. registerUserImport(
  18375. source2,
  18376. local,
  18377. imported,
  18378. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  18379. true,
  18380. !options.inlineTemplate
  18381. );
  18382. }
  18383. }
  18384. if (node.specifiers.length && removed === node.specifiers.length) {
  18385. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18386. }
  18387. }
  18388. }
  18389. const vueImportAliases = {};
  18390. for (const key in ctx.userImports) {
  18391. const { source: source2, imported, local } = ctx.userImports[key];
  18392. if (source2 === "vue")
  18393. vueImportAliases[imported] = local;
  18394. }
  18395. if (script && scriptAst) {
  18396. for (const node of scriptAst.body) {
  18397. if (node.type === "ExportDefaultDeclaration") {
  18398. defaultExport = node;
  18399. let optionProperties;
  18400. if (defaultExport.declaration.type === "ObjectExpression") {
  18401. optionProperties = defaultExport.declaration.properties;
  18402. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  18403. optionProperties = defaultExport.declaration.arguments[0].properties;
  18404. }
  18405. if (optionProperties) {
  18406. for (const p of optionProperties) {
  18407. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  18408. ctx.hasDefaultExportName = true;
  18409. }
  18410. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  18411. ctx.hasDefaultExportRender = true;
  18412. }
  18413. }
  18414. }
  18415. const start = node.start + scriptStartOffset;
  18416. const end = node.declaration.start + scriptStartOffset;
  18417. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  18418. } else if (node.type === "ExportNamedDeclaration") {
  18419. const defaultSpecifier = node.specifiers.find(
  18420. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  18421. );
  18422. if (defaultSpecifier) {
  18423. defaultExport = node;
  18424. if (node.specifiers.length > 1) {
  18425. ctx.s.remove(
  18426. defaultSpecifier.start + scriptStartOffset,
  18427. defaultSpecifier.end + scriptStartOffset
  18428. );
  18429. } else {
  18430. ctx.s.remove(
  18431. node.start + scriptStartOffset,
  18432. node.end + scriptStartOffset
  18433. );
  18434. }
  18435. if (node.source) {
  18436. ctx.s.prepend(
  18437. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  18438. `
  18439. );
  18440. } else {
  18441. ctx.s.appendLeft(
  18442. scriptEndOffset,
  18443. `
  18444. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  18445. `
  18446. );
  18447. }
  18448. }
  18449. if (node.declaration) {
  18450. walkDeclaration(
  18451. "script",
  18452. node.declaration,
  18453. scriptBindings,
  18454. vueImportAliases,
  18455. hoistStatic
  18456. );
  18457. }
  18458. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  18459. walkDeclaration(
  18460. "script",
  18461. node,
  18462. scriptBindings,
  18463. vueImportAliases,
  18464. hoistStatic
  18465. );
  18466. }
  18467. }
  18468. if (scriptStartOffset > startOffset) {
  18469. if (!/\n$/.test(script.content.trim())) {
  18470. ctx.s.appendLeft(scriptEndOffset, `
  18471. `);
  18472. }
  18473. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  18474. }
  18475. }
  18476. for (const node of scriptSetupAst.body) {
  18477. if (node.type === "ExpressionStatement") {
  18478. const expr = CompilerDOM.unwrapTSNode(node.expression);
  18479. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  18480. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18481. } else if (processDefineExpose(ctx, expr)) {
  18482. const callee = expr.callee;
  18483. ctx.s.overwrite(
  18484. callee.start + startOffset,
  18485. callee.end + startOffset,
  18486. "__expose"
  18487. );
  18488. } else {
  18489. processDefineModel(ctx, expr);
  18490. }
  18491. }
  18492. if (node.type === "VariableDeclaration" && !node.declare) {
  18493. const total = node.declarations.length;
  18494. let left = total;
  18495. let lastNonRemoved;
  18496. for (let i = 0; i < total; i++) {
  18497. const decl = node.declarations[i];
  18498. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  18499. if (init) {
  18500. if (processDefineOptions(ctx, init)) {
  18501. ctx.error(
  18502. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  18503. node
  18504. );
  18505. }
  18506. const isDefineProps = processDefineProps(ctx, init, decl.id);
  18507. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  18508. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  18509. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  18510. if (left === 1) {
  18511. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18512. } else {
  18513. let start = decl.start + startOffset;
  18514. let end = decl.end + startOffset;
  18515. if (i === total - 1) {
  18516. start = node.declarations[lastNonRemoved].end + startOffset;
  18517. } else {
  18518. end = node.declarations[i + 1].start + startOffset;
  18519. }
  18520. ctx.s.remove(start, end);
  18521. left--;
  18522. }
  18523. } else if (isDefineEmits) {
  18524. ctx.s.overwrite(
  18525. startOffset + init.start,
  18526. startOffset + init.end,
  18527. "__emit"
  18528. );
  18529. } else {
  18530. lastNonRemoved = i;
  18531. }
  18532. }
  18533. }
  18534. }
  18535. let isAllLiteral = false;
  18536. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  18537. isAllLiteral = walkDeclaration(
  18538. "scriptSetup",
  18539. node,
  18540. setupBindings,
  18541. vueImportAliases,
  18542. hoistStatic
  18543. );
  18544. }
  18545. if (hoistStatic && isAllLiteral) {
  18546. hoistNode(node);
  18547. }
  18548. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  18549. const scope = [scriptSetupAst.body];
  18550. estreeWalker.walk(node, {
  18551. enter(child, parent) {
  18552. if (CompilerDOM.isFunctionType(child)) {
  18553. this.skip();
  18554. }
  18555. if (child.type === "BlockStatement") {
  18556. scope.push(child.body);
  18557. }
  18558. if (child.type === "AwaitExpression") {
  18559. hasAwait = true;
  18560. const currentScope = scope[scope.length - 1];
  18561. const needsSemi = currentScope.some((n, i) => {
  18562. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  18563. });
  18564. processAwait(
  18565. ctx,
  18566. child,
  18567. needsSemi,
  18568. parent.type === "ExpressionStatement"
  18569. );
  18570. }
  18571. },
  18572. exit(node2) {
  18573. if (node2.type === "BlockStatement")
  18574. scope.pop();
  18575. }
  18576. });
  18577. }
  18578. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  18579. ctx.error(
  18580. `<script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`,
  18581. node
  18582. );
  18583. }
  18584. if (ctx.isTS) {
  18585. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  18586. if (node.type !== "TSEnumDeclaration") {
  18587. hoistNode(node);
  18588. }
  18589. }
  18590. }
  18591. }
  18592. if (ctx.propsDestructureDecl) {
  18593. transformDestructuredProps(ctx, vueImportAliases);
  18594. }
  18595. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  18596. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  18597. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  18598. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  18599. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  18600. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  18601. for (const node of runtimeOptionNodes) {
  18602. checkInvalidScopeReference(node, DEFINE_MODEL);
  18603. }
  18604. }
  18605. if (script) {
  18606. if (startOffset < scriptStartOffset) {
  18607. ctx.s.remove(0, startOffset);
  18608. ctx.s.remove(endOffset, scriptStartOffset);
  18609. ctx.s.remove(scriptEndOffset, source.length);
  18610. } else {
  18611. ctx.s.remove(0, scriptStartOffset);
  18612. ctx.s.remove(scriptEndOffset, startOffset);
  18613. ctx.s.remove(endOffset, source.length);
  18614. }
  18615. } else {
  18616. ctx.s.remove(0, startOffset);
  18617. ctx.s.remove(endOffset, source.length);
  18618. }
  18619. if (scriptAst) {
  18620. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  18621. }
  18622. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  18623. ctx.userImports
  18624. )) {
  18625. if (isType)
  18626. continue;
  18627. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  18628. }
  18629. for (const key in scriptBindings) {
  18630. ctx.bindingMetadata[key] = scriptBindings[key];
  18631. }
  18632. for (const key in setupBindings) {
  18633. ctx.bindingMetadata[key] = setupBindings[key];
  18634. }
  18635. if (sfc.cssVars.length && // no need to do this when targeting SSR
  18636. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  18637. ctx.helperImports.add(CSS_VARS_HELPER);
  18638. ctx.helperImports.add("unref");
  18639. ctx.s.prependLeft(
  18640. startOffset,
  18641. `
  18642. ${genCssVarsCode(
  18643. sfc.cssVars,
  18644. ctx.bindingMetadata,
  18645. scopeId,
  18646. !!options.isProd
  18647. )}
  18648. `
  18649. );
  18650. }
  18651. let args = `__props`;
  18652. if (ctx.propsTypeDecl) {
  18653. args += `: any`;
  18654. }
  18655. if (ctx.propsDecl) {
  18656. if (ctx.propsDestructureRestId) {
  18657. ctx.s.overwrite(
  18658. startOffset + ctx.propsCall.start,
  18659. startOffset + ctx.propsCall.end,
  18660. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  18661. Object.keys(ctx.propsDestructuredBindings)
  18662. )})`
  18663. );
  18664. ctx.s.overwrite(
  18665. startOffset + ctx.propsDestructureDecl.start,
  18666. startOffset + ctx.propsDestructureDecl.end,
  18667. ctx.propsDestructureRestId
  18668. );
  18669. } else if (!ctx.propsDestructureDecl) {
  18670. ctx.s.overwrite(
  18671. startOffset + ctx.propsCall.start,
  18672. startOffset + ctx.propsCall.end,
  18673. "__props"
  18674. );
  18675. }
  18676. }
  18677. if (hasAwait) {
  18678. const any = ctx.isTS ? `: any` : ``;
  18679. ctx.s.prependLeft(startOffset, `
  18680. let __temp${any}, __restore${any}
  18681. `);
  18682. }
  18683. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  18684. if (ctx.emitDecl) {
  18685. destructureElements.push(`emit: __emit`);
  18686. }
  18687. if (destructureElements.length) {
  18688. args += `, { ${destructureElements.join(", ")} }`;
  18689. }
  18690. let returned;
  18691. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  18692. const allBindings = {
  18693. ...scriptBindings,
  18694. ...setupBindings
  18695. };
  18696. for (const key in ctx.userImports) {
  18697. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  18698. allBindings[key] = true;
  18699. }
  18700. }
  18701. returned = `{ `;
  18702. for (const key in allBindings) {
  18703. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  18704. returned += `get ${key}() { return ${key} }, `;
  18705. } else if (ctx.bindingMetadata[key] === "setup-let") {
  18706. const setArg = key === "v" ? `_v` : `v`;
  18707. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  18708. } else {
  18709. returned += `${key}, `;
  18710. }
  18711. }
  18712. returned = returned.replace(/, $/, "") + ` }`;
  18713. } else {
  18714. if (sfc.template && !sfc.template.src) {
  18715. if (options.templateOptions && options.templateOptions.ssr) {
  18716. hasInlinedSsrRenderFn = true;
  18717. }
  18718. const { code, ast, preamble, tips, errors } = compileTemplate({
  18719. filename,
  18720. ast: sfc.template.ast,
  18721. source: sfc.template.content,
  18722. inMap: sfc.template.map,
  18723. ...options.templateOptions,
  18724. id: scopeId,
  18725. scoped: sfc.styles.some((s) => s.scoped),
  18726. isProd: options.isProd,
  18727. ssrCssVars: sfc.cssVars,
  18728. compilerOptions: {
  18729. ...options.templateOptions && options.templateOptions.compilerOptions,
  18730. inline: true,
  18731. isTS: ctx.isTS,
  18732. bindingMetadata: ctx.bindingMetadata
  18733. }
  18734. });
  18735. if (tips.length) {
  18736. tips.forEach(warnOnce);
  18737. }
  18738. const err = errors[0];
  18739. if (typeof err === "string") {
  18740. throw new Error(err);
  18741. } else if (err) {
  18742. if (err.loc) {
  18743. err.message += `
  18744. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  18745. source,
  18746. err.loc.start.offset,
  18747. err.loc.end.offset
  18748. ) + `
  18749. `;
  18750. }
  18751. throw err;
  18752. }
  18753. if (preamble) {
  18754. ctx.s.prepend(preamble);
  18755. }
  18756. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  18757. ctx.helperImports.delete("unref");
  18758. }
  18759. returned = code;
  18760. } else {
  18761. returned = `() => {}`;
  18762. }
  18763. }
  18764. if (!options.inlineTemplate && true) {
  18765. ctx.s.appendRight(
  18766. endOffset,
  18767. `
  18768. const __returned__ = ${returned}
  18769. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  18770. return __returned__
  18771. }
  18772. `
  18773. );
  18774. } else {
  18775. ctx.s.appendRight(endOffset, `
  18776. return ${returned}
  18777. }
  18778. `);
  18779. }
  18780. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  18781. let runtimeOptions = ``;
  18782. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  18783. const match = filename.match(/([^/\\]+)\.\w+$/);
  18784. if (match) {
  18785. runtimeOptions += `
  18786. __name: '${match[1]}',`;
  18787. }
  18788. }
  18789. if (hasInlinedSsrRenderFn) {
  18790. runtimeOptions += `
  18791. __ssrInlineRender: true,`;
  18792. }
  18793. const propsDecl = genRuntimeProps(ctx);
  18794. if (propsDecl)
  18795. runtimeOptions += `
  18796. props: ${propsDecl},`;
  18797. const emitsDecl = genRuntimeEmits(ctx);
  18798. if (emitsDecl)
  18799. runtimeOptions += `
  18800. emits: ${emitsDecl},`;
  18801. let definedOptions = "";
  18802. if (ctx.optionsRuntimeDecl) {
  18803. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  18804. }
  18805. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  18806. `;
  18807. if (ctx.isTS) {
  18808. const def = (defaultExport ? `
  18809. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  18810. ...${definedOptions},` : "");
  18811. ctx.s.prependLeft(
  18812. startOffset,
  18813. `
  18814. ${genDefaultAs} /*#__PURE__*/${ctx.helper(
  18815. `defineComponent`
  18816. )}({${def}${runtimeOptions}
  18817. ${hasAwait ? `async ` : ``}setup(${args}) {
  18818. ${exposeCall}`
  18819. );
  18820. ctx.s.appendRight(endOffset, `})`);
  18821. } else {
  18822. if (defaultExport || definedOptions) {
  18823. ctx.s.prependLeft(
  18824. startOffset,
  18825. `
  18826. ${genDefaultAs} /*#__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  18827. ${hasAwait ? `async ` : ``}setup(${args}) {
  18828. ${exposeCall}`
  18829. );
  18830. ctx.s.appendRight(endOffset, `})`);
  18831. } else {
  18832. ctx.s.prependLeft(
  18833. startOffset,
  18834. `
  18835. ${genDefaultAs} {${runtimeOptions}
  18836. ${hasAwait ? `async ` : ``}setup(${args}) {
  18837. ${exposeCall}`
  18838. );
  18839. ctx.s.appendRight(endOffset, `}`);
  18840. }
  18841. }
  18842. if (ctx.helperImports.size > 0) {
  18843. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  18844. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  18845. ctx.s.prepend(
  18846. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  18847. `
  18848. );
  18849. }
  18850. return {
  18851. ...scriptSetup,
  18852. bindings: ctx.bindingMetadata,
  18853. imports: ctx.userImports,
  18854. content: ctx.s.toString(),
  18855. map: options.sourceMap !== false ? ctx.s.generateMap({
  18856. source: filename,
  18857. hires: true,
  18858. includeContent: true
  18859. }) : void 0,
  18860. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  18861. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  18862. deps: ctx.deps ? [...ctx.deps] : void 0
  18863. };
  18864. }
  18865. function registerBinding(bindings, node, type) {
  18866. bindings[node.name] = type;
  18867. }
  18868. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic) {
  18869. let isAllLiteral = false;
  18870. if (node.type === "VariableDeclaration") {
  18871. const isConst = node.kind === "const";
  18872. isAllLiteral = isConst && node.declarations.every(
  18873. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  18874. );
  18875. for (const { id, init: _init } of node.declarations) {
  18876. const init = _init && CompilerDOM.unwrapTSNode(_init);
  18877. const isDefineCall = !!(isConst && isCallOf(
  18878. init,
  18879. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS
  18880. ));
  18881. if (id.type === "Identifier") {
  18882. let bindingType;
  18883. const userReactiveBinding = userImportAliases["reactive"];
  18884. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  18885. bindingType = "literal-const";
  18886. } else if (isCallOf(init, userReactiveBinding)) {
  18887. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  18888. } else if (
  18889. // if a declaration is a const literal, we can mark it so that
  18890. // the generated render fn code doesn't need to unref() it
  18891. isDefineCall || isConst && canNeverBeRef(init, userReactiveBinding)
  18892. ) {
  18893. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  18894. } else if (isConst) {
  18895. if (isCallOf(
  18896. init,
  18897. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === DEFINE_MODEL
  18898. )) {
  18899. bindingType = "setup-ref";
  18900. } else {
  18901. bindingType = "setup-maybe-ref";
  18902. }
  18903. } else {
  18904. bindingType = "setup-let";
  18905. }
  18906. registerBinding(bindings, id, bindingType);
  18907. } else {
  18908. if (isCallOf(init, DEFINE_PROPS)) {
  18909. continue;
  18910. }
  18911. if (id.type === "ObjectPattern") {
  18912. walkObjectPattern(id, bindings, isConst, isDefineCall);
  18913. } else if (id.type === "ArrayPattern") {
  18914. walkArrayPattern(id, bindings, isConst, isDefineCall);
  18915. }
  18916. }
  18917. }
  18918. } else if (node.type === "TSEnumDeclaration") {
  18919. isAllLiteral = node.members.every(
  18920. (member) => !member.initializer || isStaticNode(member.initializer)
  18921. );
  18922. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  18923. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  18924. bindings[node.id.name] = "setup-const";
  18925. }
  18926. return isAllLiteral;
  18927. }
  18928. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  18929. for (const p of node.properties) {
  18930. if (p.type === "ObjectProperty") {
  18931. if (p.key.type === "Identifier" && p.key === p.value) {
  18932. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18933. registerBinding(bindings, p.key, type);
  18934. } else {
  18935. walkPattern(p.value, bindings, isConst, isDefineCall);
  18936. }
  18937. } else {
  18938. const type = isConst ? "setup-const" : "setup-let";
  18939. registerBinding(bindings, p.argument, type);
  18940. }
  18941. }
  18942. }
  18943. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  18944. for (const e of node.elements) {
  18945. e && walkPattern(e, bindings, isConst, isDefineCall);
  18946. }
  18947. }
  18948. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  18949. if (node.type === "Identifier") {
  18950. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18951. registerBinding(bindings, node, type);
  18952. } else if (node.type === "RestElement") {
  18953. const type = isConst ? "setup-const" : "setup-let";
  18954. registerBinding(bindings, node.argument, type);
  18955. } else if (node.type === "ObjectPattern") {
  18956. walkObjectPattern(node, bindings, isConst);
  18957. } else if (node.type === "ArrayPattern") {
  18958. walkArrayPattern(node, bindings, isConst);
  18959. } else if (node.type === "AssignmentPattern") {
  18960. if (node.left.type === "Identifier") {
  18961. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18962. registerBinding(bindings, node.left, type);
  18963. } else {
  18964. walkPattern(node.left, bindings, isConst);
  18965. }
  18966. }
  18967. }
  18968. function canNeverBeRef(node, userReactiveImport) {
  18969. if (isCallOf(node, userReactiveImport)) {
  18970. return true;
  18971. }
  18972. switch (node.type) {
  18973. case "UnaryExpression":
  18974. case "BinaryExpression":
  18975. case "ArrayExpression":
  18976. case "ObjectExpression":
  18977. case "FunctionExpression":
  18978. case "ArrowFunctionExpression":
  18979. case "UpdateExpression":
  18980. case "ClassExpression":
  18981. case "TaggedTemplateExpression":
  18982. return true;
  18983. case "SequenceExpression":
  18984. return canNeverBeRef(
  18985. node.expressions[node.expressions.length - 1],
  18986. userReactiveImport
  18987. );
  18988. default:
  18989. if (isLiteralNode(node)) {
  18990. return true;
  18991. }
  18992. return false;
  18993. }
  18994. }
  18995. function isStaticNode(node) {
  18996. node = CompilerDOM.unwrapTSNode(node);
  18997. switch (node.type) {
  18998. case "UnaryExpression":
  18999. return isStaticNode(node.argument);
  19000. case "LogicalExpression":
  19001. case "BinaryExpression":
  19002. return isStaticNode(node.left) && isStaticNode(node.right);
  19003. case "ConditionalExpression": {
  19004. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  19005. }
  19006. case "SequenceExpression":
  19007. case "TemplateLiteral":
  19008. return node.expressions.every((expr) => isStaticNode(expr));
  19009. case "ParenthesizedExpression":
  19010. return isStaticNode(node.expression);
  19011. case "StringLiteral":
  19012. case "NumericLiteral":
  19013. case "BooleanLiteral":
  19014. case "NullLiteral":
  19015. case "BigIntLiteral":
  19016. return true;
  19017. }
  19018. return false;
  19019. }
  19020. const version = "3.4.23";
  19021. const parseCache = parseCache$1;
  19022. const errorMessages = {
  19023. ...CompilerDOM.errorMessages,
  19024. ...CompilerDOM.DOMErrorMessages
  19025. };
  19026. const walk = estreeWalker.walk;
  19027. const shouldTransformRef = () => false;
  19028. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  19029. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  19030. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  19031. exports.isStaticProperty = compilerCore.isStaticProperty;
  19032. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  19033. exports.MagicString = MagicString;
  19034. exports.babelParse = parser$1.parse;
  19035. exports.compileScript = compileScript;
  19036. exports.compileStyle = compileStyle;
  19037. exports.compileStyleAsync = compileStyleAsync;
  19038. exports.compileTemplate = compileTemplate;
  19039. exports.errorMessages = errorMessages;
  19040. exports.extractRuntimeEmits = extractRuntimeEmits;
  19041. exports.extractRuntimeProps = extractRuntimeProps;
  19042. exports.inferRuntimeType = inferRuntimeType;
  19043. exports.invalidateTypeCache = invalidateTypeCache;
  19044. exports.parse = parse$2;
  19045. exports.parseCache = parseCache;
  19046. exports.registerTS = registerTS;
  19047. exports.resolveTypeElements = resolveTypeElements;
  19048. exports.rewriteDefault = rewriteDefault;
  19049. exports.rewriteDefaultAST = rewriteDefaultAST;
  19050. exports.shouldTransformRef = shouldTransformRef;
  19051. exports.version = version;
  19052. exports.walk = walk;