compiler-sfc.cjs.js 847 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799
  1. /**
  2. * @vue/compiler-sfc v3.5.35
  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 shared = require('@vue/shared');
  12. var path$1 = require('path');
  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$2 = 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. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  36. function getDefaultExportFromCjs (x) {
  37. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  38. }
  39. var hashSum;
  40. var hasRequiredHashSum;
  41. function requireHashSum () {
  42. if (hasRequiredHashSum) return hashSum;
  43. hasRequiredHashSum = 1;
  44. function pad (hash, len) {
  45. while (hash.length < len) {
  46. hash = '0' + hash;
  47. }
  48. return hash;
  49. }
  50. function fold (hash, text) {
  51. var i;
  52. var chr;
  53. var len;
  54. if (text.length === 0) {
  55. return hash;
  56. }
  57. for (i = 0, len = text.length; i < len; i++) {
  58. chr = text.charCodeAt(i);
  59. hash = ((hash << 5) - hash) + chr;
  60. hash |= 0;
  61. }
  62. return hash < 0 ? hash * -2 : hash;
  63. }
  64. function foldObject (hash, o, seen) {
  65. return Object.keys(o).sort().reduce(foldKey, hash);
  66. function foldKey (hash, key) {
  67. return foldValue(hash, o[key], key, seen);
  68. }
  69. }
  70. function foldValue (input, value, key, seen) {
  71. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  72. if (value === null) {
  73. return fold(hash, 'null');
  74. }
  75. if (value === undefined) {
  76. return fold(hash, 'undefined');
  77. }
  78. if (typeof value === 'object' || typeof value === 'function') {
  79. if (seen.indexOf(value) !== -1) {
  80. return fold(hash, '[Circular]' + key);
  81. }
  82. seen.push(value);
  83. var objHash = foldObject(hash, value, seen);
  84. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  85. return objHash;
  86. }
  87. try {
  88. return fold(objHash, String(value.valueOf()))
  89. } catch (err) {
  90. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  91. }
  92. }
  93. return fold(hash, value.toString());
  94. }
  95. function toString (o) {
  96. return Object.prototype.toString.call(o);
  97. }
  98. function sum (o) {
  99. return pad(foldValue(0, o, '', []).toString(16), 8);
  100. }
  101. hashSum = sum;
  102. return hashSum;
  103. }
  104. var hashSumExports = /*@__PURE__*/ requireHashSum();
  105. var hash = /*@__PURE__*/getDefaultExportFromCjs(hashSumExports);
  106. const CSS_VARS_HELPER = `useCssVars`;
  107. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  108. return `{
  109. ${vars.map(
  110. (key) => (
  111. // The `:` prefix here is used in `ssrRenderStyle` to distinguish whether
  112. // a custom property comes from `ssrCssVars`. If it does, we need to reset
  113. // its value to `initial` on the component instance to avoid unintentionally
  114. // inheriting the same property value from a different instance of the same
  115. // component in the outer scope.
  116. `"${isSSR ? `:--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  117. )
  118. ).join(",\n ")}
  119. }`;
  120. }
  121. function genVarName(id, raw, isProd, isSSR = false) {
  122. if (isProd) {
  123. return hash(id + raw).replace(/^\d/, (r) => `v${r}`);
  124. } else {
  125. return `${id}-${shared.getEscapedCssVarName(raw, isSSR)}`;
  126. }
  127. }
  128. function normalizeExpression(exp) {
  129. exp = exp.trim();
  130. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  131. return exp.slice(1, -1);
  132. }
  133. return exp;
  134. }
  135. const vBindRE = /v-bind\s*\(/g;
  136. function parseCssVars(sfc) {
  137. const vars = [];
  138. sfc.styles.forEach((style) => {
  139. let match;
  140. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  141. while (match = vBindRE.exec(content)) {
  142. const start = match.index + match[0].length;
  143. const end = lexBinding(content, start);
  144. if (end !== null) {
  145. const variable = normalizeExpression(content.slice(start, end));
  146. if (!vars.includes(variable)) {
  147. vars.push(variable);
  148. }
  149. }
  150. }
  151. });
  152. return vars;
  153. }
  154. function lexBinding(content, start) {
  155. let state = 0 /* inParens */;
  156. let parenDepth = 0;
  157. for (let i = start; i < content.length; i++) {
  158. const char = content.charAt(i);
  159. switch (state) {
  160. case 0 /* inParens */:
  161. if (char === `'`) {
  162. state = 1 /* inSingleQuoteString */;
  163. } else if (char === `"`) {
  164. state = 2 /* inDoubleQuoteString */;
  165. } else if (char === `(`) {
  166. parenDepth++;
  167. } else if (char === `)`) {
  168. if (parenDepth > 0) {
  169. parenDepth--;
  170. } else {
  171. return i;
  172. }
  173. }
  174. break;
  175. case 1 /* inSingleQuoteString */:
  176. if (char === `'`) {
  177. state = 0 /* inParens */;
  178. }
  179. break;
  180. case 2 /* inDoubleQuoteString */:
  181. if (char === `"`) {
  182. state = 0 /* inParens */;
  183. }
  184. break;
  185. }
  186. }
  187. return null;
  188. }
  189. const cssVarsPlugin = (opts) => {
  190. const { id, isProd } = opts;
  191. return {
  192. postcssPlugin: "vue-sfc-vars",
  193. Declaration(decl) {
  194. const value = decl.value;
  195. if (vBindRE.test(value)) {
  196. vBindRE.lastIndex = 0;
  197. let transformed = "";
  198. let lastIndex = 0;
  199. let match;
  200. while (match = vBindRE.exec(value)) {
  201. const start = match.index + match[0].length;
  202. const end = lexBinding(value, start);
  203. if (end !== null) {
  204. const variable = normalizeExpression(value.slice(start, end));
  205. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  206. lastIndex = end + 1;
  207. }
  208. }
  209. decl.value = transformed + value.slice(lastIndex);
  210. }
  211. }
  212. };
  213. };
  214. cssVarsPlugin.postcss = true;
  215. function genCssVarsCode(vars, bindings, id, isProd) {
  216. const varsExp = genCssVarsFromList(vars, id, isProd);
  217. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  218. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  219. prefixIdentifiers: true,
  220. inline: true,
  221. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  222. });
  223. const transformed = CompilerDOM.processExpression(exp, context);
  224. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  225. return typeof c === "string" ? c : c.content;
  226. }).join("");
  227. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  228. }
  229. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  230. return `
  231. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  232. const __injectCSSVars__ = () => {
  233. ${genCssVarsCode(
  234. cssVars,
  235. bindings,
  236. id,
  237. isProd
  238. )}}
  239. const __setup__ = ${defaultVar}.setup
  240. ${defaultVar}.setup = __setup__
  241. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  242. : __injectCSSVars__
  243. `;
  244. }
  245. /**
  246. * @module LRUCache
  247. */
  248. const perf = typeof performance === 'object' &&
  249. performance &&
  250. typeof performance.now === 'function'
  251. ? performance
  252. : Date;
  253. const warned = new Set();
  254. /* c8 ignore start */
  255. const PROCESS = (typeof process === 'object' && !!process ? process : {});
  256. /* c8 ignore start */
  257. const emitWarning = (msg, type, code, fn) => {
  258. typeof PROCESS.emitWarning === 'function'
  259. ? PROCESS.emitWarning(msg, type, code, fn)
  260. : console.error(`[${code}] ${type}: ${msg}`);
  261. };
  262. let AC = globalThis.AbortController;
  263. let AS = globalThis.AbortSignal;
  264. /* c8 ignore start */
  265. if (typeof AC === 'undefined') {
  266. //@ts-ignore
  267. AS = class AbortSignal {
  268. onabort;
  269. _onabort = [];
  270. reason;
  271. aborted = false;
  272. addEventListener(_, fn) {
  273. this._onabort.push(fn);
  274. }
  275. };
  276. //@ts-ignore
  277. AC = class AbortController {
  278. constructor() {
  279. warnACPolyfill();
  280. }
  281. signal = new AS();
  282. abort(reason) {
  283. if (this.signal.aborted)
  284. return;
  285. //@ts-ignore
  286. this.signal.reason = reason;
  287. //@ts-ignore
  288. this.signal.aborted = true;
  289. //@ts-ignore
  290. for (const fn of this.signal._onabort) {
  291. fn(reason);
  292. }
  293. this.signal.onabort?.(reason);
  294. }
  295. };
  296. let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
  297. const warnACPolyfill = () => {
  298. if (!printACPolyfillWarning)
  299. return;
  300. printACPolyfillWarning = false;
  301. emitWarning('AbortController is not defined. If using lru-cache in ' +
  302. 'node 14, load an AbortController polyfill from the ' +
  303. '`node-abort-controller` package. A minimal polyfill is ' +
  304. 'provided for use by LRUCache.fetch(), but it should not be ' +
  305. 'relied upon in other contexts (eg, passing it to other APIs that ' +
  306. 'use AbortController/AbortSignal might have undesirable effects). ' +
  307. 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
  308. };
  309. }
  310. /* c8 ignore stop */
  311. const shouldWarn = (code) => !warned.has(code);
  312. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  313. /* c8 ignore start */
  314. // This is a little bit ridiculous, tbh.
  315. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  316. // And well before that point, you're caching the entire world, I mean,
  317. // that's ~32GB of just integers for the next/prev links, plus whatever
  318. // else to hold that many keys and values. Just filling the memory with
  319. // zeroes at init time is brutal when you get that big.
  320. // But why not be complete?
  321. // Maybe in the future, these limits will have expanded.
  322. const getUintArray = (max) => !isPosInt(max)
  323. ? null
  324. : max <= Math.pow(2, 8)
  325. ? Uint8Array
  326. : max <= Math.pow(2, 16)
  327. ? Uint16Array
  328. : max <= Math.pow(2, 32)
  329. ? Uint32Array
  330. : max <= Number.MAX_SAFE_INTEGER
  331. ? ZeroArray
  332. : null;
  333. /* c8 ignore stop */
  334. class ZeroArray extends Array {
  335. constructor(size) {
  336. super(size);
  337. this.fill(0);
  338. }
  339. }
  340. class Stack {
  341. heap;
  342. length;
  343. // private constructor
  344. static #constructing = false;
  345. static create(max) {
  346. const HeapCls = getUintArray(max);
  347. if (!HeapCls)
  348. return [];
  349. Stack.#constructing = true;
  350. const s = new Stack(max, HeapCls);
  351. Stack.#constructing = false;
  352. return s;
  353. }
  354. constructor(max, HeapCls) {
  355. /* c8 ignore start */
  356. if (!Stack.#constructing) {
  357. throw new TypeError('instantiate Stack using Stack.create(n)');
  358. }
  359. /* c8 ignore stop */
  360. this.heap = new HeapCls(max);
  361. this.length = 0;
  362. }
  363. push(n) {
  364. this.heap[this.length++] = n;
  365. }
  366. pop() {
  367. return this.heap[--this.length];
  368. }
  369. }
  370. /**
  371. * Default export, the thing you're using this module to get.
  372. *
  373. * All properties from the options object (with the exception of
  374. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  375. * normal public members. (`max` and `maxBase` are read-only getters.)
  376. * Changing any of these will alter the defaults for subsequent method calls,
  377. * but is otherwise safe.
  378. */
  379. class LRUCache {
  380. // properties coming in from the options of these, only max and maxSize
  381. // really *need* to be protected. The rest can be modified, as they just
  382. // set defaults for various methods.
  383. #max;
  384. #maxSize;
  385. #dispose;
  386. #disposeAfter;
  387. #fetchMethod;
  388. /**
  389. * {@link LRUCache.OptionsBase.ttl}
  390. */
  391. ttl;
  392. /**
  393. * {@link LRUCache.OptionsBase.ttlResolution}
  394. */
  395. ttlResolution;
  396. /**
  397. * {@link LRUCache.OptionsBase.ttlAutopurge}
  398. */
  399. ttlAutopurge;
  400. /**
  401. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  402. */
  403. updateAgeOnGet;
  404. /**
  405. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  406. */
  407. updateAgeOnHas;
  408. /**
  409. * {@link LRUCache.OptionsBase.allowStale}
  410. */
  411. allowStale;
  412. /**
  413. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  414. */
  415. noDisposeOnSet;
  416. /**
  417. * {@link LRUCache.OptionsBase.noUpdateTTL}
  418. */
  419. noUpdateTTL;
  420. /**
  421. * {@link LRUCache.OptionsBase.maxEntrySize}
  422. */
  423. maxEntrySize;
  424. /**
  425. * {@link LRUCache.OptionsBase.sizeCalculation}
  426. */
  427. sizeCalculation;
  428. /**
  429. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  430. */
  431. noDeleteOnFetchRejection;
  432. /**
  433. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  434. */
  435. noDeleteOnStaleGet;
  436. /**
  437. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  438. */
  439. allowStaleOnFetchAbort;
  440. /**
  441. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  442. */
  443. allowStaleOnFetchRejection;
  444. /**
  445. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  446. */
  447. ignoreFetchAbort;
  448. // computed properties
  449. #size;
  450. #calculatedSize;
  451. #keyMap;
  452. #keyList;
  453. #valList;
  454. #next;
  455. #prev;
  456. #head;
  457. #tail;
  458. #free;
  459. #disposed;
  460. #sizes;
  461. #starts;
  462. #ttls;
  463. #hasDispose;
  464. #hasFetchMethod;
  465. #hasDisposeAfter;
  466. /**
  467. * Do not call this method unless you need to inspect the
  468. * inner workings of the cache. If anything returned by this
  469. * object is modified in any way, strange breakage may occur.
  470. *
  471. * These fields are private for a reason!
  472. *
  473. * @internal
  474. */
  475. static unsafeExposeInternals(c) {
  476. return {
  477. // properties
  478. starts: c.#starts,
  479. ttls: c.#ttls,
  480. sizes: c.#sizes,
  481. keyMap: c.#keyMap,
  482. keyList: c.#keyList,
  483. valList: c.#valList,
  484. next: c.#next,
  485. prev: c.#prev,
  486. get head() {
  487. return c.#head;
  488. },
  489. get tail() {
  490. return c.#tail;
  491. },
  492. free: c.#free,
  493. // methods
  494. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  495. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  496. moveToTail: (index) => c.#moveToTail(index),
  497. indexes: (options) => c.#indexes(options),
  498. rindexes: (options) => c.#rindexes(options),
  499. isStale: (index) => c.#isStale(index),
  500. };
  501. }
  502. // Protected read-only members
  503. /**
  504. * {@link LRUCache.OptionsBase.max} (read-only)
  505. */
  506. get max() {
  507. return this.#max;
  508. }
  509. /**
  510. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  511. */
  512. get maxSize() {
  513. return this.#maxSize;
  514. }
  515. /**
  516. * The total computed size of items in the cache (read-only)
  517. */
  518. get calculatedSize() {
  519. return this.#calculatedSize;
  520. }
  521. /**
  522. * The number of items stored in the cache (read-only)
  523. */
  524. get size() {
  525. return this.#size;
  526. }
  527. /**
  528. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  529. */
  530. get fetchMethod() {
  531. return this.#fetchMethod;
  532. }
  533. /**
  534. * {@link LRUCache.OptionsBase.dispose} (read-only)
  535. */
  536. get dispose() {
  537. return this.#dispose;
  538. }
  539. /**
  540. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  541. */
  542. get disposeAfter() {
  543. return this.#disposeAfter;
  544. }
  545. constructor(options) {
  546. 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;
  547. if (max !== 0 && !isPosInt(max)) {
  548. throw new TypeError('max option must be a nonnegative integer');
  549. }
  550. const UintArray = max ? getUintArray(max) : Array;
  551. if (!UintArray) {
  552. throw new Error('invalid max value: ' + max);
  553. }
  554. this.#max = max;
  555. this.#maxSize = maxSize;
  556. this.maxEntrySize = maxEntrySize || this.#maxSize;
  557. this.sizeCalculation = sizeCalculation;
  558. if (this.sizeCalculation) {
  559. if (!this.#maxSize && !this.maxEntrySize) {
  560. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  561. }
  562. if (typeof this.sizeCalculation !== 'function') {
  563. throw new TypeError('sizeCalculation set to non-function');
  564. }
  565. }
  566. if (fetchMethod !== undefined &&
  567. typeof fetchMethod !== 'function') {
  568. throw new TypeError('fetchMethod must be a function if specified');
  569. }
  570. this.#fetchMethod = fetchMethod;
  571. this.#hasFetchMethod = !!fetchMethod;
  572. this.#keyMap = new Map();
  573. this.#keyList = new Array(max).fill(undefined);
  574. this.#valList = new Array(max).fill(undefined);
  575. this.#next = new UintArray(max);
  576. this.#prev = new UintArray(max);
  577. this.#head = 0;
  578. this.#tail = 0;
  579. this.#free = Stack.create(max);
  580. this.#size = 0;
  581. this.#calculatedSize = 0;
  582. if (typeof dispose === 'function') {
  583. this.#dispose = dispose;
  584. }
  585. if (typeof disposeAfter === 'function') {
  586. this.#disposeAfter = disposeAfter;
  587. this.#disposed = [];
  588. }
  589. else {
  590. this.#disposeAfter = undefined;
  591. this.#disposed = undefined;
  592. }
  593. this.#hasDispose = !!this.#dispose;
  594. this.#hasDisposeAfter = !!this.#disposeAfter;
  595. this.noDisposeOnSet = !!noDisposeOnSet;
  596. this.noUpdateTTL = !!noUpdateTTL;
  597. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  598. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  599. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  600. this.ignoreFetchAbort = !!ignoreFetchAbort;
  601. // NB: maxEntrySize is set to maxSize if it's set
  602. if (this.maxEntrySize !== 0) {
  603. if (this.#maxSize !== 0) {
  604. if (!isPosInt(this.#maxSize)) {
  605. throw new TypeError('maxSize must be a positive integer if specified');
  606. }
  607. }
  608. if (!isPosInt(this.maxEntrySize)) {
  609. throw new TypeError('maxEntrySize must be a positive integer if specified');
  610. }
  611. this.#initializeSizeTracking();
  612. }
  613. this.allowStale = !!allowStale;
  614. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  615. this.updateAgeOnGet = !!updateAgeOnGet;
  616. this.updateAgeOnHas = !!updateAgeOnHas;
  617. this.ttlResolution =
  618. isPosInt(ttlResolution) || ttlResolution === 0
  619. ? ttlResolution
  620. : 1;
  621. this.ttlAutopurge = !!ttlAutopurge;
  622. this.ttl = ttl || 0;
  623. if (this.ttl) {
  624. if (!isPosInt(this.ttl)) {
  625. throw new TypeError('ttl must be a positive integer if specified');
  626. }
  627. this.#initializeTTLTracking();
  628. }
  629. // do not allow completely unbounded caches
  630. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  631. throw new TypeError('At least one of max, maxSize, or ttl is required');
  632. }
  633. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  634. const code = 'LRU_CACHE_UNBOUNDED';
  635. if (shouldWarn(code)) {
  636. warned.add(code);
  637. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  638. 'result in unbounded memory consumption.';
  639. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  640. }
  641. }
  642. }
  643. /**
  644. * Return the remaining TTL time for a given entry key
  645. */
  646. getRemainingTTL(key) {
  647. return this.#keyMap.has(key) ? Infinity : 0;
  648. }
  649. #initializeTTLTracking() {
  650. const ttls = new ZeroArray(this.#max);
  651. const starts = new ZeroArray(this.#max);
  652. this.#ttls = ttls;
  653. this.#starts = starts;
  654. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  655. starts[index] = ttl !== 0 ? start : 0;
  656. ttls[index] = ttl;
  657. if (ttl !== 0 && this.ttlAutopurge) {
  658. const t = setTimeout(() => {
  659. if (this.#isStale(index)) {
  660. this.delete(this.#keyList[index]);
  661. }
  662. }, ttl + 1);
  663. // unref() not supported on all platforms
  664. /* c8 ignore start */
  665. if (t.unref) {
  666. t.unref();
  667. }
  668. /* c8 ignore stop */
  669. }
  670. };
  671. this.#updateItemAge = index => {
  672. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  673. };
  674. this.#statusTTL = (status, index) => {
  675. if (ttls[index]) {
  676. const ttl = ttls[index];
  677. const start = starts[index];
  678. /* c8 ignore next */
  679. if (!ttl || !start)
  680. return;
  681. status.ttl = ttl;
  682. status.start = start;
  683. status.now = cachedNow || getNow();
  684. const age = status.now - start;
  685. status.remainingTTL = ttl - age;
  686. }
  687. };
  688. // debounce calls to perf.now() to 1s so we're not hitting
  689. // that costly call repeatedly.
  690. let cachedNow = 0;
  691. const getNow = () => {
  692. const n = perf.now();
  693. if (this.ttlResolution > 0) {
  694. cachedNow = n;
  695. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  696. // not available on all platforms
  697. /* c8 ignore start */
  698. if (t.unref) {
  699. t.unref();
  700. }
  701. /* c8 ignore stop */
  702. }
  703. return n;
  704. };
  705. this.getRemainingTTL = key => {
  706. const index = this.#keyMap.get(key);
  707. if (index === undefined) {
  708. return 0;
  709. }
  710. const ttl = ttls[index];
  711. const start = starts[index];
  712. if (!ttl || !start) {
  713. return Infinity;
  714. }
  715. const age = (cachedNow || getNow()) - start;
  716. return ttl - age;
  717. };
  718. this.#isStale = index => {
  719. const s = starts[index];
  720. const t = ttls[index];
  721. return !!t && !!s && (cachedNow || getNow()) - s > t;
  722. };
  723. }
  724. // conditionally set private methods related to TTL
  725. #updateItemAge = () => { };
  726. #statusTTL = () => { };
  727. #setItemTTL = () => { };
  728. /* c8 ignore stop */
  729. #isStale = () => false;
  730. #initializeSizeTracking() {
  731. const sizes = new ZeroArray(this.#max);
  732. this.#calculatedSize = 0;
  733. this.#sizes = sizes;
  734. this.#removeItemSize = index => {
  735. this.#calculatedSize -= sizes[index];
  736. sizes[index] = 0;
  737. };
  738. this.#requireSize = (k, v, size, sizeCalculation) => {
  739. // provisionally accept background fetches.
  740. // actual value size will be checked when they return.
  741. if (this.#isBackgroundFetch(v)) {
  742. return 0;
  743. }
  744. if (!isPosInt(size)) {
  745. if (sizeCalculation) {
  746. if (typeof sizeCalculation !== 'function') {
  747. throw new TypeError('sizeCalculation must be a function');
  748. }
  749. size = sizeCalculation(v, k);
  750. if (!isPosInt(size)) {
  751. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  752. }
  753. }
  754. else {
  755. throw new TypeError('invalid size value (must be positive integer). ' +
  756. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  757. 'or size must be set.');
  758. }
  759. }
  760. return size;
  761. };
  762. this.#addItemSize = (index, size, status) => {
  763. sizes[index] = size;
  764. if (this.#maxSize) {
  765. const maxSize = this.#maxSize - sizes[index];
  766. while (this.#calculatedSize > maxSize) {
  767. this.#evict(true);
  768. }
  769. }
  770. this.#calculatedSize += sizes[index];
  771. if (status) {
  772. status.entrySize = size;
  773. status.totalCalculatedSize = this.#calculatedSize;
  774. }
  775. };
  776. }
  777. #removeItemSize = _i => { };
  778. #addItemSize = (_i, _s, _st) => { };
  779. #requireSize = (_k, _v, size, sizeCalculation) => {
  780. if (size || sizeCalculation) {
  781. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  782. }
  783. return 0;
  784. };
  785. *#indexes({ allowStale = this.allowStale } = {}) {
  786. if (this.#size) {
  787. for (let i = this.#tail; true;) {
  788. if (!this.#isValidIndex(i)) {
  789. break;
  790. }
  791. if (allowStale || !this.#isStale(i)) {
  792. yield i;
  793. }
  794. if (i === this.#head) {
  795. break;
  796. }
  797. else {
  798. i = this.#prev[i];
  799. }
  800. }
  801. }
  802. }
  803. *#rindexes({ allowStale = this.allowStale } = {}) {
  804. if (this.#size) {
  805. for (let i = this.#head; true;) {
  806. if (!this.#isValidIndex(i)) {
  807. break;
  808. }
  809. if (allowStale || !this.#isStale(i)) {
  810. yield i;
  811. }
  812. if (i === this.#tail) {
  813. break;
  814. }
  815. else {
  816. i = this.#next[i];
  817. }
  818. }
  819. }
  820. }
  821. #isValidIndex(index) {
  822. return (index !== undefined &&
  823. this.#keyMap.get(this.#keyList[index]) === index);
  824. }
  825. /**
  826. * Return a generator yielding `[key, value]` pairs,
  827. * in order from most recently used to least recently used.
  828. */
  829. *entries() {
  830. for (const i of this.#indexes()) {
  831. if (this.#valList[i] !== undefined &&
  832. this.#keyList[i] !== undefined &&
  833. !this.#isBackgroundFetch(this.#valList[i])) {
  834. yield [this.#keyList[i], this.#valList[i]];
  835. }
  836. }
  837. }
  838. /**
  839. * Inverse order version of {@link LRUCache.entries}
  840. *
  841. * Return a generator yielding `[key, value]` pairs,
  842. * in order from least recently used to most recently used.
  843. */
  844. *rentries() {
  845. for (const i of this.#rindexes()) {
  846. if (this.#valList[i] !== undefined &&
  847. this.#keyList[i] !== undefined &&
  848. !this.#isBackgroundFetch(this.#valList[i])) {
  849. yield [this.#keyList[i], this.#valList[i]];
  850. }
  851. }
  852. }
  853. /**
  854. * Return a generator yielding the keys in the cache,
  855. * in order from most recently used to least recently used.
  856. */
  857. *keys() {
  858. for (const i of this.#indexes()) {
  859. const k = this.#keyList[i];
  860. if (k !== undefined &&
  861. !this.#isBackgroundFetch(this.#valList[i])) {
  862. yield k;
  863. }
  864. }
  865. }
  866. /**
  867. * Inverse order version of {@link LRUCache.keys}
  868. *
  869. * Return a generator yielding the keys in the cache,
  870. * in order from least recently used to most recently used.
  871. */
  872. *rkeys() {
  873. for (const i of this.#rindexes()) {
  874. const k = this.#keyList[i];
  875. if (k !== undefined &&
  876. !this.#isBackgroundFetch(this.#valList[i])) {
  877. yield k;
  878. }
  879. }
  880. }
  881. /**
  882. * Return a generator yielding the values in the cache,
  883. * in order from most recently used to least recently used.
  884. */
  885. *values() {
  886. for (const i of this.#indexes()) {
  887. const v = this.#valList[i];
  888. if (v !== undefined &&
  889. !this.#isBackgroundFetch(this.#valList[i])) {
  890. yield this.#valList[i];
  891. }
  892. }
  893. }
  894. /**
  895. * Inverse order version of {@link LRUCache.values}
  896. *
  897. * Return a generator yielding the values in the cache,
  898. * in order from least recently used to most recently used.
  899. */
  900. *rvalues() {
  901. for (const i of this.#rindexes()) {
  902. const v = this.#valList[i];
  903. if (v !== undefined &&
  904. !this.#isBackgroundFetch(this.#valList[i])) {
  905. yield this.#valList[i];
  906. }
  907. }
  908. }
  909. /**
  910. * Iterating over the cache itself yields the same results as
  911. * {@link LRUCache.entries}
  912. */
  913. [Symbol.iterator]() {
  914. return this.entries();
  915. }
  916. /**
  917. * Find a value for which the supplied fn method returns a truthy value,
  918. * similar to Array.find(). fn is called as fn(value, key, cache).
  919. */
  920. find(fn, getOptions = {}) {
  921. for (const i of this.#indexes()) {
  922. const v = this.#valList[i];
  923. const value = this.#isBackgroundFetch(v)
  924. ? v.__staleWhileFetching
  925. : v;
  926. if (value === undefined)
  927. continue;
  928. if (fn(value, this.#keyList[i], this)) {
  929. return this.get(this.#keyList[i], getOptions);
  930. }
  931. }
  932. }
  933. /**
  934. * Call the supplied function on each item in the cache, in order from
  935. * most recently used to least recently used. fn is called as
  936. * fn(value, key, cache). Does not update age or recenty of use.
  937. * Does not iterate over stale values.
  938. */
  939. forEach(fn, thisp = this) {
  940. for (const i of this.#indexes()) {
  941. const v = this.#valList[i];
  942. const value = this.#isBackgroundFetch(v)
  943. ? v.__staleWhileFetching
  944. : v;
  945. if (value === undefined)
  946. continue;
  947. fn.call(thisp, value, this.#keyList[i], this);
  948. }
  949. }
  950. /**
  951. * The same as {@link LRUCache.forEach} but items are iterated over in
  952. * reverse order. (ie, less recently used items are iterated over first.)
  953. */
  954. rforEach(fn, thisp = this) {
  955. for (const i of this.#rindexes()) {
  956. const v = this.#valList[i];
  957. const value = this.#isBackgroundFetch(v)
  958. ? v.__staleWhileFetching
  959. : v;
  960. if (value === undefined)
  961. continue;
  962. fn.call(thisp, value, this.#keyList[i], this);
  963. }
  964. }
  965. /**
  966. * Delete any stale entries. Returns true if anything was removed,
  967. * false otherwise.
  968. */
  969. purgeStale() {
  970. let deleted = false;
  971. for (const i of this.#rindexes({ allowStale: true })) {
  972. if (this.#isStale(i)) {
  973. this.delete(this.#keyList[i]);
  974. deleted = true;
  975. }
  976. }
  977. return deleted;
  978. }
  979. /**
  980. * Get the extended info about a given entry, to get its value, size, and
  981. * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
  982. * single key. Always returns stale values, if their info is found in the
  983. * cache, so be sure to check for expired TTLs if relevant.
  984. */
  985. info(key) {
  986. const i = this.#keyMap.get(key);
  987. if (i === undefined)
  988. return undefined;
  989. const v = this.#valList[i];
  990. const value = this.#isBackgroundFetch(v)
  991. ? v.__staleWhileFetching
  992. : v;
  993. if (value === undefined)
  994. return undefined;
  995. const entry = { value };
  996. if (this.#ttls && this.#starts) {
  997. const ttl = this.#ttls[i];
  998. const start = this.#starts[i];
  999. if (ttl && start) {
  1000. const remain = ttl - (perf.now() - start);
  1001. entry.ttl = remain;
  1002. entry.start = Date.now();
  1003. }
  1004. }
  1005. if (this.#sizes) {
  1006. entry.size = this.#sizes[i];
  1007. }
  1008. return entry;
  1009. }
  1010. /**
  1011. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1012. * passed to cache.load()
  1013. */
  1014. dump() {
  1015. const arr = [];
  1016. for (const i of this.#indexes({ allowStale: true })) {
  1017. const key = this.#keyList[i];
  1018. const v = this.#valList[i];
  1019. const value = this.#isBackgroundFetch(v)
  1020. ? v.__staleWhileFetching
  1021. : v;
  1022. if (value === undefined || key === undefined)
  1023. continue;
  1024. const entry = { value };
  1025. if (this.#ttls && this.#starts) {
  1026. entry.ttl = this.#ttls[i];
  1027. // always dump the start relative to a portable timestamp
  1028. // it's ok for this to be a bit slow, it's a rare operation.
  1029. const age = perf.now() - this.#starts[i];
  1030. entry.start = Math.floor(Date.now() - age);
  1031. }
  1032. if (this.#sizes) {
  1033. entry.size = this.#sizes[i];
  1034. }
  1035. arr.unshift([key, entry]);
  1036. }
  1037. return arr;
  1038. }
  1039. /**
  1040. * Reset the cache and load in the items in entries in the order listed.
  1041. * Note that the shape of the resulting cache may be different if the
  1042. * same options are not used in both caches.
  1043. */
  1044. load(arr) {
  1045. this.clear();
  1046. for (const [key, entry] of arr) {
  1047. if (entry.start) {
  1048. // entry.start is a portable timestamp, but we may be using
  1049. // node's performance.now(), so calculate the offset, so that
  1050. // we get the intended remaining TTL, no matter how long it's
  1051. // been on ice.
  1052. //
  1053. // it's ok for this to be a bit slow, it's a rare operation.
  1054. const age = Date.now() - entry.start;
  1055. entry.start = perf.now() - age;
  1056. }
  1057. this.set(key, entry.value, entry);
  1058. }
  1059. }
  1060. /**
  1061. * Add a value to the cache.
  1062. *
  1063. * Note: if `undefined` is specified as a value, this is an alias for
  1064. * {@link LRUCache#delete}
  1065. */
  1066. set(k, v, setOptions = {}) {
  1067. if (v === undefined) {
  1068. this.delete(k);
  1069. return this;
  1070. }
  1071. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  1072. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  1073. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  1074. // if the item doesn't fit, don't do anything
  1075. // NB: maxEntrySize set to maxSize by default
  1076. if (this.maxEntrySize && size > this.maxEntrySize) {
  1077. if (status) {
  1078. status.set = 'miss';
  1079. status.maxEntrySizeExceeded = true;
  1080. }
  1081. // have to delete, in case something is there already.
  1082. this.delete(k);
  1083. return this;
  1084. }
  1085. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  1086. if (index === undefined) {
  1087. // addition
  1088. index = (this.#size === 0
  1089. ? this.#tail
  1090. : this.#free.length !== 0
  1091. ? this.#free.pop()
  1092. : this.#size === this.#max
  1093. ? this.#evict(false)
  1094. : this.#size);
  1095. this.#keyList[index] = k;
  1096. this.#valList[index] = v;
  1097. this.#keyMap.set(k, index);
  1098. this.#next[this.#tail] = index;
  1099. this.#prev[index] = this.#tail;
  1100. this.#tail = index;
  1101. this.#size++;
  1102. this.#addItemSize(index, size, status);
  1103. if (status)
  1104. status.set = 'add';
  1105. noUpdateTTL = false;
  1106. }
  1107. else {
  1108. // update
  1109. this.#moveToTail(index);
  1110. const oldVal = this.#valList[index];
  1111. if (v !== oldVal) {
  1112. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  1113. oldVal.__abortController.abort(new Error('replaced'));
  1114. const { __staleWhileFetching: s } = oldVal;
  1115. if (s !== undefined && !noDisposeOnSet) {
  1116. if (this.#hasDispose) {
  1117. this.#dispose?.(s, k, 'set');
  1118. }
  1119. if (this.#hasDisposeAfter) {
  1120. this.#disposed?.push([s, k, 'set']);
  1121. }
  1122. }
  1123. }
  1124. else if (!noDisposeOnSet) {
  1125. if (this.#hasDispose) {
  1126. this.#dispose?.(oldVal, k, 'set');
  1127. }
  1128. if (this.#hasDisposeAfter) {
  1129. this.#disposed?.push([oldVal, k, 'set']);
  1130. }
  1131. }
  1132. this.#removeItemSize(index);
  1133. this.#addItemSize(index, size, status);
  1134. this.#valList[index] = v;
  1135. if (status) {
  1136. status.set = 'replace';
  1137. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  1138. ? oldVal.__staleWhileFetching
  1139. : oldVal;
  1140. if (oldValue !== undefined)
  1141. status.oldValue = oldValue;
  1142. }
  1143. }
  1144. else if (status) {
  1145. status.set = 'update';
  1146. }
  1147. }
  1148. if (ttl !== 0 && !this.#ttls) {
  1149. this.#initializeTTLTracking();
  1150. }
  1151. if (this.#ttls) {
  1152. if (!noUpdateTTL) {
  1153. this.#setItemTTL(index, ttl, start);
  1154. }
  1155. if (status)
  1156. this.#statusTTL(status, index);
  1157. }
  1158. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  1159. const dt = this.#disposed;
  1160. let task;
  1161. while ((task = dt?.shift())) {
  1162. this.#disposeAfter?.(...task);
  1163. }
  1164. }
  1165. return this;
  1166. }
  1167. /**
  1168. * Evict the least recently used item, returning its value or
  1169. * `undefined` if cache is empty.
  1170. */
  1171. pop() {
  1172. try {
  1173. while (this.#size) {
  1174. const val = this.#valList[this.#head];
  1175. this.#evict(true);
  1176. if (this.#isBackgroundFetch(val)) {
  1177. if (val.__staleWhileFetching) {
  1178. return val.__staleWhileFetching;
  1179. }
  1180. }
  1181. else if (val !== undefined) {
  1182. return val;
  1183. }
  1184. }
  1185. }
  1186. finally {
  1187. if (this.#hasDisposeAfter && this.#disposed) {
  1188. const dt = this.#disposed;
  1189. let task;
  1190. while ((task = dt?.shift())) {
  1191. this.#disposeAfter?.(...task);
  1192. }
  1193. }
  1194. }
  1195. }
  1196. #evict(free) {
  1197. const head = this.#head;
  1198. const k = this.#keyList[head];
  1199. const v = this.#valList[head];
  1200. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  1201. v.__abortController.abort(new Error('evicted'));
  1202. }
  1203. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1204. if (this.#hasDispose) {
  1205. this.#dispose?.(v, k, 'evict');
  1206. }
  1207. if (this.#hasDisposeAfter) {
  1208. this.#disposed?.push([v, k, 'evict']);
  1209. }
  1210. }
  1211. this.#removeItemSize(head);
  1212. // if we aren't about to use the index, then null these out
  1213. if (free) {
  1214. this.#keyList[head] = undefined;
  1215. this.#valList[head] = undefined;
  1216. this.#free.push(head);
  1217. }
  1218. if (this.#size === 1) {
  1219. this.#head = this.#tail = 0;
  1220. this.#free.length = 0;
  1221. }
  1222. else {
  1223. this.#head = this.#next[head];
  1224. }
  1225. this.#keyMap.delete(k);
  1226. this.#size--;
  1227. return head;
  1228. }
  1229. /**
  1230. * Check if a key is in the cache, without updating the recency of use.
  1231. * Will return false if the item is stale, even though it is technically
  1232. * in the cache.
  1233. *
  1234. * Will not update item age unless
  1235. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1236. */
  1237. has(k, hasOptions = {}) {
  1238. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  1239. const index = this.#keyMap.get(k);
  1240. if (index !== undefined) {
  1241. const v = this.#valList[index];
  1242. if (this.#isBackgroundFetch(v) &&
  1243. v.__staleWhileFetching === undefined) {
  1244. return false;
  1245. }
  1246. if (!this.#isStale(index)) {
  1247. if (updateAgeOnHas) {
  1248. this.#updateItemAge(index);
  1249. }
  1250. if (status) {
  1251. status.has = 'hit';
  1252. this.#statusTTL(status, index);
  1253. }
  1254. return true;
  1255. }
  1256. else if (status) {
  1257. status.has = 'stale';
  1258. this.#statusTTL(status, index);
  1259. }
  1260. }
  1261. else if (status) {
  1262. status.has = 'miss';
  1263. }
  1264. return false;
  1265. }
  1266. /**
  1267. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1268. * items.
  1269. *
  1270. * Returns `undefined` if the item is stale, unless
  1271. * {@link LRUCache.OptionsBase.allowStale} is set.
  1272. */
  1273. peek(k, peekOptions = {}) {
  1274. const { allowStale = this.allowStale } = peekOptions;
  1275. const index = this.#keyMap.get(k);
  1276. if (index === undefined ||
  1277. (!allowStale && this.#isStale(index))) {
  1278. return;
  1279. }
  1280. const v = this.#valList[index];
  1281. // either stale and allowed, or forcing a refresh of non-stale value
  1282. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  1283. }
  1284. #backgroundFetch(k, index, options, context) {
  1285. const v = index === undefined ? undefined : this.#valList[index];
  1286. if (this.#isBackgroundFetch(v)) {
  1287. return v;
  1288. }
  1289. const ac = new AC();
  1290. const { signal } = options;
  1291. // when/if our AC signals, then stop listening to theirs.
  1292. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  1293. signal: ac.signal,
  1294. });
  1295. const fetchOpts = {
  1296. signal: ac.signal,
  1297. options,
  1298. context,
  1299. };
  1300. const cb = (v, updateCache = false) => {
  1301. const { aborted } = ac.signal;
  1302. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  1303. if (options.status) {
  1304. if (aborted && !updateCache) {
  1305. options.status.fetchAborted = true;
  1306. options.status.fetchError = ac.signal.reason;
  1307. if (ignoreAbort)
  1308. options.status.fetchAbortIgnored = true;
  1309. }
  1310. else {
  1311. options.status.fetchResolved = true;
  1312. }
  1313. }
  1314. if (aborted && !ignoreAbort && !updateCache) {
  1315. return fetchFail(ac.signal.reason);
  1316. }
  1317. // either we didn't abort, and are still here, or we did, and ignored
  1318. const bf = p;
  1319. if (this.#valList[index] === p) {
  1320. if (v === undefined) {
  1321. if (bf.__staleWhileFetching) {
  1322. this.#valList[index] = bf.__staleWhileFetching;
  1323. }
  1324. else {
  1325. this.delete(k);
  1326. }
  1327. }
  1328. else {
  1329. if (options.status)
  1330. options.status.fetchUpdated = true;
  1331. this.set(k, v, fetchOpts.options);
  1332. }
  1333. }
  1334. return v;
  1335. };
  1336. const eb = (er) => {
  1337. if (options.status) {
  1338. options.status.fetchRejected = true;
  1339. options.status.fetchError = er;
  1340. }
  1341. return fetchFail(er);
  1342. };
  1343. const fetchFail = (er) => {
  1344. const { aborted } = ac.signal;
  1345. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1346. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1347. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1348. const bf = p;
  1349. if (this.#valList[index] === p) {
  1350. // if we allow stale on fetch rejections, then we need to ensure that
  1351. // the stale value is not removed from the cache when the fetch fails.
  1352. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1353. if (del) {
  1354. this.delete(k);
  1355. }
  1356. else if (!allowStaleAborted) {
  1357. // still replace the *promise* with the stale value,
  1358. // since we are done with the promise at this point.
  1359. // leave it untouched if we're still waiting for an
  1360. // aborted background fetch that hasn't yet returned.
  1361. this.#valList[index] = bf.__staleWhileFetching;
  1362. }
  1363. }
  1364. if (allowStale) {
  1365. if (options.status && bf.__staleWhileFetching !== undefined) {
  1366. options.status.returnedStale = true;
  1367. }
  1368. return bf.__staleWhileFetching;
  1369. }
  1370. else if (bf.__returned === bf) {
  1371. throw er;
  1372. }
  1373. };
  1374. const pcall = (res, rej) => {
  1375. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1376. if (fmp && fmp instanceof Promise) {
  1377. fmp.then(v => res(v === undefined ? undefined : v), rej);
  1378. }
  1379. // ignored, we go until we finish, regardless.
  1380. // defer check until we are actually aborting,
  1381. // so fetchMethod can override.
  1382. ac.signal.addEventListener('abort', () => {
  1383. if (!options.ignoreFetchAbort ||
  1384. options.allowStaleOnFetchAbort) {
  1385. res(undefined);
  1386. // when it eventually resolves, update the cache.
  1387. if (options.allowStaleOnFetchAbort) {
  1388. res = v => cb(v, true);
  1389. }
  1390. }
  1391. });
  1392. };
  1393. if (options.status)
  1394. options.status.fetchDispatched = true;
  1395. const p = new Promise(pcall).then(cb, eb);
  1396. const bf = Object.assign(p, {
  1397. __abortController: ac,
  1398. __staleWhileFetching: v,
  1399. __returned: undefined,
  1400. });
  1401. if (index === undefined) {
  1402. // internal, don't expose status.
  1403. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1404. index = this.#keyMap.get(k);
  1405. }
  1406. else {
  1407. this.#valList[index] = bf;
  1408. }
  1409. return bf;
  1410. }
  1411. #isBackgroundFetch(p) {
  1412. if (!this.#hasFetchMethod)
  1413. return false;
  1414. const b = p;
  1415. return (!!b &&
  1416. b instanceof Promise &&
  1417. b.hasOwnProperty('__staleWhileFetching') &&
  1418. b.__abortController instanceof AC);
  1419. }
  1420. async fetch(k, fetchOptions = {}) {
  1421. const {
  1422. // get options
  1423. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1424. // set options
  1425. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1426. // fetch exclusive options
  1427. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1428. if (!this.#hasFetchMethod) {
  1429. if (status)
  1430. status.fetch = 'get';
  1431. return this.get(k, {
  1432. allowStale,
  1433. updateAgeOnGet,
  1434. noDeleteOnStaleGet,
  1435. status,
  1436. });
  1437. }
  1438. const options = {
  1439. allowStale,
  1440. updateAgeOnGet,
  1441. noDeleteOnStaleGet,
  1442. ttl,
  1443. noDisposeOnSet,
  1444. size,
  1445. sizeCalculation,
  1446. noUpdateTTL,
  1447. noDeleteOnFetchRejection,
  1448. allowStaleOnFetchRejection,
  1449. allowStaleOnFetchAbort,
  1450. ignoreFetchAbort,
  1451. status,
  1452. signal,
  1453. };
  1454. let index = this.#keyMap.get(k);
  1455. if (index === undefined) {
  1456. if (status)
  1457. status.fetch = 'miss';
  1458. const p = this.#backgroundFetch(k, index, options, context);
  1459. return (p.__returned = p);
  1460. }
  1461. else {
  1462. // in cache, maybe already fetching
  1463. const v = this.#valList[index];
  1464. if (this.#isBackgroundFetch(v)) {
  1465. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1466. if (status) {
  1467. status.fetch = 'inflight';
  1468. if (stale)
  1469. status.returnedStale = true;
  1470. }
  1471. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1472. }
  1473. // if we force a refresh, that means do NOT serve the cached value,
  1474. // unless we are already in the process of refreshing the cache.
  1475. const isStale = this.#isStale(index);
  1476. if (!forceRefresh && !isStale) {
  1477. if (status)
  1478. status.fetch = 'hit';
  1479. this.#moveToTail(index);
  1480. if (updateAgeOnGet) {
  1481. this.#updateItemAge(index);
  1482. }
  1483. if (status)
  1484. this.#statusTTL(status, index);
  1485. return v;
  1486. }
  1487. // ok, it is stale or a forced refresh, and not already fetching.
  1488. // refresh the cache.
  1489. const p = this.#backgroundFetch(k, index, options, context);
  1490. const hasStale = p.__staleWhileFetching !== undefined;
  1491. const staleVal = hasStale && allowStale;
  1492. if (status) {
  1493. status.fetch = isStale ? 'stale' : 'refresh';
  1494. if (staleVal && isStale)
  1495. status.returnedStale = true;
  1496. }
  1497. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1498. }
  1499. }
  1500. /**
  1501. * Return a value from the cache. Will update the recency of the cache
  1502. * entry found.
  1503. *
  1504. * If the key is not found, get() will return `undefined`.
  1505. */
  1506. get(k, getOptions = {}) {
  1507. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1508. const index = this.#keyMap.get(k);
  1509. if (index !== undefined) {
  1510. const value = this.#valList[index];
  1511. const fetching = this.#isBackgroundFetch(value);
  1512. if (status)
  1513. this.#statusTTL(status, index);
  1514. if (this.#isStale(index)) {
  1515. if (status)
  1516. status.get = 'stale';
  1517. // delete only if not an in-flight background fetch
  1518. if (!fetching) {
  1519. if (!noDeleteOnStaleGet) {
  1520. this.delete(k);
  1521. }
  1522. if (status && allowStale)
  1523. status.returnedStale = true;
  1524. return allowStale ? value : undefined;
  1525. }
  1526. else {
  1527. if (status &&
  1528. allowStale &&
  1529. value.__staleWhileFetching !== undefined) {
  1530. status.returnedStale = true;
  1531. }
  1532. return allowStale ? value.__staleWhileFetching : undefined;
  1533. }
  1534. }
  1535. else {
  1536. if (status)
  1537. status.get = 'hit';
  1538. // if we're currently fetching it, we don't actually have it yet
  1539. // it's not stale, which means this isn't a staleWhileRefetching.
  1540. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1541. // value, then that means the user fetched with {forceRefresh:true},
  1542. // so it's safe to return that value.
  1543. if (fetching) {
  1544. return value.__staleWhileFetching;
  1545. }
  1546. this.#moveToTail(index);
  1547. if (updateAgeOnGet) {
  1548. this.#updateItemAge(index);
  1549. }
  1550. return value;
  1551. }
  1552. }
  1553. else if (status) {
  1554. status.get = 'miss';
  1555. }
  1556. }
  1557. #connect(p, n) {
  1558. this.#prev[n] = p;
  1559. this.#next[p] = n;
  1560. }
  1561. #moveToTail(index) {
  1562. // if tail already, nothing to do
  1563. // if head, move head to next[index]
  1564. // else
  1565. // move next[prev[index]] to next[index] (head has no prev)
  1566. // move prev[next[index]] to prev[index]
  1567. // prev[index] = tail
  1568. // next[tail] = index
  1569. // tail = index
  1570. if (index !== this.#tail) {
  1571. if (index === this.#head) {
  1572. this.#head = this.#next[index];
  1573. }
  1574. else {
  1575. this.#connect(this.#prev[index], this.#next[index]);
  1576. }
  1577. this.#connect(this.#tail, index);
  1578. this.#tail = index;
  1579. }
  1580. }
  1581. /**
  1582. * Deletes a key out of the cache.
  1583. * Returns true if the key was deleted, false otherwise.
  1584. */
  1585. delete(k) {
  1586. let deleted = false;
  1587. if (this.#size !== 0) {
  1588. const index = this.#keyMap.get(k);
  1589. if (index !== undefined) {
  1590. deleted = true;
  1591. if (this.#size === 1) {
  1592. this.clear();
  1593. }
  1594. else {
  1595. this.#removeItemSize(index);
  1596. const v = this.#valList[index];
  1597. if (this.#isBackgroundFetch(v)) {
  1598. v.__abortController.abort(new Error('deleted'));
  1599. }
  1600. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1601. if (this.#hasDispose) {
  1602. this.#dispose?.(v, k, 'delete');
  1603. }
  1604. if (this.#hasDisposeAfter) {
  1605. this.#disposed?.push([v, k, 'delete']);
  1606. }
  1607. }
  1608. this.#keyMap.delete(k);
  1609. this.#keyList[index] = undefined;
  1610. this.#valList[index] = undefined;
  1611. if (index === this.#tail) {
  1612. this.#tail = this.#prev[index];
  1613. }
  1614. else if (index === this.#head) {
  1615. this.#head = this.#next[index];
  1616. }
  1617. else {
  1618. const pi = this.#prev[index];
  1619. this.#next[pi] = this.#next[index];
  1620. const ni = this.#next[index];
  1621. this.#prev[ni] = this.#prev[index];
  1622. }
  1623. this.#size--;
  1624. this.#free.push(index);
  1625. }
  1626. }
  1627. }
  1628. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1629. const dt = this.#disposed;
  1630. let task;
  1631. while ((task = dt?.shift())) {
  1632. this.#disposeAfter?.(...task);
  1633. }
  1634. }
  1635. return deleted;
  1636. }
  1637. /**
  1638. * Clear the cache entirely, throwing away all values.
  1639. */
  1640. clear() {
  1641. for (const index of this.#rindexes({ allowStale: true })) {
  1642. const v = this.#valList[index];
  1643. if (this.#isBackgroundFetch(v)) {
  1644. v.__abortController.abort(new Error('deleted'));
  1645. }
  1646. else {
  1647. const k = this.#keyList[index];
  1648. if (this.#hasDispose) {
  1649. this.#dispose?.(v, k, 'delete');
  1650. }
  1651. if (this.#hasDisposeAfter) {
  1652. this.#disposed?.push([v, k, 'delete']);
  1653. }
  1654. }
  1655. }
  1656. this.#keyMap.clear();
  1657. this.#valList.fill(undefined);
  1658. this.#keyList.fill(undefined);
  1659. if (this.#ttls && this.#starts) {
  1660. this.#ttls.fill(0);
  1661. this.#starts.fill(0);
  1662. }
  1663. if (this.#sizes) {
  1664. this.#sizes.fill(0);
  1665. }
  1666. this.#head = 0;
  1667. this.#tail = 0;
  1668. this.#free.length = 0;
  1669. this.#calculatedSize = 0;
  1670. this.#size = 0;
  1671. if (this.#hasDisposeAfter && this.#disposed) {
  1672. const dt = this.#disposed;
  1673. let task;
  1674. while ((task = dt?.shift())) {
  1675. this.#disposeAfter?.(...task);
  1676. }
  1677. }
  1678. }
  1679. }
  1680. function createCache(max = 500) {
  1681. return new LRUCache({ max });
  1682. }
  1683. function isImportUsed(local, sfc) {
  1684. return resolveTemplateUsedIdentifiers(sfc).has(local);
  1685. }
  1686. const templateAnalysisCache = createCache();
  1687. function resolveTemplateVModelIdentifiers(sfc) {
  1688. return resolveTemplateAnalysisResult(sfc, false).vModelIds;
  1689. }
  1690. function resolveTemplateUsedIdentifiers(sfc) {
  1691. return resolveTemplateAnalysisResult(sfc).usedIds;
  1692. }
  1693. function resolveTemplateAnalysisResult(sfc, collectUsedIds = true) {
  1694. const { content, ast } = sfc.template;
  1695. const cached = templateAnalysisCache.get(content);
  1696. if (cached && (!collectUsedIds || cached.usedIds)) {
  1697. return cached;
  1698. }
  1699. const ids = collectUsedIds ? /* @__PURE__ */ new Set() : void 0;
  1700. const vModelIds = /* @__PURE__ */ new Set();
  1701. ast.children.forEach(walk);
  1702. function walk(node) {
  1703. var _a;
  1704. switch (node.type) {
  1705. case 1:
  1706. let tag = node.tag;
  1707. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  1708. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1709. if (ids) {
  1710. ids.add(shared.camelize(tag));
  1711. ids.add(shared.capitalize(shared.camelize(tag)));
  1712. }
  1713. }
  1714. for (let i = 0; i < node.props.length; i++) {
  1715. const prop = node.props[i];
  1716. if (prop.type === 7) {
  1717. if (ids) {
  1718. if (!shared.isBuiltInDirective(prop.name)) {
  1719. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1720. }
  1721. }
  1722. if (prop.name === "model") {
  1723. const exp = prop.exp;
  1724. if (exp && exp.type === 4) {
  1725. const expString = exp.content.trim();
  1726. if (CompilerDOM.isSimpleIdentifier(expString) && expString !== "undefined") {
  1727. vModelIds.add(expString);
  1728. }
  1729. }
  1730. }
  1731. if (ids && prop.arg && !prop.arg.isStatic) {
  1732. extractIdentifiers(ids, prop.arg);
  1733. }
  1734. if (ids) {
  1735. if (prop.name === "for") {
  1736. extractIdentifiers(ids, prop.forParseResult.source);
  1737. } else if (prop.exp) {
  1738. extractIdentifiers(ids, prop.exp);
  1739. } else if (prop.name === "bind" && !prop.exp) {
  1740. ids.add(shared.camelize(prop.arg.content));
  1741. }
  1742. }
  1743. }
  1744. if (ids && prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1745. ids.add(prop.value.content);
  1746. }
  1747. }
  1748. node.children.forEach(walk);
  1749. break;
  1750. case 5:
  1751. if (ids) extractIdentifiers(ids, node.content);
  1752. break;
  1753. }
  1754. }
  1755. const result = { usedIds: ids, vModelIds };
  1756. templateAnalysisCache.set(content, result);
  1757. return result;
  1758. }
  1759. function extractIdentifiers(ids, node) {
  1760. if (node.ast) {
  1761. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1762. } else if (node.ast === null) {
  1763. ids.add(node.content);
  1764. }
  1765. }
  1766. const DEFAULT_FILENAME = "anonymous.vue";
  1767. const parseCache$1 = createCache();
  1768. function parse$1(source, options = {}) {
  1769. var _a;
  1770. const sourceKey = shared.genCacheKey(source, {
  1771. ...options,
  1772. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1773. });
  1774. const cache = parseCache$1.get(sourceKey);
  1775. if (cache) {
  1776. return cache;
  1777. }
  1778. const {
  1779. sourceMap = true,
  1780. filename = DEFAULT_FILENAME,
  1781. sourceRoot = "",
  1782. pad = false,
  1783. ignoreEmpty = true,
  1784. compiler = CompilerDOM__namespace,
  1785. templateParseOptions = {}
  1786. } = options;
  1787. const descriptor = {
  1788. filename,
  1789. source,
  1790. template: null,
  1791. script: null,
  1792. scriptSetup: null,
  1793. styles: [],
  1794. customBlocks: [],
  1795. cssVars: [],
  1796. slotted: false,
  1797. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1798. };
  1799. const errors = [];
  1800. const ast = compiler.parse(source, {
  1801. parseMode: "sfc",
  1802. prefixIdentifiers: true,
  1803. ...templateParseOptions,
  1804. onError: (e) => {
  1805. errors.push(e);
  1806. }
  1807. });
  1808. ast.children.forEach((node) => {
  1809. if (node.type !== 1) {
  1810. return;
  1811. }
  1812. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1813. return;
  1814. }
  1815. switch (node.tag) {
  1816. case "template":
  1817. if (!descriptor.template) {
  1818. const templateBlock = descriptor.template = createBlock(
  1819. node,
  1820. source,
  1821. false
  1822. );
  1823. if (!templateBlock.attrs.src) {
  1824. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1825. }
  1826. if (templateBlock.attrs.functional) {
  1827. const err = new SyntaxError(
  1828. `<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.`
  1829. );
  1830. err.loc = node.props.find(
  1831. (p) => p.type === 6 && p.name === "functional"
  1832. ).loc;
  1833. errors.push(err);
  1834. }
  1835. } else {
  1836. errors.push(createDuplicateBlockError(node));
  1837. }
  1838. break;
  1839. case "script":
  1840. const scriptBlock = createBlock(node, source, pad);
  1841. const isSetup = !!scriptBlock.attrs.setup;
  1842. if (isSetup && !descriptor.scriptSetup) {
  1843. descriptor.scriptSetup = scriptBlock;
  1844. break;
  1845. }
  1846. if (!isSetup && !descriptor.script) {
  1847. descriptor.script = scriptBlock;
  1848. break;
  1849. }
  1850. errors.push(createDuplicateBlockError(node, isSetup));
  1851. break;
  1852. case "style":
  1853. const styleBlock = createBlock(node, source, pad);
  1854. if (styleBlock.attrs.vars) {
  1855. errors.push(
  1856. new SyntaxError(
  1857. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1858. )
  1859. );
  1860. }
  1861. descriptor.styles.push(styleBlock);
  1862. break;
  1863. default:
  1864. descriptor.customBlocks.push(createBlock(node, source, pad));
  1865. break;
  1866. }
  1867. });
  1868. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1869. errors.push(
  1870. new SyntaxError(
  1871. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  1872. )
  1873. );
  1874. }
  1875. if (descriptor.scriptSetup) {
  1876. if (descriptor.scriptSetup.src) {
  1877. errors.push(
  1878. new SyntaxError(
  1879. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1880. )
  1881. );
  1882. descriptor.scriptSetup = null;
  1883. }
  1884. if (descriptor.script && descriptor.script.src) {
  1885. errors.push(
  1886. new SyntaxError(
  1887. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1888. )
  1889. );
  1890. descriptor.script = null;
  1891. }
  1892. }
  1893. let templateColumnOffset = 0;
  1894. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1895. [descriptor.template.content, templateColumnOffset] = dedent(
  1896. descriptor.template.content
  1897. );
  1898. }
  1899. if (sourceMap) {
  1900. const genMap = (block, columnOffset = 0) => {
  1901. if (block && !block.src) {
  1902. block.map = generateSourceMap(
  1903. filename,
  1904. source,
  1905. block.content,
  1906. sourceRoot,
  1907. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1908. columnOffset
  1909. );
  1910. }
  1911. };
  1912. genMap(descriptor.template, templateColumnOffset);
  1913. genMap(descriptor.script);
  1914. descriptor.styles.forEach((s) => genMap(s));
  1915. descriptor.customBlocks.forEach((s) => genMap(s));
  1916. }
  1917. descriptor.cssVars = parseCssVars(descriptor);
  1918. const slottedRE = /(?:::v-|:)slotted\(/;
  1919. descriptor.slotted = descriptor.styles.some(
  1920. (s) => s.scoped && slottedRE.test(s.content)
  1921. );
  1922. const result = {
  1923. descriptor,
  1924. errors
  1925. };
  1926. parseCache$1.set(sourceKey, result);
  1927. return result;
  1928. }
  1929. function createDuplicateBlockError(node, isScriptSetup = false) {
  1930. const err = new SyntaxError(
  1931. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1932. );
  1933. err.loc = node.loc;
  1934. return err;
  1935. }
  1936. function createBlock(node, source, pad) {
  1937. const type = node.tag;
  1938. const loc = node.innerLoc;
  1939. const attrs = {};
  1940. const block = {
  1941. type,
  1942. content: source.slice(loc.start.offset, loc.end.offset),
  1943. loc,
  1944. attrs
  1945. };
  1946. if (pad) {
  1947. block.content = padContent(source, block, pad) + block.content;
  1948. }
  1949. node.props.forEach((p) => {
  1950. if (p.type === 6) {
  1951. const name = p.name;
  1952. attrs[name] = p.value ? p.value.content || true : true;
  1953. if (name === "lang") {
  1954. block.lang = p.value && p.value.content;
  1955. } else if (name === "src") {
  1956. block.src = p.value && p.value.content;
  1957. } else if (type === "style") {
  1958. if (name === "scoped") {
  1959. block.scoped = true;
  1960. } else if (name === "module") {
  1961. block.module = attrs[name];
  1962. }
  1963. } else if (type === "script" && name === "setup") {
  1964. block.setup = attrs.setup;
  1965. }
  1966. }
  1967. });
  1968. return block;
  1969. }
  1970. const splitRE = /\r?\n/g;
  1971. const emptyRE = /^(?:\/\/)?\s*$/;
  1972. const replaceRE = /./g;
  1973. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  1974. const map = new sourceMapJs.SourceMapGenerator({
  1975. file: filename.replace(/\\/g, "/"),
  1976. sourceRoot: sourceRoot.replace(/\\/g, "/")
  1977. });
  1978. map.setSourceContent(filename, source);
  1979. map._sources.add(filename);
  1980. generated.split(splitRE).forEach((line, index) => {
  1981. if (!emptyRE.test(line)) {
  1982. const originalLine = index + 1 + lineOffset;
  1983. const generatedLine = index + 1;
  1984. for (let i = 0; i < line.length; i++) {
  1985. if (!/\s/.test(line[i])) {
  1986. map._mappings.add({
  1987. originalLine,
  1988. originalColumn: i + columnOffset,
  1989. generatedLine,
  1990. generatedColumn: i,
  1991. source: filename,
  1992. name: null
  1993. });
  1994. }
  1995. }
  1996. }
  1997. });
  1998. return map.toJSON();
  1999. }
  2000. function padContent(content, block, pad) {
  2001. content = content.slice(0, block.loc.start.offset);
  2002. if (pad === "space") {
  2003. return content.replace(replaceRE, " ");
  2004. } else {
  2005. const offset = content.split(splitRE).length;
  2006. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  2007. return Array(offset).join(padChar);
  2008. }
  2009. }
  2010. function hasSrc(node) {
  2011. return node.props.some((p) => {
  2012. if (p.type !== 6) {
  2013. return false;
  2014. }
  2015. return p.name === "src";
  2016. });
  2017. }
  2018. function isEmpty(node) {
  2019. for (let i = 0; i < node.children.length; i++) {
  2020. const child = node.children[i];
  2021. if (child.type !== 2 || child.content.trim() !== "") {
  2022. return false;
  2023. }
  2024. }
  2025. return true;
  2026. }
  2027. function hmrShouldReload(prevImports, next) {
  2028. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  2029. return false;
  2030. }
  2031. for (const key in prevImports) {
  2032. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2033. return true;
  2034. }
  2035. }
  2036. return false;
  2037. }
  2038. function dedent(s) {
  2039. const lines = s.split("\n");
  2040. const minIndent = lines.reduce(function(minIndent2, line) {
  2041. var _a, _b;
  2042. if (line.trim() === "") {
  2043. return minIndent2;
  2044. }
  2045. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2046. return Math.min(indent, minIndent2);
  2047. }, Infinity);
  2048. if (minIndent === 0) {
  2049. return [s, minIndent];
  2050. }
  2051. return [
  2052. lines.map(function(line) {
  2053. return line.slice(minIndent);
  2054. }).join("\n"),
  2055. minIndent
  2056. ];
  2057. }
  2058. function isRelativeUrl(url) {
  2059. const firstChar = url.charAt(0);
  2060. return firstChar === "." || firstChar === "~" || firstChar === "@" || firstChar === "#";
  2061. }
  2062. const externalRE = /^(?:https?:)?\/\//;
  2063. function isExternalUrl(url) {
  2064. return externalRE.test(url);
  2065. }
  2066. const dataUrlRE = /^\s*data:/i;
  2067. function isDataUrl(url) {
  2068. return dataUrlRE.test(url);
  2069. }
  2070. function normalizeDecodedImportPath(source) {
  2071. try {
  2072. return decodeURIComponent(source);
  2073. } catch {
  2074. return source;
  2075. }
  2076. }
  2077. function parseUrl(url) {
  2078. const firstChar = url.charAt(0);
  2079. if (firstChar === "~") {
  2080. const secondChar = url.charAt(1);
  2081. url = url.slice(secondChar === "/" ? 2 : 1);
  2082. }
  2083. return parseUriParts(url);
  2084. }
  2085. function parseUriParts(urlString) {
  2086. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2087. }
  2088. const resourceUrlTagConfig = {
  2089. video: ["src", "poster"],
  2090. source: ["src"],
  2091. img: ["src"]
  2092. };
  2093. const defaultAssetUrlOptions = {
  2094. base: null,
  2095. includeAbsolute: false,
  2096. tags: {
  2097. ...resourceUrlTagConfig,
  2098. image: ["xlink:href", "href"],
  2099. use: ["xlink:href", "href"]
  2100. }
  2101. };
  2102. const normalizeOptions = (options) => {
  2103. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2104. return {
  2105. ...defaultAssetUrlOptions,
  2106. tags: options
  2107. };
  2108. }
  2109. return {
  2110. ...defaultAssetUrlOptions,
  2111. ...options
  2112. };
  2113. };
  2114. const createAssetUrlTransformWithOptions = (options) => {
  2115. return (node, context) => transformAssetUrl(node, context, options);
  2116. };
  2117. function canTransformHashImport(tag, attrName) {
  2118. var _a;
  2119. return !!((_a = resourceUrlTagConfig[tag]) == null ? void 0 : _a.includes(attrName));
  2120. }
  2121. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2122. if (node.type === 1) {
  2123. if (!node.props.length) {
  2124. return;
  2125. }
  2126. const tags = options.tags || defaultAssetUrlOptions.tags;
  2127. const attrs = tags[node.tag];
  2128. const wildCardAttrs = tags["*"];
  2129. if (!attrs && !wildCardAttrs) {
  2130. return;
  2131. }
  2132. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2133. node.props.forEach((attr, index) => {
  2134. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value) {
  2135. return;
  2136. }
  2137. const urlValue = attr.value.content;
  2138. const isHashOnlyValue = urlValue[0] === "#";
  2139. if (isExternalUrl(urlValue) || isDataUrl(urlValue) || // a bare `#` is never a valid import specifier
  2140. urlValue === "#" || isHashOnlyValue && !canTransformHashImport(node.tag, attr.name) || !options.includeAbsolute && !isRelativeUrl(urlValue)) {
  2141. return;
  2142. }
  2143. const url = parseUrl(urlValue);
  2144. if (options.base && urlValue[0] === ".") {
  2145. const base = parseUrl(options.base);
  2146. const protocol = base.protocol || "";
  2147. const host = base.host ? protocol + "//" + base.host : "";
  2148. const basePath = base.path || "/";
  2149. attr.value.content = host + (path$1.posix || path$1).join(basePath, url.path + (url.hash || ""));
  2150. return;
  2151. }
  2152. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2153. node.props[index] = {
  2154. type: 7,
  2155. name: "bind",
  2156. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2157. exp,
  2158. modifiers: [],
  2159. loc: attr.loc
  2160. };
  2161. });
  2162. }
  2163. };
  2164. function resolveOrRegisterImport(source, loc, context) {
  2165. const normalizedSource = normalizeDecodedImportPath(source);
  2166. const existingIndex = context.imports.findIndex(
  2167. (i) => i.path === normalizedSource
  2168. );
  2169. if (existingIndex > -1) {
  2170. return {
  2171. name: `_imports_${existingIndex}`,
  2172. exp: context.imports[existingIndex].exp
  2173. };
  2174. }
  2175. const name = `_imports_${context.imports.length}`;
  2176. const exp = compilerCore.createSimpleExpression(
  2177. name,
  2178. false,
  2179. loc,
  2180. 3
  2181. );
  2182. context.imports.push({
  2183. exp,
  2184. path: normalizedSource
  2185. });
  2186. return { name, exp };
  2187. }
  2188. function getImportsExpressionExp(path2, hash, loc, context) {
  2189. if (!path2 && !hash) {
  2190. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2191. }
  2192. if (!path2 && hash) {
  2193. const { exp } = resolveOrRegisterImport(hash, loc, context);
  2194. return exp;
  2195. }
  2196. if (path2 && !hash) {
  2197. const { exp } = resolveOrRegisterImport(path2, loc, context);
  2198. return exp;
  2199. }
  2200. const { name } = resolveOrRegisterImport(path2, loc, context);
  2201. const hashExp = `${name} + '${hash}'`;
  2202. const finalExp = compilerCore.createSimpleExpression(
  2203. hashExp,
  2204. false,
  2205. loc,
  2206. 3
  2207. );
  2208. if (!context.hoistStatic) {
  2209. return finalExp;
  2210. }
  2211. const existingHoistIndex = context.hoists.findIndex((h) => {
  2212. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2213. });
  2214. if (existingHoistIndex > -1) {
  2215. return compilerCore.createSimpleExpression(
  2216. `_hoisted_${existingHoistIndex + 1}`,
  2217. false,
  2218. loc,
  2219. 3
  2220. );
  2221. }
  2222. return context.hoist(finalExp);
  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) return;
  2235. const value = attr.value.content;
  2236. if (!value) return;
  2237. const imageCandidates = value.split(",").map((s) => {
  2238. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2239. return { url, descriptor };
  2240. });
  2241. for (let i = 0; i < imageCandidates.length; i++) {
  2242. const { url } = imageCandidates[i];
  2243. if (isDataUrl(url)) {
  2244. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2245. imageCandidates.splice(i, 1);
  2246. }
  2247. }
  2248. const shouldProcessUrl = (url) => {
  2249. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2250. };
  2251. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2252. return;
  2253. }
  2254. if (options.base) {
  2255. const base = options.base;
  2256. const set = [];
  2257. let needImportTransform = false;
  2258. imageCandidates.forEach((candidate) => {
  2259. let { url, descriptor } = candidate;
  2260. descriptor = descriptor ? ` ${descriptor}` : ``;
  2261. if (url[0] === ".") {
  2262. candidate.url = (path$1.posix || path$1).join(base, url);
  2263. set.push(candidate.url + descriptor);
  2264. } else if (shouldProcessUrl(url)) {
  2265. needImportTransform = true;
  2266. } else {
  2267. set.push(url + descriptor);
  2268. }
  2269. });
  2270. if (!needImportTransform) {
  2271. attr.value.content = set.join(", ");
  2272. return;
  2273. }
  2274. }
  2275. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2276. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2277. if (shouldProcessUrl(url)) {
  2278. const { path: path2, hash } = parseUrl(url);
  2279. const source = path2 ? path2 : hash;
  2280. if (source) {
  2281. const normalizedSource = normalizeDecodedImportPath(source);
  2282. const existingImportsIndex = context.imports.findIndex(
  2283. (i) => i.path === normalizedSource
  2284. );
  2285. let exp2;
  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: normalizedSource });
  2301. }
  2302. if (path2 && hash) {
  2303. exp2 = compilerCore.createSimpleExpression(
  2304. `${exp2.content} + '${hash}'`,
  2305. false,
  2306. attr.loc,
  2307. 3
  2308. );
  2309. }
  2310. compoundExpression.children.push(exp2);
  2311. }
  2312. } else {
  2313. const exp2 = compilerCore.createSimpleExpression(
  2314. `"${url}"`,
  2315. false,
  2316. attr.loc,
  2317. 3
  2318. );
  2319. compoundExpression.children.push(exp2);
  2320. }
  2321. const isNotLast = imageCandidates.length - 1 > index2;
  2322. if (descriptor && isNotLast) {
  2323. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2324. } else if (descriptor) {
  2325. compoundExpression.children.push(` + ' ${descriptor}'`);
  2326. } else if (isNotLast) {
  2327. compoundExpression.children.push(` + ', ' + `);
  2328. }
  2329. });
  2330. let exp = compoundExpression;
  2331. if (context.hoistStatic) {
  2332. exp = context.hoist(compoundExpression);
  2333. exp.constType = 3;
  2334. }
  2335. node.props[index] = {
  2336. type: 7,
  2337. name: "bind",
  2338. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2339. exp,
  2340. modifiers: [],
  2341. loc: attr.loc
  2342. };
  2343. }
  2344. });
  2345. }
  2346. }
  2347. };
  2348. function commonjsRequire(path) {
  2349. 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.');
  2350. }
  2351. var consolidate$2 = {exports: {}};
  2352. var hasRequiredConsolidate$1;
  2353. function requireConsolidate$1 () {
  2354. if (hasRequiredConsolidate$1) return consolidate$2.exports;
  2355. hasRequiredConsolidate$1 = 1;
  2356. (function (module, exports) {
  2357. /*
  2358. * Engines which do not support caching of their file contents
  2359. * should use the `read()` function defined in consolidate.js
  2360. * On top of this, when an engine compiles to a `Function`,
  2361. * these functions should either be cached within consolidate.js
  2362. * or the engine itself via `options.cache`. This will allow
  2363. * users and frameworks to pass `options.cache = true` for
  2364. * `NODE_ENV=production`, however edit the file(s) without
  2365. * re-loading the application in development.
  2366. */
  2367. /**
  2368. * Module dependencies.
  2369. */
  2370. var fs = require$$0;
  2371. var path = path$1;
  2372. var util = require$$2;
  2373. var join = path.join;
  2374. var resolve = path.resolve;
  2375. var extname = path.extname;
  2376. var dirname = path.dirname;
  2377. var isAbsolute = path.isAbsolute;
  2378. var readCache = {};
  2379. /**
  2380. * Require cache.
  2381. */
  2382. var cacheStore = {};
  2383. /**
  2384. * Require cache.
  2385. */
  2386. var requires = {};
  2387. /**
  2388. * Clear the cache.
  2389. *
  2390. * @api public
  2391. */
  2392. exports.clearCache = function() {
  2393. readCache = {};
  2394. cacheStore = {};
  2395. };
  2396. /**
  2397. * Conditionally cache `compiled` template based
  2398. * on the `options` filename and `.cache` boolean.
  2399. *
  2400. * @param {Object} options
  2401. * @param {Function} compiled
  2402. * @return {Function}
  2403. * @api private
  2404. */
  2405. function cache(options, compiled) {
  2406. // cachable
  2407. if (compiled && options.filename && options.cache) {
  2408. delete readCache[options.filename];
  2409. cacheStore[options.filename] = compiled;
  2410. return compiled;
  2411. }
  2412. // check cache
  2413. if (options.filename && options.cache) {
  2414. return cacheStore[options.filename];
  2415. }
  2416. return compiled;
  2417. }
  2418. /**
  2419. * Read `path` with `options` with
  2420. * callback `(err, str)`. When `options.cache`
  2421. * is true the template string will be cached.
  2422. *
  2423. * @param {String} options
  2424. * @param {Function} cb
  2425. * @api private
  2426. */
  2427. function read(path, options, cb) {
  2428. var str = readCache[path];
  2429. var cached = options.cache && str && typeof str === 'string';
  2430. // cached (only if cached is a string and not a compiled template function)
  2431. if (cached) return cb(null, str);
  2432. // read
  2433. fs.readFile(path, 'utf8', function(err, str) {
  2434. if (err) return cb(err);
  2435. // remove extraneous utf8 BOM marker
  2436. str = str.replace(/^\uFEFF/, '');
  2437. if (options.cache) readCache[path] = str;
  2438. cb(null, str);
  2439. });
  2440. }
  2441. /**
  2442. * Read `path` with `options` with
  2443. * callback `(err, str)`. When `options.cache`
  2444. * is true the partial string will be cached.
  2445. *
  2446. * @param {String} options
  2447. * @param {Function} fn
  2448. * @api private
  2449. */
  2450. function readPartials(path, options, cb) {
  2451. if (!options.partials) return cb();
  2452. var keys = Object.keys(options.partials);
  2453. var partials = {};
  2454. function next(index) {
  2455. if (index === keys.length) return cb(null, partials);
  2456. var key = keys[index];
  2457. var partialPath = options.partials[key];
  2458. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2459. return next(++index);
  2460. }
  2461. var file;
  2462. if (isAbsolute(partialPath)) {
  2463. if (extname(partialPath) !== '') {
  2464. file = partialPath;
  2465. } else {
  2466. file = join(partialPath + extname(path));
  2467. }
  2468. } else {
  2469. file = join(dirname(path), partialPath + extname(path));
  2470. }
  2471. read(file, options, function(err, str) {
  2472. if (err) return cb(err);
  2473. partials[key] = str;
  2474. next(++index);
  2475. });
  2476. }
  2477. next(0);
  2478. }
  2479. /**
  2480. * promisify
  2481. */
  2482. function promisify(cb, fn) {
  2483. return new Promise(function(resolve, reject) {
  2484. cb = cb || function(err, html) {
  2485. if (err) {
  2486. return reject(err);
  2487. }
  2488. resolve(html);
  2489. };
  2490. fn(cb);
  2491. });
  2492. }
  2493. /**
  2494. * fromStringRenderer
  2495. */
  2496. function fromStringRenderer(name) {
  2497. return function(path, options, cb) {
  2498. options.filename = path;
  2499. return promisify(cb, function(cb) {
  2500. readPartials(path, options, function(err, partials) {
  2501. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2502. var opts = extend({}, options);
  2503. opts.partials = partials;
  2504. if (err) return cb(err);
  2505. if (cache(opts)) {
  2506. exports[name].render('', opts, cb);
  2507. } else {
  2508. read(path, opts, function(err, str) {
  2509. if (err) return cb(err);
  2510. exports[name].render(str, opts, cb);
  2511. });
  2512. }
  2513. });
  2514. });
  2515. };
  2516. }
  2517. /**
  2518. * velocity support.
  2519. */
  2520. exports.velocityjs = fromStringRenderer('velocityjs');
  2521. /**
  2522. * velocity string support.
  2523. */
  2524. exports.velocityjs.render = function(str, options, cb) {
  2525. return promisify(cb, function(cb) {
  2526. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2527. try {
  2528. options.locals = options;
  2529. cb(null, engine.render(str, options).trimLeft());
  2530. } catch (err) {
  2531. cb(err);
  2532. }
  2533. });
  2534. };
  2535. /**
  2536. * Liquid support.
  2537. */
  2538. exports.liquid = fromStringRenderer('liquid');
  2539. /**
  2540. * Liquid string support.
  2541. */
  2542. /**
  2543. * Note that in order to get filters and custom tags we've had to push
  2544. * all user-defined locals down into @locals. However, just to make things
  2545. * backwards-compatible, any property of `options` that is left after
  2546. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2547. * `includeDir` will also become a local.
  2548. */
  2549. function _renderTinyliquid(engine, str, options, cb) {
  2550. var context = engine.newContext();
  2551. var k;
  2552. /**
  2553. * Note that there's a bug in the library that doesn't allow us to pass
  2554. * the locals to newContext(), hence looping through the keys:
  2555. */
  2556. if (options.locals) {
  2557. for (k in options.locals) {
  2558. context.setLocals(k, options.locals[k]);
  2559. }
  2560. delete options.locals;
  2561. }
  2562. if (options.meta) {
  2563. context.setLocals('page', options.meta);
  2564. delete options.meta;
  2565. }
  2566. /**
  2567. * Add any defined filters:
  2568. */
  2569. if (options.filters) {
  2570. for (k in options.filters) {
  2571. context.setFilter(k, options.filters[k]);
  2572. }
  2573. delete options.filters;
  2574. }
  2575. /**
  2576. * Set up a callback for the include directory:
  2577. */
  2578. var includeDir = options.includeDir || process.cwd();
  2579. context.onInclude(function(name, callback) {
  2580. var extname = path.extname(name) ? '' : '.liquid';
  2581. var filename = path.resolve(includeDir, name + extname);
  2582. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2583. if (err) return callback(err);
  2584. callback(null, engine.parse(data));
  2585. });
  2586. });
  2587. delete options.includeDir;
  2588. /**
  2589. * The custom tag functions need to have their results pushed back
  2590. * through the parser, so set up a shim before calling the provided
  2591. * callback:
  2592. */
  2593. var compileOptions = {
  2594. customTags: {}
  2595. };
  2596. if (options.customTags) {
  2597. var tagFunctions = options.customTags;
  2598. for (k in options.customTags) {
  2599. /*Tell jshint there's no problem with having this function in the loop */
  2600. /*jshint -W083 */
  2601. compileOptions.customTags[k] = function(context, name, body) {
  2602. var tpl = tagFunctions[name](body.trim());
  2603. context.astStack.push(engine.parse(tpl));
  2604. };
  2605. /*jshint +W083 */
  2606. }
  2607. delete options.customTags;
  2608. }
  2609. /**
  2610. * Now anything left in `options` becomes a local:
  2611. */
  2612. for (k in options) {
  2613. context.setLocals(k, options[k]);
  2614. }
  2615. /**
  2616. * Finally, execute the template:
  2617. */
  2618. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2619. tmpl(context, cb);
  2620. }
  2621. exports.liquid.render = function(str, options, cb) {
  2622. return promisify(cb, function(cb) {
  2623. var engine = requires.liquid;
  2624. var Liquid;
  2625. try {
  2626. // set up tinyliquid engine
  2627. engine = requires.liquid = require('tinyliquid');
  2628. // use tinyliquid engine
  2629. _renderTinyliquid(engine, str, options, cb);
  2630. return;
  2631. } catch (err) {
  2632. // set up liquid-node engine
  2633. try {
  2634. Liquid = requires.liquid = require('liquid-node');
  2635. engine = new Liquid.Engine();
  2636. } catch (err) {
  2637. throw err;
  2638. }
  2639. }
  2640. // use liquid-node engine
  2641. try {
  2642. var locals = options.locals || {};
  2643. if (options.meta) {
  2644. locals.pages = options.meta;
  2645. delete options.meta;
  2646. }
  2647. /**
  2648. * Add any defined filters:
  2649. */
  2650. if (options.filters) {
  2651. engine.registerFilters(options.filters);
  2652. delete options.filters;
  2653. }
  2654. /**
  2655. * Set up a callback for the include directory:
  2656. */
  2657. var includeDir = options.includeDir || process.cwd();
  2658. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2659. delete options.includeDir;
  2660. /**
  2661. * The custom tag functions need to have their results pushed back
  2662. * through the parser, so set up a shim before calling the provided
  2663. * callback:
  2664. */
  2665. if (options.customTags) {
  2666. var tagFunctions = options.customTags;
  2667. for (k in options.customTags) {
  2668. engine.registerTag(k, tagFunctions[k]);
  2669. }
  2670. delete options.customTags;
  2671. }
  2672. /**
  2673. * Now anything left in `options` becomes a local:
  2674. */
  2675. for (var k in options) {
  2676. locals[k] = options[k];
  2677. }
  2678. /**
  2679. * Finally, execute the template:
  2680. */
  2681. return engine
  2682. .parseAndRender(str, locals)
  2683. .nodeify(function(err, result) {
  2684. if (err) {
  2685. throw new Error(err);
  2686. } else {
  2687. return cb(null, result);
  2688. }
  2689. });
  2690. } catch (err) {
  2691. cb(err);
  2692. }
  2693. });
  2694. };
  2695. /**
  2696. * Jade support.
  2697. */
  2698. exports.jade = function(path, options, cb) {
  2699. return promisify(cb, function(cb) {
  2700. var engine = requires.jade;
  2701. if (!engine) {
  2702. try {
  2703. engine = requires.jade = require('jade');
  2704. } catch (err) {
  2705. try {
  2706. engine = requires.jade = require('then-jade');
  2707. } catch (otherError) {
  2708. throw err;
  2709. }
  2710. }
  2711. }
  2712. try {
  2713. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2714. cb(null, tmpl(options));
  2715. } catch (err) {
  2716. cb(err);
  2717. }
  2718. });
  2719. };
  2720. /**
  2721. * Jade string support.
  2722. */
  2723. exports.jade.render = function(str, options, cb) {
  2724. return promisify(cb, function(cb) {
  2725. var engine = requires.jade;
  2726. if (!engine) {
  2727. try {
  2728. engine = requires.jade = require('jade');
  2729. } catch (err) {
  2730. try {
  2731. engine = requires.jade = require('then-jade');
  2732. } catch (otherError) {
  2733. throw err;
  2734. }
  2735. }
  2736. }
  2737. try {
  2738. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2739. cb(null, tmpl(options));
  2740. } catch (err) {
  2741. cb(err);
  2742. }
  2743. });
  2744. };
  2745. /**
  2746. * Dust support.
  2747. */
  2748. exports.dust = fromStringRenderer('dust');
  2749. /**
  2750. * Dust string support.
  2751. */
  2752. exports.dust.render = function(str, options, cb) {
  2753. return promisify(cb, function(cb) {
  2754. var engine = requires.dust;
  2755. if (!engine) {
  2756. try {
  2757. engine = requires.dust = require('dust');
  2758. } catch (err) {
  2759. try {
  2760. engine = requires.dust = require('dustjs-helpers');
  2761. } catch (err) {
  2762. engine = requires.dust = require('dustjs-linkedin');
  2763. }
  2764. }
  2765. }
  2766. var ext = 'dust';
  2767. var views = '.';
  2768. if (options) {
  2769. if (options.ext) ext = options.ext;
  2770. if (options.views) views = options.views;
  2771. if (options.settings && options.settings.views) views = options.settings.views;
  2772. }
  2773. if (!options || (options && !options.cache)) engine.cache = {};
  2774. engine.onLoad = function(path, callback) {
  2775. if (extname(path) === '') path += '.' + ext;
  2776. if (path[0] !== '/') path = views + '/' + path;
  2777. read(path, options, callback);
  2778. };
  2779. try {
  2780. var templateName;
  2781. if (options.filename) {
  2782. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2783. }
  2784. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2785. tmpl(options, cb);
  2786. } catch (err) {
  2787. cb(err);
  2788. }
  2789. });
  2790. };
  2791. /**
  2792. * Swig support.
  2793. */
  2794. exports.swig = fromStringRenderer('swig');
  2795. /**
  2796. * Swig string support.
  2797. */
  2798. exports.swig.render = function(str, options, cb) {
  2799. return promisify(cb, function(cb) {
  2800. var engine = requires.swig;
  2801. if (!engine) {
  2802. try {
  2803. engine = requires.swig = require('swig');
  2804. } catch (err) {
  2805. try {
  2806. engine = requires.swig = require('swig-templates');
  2807. } catch (otherError) {
  2808. throw err;
  2809. }
  2810. }
  2811. }
  2812. try {
  2813. if (options.cache === true) options.cache = 'memory';
  2814. engine.setDefaults({ cache: options.cache });
  2815. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2816. cb(null, tmpl(options));
  2817. } catch (err) {
  2818. cb(err);
  2819. }
  2820. });
  2821. };
  2822. /**
  2823. * Razor support.
  2824. */
  2825. exports.razor = function(path, options, cb) {
  2826. return promisify(cb, function(cb) {
  2827. var engine = requires.razor;
  2828. if (!engine) {
  2829. try {
  2830. engine = requires.razor = require('razor-tmpl');
  2831. } catch (err) {
  2832. throw err;
  2833. }
  2834. }
  2835. try {
  2836. var tmpl = cache(options) || cache(options, (locals) => {
  2837. console.log('Rendering razor file', path);
  2838. return engine.renderFileSync(path, locals);
  2839. });
  2840. cb(null, tmpl(options));
  2841. } catch (err) {
  2842. cb(err);
  2843. }
  2844. });
  2845. };
  2846. /**
  2847. * razor string support.
  2848. */
  2849. exports.razor.render = function(str, options, cb) {
  2850. return promisify(cb, function(cb) {
  2851. try {
  2852. var engine = requires.razor = require('razor-tmpl');
  2853. } catch (err) {
  2854. throw err;
  2855. }
  2856. try {
  2857. var tf = engine.compile(str);
  2858. var tmpl = cache(options) || cache(options, tf);
  2859. cb(null, tmpl(options));
  2860. } catch (err) {
  2861. cb(err);
  2862. }
  2863. });
  2864. };
  2865. /**
  2866. * Atpl support.
  2867. */
  2868. exports.atpl = fromStringRenderer('atpl');
  2869. /**
  2870. * Atpl string support.
  2871. */
  2872. exports.atpl.render = function(str, options, cb) {
  2873. return promisify(cb, function(cb) {
  2874. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2875. try {
  2876. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2877. cb(null, tmpl(options));
  2878. } catch (err) {
  2879. cb(err);
  2880. }
  2881. });
  2882. };
  2883. /**
  2884. * Liquor support,
  2885. */
  2886. exports.liquor = fromStringRenderer('liquor');
  2887. /**
  2888. * Liquor string support.
  2889. */
  2890. exports.liquor.render = function(str, options, cb) {
  2891. return promisify(cb, function(cb) {
  2892. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2893. try {
  2894. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2895. cb(null, tmpl(options));
  2896. } catch (err) {
  2897. cb(err);
  2898. }
  2899. });
  2900. };
  2901. /**
  2902. * Twig support.
  2903. */
  2904. exports.twig = fromStringRenderer('twig');
  2905. /**
  2906. * Twig string support.
  2907. */
  2908. exports.twig.render = function(str, options, cb) {
  2909. return promisify(cb, function(cb) {
  2910. var engine = requires.twig || (requires.twig = require('twig').twig);
  2911. var templateData = {
  2912. data: str,
  2913. allowInlineIncludes: options.allowInlineIncludes,
  2914. namespaces: options.namespaces,
  2915. path: options.path
  2916. };
  2917. try {
  2918. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2919. cb(null, tmpl.render(options));
  2920. } catch (err) {
  2921. cb(err);
  2922. }
  2923. });
  2924. };
  2925. /**
  2926. * EJS support.
  2927. */
  2928. exports.ejs = fromStringRenderer('ejs');
  2929. /**
  2930. * EJS string support.
  2931. */
  2932. exports.ejs.render = function(str, options, cb) {
  2933. return promisify(cb, function(cb) {
  2934. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2935. try {
  2936. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2937. cb(null, tmpl(options));
  2938. } catch (err) {
  2939. cb(err);
  2940. }
  2941. });
  2942. };
  2943. /**
  2944. * Eco support.
  2945. */
  2946. exports.eco = fromStringRenderer('eco');
  2947. /**
  2948. * Eco string support.
  2949. */
  2950. exports.eco.render = function(str, options, cb) {
  2951. return promisify(cb, function(cb) {
  2952. var engine = requires.eco || (requires.eco = require('eco'));
  2953. try {
  2954. cb(null, engine.render(str, options));
  2955. } catch (err) {
  2956. cb(err);
  2957. }
  2958. });
  2959. };
  2960. /**
  2961. * Jazz support.
  2962. */
  2963. exports.jazz = fromStringRenderer('jazz');
  2964. /**
  2965. * Jazz string support.
  2966. */
  2967. exports.jazz.render = function(str, options, cb) {
  2968. return promisify(cb, function(cb) {
  2969. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2970. try {
  2971. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2972. tmpl.eval(options, function(str) {
  2973. cb(null, str);
  2974. });
  2975. } catch (err) {
  2976. cb(err);
  2977. }
  2978. });
  2979. };
  2980. /**
  2981. * JQTPL support.
  2982. */
  2983. exports.jqtpl = fromStringRenderer('jqtpl');
  2984. /**
  2985. * JQTPL string support.
  2986. */
  2987. exports.jqtpl.render = function(str, options, cb) {
  2988. return promisify(cb, function(cb) {
  2989. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2990. try {
  2991. engine.template(str, str);
  2992. cb(null, engine.tmpl(str, options));
  2993. } catch (err) {
  2994. cb(err);
  2995. }
  2996. });
  2997. };
  2998. /**
  2999. * Haml support.
  3000. */
  3001. exports.haml = fromStringRenderer('haml');
  3002. /**
  3003. * Haml string support.
  3004. */
  3005. exports.haml.render = function(str, options, cb) {
  3006. return promisify(cb, function(cb) {
  3007. var engine = requires.haml || (requires.haml = require('hamljs'));
  3008. try {
  3009. options.locals = options;
  3010. cb(null, engine.render(str, options).trimLeft());
  3011. } catch (err) {
  3012. cb(err);
  3013. }
  3014. });
  3015. };
  3016. /**
  3017. * Hamlet support.
  3018. */
  3019. exports.hamlet = fromStringRenderer('hamlet');
  3020. /**
  3021. * Hamlet string support.
  3022. */
  3023. exports.hamlet.render = function(str, options, cb) {
  3024. return promisify(cb, function(cb) {
  3025. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  3026. try {
  3027. options.locals = options;
  3028. cb(null, engine.render(str, options).trimLeft());
  3029. } catch (err) {
  3030. cb(err);
  3031. }
  3032. });
  3033. };
  3034. /**
  3035. * Whiskers support.
  3036. */
  3037. exports.whiskers = function(path, options, cb) {
  3038. return promisify(cb, function(cb) {
  3039. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3040. engine.__express(path, options, cb);
  3041. });
  3042. };
  3043. /**
  3044. * Whiskers string support.
  3045. */
  3046. exports.whiskers.render = function(str, options, cb) {
  3047. return promisify(cb, function(cb) {
  3048. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3049. try {
  3050. cb(null, engine.render(str, options));
  3051. } catch (err) {
  3052. cb(err);
  3053. }
  3054. });
  3055. };
  3056. /**
  3057. * Coffee-HAML support.
  3058. */
  3059. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  3060. /**
  3061. * Coffee-HAML string support.
  3062. */
  3063. exports['haml-coffee'].render = function(str, options, cb) {
  3064. return promisify(cb, function(cb) {
  3065. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3066. try {
  3067. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3068. cb(null, tmpl(options));
  3069. } catch (err) {
  3070. cb(err);
  3071. }
  3072. });
  3073. };
  3074. /**
  3075. * Hogan support.
  3076. */
  3077. exports.hogan = fromStringRenderer('hogan');
  3078. /**
  3079. * Hogan string support.
  3080. */
  3081. exports.hogan.render = function(str, options, cb) {
  3082. return promisify(cb, function(cb) {
  3083. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3084. try {
  3085. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3086. cb(null, tmpl.render(options, options.partials));
  3087. } catch (err) {
  3088. cb(err);
  3089. }
  3090. });
  3091. };
  3092. /**
  3093. * templayed.js support.
  3094. */
  3095. exports.templayed = fromStringRenderer('templayed');
  3096. /**
  3097. * templayed.js string support.
  3098. */
  3099. exports.templayed.render = function(str, options, cb) {
  3100. return promisify(cb, function(cb) {
  3101. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3102. try {
  3103. var tmpl = cache(options) || cache(options, engine(str));
  3104. cb(null, tmpl(options));
  3105. } catch (err) {
  3106. cb(err);
  3107. }
  3108. });
  3109. };
  3110. /**
  3111. * Handlebars support.
  3112. */
  3113. exports.handlebars = fromStringRenderer('handlebars');
  3114. /**
  3115. * Handlebars string support.
  3116. */
  3117. exports.handlebars.render = function(str, options, cb) {
  3118. return promisify(cb, function(cb) {
  3119. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3120. try {
  3121. for (var partial in options.partials) {
  3122. engine.registerPartial(partial, options.partials[partial]);
  3123. }
  3124. for (var helper in options.helpers) {
  3125. engine.registerHelper(helper, options.helpers[helper]);
  3126. }
  3127. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3128. cb(null, tmpl(options));
  3129. } catch (err) {
  3130. cb(err);
  3131. }
  3132. });
  3133. };
  3134. /**
  3135. * Underscore support.
  3136. */
  3137. exports.underscore = fromStringRenderer('underscore');
  3138. /**
  3139. * Underscore string support.
  3140. */
  3141. exports.underscore.render = function(str, options, cb) {
  3142. return promisify(cb, function(cb) {
  3143. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3144. try {
  3145. const partials = {};
  3146. for (var partial in options.partials) {
  3147. partials[partial] = engine.template(options.partials[partial]);
  3148. }
  3149. options.partials = partials;
  3150. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3151. cb(null, tmpl(options).replace(/\n$/, ''));
  3152. } catch (err) {
  3153. cb(err);
  3154. }
  3155. });
  3156. };
  3157. /**
  3158. * Lodash support.
  3159. */
  3160. exports.lodash = fromStringRenderer('lodash');
  3161. /**
  3162. * Lodash string support.
  3163. */
  3164. exports.lodash.render = function(str, options, cb) {
  3165. return promisify(cb, function(cb) {
  3166. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3167. try {
  3168. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3169. cb(null, tmpl(options).replace(/\n$/, ''));
  3170. } catch (err) {
  3171. cb(err);
  3172. }
  3173. });
  3174. };
  3175. /**
  3176. * Pug support. (formerly Jade)
  3177. */
  3178. exports.pug = function(path, options, cb) {
  3179. return promisify(cb, function(cb) {
  3180. var engine = requires.pug;
  3181. if (!engine) {
  3182. try {
  3183. engine = requires.pug = require('pug');
  3184. } catch (err) {
  3185. try {
  3186. engine = requires.pug = require('then-pug');
  3187. } catch (otherError) {
  3188. throw err;
  3189. }
  3190. }
  3191. }
  3192. try {
  3193. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3194. cb(null, tmpl(options));
  3195. } catch (err) {
  3196. cb(err);
  3197. }
  3198. });
  3199. };
  3200. /**
  3201. * Pug string support.
  3202. */
  3203. exports.pug.render = function(str, options, cb) {
  3204. return promisify(cb, function(cb) {
  3205. var engine = requires.pug;
  3206. if (!engine) {
  3207. try {
  3208. engine = requires.pug = require('pug');
  3209. } catch (err) {
  3210. try {
  3211. engine = requires.pug = require('then-pug');
  3212. } catch (otherError) {
  3213. throw err;
  3214. }
  3215. }
  3216. }
  3217. try {
  3218. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3219. cb(null, tmpl(options));
  3220. } catch (err) {
  3221. cb(err);
  3222. }
  3223. });
  3224. };
  3225. /**
  3226. * QEJS support.
  3227. */
  3228. exports.qejs = fromStringRenderer('qejs');
  3229. /**
  3230. * QEJS string support.
  3231. */
  3232. exports.qejs.render = function(str, options, cb) {
  3233. return promisify(cb, function(cb) {
  3234. try {
  3235. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3236. engine.render(str, options).then(function(result) {
  3237. cb(null, result);
  3238. }, function(err) {
  3239. cb(err);
  3240. }).done();
  3241. } catch (err) {
  3242. cb(err);
  3243. }
  3244. });
  3245. };
  3246. /**
  3247. * Walrus support.
  3248. */
  3249. exports.walrus = fromStringRenderer('walrus');
  3250. /**
  3251. * Walrus string support.
  3252. */
  3253. exports.walrus.render = function(str, options, cb) {
  3254. return promisify(cb, function(cb) {
  3255. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3256. try {
  3257. var tmpl = cache(options) || cache(options, engine.parse(str));
  3258. cb(null, tmpl.compile(options));
  3259. } catch (err) {
  3260. cb(err);
  3261. }
  3262. });
  3263. };
  3264. /**
  3265. * Mustache support.
  3266. */
  3267. exports.mustache = fromStringRenderer('mustache');
  3268. /**
  3269. * Mustache string support.
  3270. */
  3271. exports.mustache.render = function(str, options, cb) {
  3272. return promisify(cb, function(cb) {
  3273. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3274. try {
  3275. cb(null, engine.render(str, options, options.partials));
  3276. } catch (err) {
  3277. cb(err);
  3278. }
  3279. });
  3280. };
  3281. /**
  3282. * Just support.
  3283. */
  3284. exports.just = function(path, options, cb) {
  3285. return promisify(cb, function(cb) {
  3286. var engine = requires.just;
  3287. if (!engine) {
  3288. var JUST = require('just');
  3289. engine = requires.just = new JUST();
  3290. }
  3291. engine.configure({ useCache: options.cache });
  3292. engine.render(path, options, cb);
  3293. });
  3294. };
  3295. /**
  3296. * Just string support.
  3297. */
  3298. exports.just.render = function(str, options, cb) {
  3299. return promisify(cb, function(cb) {
  3300. var JUST = require('just');
  3301. var engine = new JUST({ root: { page: str }});
  3302. engine.render('page', options, cb);
  3303. });
  3304. };
  3305. /**
  3306. * ECT support.
  3307. */
  3308. exports.ect = function(path, options, cb) {
  3309. return promisify(cb, function(cb) {
  3310. var engine = requires.ect;
  3311. if (!engine) {
  3312. var ECT = require('ect');
  3313. engine = requires.ect = new ECT(options);
  3314. }
  3315. engine.configure({ cache: options.cache });
  3316. engine.render(path, options, cb);
  3317. });
  3318. };
  3319. /**
  3320. * ECT string support.
  3321. */
  3322. exports.ect.render = function(str, options, cb) {
  3323. return promisify(cb, function(cb) {
  3324. var ECT = require('ect');
  3325. var engine = new ECT({ root: { page: str }});
  3326. engine.render('page', options, cb);
  3327. });
  3328. };
  3329. /**
  3330. * mote support.
  3331. */
  3332. exports.mote = fromStringRenderer('mote');
  3333. /**
  3334. * mote string support.
  3335. */
  3336. exports.mote.render = function(str, options, cb) {
  3337. return promisify(cb, function(cb) {
  3338. var engine = requires.mote || (requires.mote = require('mote'));
  3339. try {
  3340. var tmpl = cache(options) || cache(options, engine.compile(str));
  3341. cb(null, tmpl(options));
  3342. } catch (err) {
  3343. cb(err);
  3344. }
  3345. });
  3346. };
  3347. /**
  3348. * Toffee support.
  3349. */
  3350. exports.toffee = function(path, options, cb) {
  3351. return promisify(cb, function(cb) {
  3352. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3353. toffee.__consolidate_engine_render(path, options, cb);
  3354. });
  3355. };
  3356. /**
  3357. * Toffee string support.
  3358. */
  3359. exports.toffee.render = function(str, options, cb) {
  3360. return promisify(cb, function(cb) {
  3361. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3362. try {
  3363. engine.str_render(str, options, cb);
  3364. } catch (err) {
  3365. cb(err);
  3366. }
  3367. });
  3368. };
  3369. /**
  3370. * doT support.
  3371. */
  3372. exports.dot = fromStringRenderer('dot');
  3373. /**
  3374. * doT string support.
  3375. */
  3376. exports.dot.render = function(str, options, cb) {
  3377. return promisify(cb, function(cb) {
  3378. var engine = requires.dot || (requires.dot = require('dot'));
  3379. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3380. try {
  3381. var settings = {};
  3382. settings = extend(settings, engine.templateSettings);
  3383. settings = extend(settings, options ? options.dot : {});
  3384. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3385. cb(null, tmpl(options));
  3386. } catch (err) {
  3387. cb(err);
  3388. }
  3389. });
  3390. };
  3391. /**
  3392. * bracket support.
  3393. */
  3394. exports.bracket = fromStringRenderer('bracket');
  3395. /**
  3396. * bracket string support.
  3397. */
  3398. exports.bracket.render = function(str, options, cb) {
  3399. return promisify(cb, function(cb) {
  3400. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3401. try {
  3402. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3403. cb(null, tmpl(options));
  3404. } catch (err) {
  3405. cb(err);
  3406. }
  3407. });
  3408. };
  3409. /**
  3410. * Ractive support.
  3411. */
  3412. exports.ractive = fromStringRenderer('ractive');
  3413. /**
  3414. * Ractive string support.
  3415. */
  3416. exports.ractive.render = function(str, options, cb) {
  3417. return promisify(cb, function(cb) {
  3418. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3419. var template = cache(options) || cache(options, Engine.parse(str));
  3420. options.template = template;
  3421. if (options.data === null || options.data === undefined) {
  3422. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3423. // Shallow clone the options object
  3424. options.data = extend({}, options);
  3425. // Remove consolidate-specific properties from the clone
  3426. var i;
  3427. var length;
  3428. var properties = ['template', 'filename', 'cache', 'partials'];
  3429. for (i = 0, length = properties.length; i < length; i++) {
  3430. var property = properties[i];
  3431. delete options.data[property];
  3432. }
  3433. }
  3434. try {
  3435. cb(null, new Engine(options).toHTML());
  3436. } catch (err) {
  3437. cb(err);
  3438. }
  3439. });
  3440. };
  3441. /**
  3442. * Nunjucks support.
  3443. */
  3444. exports.nunjucks = fromStringRenderer('nunjucks');
  3445. /**
  3446. * Nunjucks string support.
  3447. */
  3448. exports.nunjucks.render = function(str, options, cb) {
  3449. return promisify(cb, function(cb) {
  3450. try {
  3451. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3452. var env = engine;
  3453. // deprecated fallback support for express
  3454. // <https://github.com/tj/consolidate.js/pull/152>
  3455. // <https://github.com/tj/consolidate.js/pull/224>
  3456. if (options.settings && options.settings.views) {
  3457. env = engine.configure(options.settings.views);
  3458. } else if (options.nunjucks && options.nunjucks.configure) {
  3459. env = engine.configure.apply(engine, options.nunjucks.configure);
  3460. }
  3461. //
  3462. // because `renderString` does not initiate loaders
  3463. // we must manually create a loader for it based off
  3464. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3465. //
  3466. // <https://github.com/mozilla/nunjucks/issues/730>
  3467. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3468. //
  3469. // so instead we simply check if we passed a custom loader
  3470. // otherwise we create a simple file based loader
  3471. if (options.loader) {
  3472. env = new engine.Environment(options.loader);
  3473. } else if (options.settings && options.settings.views) {
  3474. env = new engine.Environment(
  3475. new engine.FileSystemLoader(options.settings.views)
  3476. );
  3477. } else if (options.nunjucks && options.nunjucks.loader) {
  3478. if (typeof options.nunjucks.loader === 'string') {
  3479. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3480. } else {
  3481. env = new engine.Environment(
  3482. new engine.FileSystemLoader(
  3483. options.nunjucks.loader[0],
  3484. options.nunjucks.loader[1]
  3485. )
  3486. );
  3487. }
  3488. }
  3489. env.renderString(str, options, cb);
  3490. } catch (err) {
  3491. throw cb(err);
  3492. }
  3493. });
  3494. };
  3495. /**
  3496. * HTMLing support.
  3497. */
  3498. exports.htmling = fromStringRenderer('htmling');
  3499. /**
  3500. * HTMLing string support.
  3501. */
  3502. exports.htmling.render = function(str, options, cb) {
  3503. return promisify(cb, function(cb) {
  3504. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3505. try {
  3506. var tmpl = cache(options) || cache(options, engine.string(str));
  3507. cb(null, tmpl.render(options));
  3508. } catch (err) {
  3509. cb(err);
  3510. }
  3511. });
  3512. };
  3513. /**
  3514. * Rendering function
  3515. */
  3516. function requireReact(module, filename) {
  3517. var babel = requires.babel || (requires.babel = require('babel-core'));
  3518. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3519. return module._compile(compiled, filename);
  3520. }
  3521. exports.requireReact = requireReact;
  3522. /**
  3523. * Converting a string into a node module.
  3524. */
  3525. function requireReactString(src, filename) {
  3526. var babel = requires.babel || (requires.babel = require('babel-core'));
  3527. if (!filename) filename = '';
  3528. var m = new module.constructor();
  3529. filename = filename || '';
  3530. // Compile Using React
  3531. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3532. // Compile as a module
  3533. m.paths = module.paths;
  3534. m._compile(compiled, filename);
  3535. return m.exports;
  3536. }
  3537. /**
  3538. * A naive helper to replace {{tags}} with options.tags content
  3539. */
  3540. function reactBaseTmpl(data, options) {
  3541. var exp;
  3542. var regex;
  3543. // Iterates through the keys in file object
  3544. // and interpolate / replace {{key}} with it's value
  3545. for (var k in options) {
  3546. if (options.hasOwnProperty(k)) {
  3547. exp = '{{' + k + '}}';
  3548. regex = new RegExp(exp, 'g');
  3549. if (data.match(regex)) {
  3550. data = data.replace(regex, options[k]);
  3551. }
  3552. }
  3553. }
  3554. return data;
  3555. }
  3556. /**
  3557. * Plates Support.
  3558. */
  3559. exports.plates = fromStringRenderer('plates');
  3560. /**
  3561. * Plates string support.
  3562. */
  3563. exports.plates.render = function(str, options, cb) {
  3564. return promisify(cb, function(cb) {
  3565. var engine = requires.plates || (requires.plates = require('plates'));
  3566. var map = options.map || undefined;
  3567. try {
  3568. var tmpl = engine.bind(str, options, map);
  3569. cb(null, tmpl);
  3570. } catch (err) {
  3571. cb(err);
  3572. }
  3573. });
  3574. };
  3575. /**
  3576. * The main render parser for React bsaed templates
  3577. */
  3578. function reactRenderer(type) {
  3579. if (commonjsRequire.extensions) {
  3580. // Ensure JSX is transformed on require
  3581. if (!commonjsRequire.extensions['.jsx']) {
  3582. commonjsRequire.extensions['.jsx'] = requireReact;
  3583. }
  3584. // Supporting .react extension as well as test cases
  3585. // Using .react extension is not recommended.
  3586. if (!commonjsRequire.extensions['.react']) {
  3587. commonjsRequire.extensions['.react'] = requireReact;
  3588. }
  3589. }
  3590. // Return rendering fx
  3591. return function(str, options, cb) {
  3592. return promisify(cb, function(cb) {
  3593. // React Import
  3594. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3595. var react = requires.react || (requires.react = require('react'));
  3596. // Assign HTML Base
  3597. var base = options.base;
  3598. delete options.base;
  3599. var enableCache = options.cache;
  3600. delete options.cache;
  3601. var isNonStatic = options.isNonStatic;
  3602. delete options.isNonStatic;
  3603. // Start Conversion
  3604. try {
  3605. var Code;
  3606. var Factory;
  3607. var baseStr;
  3608. var content;
  3609. var parsed;
  3610. if (!cache(options)) {
  3611. // Parsing
  3612. if (type === 'path') {
  3613. var path = resolve(str);
  3614. delete require.cache[path];
  3615. Code = commonjsRequire(path);
  3616. } else {
  3617. Code = requireReactString(str);
  3618. }
  3619. Factory = cache(options, react.createFactory(Code));
  3620. } else {
  3621. Factory = cache(options);
  3622. }
  3623. parsed = new Factory(options);
  3624. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3625. if (base) {
  3626. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3627. if (enableCache) {
  3628. readCache[str] = baseStr;
  3629. }
  3630. options.content = content;
  3631. content = reactBaseTmpl(baseStr, options);
  3632. }
  3633. cb(null, content);
  3634. } catch (err) {
  3635. cb(err);
  3636. }
  3637. });
  3638. };
  3639. }
  3640. /**
  3641. * React JS Support
  3642. */
  3643. exports.react = reactRenderer('path');
  3644. /**
  3645. * React JS string support.
  3646. */
  3647. exports.react.render = reactRenderer('string');
  3648. /**
  3649. * ARC-templates support.
  3650. */
  3651. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3652. /**
  3653. * ARC-templates string support.
  3654. */
  3655. exports['arc-templates'].render = function(str, options, cb) {
  3656. var readFileWithOptions = util.promisify(read);
  3657. var consolidateFileSystem = {};
  3658. consolidateFileSystem.readFile = function(path) {
  3659. return readFileWithOptions(path, options);
  3660. };
  3661. return promisify(cb, function(cb) {
  3662. try {
  3663. var engine = requires['arc-templates'];
  3664. if (!engine) {
  3665. var Engine = require('arc-templates/dist/es5');
  3666. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3667. }
  3668. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3669. compiler.then(function(func) { return func(options); })
  3670. .then(function(result) { cb(null, result.content); })
  3671. .catch(cb);
  3672. } catch (err) {
  3673. cb(err);
  3674. }
  3675. });
  3676. };
  3677. /**
  3678. * Vash support
  3679. */
  3680. exports.vash = fromStringRenderer('vash');
  3681. /**
  3682. * Vash string support
  3683. */
  3684. exports.vash.render = function(str, options, cb) {
  3685. return promisify(cb, function(cb) {
  3686. var engine = requires.vash || (requires.vash = require('vash'));
  3687. try {
  3688. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3689. if (options.helpers) {
  3690. for (var key in options.helpers) {
  3691. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3692. continue;
  3693. }
  3694. engine.helpers[key] = options.helpers[key];
  3695. }
  3696. }
  3697. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3698. tmpl(options, function sealLayout(err, ctx) {
  3699. if (err) cb(err);
  3700. ctx.finishLayout();
  3701. cb(null, ctx.toString().replace(/\n$/, ''));
  3702. });
  3703. } catch (err) {
  3704. cb(err);
  3705. }
  3706. });
  3707. };
  3708. /**
  3709. * Slm support.
  3710. */
  3711. exports.slm = fromStringRenderer('slm');
  3712. /**
  3713. * Slm string support.
  3714. */
  3715. exports.slm.render = function(str, options, cb) {
  3716. return promisify(cb, function(cb) {
  3717. var engine = requires.slm || (requires.slm = require('slm'));
  3718. try {
  3719. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3720. cb(null, tmpl(options));
  3721. } catch (err) {
  3722. cb(err);
  3723. }
  3724. });
  3725. };
  3726. /**
  3727. * Marko support.
  3728. */
  3729. exports.marko = function(path, options, cb) {
  3730. return promisify(cb, function(cb) {
  3731. var engine = requires.marko || (requires.marko = require('marko'));
  3732. options.writeToDisk = !!options.cache;
  3733. try {
  3734. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3735. tmpl.renderToString(options, cb);
  3736. } catch (err) {
  3737. cb(err);
  3738. }
  3739. });
  3740. };
  3741. /**
  3742. * Marko string support.
  3743. */
  3744. exports.marko.render = function(str, options, cb) {
  3745. return promisify(cb, function(cb) {
  3746. var engine = requires.marko || (requires.marko = require('marko'));
  3747. options.writeToDisk = !!options.cache;
  3748. options.filename = options.filename || 'string.marko';
  3749. try {
  3750. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3751. tmpl.renderToString(options, cb);
  3752. } catch (err) {
  3753. cb(err);
  3754. }
  3755. });
  3756. };
  3757. /**
  3758. * Teacup support.
  3759. */
  3760. exports.teacup = function(path, options, cb) {
  3761. return promisify(cb, function(cb) {
  3762. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3763. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3764. if (path[0] !== '/') {
  3765. path = join(process.cwd(), path);
  3766. }
  3767. if (!options.cache) {
  3768. var callback = cb;
  3769. cb = function() {
  3770. delete require.cache[path];
  3771. callback.apply(this, arguments);
  3772. };
  3773. }
  3774. engine.renderFile(path, options, cb);
  3775. });
  3776. };
  3777. /**
  3778. * Teacup string support.
  3779. */
  3780. exports.teacup.render = function(str, options, cb) {
  3781. var coffee = require('coffee-script');
  3782. var vm = require('vm');
  3783. var sandbox = {
  3784. module: {exports: {}},
  3785. require: commonjsRequire
  3786. };
  3787. return promisify(cb, function(cb) {
  3788. vm.runInNewContext(coffee.compile(str), sandbox);
  3789. var tmpl = sandbox.module.exports;
  3790. cb(null, tmpl(options));
  3791. });
  3792. };
  3793. /**
  3794. * Squirrelly support.
  3795. */
  3796. exports.squirrelly = fromStringRenderer('squirrelly');
  3797. /**
  3798. * Squirrelly string support.
  3799. */
  3800. exports.squirrelly.render = function(str, options, cb) {
  3801. return promisify(cb, function(cb) {
  3802. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3803. try {
  3804. for (var partial in options.partials) {
  3805. engine.definePartial(partial, options.partials[partial]);
  3806. }
  3807. for (var helper in options.helpers) {
  3808. engine.defineHelper(helper, options.helpers[helper]);
  3809. }
  3810. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3811. cb(null, tmpl(options, engine));
  3812. } catch (err) {
  3813. cb(err);
  3814. }
  3815. });
  3816. };
  3817. /**
  3818. * Twing support.
  3819. */
  3820. exports.twing = fromStringRenderer('twing');
  3821. /**
  3822. * Twing string support.
  3823. */
  3824. exports.twing.render = function(str, options, cb) {
  3825. return promisify(cb, function(cb) {
  3826. var engine = requires.twing || (requires.twing = require('twing'));
  3827. try {
  3828. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3829. twingTemplate.render(options).then((rendTmpl) => {
  3830. var tmpl = cache(options) || cache(options, rendTmpl);
  3831. cb(null, tmpl);
  3832. });
  3833. });
  3834. } catch (err) {
  3835. cb(err);
  3836. }
  3837. });
  3838. };
  3839. /**
  3840. * expose the instance of the engine
  3841. */
  3842. exports.requires = requires;
  3843. } (consolidate$2, consolidate$2.exports));
  3844. return consolidate$2.exports;
  3845. }
  3846. var consolidate$1;
  3847. var hasRequiredConsolidate;
  3848. function requireConsolidate () {
  3849. if (hasRequiredConsolidate) return consolidate$1;
  3850. hasRequiredConsolidate = 1;
  3851. consolidate$1 = /*@__PURE__*/ requireConsolidate$1();
  3852. return consolidate$1;
  3853. }
  3854. var consolidateExports = /*@__PURE__*/ requireConsolidate();
  3855. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports);
  3856. const hasWarned = {};
  3857. function warnOnce(msg) {
  3858. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3859. if (!isNodeProd && true && !hasWarned[msg]) {
  3860. hasWarned[msg] = true;
  3861. warn(msg);
  3862. }
  3863. }
  3864. function warn(msg) {
  3865. console.warn(
  3866. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3867. `
  3868. );
  3869. }
  3870. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3871. let res = "";
  3872. let err = null;
  3873. preprocessor.render(
  3874. source,
  3875. { filename, ...preprocessOptions },
  3876. (_err, _res) => {
  3877. if (_err) err = _err;
  3878. res = _res;
  3879. }
  3880. );
  3881. if (err) throw err;
  3882. return res;
  3883. }
  3884. function compileTemplate(options) {
  3885. const { preprocessLang, preprocessCustomRequire } = options;
  3886. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3887. if (preprocessor) {
  3888. try {
  3889. return doCompileTemplate({
  3890. ...options,
  3891. source: preprocess$1(options, preprocessor),
  3892. ast: void 0
  3893. // invalidate AST if template goes through preprocessor
  3894. });
  3895. } catch (e) {
  3896. return {
  3897. code: `export default function render() {}`,
  3898. source: options.source,
  3899. tips: [],
  3900. errors: [e]
  3901. };
  3902. }
  3903. } else if (preprocessLang) {
  3904. return {
  3905. code: `export default function render() {}`,
  3906. source: options.source,
  3907. tips: [
  3908. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3909. ],
  3910. errors: [
  3911. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3912. ]
  3913. };
  3914. } else {
  3915. return doCompileTemplate(options);
  3916. }
  3917. }
  3918. function doCompileTemplate({
  3919. filename,
  3920. id,
  3921. scoped,
  3922. slotted,
  3923. inMap,
  3924. source,
  3925. ast: inAST,
  3926. ssr = false,
  3927. ssrCssVars,
  3928. isProd = false,
  3929. compiler,
  3930. compilerOptions = {},
  3931. transformAssetUrls
  3932. }) {
  3933. const errors = [];
  3934. const warnings = [];
  3935. let nodeTransforms = [];
  3936. if (shared.isObject(transformAssetUrls)) {
  3937. const assetOptions = normalizeOptions(transformAssetUrls);
  3938. nodeTransforms = [
  3939. createAssetUrlTransformWithOptions(assetOptions),
  3940. createSrcsetTransformWithOptions(assetOptions)
  3941. ];
  3942. } else if (transformAssetUrls !== false) {
  3943. nodeTransforms = [transformAssetUrl, transformSrcset];
  3944. }
  3945. if (ssr && !ssrCssVars) {
  3946. warnOnce(
  3947. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3948. );
  3949. }
  3950. if (!id) {
  3951. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3952. id = "";
  3953. }
  3954. const shortId = id.replace(/^data-v-/, "");
  3955. const longId = `data-v-${shortId}`;
  3956. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3957. compiler = compiler || defaultCompiler;
  3958. if (compiler !== defaultCompiler) {
  3959. inAST = void 0;
  3960. }
  3961. if (inAST == null ? void 0 : inAST.transformed) {
  3962. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3963. prefixIdentifiers: true,
  3964. ...compilerOptions,
  3965. parseMode: "sfc",
  3966. onError: (e) => errors.push(e)
  3967. });
  3968. const template = newAST.children.find(
  3969. (node) => node.type === 1 && node.tag === "template"
  3970. );
  3971. inAST = compilerCore.createRoot(template.children, inAST.source);
  3972. }
  3973. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3974. mode: "module",
  3975. prefixIdentifiers: true,
  3976. hoistStatic: true,
  3977. cacheHandlers: true,
  3978. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3979. scopeId: scoped ? longId : void 0,
  3980. slotted,
  3981. sourceMap: true,
  3982. ...compilerOptions,
  3983. hmr: !isProd,
  3984. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3985. filename,
  3986. onError: (e) => errors.push(e),
  3987. onWarn: (w) => warnings.push(w)
  3988. });
  3989. if (inMap && !inAST) {
  3990. if (map) {
  3991. map = mapLines(inMap, map);
  3992. }
  3993. if (errors.length) {
  3994. patchErrors(errors, source, inMap);
  3995. }
  3996. }
  3997. const tips = warnings.map((w) => {
  3998. let msg = w.message;
  3999. if (w.loc) {
  4000. msg += `
  4001. ${shared.generateCodeFrame(
  4002. (inAST == null ? void 0 : inAST.source) || source,
  4003. w.loc.start.offset,
  4004. w.loc.end.offset
  4005. )}`;
  4006. }
  4007. return msg;
  4008. });
  4009. return { code, ast, preamble, source, errors, tips, map };
  4010. }
  4011. function mapLines(oldMap, newMap) {
  4012. if (!oldMap) return newMap;
  4013. if (!newMap) return oldMap;
  4014. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  4015. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  4016. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  4017. newMapConsumer.eachMapping((m) => {
  4018. if (m.originalLine == null) {
  4019. return;
  4020. }
  4021. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  4022. line: m.originalLine,
  4023. column: m.originalColumn
  4024. });
  4025. if (origPosInOldMap.source == null) {
  4026. return;
  4027. }
  4028. mergedMapGenerator.addMapping({
  4029. generated: {
  4030. line: m.generatedLine,
  4031. column: m.generatedColumn
  4032. },
  4033. original: {
  4034. line: origPosInOldMap.line,
  4035. // map line
  4036. // use current column, since the oldMap produced by @vue/compiler-sfc
  4037. // does not
  4038. column: m.originalColumn
  4039. },
  4040. source: origPosInOldMap.source,
  4041. name: origPosInOldMap.name
  4042. });
  4043. });
  4044. const generator = mergedMapGenerator;
  4045. oldMapConsumer.sources.forEach((sourceFile) => {
  4046. generator._sources.add(sourceFile);
  4047. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  4048. if (sourceContent != null) {
  4049. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  4050. }
  4051. });
  4052. generator._sourceRoot = oldMap.sourceRoot;
  4053. generator._file = oldMap.file;
  4054. return generator.toJSON();
  4055. }
  4056. function patchErrors(errors, source, inMap) {
  4057. const originalSource = inMap.sourcesContent[0];
  4058. const offset = originalSource.indexOf(source);
  4059. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  4060. errors.forEach((err) => {
  4061. if (err.loc) {
  4062. err.loc.start.line += lineOffset;
  4063. err.loc.start.offset += offset;
  4064. if (err.loc.end !== err.loc.start) {
  4065. err.loc.end.line += lineOffset;
  4066. err.loc.end.offset += offset;
  4067. }
  4068. }
  4069. });
  4070. }
  4071. const trimPlugin = () => {
  4072. return {
  4073. postcssPlugin: "vue-sfc-trim",
  4074. Once(root) {
  4075. root.walk(({ type, raws }) => {
  4076. if (type === "rule" || type === "atrule") {
  4077. if (raws.before) raws.before = "\n";
  4078. if ("after" in raws && raws.after) raws.after = "\n";
  4079. }
  4080. });
  4081. }
  4082. };
  4083. };
  4084. trimPlugin.postcss = true;
  4085. var dist$1 = {exports: {}};
  4086. var processor$1 = {exports: {}};
  4087. var parser$1 = {exports: {}};
  4088. var root$1 = {exports: {}};
  4089. var container$1 = {exports: {}};
  4090. var node$2 = {exports: {}};
  4091. var util$2 = {};
  4092. var unesc$1 = {exports: {}};
  4093. var hasRequiredUnesc$1;
  4094. function requireUnesc$1 () {
  4095. if (hasRequiredUnesc$1) return unesc$1.exports;
  4096. hasRequiredUnesc$1 = 1;
  4097. (function (module, exports) {
  4098. exports.__esModule = true;
  4099. exports["default"] = unesc;
  4100. // Many thanks for this post which made this migration much easier.
  4101. // https://mathiasbynens.be/notes/css-escapes
  4102. /**
  4103. *
  4104. * @param {string} str
  4105. * @returns {[string, number]|undefined}
  4106. */
  4107. function gobbleHex(str) {
  4108. var lower = str.toLowerCase();
  4109. var hex = '';
  4110. var spaceTerminated = false;
  4111. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4112. var code = lower.charCodeAt(i);
  4113. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4114. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4115. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4116. spaceTerminated = code === 32;
  4117. if (!valid) {
  4118. break;
  4119. }
  4120. hex += lower[i];
  4121. }
  4122. if (hex.length === 0) {
  4123. return undefined;
  4124. }
  4125. var codePoint = parseInt(hex, 16);
  4126. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4127. // Add special case for
  4128. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4129. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4130. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4131. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4132. }
  4133. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4134. }
  4135. var CONTAINS_ESCAPE = /\\/;
  4136. function unesc(str) {
  4137. var needToProcess = CONTAINS_ESCAPE.test(str);
  4138. if (!needToProcess) {
  4139. return str;
  4140. }
  4141. var ret = "";
  4142. for (var i = 0; i < str.length; i++) {
  4143. if (str[i] === "\\") {
  4144. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4145. if (gobbled !== undefined) {
  4146. ret += gobbled[0];
  4147. i += gobbled[1];
  4148. continue;
  4149. }
  4150. // Retain a pair of \\ if double escaped `\\\\`
  4151. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4152. if (str[i + 1] === "\\") {
  4153. ret += "\\";
  4154. i++;
  4155. continue;
  4156. }
  4157. // if \\ is at the end of the string retain it
  4158. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4159. if (str.length === i + 1) {
  4160. ret += str[i];
  4161. }
  4162. continue;
  4163. }
  4164. ret += str[i];
  4165. }
  4166. return ret;
  4167. }
  4168. module.exports = exports.default;
  4169. } (unesc$1, unesc$1.exports));
  4170. return unesc$1.exports;
  4171. }
  4172. var getProp$1 = {exports: {}};
  4173. var hasRequiredGetProp$1;
  4174. function requireGetProp$1 () {
  4175. if (hasRequiredGetProp$1) return getProp$1.exports;
  4176. hasRequiredGetProp$1 = 1;
  4177. (function (module, exports) {
  4178. exports.__esModule = true;
  4179. exports["default"] = getProp;
  4180. function getProp(obj) {
  4181. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4182. props[_key - 1] = arguments[_key];
  4183. }
  4184. while (props.length > 0) {
  4185. var prop = props.shift();
  4186. if (!obj[prop]) {
  4187. return undefined;
  4188. }
  4189. obj = obj[prop];
  4190. }
  4191. return obj;
  4192. }
  4193. module.exports = exports.default;
  4194. } (getProp$1, getProp$1.exports));
  4195. return getProp$1.exports;
  4196. }
  4197. var ensureObject$1 = {exports: {}};
  4198. var hasRequiredEnsureObject$1;
  4199. function requireEnsureObject$1 () {
  4200. if (hasRequiredEnsureObject$1) return ensureObject$1.exports;
  4201. hasRequiredEnsureObject$1 = 1;
  4202. (function (module, exports) {
  4203. exports.__esModule = true;
  4204. exports["default"] = ensureObject;
  4205. function ensureObject(obj) {
  4206. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4207. props[_key - 1] = arguments[_key];
  4208. }
  4209. while (props.length > 0) {
  4210. var prop = props.shift();
  4211. if (!obj[prop]) {
  4212. obj[prop] = {};
  4213. }
  4214. obj = obj[prop];
  4215. }
  4216. }
  4217. module.exports = exports.default;
  4218. } (ensureObject$1, ensureObject$1.exports));
  4219. return ensureObject$1.exports;
  4220. }
  4221. var stripComments$1 = {exports: {}};
  4222. var hasRequiredStripComments$1;
  4223. function requireStripComments$1 () {
  4224. if (hasRequiredStripComments$1) return stripComments$1.exports;
  4225. hasRequiredStripComments$1 = 1;
  4226. (function (module, exports) {
  4227. exports.__esModule = true;
  4228. exports["default"] = stripComments;
  4229. function stripComments(str) {
  4230. var s = "";
  4231. var commentStart = str.indexOf("/*");
  4232. var lastEnd = 0;
  4233. while (commentStart >= 0) {
  4234. s = s + str.slice(lastEnd, commentStart);
  4235. var commentEnd = str.indexOf("*/", commentStart + 2);
  4236. if (commentEnd < 0) {
  4237. return s;
  4238. }
  4239. lastEnd = commentEnd + 2;
  4240. commentStart = str.indexOf("/*", lastEnd);
  4241. }
  4242. s = s + str.slice(lastEnd);
  4243. return s;
  4244. }
  4245. module.exports = exports.default;
  4246. } (stripComments$1, stripComments$1.exports));
  4247. return stripComments$1.exports;
  4248. }
  4249. var hasRequiredUtil$2;
  4250. function requireUtil$2 () {
  4251. if (hasRequiredUtil$2) return util$2;
  4252. hasRequiredUtil$2 = 1;
  4253. util$2.__esModule = true;
  4254. util$2.unesc = util$2.stripComments = util$2.getProp = util$2.ensureObject = void 0;
  4255. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  4256. util$2.unesc = _unesc["default"];
  4257. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp$1());
  4258. util$2.getProp = _getProp["default"];
  4259. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject$1());
  4260. util$2.ensureObject = _ensureObject["default"];
  4261. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments$1());
  4262. util$2.stripComments = _stripComments["default"];
  4263. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4264. return util$2;
  4265. }
  4266. var hasRequiredNode$2;
  4267. function requireNode$2 () {
  4268. if (hasRequiredNode$2) return node$2.exports;
  4269. hasRequiredNode$2 = 1;
  4270. (function (module, exports) {
  4271. exports.__esModule = true;
  4272. exports["default"] = void 0;
  4273. var _util = /*@__PURE__*/ requireUtil$2();
  4274. 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); } }
  4275. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4276. var cloneNode = function cloneNode(obj, parent) {
  4277. if (typeof obj !== 'object' || obj === null) {
  4278. return obj;
  4279. }
  4280. var cloned = new obj.constructor();
  4281. for (var i in obj) {
  4282. if (!obj.hasOwnProperty(i)) {
  4283. continue;
  4284. }
  4285. var value = obj[i];
  4286. var type = typeof value;
  4287. if (i === 'parent' && type === 'object') {
  4288. if (parent) {
  4289. cloned[i] = parent;
  4290. }
  4291. } else if (value instanceof Array) {
  4292. cloned[i] = value.map(function (j) {
  4293. return cloneNode(j, cloned);
  4294. });
  4295. } else {
  4296. cloned[i] = cloneNode(value, cloned);
  4297. }
  4298. }
  4299. return cloned;
  4300. };
  4301. var Node = /*#__PURE__*/function () {
  4302. function Node(opts) {
  4303. if (opts === void 0) {
  4304. opts = {};
  4305. }
  4306. Object.assign(this, opts);
  4307. this.spaces = this.spaces || {};
  4308. this.spaces.before = this.spaces.before || '';
  4309. this.spaces.after = this.spaces.after || '';
  4310. }
  4311. var _proto = Node.prototype;
  4312. _proto.remove = function remove() {
  4313. if (this.parent) {
  4314. this.parent.removeChild(this);
  4315. }
  4316. this.parent = undefined;
  4317. return this;
  4318. };
  4319. _proto.replaceWith = function replaceWith() {
  4320. if (this.parent) {
  4321. for (var index in arguments) {
  4322. this.parent.insertBefore(this, arguments[index]);
  4323. }
  4324. this.remove();
  4325. }
  4326. return this;
  4327. };
  4328. _proto.next = function next() {
  4329. return this.parent.at(this.parent.index(this) + 1);
  4330. };
  4331. _proto.prev = function prev() {
  4332. return this.parent.at(this.parent.index(this) - 1);
  4333. };
  4334. _proto.clone = function clone(overrides) {
  4335. if (overrides === void 0) {
  4336. overrides = {};
  4337. }
  4338. var cloned = cloneNode(this);
  4339. for (var name in overrides) {
  4340. cloned[name] = overrides[name];
  4341. }
  4342. return cloned;
  4343. }
  4344. /**
  4345. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4346. * This allows non standard syntax to be appended to an existing property
  4347. * by specifying the escaped value. By specifying the escaped value,
  4348. * illegal characters are allowed to be directly inserted into css output.
  4349. * @param {string} name the property to set
  4350. * @param {any} value the unescaped value of the property
  4351. * @param {string} valueEscaped optional. the escaped value of the property.
  4352. */;
  4353. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4354. if (!this.raws) {
  4355. this.raws = {};
  4356. }
  4357. var originalValue = this[name];
  4358. var originalEscaped = this.raws[name];
  4359. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4360. if (originalEscaped || valueEscaped !== value) {
  4361. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4362. } else {
  4363. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4364. }
  4365. }
  4366. /**
  4367. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4368. * This allows the escaped value to be specified directly, allowing illegal
  4369. * characters to be directly inserted into css output.
  4370. * @param {string} name the property to set
  4371. * @param {any} value the unescaped value of the property
  4372. * @param {string} valueEscaped the escaped value of the property.
  4373. */;
  4374. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4375. if (!this.raws) {
  4376. this.raws = {};
  4377. }
  4378. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4379. this.raws[name] = valueEscaped;
  4380. }
  4381. /**
  4382. * When you want a value to passed through to CSS directly. This method
  4383. * deletes the corresponding raw value causing the stringifier to fallback
  4384. * to the unescaped value.
  4385. * @param {string} name the property to set.
  4386. * @param {any} value The value that is both escaped and unescaped.
  4387. */;
  4388. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4389. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4390. if (this.raws) {
  4391. delete this.raws[name];
  4392. }
  4393. }
  4394. /**
  4395. *
  4396. * @param {number} line The number (starting with 1)
  4397. * @param {number} column The column number (starting with 1)
  4398. */;
  4399. _proto.isAtPosition = function isAtPosition(line, column) {
  4400. if (this.source && this.source.start && this.source.end) {
  4401. if (this.source.start.line > line) {
  4402. return false;
  4403. }
  4404. if (this.source.end.line < line) {
  4405. return false;
  4406. }
  4407. if (this.source.start.line === line && this.source.start.column > column) {
  4408. return false;
  4409. }
  4410. if (this.source.end.line === line && this.source.end.column < column) {
  4411. return false;
  4412. }
  4413. return true;
  4414. }
  4415. return undefined;
  4416. };
  4417. _proto.stringifyProperty = function stringifyProperty(name) {
  4418. return this.raws && this.raws[name] || this[name];
  4419. };
  4420. _proto.valueToString = function valueToString() {
  4421. return String(this.stringifyProperty("value"));
  4422. };
  4423. _proto.toString = function toString() {
  4424. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4425. };
  4426. _createClass(Node, [{
  4427. key: "rawSpaceBefore",
  4428. get: function get() {
  4429. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4430. if (rawSpace === undefined) {
  4431. rawSpace = this.spaces && this.spaces.before;
  4432. }
  4433. return rawSpace || "";
  4434. },
  4435. set: function set(raw) {
  4436. (0, _util.ensureObject)(this, "raws", "spaces");
  4437. this.raws.spaces.before = raw;
  4438. }
  4439. }, {
  4440. key: "rawSpaceAfter",
  4441. get: function get() {
  4442. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4443. if (rawSpace === undefined) {
  4444. rawSpace = this.spaces.after;
  4445. }
  4446. return rawSpace || "";
  4447. },
  4448. set: function set(raw) {
  4449. (0, _util.ensureObject)(this, "raws", "spaces");
  4450. this.raws.spaces.after = raw;
  4451. }
  4452. }]);
  4453. return Node;
  4454. }();
  4455. exports["default"] = Node;
  4456. module.exports = exports.default;
  4457. } (node$2, node$2.exports));
  4458. return node$2.exports;
  4459. }
  4460. var types$2 = {};
  4461. var hasRequiredTypes$1;
  4462. function requireTypes$1 () {
  4463. if (hasRequiredTypes$1) return types$2;
  4464. hasRequiredTypes$1 = 1;
  4465. types$2.__esModule = true;
  4466. types$2.UNIVERSAL = types$2.TAG = types$2.STRING = types$2.SELECTOR = types$2.ROOT = types$2.PSEUDO = types$2.NESTING = types$2.ID = types$2.COMMENT = types$2.COMBINATOR = types$2.CLASS = types$2.ATTRIBUTE = void 0;
  4467. var TAG = 'tag';
  4468. types$2.TAG = TAG;
  4469. var STRING = 'string';
  4470. types$2.STRING = STRING;
  4471. var SELECTOR = 'selector';
  4472. types$2.SELECTOR = SELECTOR;
  4473. var ROOT = 'root';
  4474. types$2.ROOT = ROOT;
  4475. var PSEUDO = 'pseudo';
  4476. types$2.PSEUDO = PSEUDO;
  4477. var NESTING = 'nesting';
  4478. types$2.NESTING = NESTING;
  4479. var ID = 'id';
  4480. types$2.ID = ID;
  4481. var COMMENT = 'comment';
  4482. types$2.COMMENT = COMMENT;
  4483. var COMBINATOR = 'combinator';
  4484. types$2.COMBINATOR = COMBINATOR;
  4485. var CLASS = 'class';
  4486. types$2.CLASS = CLASS;
  4487. var ATTRIBUTE = 'attribute';
  4488. types$2.ATTRIBUTE = ATTRIBUTE;
  4489. var UNIVERSAL = 'universal';
  4490. types$2.UNIVERSAL = UNIVERSAL;
  4491. return types$2;
  4492. }
  4493. var hasRequiredContainer$1;
  4494. function requireContainer$1 () {
  4495. if (hasRequiredContainer$1) return container$1.exports;
  4496. hasRequiredContainer$1 = 1;
  4497. (function (module, exports) {
  4498. exports.__esModule = true;
  4499. exports["default"] = void 0;
  4500. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4501. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  4502. 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); }
  4503. function _interopRequireWildcard(obj, nodeInterop) { if (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; }
  4504. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4505. 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) { 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."); }
  4506. 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); }
  4507. 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; }
  4508. 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); } }
  4509. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4510. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4511. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4512. var Container = /*#__PURE__*/function (_Node) {
  4513. _inheritsLoose(Container, _Node);
  4514. function Container(opts) {
  4515. var _this;
  4516. _this = _Node.call(this, opts) || this;
  4517. if (!_this.nodes) {
  4518. _this.nodes = [];
  4519. }
  4520. return _this;
  4521. }
  4522. var _proto = Container.prototype;
  4523. _proto.append = function append(selector) {
  4524. selector.parent = this;
  4525. this.nodes.push(selector);
  4526. return this;
  4527. };
  4528. _proto.prepend = function prepend(selector) {
  4529. selector.parent = this;
  4530. this.nodes.unshift(selector);
  4531. for (var id in this.indexes) {
  4532. this.indexes[id]++;
  4533. }
  4534. return this;
  4535. };
  4536. _proto.at = function at(index) {
  4537. return this.nodes[index];
  4538. };
  4539. _proto.index = function index(child) {
  4540. if (typeof child === 'number') {
  4541. return child;
  4542. }
  4543. return this.nodes.indexOf(child);
  4544. };
  4545. _proto.removeChild = function removeChild(child) {
  4546. child = this.index(child);
  4547. this.at(child).parent = undefined;
  4548. this.nodes.splice(child, 1);
  4549. var index;
  4550. for (var id in this.indexes) {
  4551. index = this.indexes[id];
  4552. if (index >= child) {
  4553. this.indexes[id] = index - 1;
  4554. }
  4555. }
  4556. return this;
  4557. };
  4558. _proto.removeAll = function removeAll() {
  4559. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4560. var node = _step.value;
  4561. node.parent = undefined;
  4562. }
  4563. this.nodes = [];
  4564. return this;
  4565. };
  4566. _proto.empty = function empty() {
  4567. return this.removeAll();
  4568. };
  4569. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4570. var _this$nodes;
  4571. newNode.parent = this;
  4572. var oldIndex = this.index(oldNode);
  4573. var resetNode = [];
  4574. for (var i = 2; i < arguments.length; i++) {
  4575. resetNode.push(arguments[i]);
  4576. }
  4577. (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
  4578. newNode.parent = this;
  4579. var index;
  4580. for (var id in this.indexes) {
  4581. index = this.indexes[id];
  4582. if (oldIndex < index) {
  4583. this.indexes[id] = index + arguments.length - 1;
  4584. }
  4585. }
  4586. return this;
  4587. };
  4588. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4589. var _this$nodes2;
  4590. newNode.parent = this;
  4591. var oldIndex = this.index(oldNode);
  4592. var resetNode = [];
  4593. for (var i = 2; i < arguments.length; i++) {
  4594. resetNode.push(arguments[i]);
  4595. }
  4596. (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
  4597. newNode.parent = this;
  4598. var index;
  4599. for (var id in this.indexes) {
  4600. index = this.indexes[id];
  4601. if (index >= oldIndex) {
  4602. this.indexes[id] = index + arguments.length - 1;
  4603. }
  4604. }
  4605. return this;
  4606. };
  4607. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4608. var found = undefined;
  4609. this.each(function (node) {
  4610. if (node.atPosition) {
  4611. var foundChild = node.atPosition(line, col);
  4612. if (foundChild) {
  4613. found = foundChild;
  4614. return false;
  4615. }
  4616. } else if (node.isAtPosition(line, col)) {
  4617. found = node;
  4618. return false;
  4619. }
  4620. });
  4621. return found;
  4622. }
  4623. /**
  4624. * Return the most specific node at the line and column number given.
  4625. * The source location is based on the original parsed location, locations aren't
  4626. * updated as selector nodes are mutated.
  4627. *
  4628. * Note that this location is relative to the location of the first character
  4629. * of the selector, and not the location of the selector in the overall document
  4630. * when used in conjunction with postcss.
  4631. *
  4632. * If not found, returns undefined.
  4633. * @param {number} line The line number of the node to find. (1-based index)
  4634. * @param {number} col The column number of the node to find. (1-based index)
  4635. */;
  4636. _proto.atPosition = function atPosition(line, col) {
  4637. if (this.isAtPosition(line, col)) {
  4638. return this._findChildAtPosition(line, col) || this;
  4639. } else {
  4640. return undefined;
  4641. }
  4642. };
  4643. _proto._inferEndPosition = function _inferEndPosition() {
  4644. if (this.last && this.last.source && this.last.source.end) {
  4645. this.source = this.source || {};
  4646. this.source.end = this.source.end || {};
  4647. Object.assign(this.source.end, this.last.source.end);
  4648. }
  4649. };
  4650. _proto.each = function each(callback) {
  4651. if (!this.lastEach) {
  4652. this.lastEach = 0;
  4653. }
  4654. if (!this.indexes) {
  4655. this.indexes = {};
  4656. }
  4657. this.lastEach++;
  4658. var id = this.lastEach;
  4659. this.indexes[id] = 0;
  4660. if (!this.length) {
  4661. return undefined;
  4662. }
  4663. var index, result;
  4664. while (this.indexes[id] < this.length) {
  4665. index = this.indexes[id];
  4666. result = callback(this.at(index), index);
  4667. if (result === false) {
  4668. break;
  4669. }
  4670. this.indexes[id] += 1;
  4671. }
  4672. delete this.indexes[id];
  4673. if (result === false) {
  4674. return false;
  4675. }
  4676. };
  4677. _proto.walk = function walk(callback) {
  4678. return this.each(function (node, i) {
  4679. var result = callback(node, i);
  4680. if (result !== false && node.length) {
  4681. result = node.walk(callback);
  4682. }
  4683. if (result === false) {
  4684. return false;
  4685. }
  4686. });
  4687. };
  4688. _proto.walkAttributes = function walkAttributes(callback) {
  4689. var _this2 = this;
  4690. return this.walk(function (selector) {
  4691. if (selector.type === types.ATTRIBUTE) {
  4692. return callback.call(_this2, selector);
  4693. }
  4694. });
  4695. };
  4696. _proto.walkClasses = function walkClasses(callback) {
  4697. var _this3 = this;
  4698. return this.walk(function (selector) {
  4699. if (selector.type === types.CLASS) {
  4700. return callback.call(_this3, selector);
  4701. }
  4702. });
  4703. };
  4704. _proto.walkCombinators = function walkCombinators(callback) {
  4705. var _this4 = this;
  4706. return this.walk(function (selector) {
  4707. if (selector.type === types.COMBINATOR) {
  4708. return callback.call(_this4, selector);
  4709. }
  4710. });
  4711. };
  4712. _proto.walkComments = function walkComments(callback) {
  4713. var _this5 = this;
  4714. return this.walk(function (selector) {
  4715. if (selector.type === types.COMMENT) {
  4716. return callback.call(_this5, selector);
  4717. }
  4718. });
  4719. };
  4720. _proto.walkIds = function walkIds(callback) {
  4721. var _this6 = this;
  4722. return this.walk(function (selector) {
  4723. if (selector.type === types.ID) {
  4724. return callback.call(_this6, selector);
  4725. }
  4726. });
  4727. };
  4728. _proto.walkNesting = function walkNesting(callback) {
  4729. var _this7 = this;
  4730. return this.walk(function (selector) {
  4731. if (selector.type === types.NESTING) {
  4732. return callback.call(_this7, selector);
  4733. }
  4734. });
  4735. };
  4736. _proto.walkPseudos = function walkPseudos(callback) {
  4737. var _this8 = this;
  4738. return this.walk(function (selector) {
  4739. if (selector.type === types.PSEUDO) {
  4740. return callback.call(_this8, selector);
  4741. }
  4742. });
  4743. };
  4744. _proto.walkTags = function walkTags(callback) {
  4745. var _this9 = this;
  4746. return this.walk(function (selector) {
  4747. if (selector.type === types.TAG) {
  4748. return callback.call(_this9, selector);
  4749. }
  4750. });
  4751. };
  4752. _proto.walkUniversals = function walkUniversals(callback) {
  4753. var _this10 = this;
  4754. return this.walk(function (selector) {
  4755. if (selector.type === types.UNIVERSAL) {
  4756. return callback.call(_this10, selector);
  4757. }
  4758. });
  4759. };
  4760. _proto.split = function split(callback) {
  4761. var _this11 = this;
  4762. var current = [];
  4763. return this.reduce(function (memo, node, index) {
  4764. var split = callback.call(_this11, node);
  4765. current.push(node);
  4766. if (split) {
  4767. memo.push(current);
  4768. current = [];
  4769. } else if (index === _this11.length - 1) {
  4770. memo.push(current);
  4771. }
  4772. return memo;
  4773. }, []);
  4774. };
  4775. _proto.map = function map(callback) {
  4776. return this.nodes.map(callback);
  4777. };
  4778. _proto.reduce = function reduce(callback, memo) {
  4779. return this.nodes.reduce(callback, memo);
  4780. };
  4781. _proto.every = function every(callback) {
  4782. return this.nodes.every(callback);
  4783. };
  4784. _proto.some = function some(callback) {
  4785. return this.nodes.some(callback);
  4786. };
  4787. _proto.filter = function filter(callback) {
  4788. return this.nodes.filter(callback);
  4789. };
  4790. _proto.sort = function sort(callback) {
  4791. return this.nodes.sort(callback);
  4792. };
  4793. _proto.toString = function toString() {
  4794. return this.map(String).join('');
  4795. };
  4796. _createClass(Container, [{
  4797. key: "first",
  4798. get: function get() {
  4799. return this.at(0);
  4800. }
  4801. }, {
  4802. key: "last",
  4803. get: function get() {
  4804. return this.at(this.length - 1);
  4805. }
  4806. }, {
  4807. key: "length",
  4808. get: function get() {
  4809. return this.nodes.length;
  4810. }
  4811. }]);
  4812. return Container;
  4813. }(_node["default"]);
  4814. exports["default"] = Container;
  4815. module.exports = exports.default;
  4816. } (container$1, container$1.exports));
  4817. return container$1.exports;
  4818. }
  4819. var hasRequiredRoot$1;
  4820. function requireRoot$1 () {
  4821. if (hasRequiredRoot$1) return root$1.exports;
  4822. hasRequiredRoot$1 = 1;
  4823. (function (module, exports) {
  4824. exports.__esModule = true;
  4825. exports["default"] = void 0;
  4826. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4827. var _types = /*@__PURE__*/ requireTypes$1();
  4828. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4829. 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); } }
  4830. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4831. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4832. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4833. var Root = /*#__PURE__*/function (_Container) {
  4834. _inheritsLoose(Root, _Container);
  4835. function Root(opts) {
  4836. var _this;
  4837. _this = _Container.call(this, opts) || this;
  4838. _this.type = _types.ROOT;
  4839. return _this;
  4840. }
  4841. var _proto = Root.prototype;
  4842. _proto.toString = function toString() {
  4843. var str = this.reduce(function (memo, selector) {
  4844. memo.push(String(selector));
  4845. return memo;
  4846. }, []).join(',');
  4847. return this.trailingComma ? str + ',' : str;
  4848. };
  4849. _proto.error = function error(message, options) {
  4850. if (this._error) {
  4851. return this._error(message, options);
  4852. } else {
  4853. return new Error(message);
  4854. }
  4855. };
  4856. _createClass(Root, [{
  4857. key: "errorGenerator",
  4858. set: function set(handler) {
  4859. this._error = handler;
  4860. }
  4861. }]);
  4862. return Root;
  4863. }(_container["default"]);
  4864. exports["default"] = Root;
  4865. module.exports = exports.default;
  4866. } (root$1, root$1.exports));
  4867. return root$1.exports;
  4868. }
  4869. var selector$1 = {exports: {}};
  4870. var hasRequiredSelector$1;
  4871. function requireSelector$1 () {
  4872. if (hasRequiredSelector$1) return selector$1.exports;
  4873. hasRequiredSelector$1 = 1;
  4874. (function (module, exports) {
  4875. exports.__esModule = true;
  4876. exports["default"] = void 0;
  4877. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4878. var _types = /*@__PURE__*/ requireTypes$1();
  4879. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4880. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4881. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4882. var Selector = /*#__PURE__*/function (_Container) {
  4883. _inheritsLoose(Selector, _Container);
  4884. function Selector(opts) {
  4885. var _this;
  4886. _this = _Container.call(this, opts) || this;
  4887. _this.type = _types.SELECTOR;
  4888. return _this;
  4889. }
  4890. return Selector;
  4891. }(_container["default"]);
  4892. exports["default"] = Selector;
  4893. module.exports = exports.default;
  4894. } (selector$1, selector$1.exports));
  4895. return selector$1.exports;
  4896. }
  4897. var className$1 = {exports: {}};
  4898. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4899. var cssesc_1;
  4900. var hasRequiredCssesc;
  4901. function requireCssesc () {
  4902. if (hasRequiredCssesc) return cssesc_1;
  4903. hasRequiredCssesc = 1;
  4904. var object = {};
  4905. var hasOwnProperty = object.hasOwnProperty;
  4906. var merge = function merge(options, defaults) {
  4907. if (!options) {
  4908. return defaults;
  4909. }
  4910. var result = {};
  4911. for (var key in defaults) {
  4912. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4913. // only recognized option names are used.
  4914. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  4915. }
  4916. return result;
  4917. };
  4918. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4919. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4920. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4921. // https://mathiasbynens.be/notes/css-escapes#css
  4922. var cssesc = function cssesc(string, options) {
  4923. options = merge(options, cssesc.options);
  4924. if (options.quotes != 'single' && options.quotes != 'double') {
  4925. options.quotes = 'single';
  4926. }
  4927. var quote = options.quotes == 'double' ? '"' : '\'';
  4928. var isIdentifier = options.isIdentifier;
  4929. var firstChar = string.charAt(0);
  4930. var output = '';
  4931. var counter = 0;
  4932. var length = string.length;
  4933. while (counter < length) {
  4934. var character = string.charAt(counter++);
  4935. var codePoint = character.charCodeAt();
  4936. var value = void 0;
  4937. // If it’s not a printable ASCII character…
  4938. if (codePoint < 0x20 || codePoint > 0x7E) {
  4939. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4940. // It’s a high surrogate, and there is a next character.
  4941. var extra = string.charCodeAt(counter++);
  4942. if ((extra & 0xFC00) == 0xDC00) {
  4943. // next character is low surrogate
  4944. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4945. } else {
  4946. // It’s an unmatched surrogate; only append this code unit, in case
  4947. // the next code unit is the high surrogate of a surrogate pair.
  4948. counter--;
  4949. }
  4950. }
  4951. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4952. } else {
  4953. if (options.escapeEverything) {
  4954. if (regexAnySingleEscape.test(character)) {
  4955. value = '\\' + character;
  4956. } else {
  4957. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4958. }
  4959. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4960. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4961. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4962. value = '\\' + character;
  4963. } else {
  4964. value = character;
  4965. }
  4966. }
  4967. output += value;
  4968. }
  4969. if (isIdentifier) {
  4970. if (/^-[-\d]/.test(output)) {
  4971. output = '\\-' + output.slice(1);
  4972. } else if (/\d/.test(firstChar)) {
  4973. output = '\\3' + firstChar + ' ' + output.slice(1);
  4974. }
  4975. }
  4976. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4977. // since they’re redundant. Note that this is only possible if the escape
  4978. // sequence isn’t preceded by an odd number of backslashes.
  4979. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4980. if ($1 && $1.length % 2) {
  4981. // It’s not safe to remove the space, so don’t.
  4982. return $0;
  4983. }
  4984. // Strip the space.
  4985. return ($1 || '') + $2;
  4986. });
  4987. if (!isIdentifier && options.wrap) {
  4988. return quote + output + quote;
  4989. }
  4990. return output;
  4991. };
  4992. // Expose default options (so they can be overridden globally).
  4993. cssesc.options = {
  4994. 'escapeEverything': false,
  4995. 'isIdentifier': false,
  4996. 'quotes': 'single',
  4997. 'wrap': false
  4998. };
  4999. cssesc.version = '3.0.0';
  5000. cssesc_1 = cssesc;
  5001. return cssesc_1;
  5002. }
  5003. var hasRequiredClassName$1;
  5004. function requireClassName$1 () {
  5005. if (hasRequiredClassName$1) return className$1.exports;
  5006. hasRequiredClassName$1 = 1;
  5007. (function (module, exports) {
  5008. exports.__esModule = true;
  5009. exports["default"] = void 0;
  5010. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5011. var _util = /*@__PURE__*/ requireUtil$2();
  5012. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5013. var _types = /*@__PURE__*/ requireTypes$1();
  5014. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5015. 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); } }
  5016. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5017. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5018. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5019. var ClassName = /*#__PURE__*/function (_Node) {
  5020. _inheritsLoose(ClassName, _Node);
  5021. function ClassName(opts) {
  5022. var _this;
  5023. _this = _Node.call(this, opts) || this;
  5024. _this.type = _types.CLASS;
  5025. _this._constructed = true;
  5026. return _this;
  5027. }
  5028. var _proto = ClassName.prototype;
  5029. _proto.valueToString = function valueToString() {
  5030. return '.' + _Node.prototype.valueToString.call(this);
  5031. };
  5032. _createClass(ClassName, [{
  5033. key: "value",
  5034. get: function get() {
  5035. return this._value;
  5036. },
  5037. set: function set(v) {
  5038. if (this._constructed) {
  5039. var escaped = (0, _cssesc["default"])(v, {
  5040. isIdentifier: true
  5041. });
  5042. if (escaped !== v) {
  5043. (0, _util.ensureObject)(this, "raws");
  5044. this.raws.value = escaped;
  5045. } else if (this.raws) {
  5046. delete this.raws.value;
  5047. }
  5048. }
  5049. this._value = v;
  5050. }
  5051. }]);
  5052. return ClassName;
  5053. }(_node["default"]);
  5054. exports["default"] = ClassName;
  5055. module.exports = exports.default;
  5056. } (className$1, className$1.exports));
  5057. return className$1.exports;
  5058. }
  5059. var comment$1 = {exports: {}};
  5060. var hasRequiredComment$1;
  5061. function requireComment$1 () {
  5062. if (hasRequiredComment$1) return comment$1.exports;
  5063. hasRequiredComment$1 = 1;
  5064. (function (module, exports) {
  5065. exports.__esModule = true;
  5066. exports["default"] = void 0;
  5067. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5068. var _types = /*@__PURE__*/ requireTypes$1();
  5069. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5070. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5071. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5072. var Comment = /*#__PURE__*/function (_Node) {
  5073. _inheritsLoose(Comment, _Node);
  5074. function Comment(opts) {
  5075. var _this;
  5076. _this = _Node.call(this, opts) || this;
  5077. _this.type = _types.COMMENT;
  5078. return _this;
  5079. }
  5080. return Comment;
  5081. }(_node["default"]);
  5082. exports["default"] = Comment;
  5083. module.exports = exports.default;
  5084. } (comment$1, comment$1.exports));
  5085. return comment$1.exports;
  5086. }
  5087. var id$1 = {exports: {}};
  5088. var hasRequiredId$1;
  5089. function requireId$1 () {
  5090. if (hasRequiredId$1) return id$1.exports;
  5091. hasRequiredId$1 = 1;
  5092. (function (module, exports) {
  5093. exports.__esModule = true;
  5094. exports["default"] = void 0;
  5095. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5096. var _types = /*@__PURE__*/ requireTypes$1();
  5097. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5098. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5099. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5100. var ID = /*#__PURE__*/function (_Node) {
  5101. _inheritsLoose(ID, _Node);
  5102. function ID(opts) {
  5103. var _this;
  5104. _this = _Node.call(this, opts) || this;
  5105. _this.type = _types.ID;
  5106. return _this;
  5107. }
  5108. var _proto = ID.prototype;
  5109. _proto.valueToString = function valueToString() {
  5110. return '#' + _Node.prototype.valueToString.call(this);
  5111. };
  5112. return ID;
  5113. }(_node["default"]);
  5114. exports["default"] = ID;
  5115. module.exports = exports.default;
  5116. } (id$1, id$1.exports));
  5117. return id$1.exports;
  5118. }
  5119. var tag$1 = {exports: {}};
  5120. var namespace$1 = {exports: {}};
  5121. var hasRequiredNamespace$1;
  5122. function requireNamespace$1 () {
  5123. if (hasRequiredNamespace$1) return namespace$1.exports;
  5124. hasRequiredNamespace$1 = 1;
  5125. (function (module, exports) {
  5126. exports.__esModule = true;
  5127. exports["default"] = void 0;
  5128. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5129. var _util = /*@__PURE__*/ requireUtil$2();
  5130. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5131. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5132. 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); } }
  5133. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5134. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5135. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5136. var Namespace = /*#__PURE__*/function (_Node) {
  5137. _inheritsLoose(Namespace, _Node);
  5138. function Namespace() {
  5139. return _Node.apply(this, arguments) || this;
  5140. }
  5141. var _proto = Namespace.prototype;
  5142. _proto.qualifiedName = function qualifiedName(value) {
  5143. if (this.namespace) {
  5144. return this.namespaceString + "|" + value;
  5145. } else {
  5146. return value;
  5147. }
  5148. };
  5149. _proto.valueToString = function valueToString() {
  5150. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5151. };
  5152. _createClass(Namespace, [{
  5153. key: "namespace",
  5154. get: function get() {
  5155. return this._namespace;
  5156. },
  5157. set: function set(namespace) {
  5158. if (namespace === true || namespace === "*" || namespace === "&") {
  5159. this._namespace = namespace;
  5160. if (this.raws) {
  5161. delete this.raws.namespace;
  5162. }
  5163. return;
  5164. }
  5165. var escaped = (0, _cssesc["default"])(namespace, {
  5166. isIdentifier: true
  5167. });
  5168. this._namespace = namespace;
  5169. if (escaped !== namespace) {
  5170. (0, _util.ensureObject)(this, "raws");
  5171. this.raws.namespace = escaped;
  5172. } else if (this.raws) {
  5173. delete this.raws.namespace;
  5174. }
  5175. }
  5176. }, {
  5177. key: "ns",
  5178. get: function get() {
  5179. return this._namespace;
  5180. },
  5181. set: function set(namespace) {
  5182. this.namespace = namespace;
  5183. }
  5184. }, {
  5185. key: "namespaceString",
  5186. get: function get() {
  5187. if (this.namespace) {
  5188. var ns = this.stringifyProperty("namespace");
  5189. if (ns === true) {
  5190. return '';
  5191. } else {
  5192. return ns;
  5193. }
  5194. } else {
  5195. return '';
  5196. }
  5197. }
  5198. }]);
  5199. return Namespace;
  5200. }(_node["default"]);
  5201. exports["default"] = Namespace;
  5202. module.exports = exports.default;
  5203. } (namespace$1, namespace$1.exports));
  5204. return namespace$1.exports;
  5205. }
  5206. var hasRequiredTag$1;
  5207. function requireTag$1 () {
  5208. if (hasRequiredTag$1) return tag$1.exports;
  5209. hasRequiredTag$1 = 1;
  5210. (function (module, exports) {
  5211. exports.__esModule = true;
  5212. exports["default"] = void 0;
  5213. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5214. var _types = /*@__PURE__*/ requireTypes$1();
  5215. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5216. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5217. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5218. var Tag = /*#__PURE__*/function (_Namespace) {
  5219. _inheritsLoose(Tag, _Namespace);
  5220. function Tag(opts) {
  5221. var _this;
  5222. _this = _Namespace.call(this, opts) || this;
  5223. _this.type = _types.TAG;
  5224. return _this;
  5225. }
  5226. return Tag;
  5227. }(_namespace["default"]);
  5228. exports["default"] = Tag;
  5229. module.exports = exports.default;
  5230. } (tag$1, tag$1.exports));
  5231. return tag$1.exports;
  5232. }
  5233. var string$1 = {exports: {}};
  5234. var hasRequiredString$1;
  5235. function requireString$1 () {
  5236. if (hasRequiredString$1) return string$1.exports;
  5237. hasRequiredString$1 = 1;
  5238. (function (module, exports) {
  5239. exports.__esModule = true;
  5240. exports["default"] = void 0;
  5241. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5242. var _types = /*@__PURE__*/ requireTypes$1();
  5243. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5244. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5245. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5246. var String = /*#__PURE__*/function (_Node) {
  5247. _inheritsLoose(String, _Node);
  5248. function String(opts) {
  5249. var _this;
  5250. _this = _Node.call(this, opts) || this;
  5251. _this.type = _types.STRING;
  5252. return _this;
  5253. }
  5254. return String;
  5255. }(_node["default"]);
  5256. exports["default"] = String;
  5257. module.exports = exports.default;
  5258. } (string$1, string$1.exports));
  5259. return string$1.exports;
  5260. }
  5261. var pseudo$1 = {exports: {}};
  5262. var hasRequiredPseudo$1;
  5263. function requirePseudo$1 () {
  5264. if (hasRequiredPseudo$1) return pseudo$1.exports;
  5265. hasRequiredPseudo$1 = 1;
  5266. (function (module, exports) {
  5267. exports.__esModule = true;
  5268. exports["default"] = void 0;
  5269. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  5270. var _types = /*@__PURE__*/ requireTypes$1();
  5271. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5272. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5273. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5274. var Pseudo = /*#__PURE__*/function (_Container) {
  5275. _inheritsLoose(Pseudo, _Container);
  5276. function Pseudo(opts) {
  5277. var _this;
  5278. _this = _Container.call(this, opts) || this;
  5279. _this.type = _types.PSEUDO;
  5280. return _this;
  5281. }
  5282. var _proto = Pseudo.prototype;
  5283. _proto.toString = function toString() {
  5284. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5285. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5286. };
  5287. return Pseudo;
  5288. }(_container["default"]);
  5289. exports["default"] = Pseudo;
  5290. module.exports = exports.default;
  5291. } (pseudo$1, pseudo$1.exports));
  5292. return pseudo$1.exports;
  5293. }
  5294. var attribute$1 = {};
  5295. var node$1;
  5296. var hasRequiredNode$1;
  5297. function requireNode$1 () {
  5298. if (hasRequiredNode$1) return node$1;
  5299. hasRequiredNode$1 = 1;
  5300. /**
  5301. * For Node.js, simply re-export the core `util.deprecate` function.
  5302. */
  5303. node$1 = require$$2.deprecate;
  5304. return node$1;
  5305. }
  5306. var hasRequiredAttribute$1;
  5307. function requireAttribute$1 () {
  5308. if (hasRequiredAttribute$1) return attribute$1;
  5309. hasRequiredAttribute$1 = 1;
  5310. (function (exports) {
  5311. exports.__esModule = true;
  5312. exports["default"] = void 0;
  5313. exports.unescapeValue = unescapeValue;
  5314. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5315. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  5316. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5317. var _types = /*@__PURE__*/ requireTypes$1();
  5318. var _CSSESC_QUOTE_OPTIONS;
  5319. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5320. 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); } }
  5321. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5322. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5323. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5324. var deprecate = /*@__PURE__*/ requireNode$1();
  5325. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5326. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5327. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5328. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5329. function unescapeValue(value) {
  5330. var deprecatedUsage = false;
  5331. var quoteMark = null;
  5332. var unescaped = value;
  5333. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5334. if (m) {
  5335. quoteMark = m[1];
  5336. unescaped = m[2];
  5337. }
  5338. unescaped = (0, _unesc["default"])(unescaped);
  5339. if (unescaped !== value) {
  5340. deprecatedUsage = true;
  5341. }
  5342. return {
  5343. deprecatedUsage: deprecatedUsage,
  5344. unescaped: unescaped,
  5345. quoteMark: quoteMark
  5346. };
  5347. }
  5348. function handleDeprecatedContructorOpts(opts) {
  5349. if (opts.quoteMark !== undefined) {
  5350. return opts;
  5351. }
  5352. if (opts.value === undefined) {
  5353. return opts;
  5354. }
  5355. warnOfDeprecatedConstructor();
  5356. var _unescapeValue = unescapeValue(opts.value),
  5357. quoteMark = _unescapeValue.quoteMark,
  5358. unescaped = _unescapeValue.unescaped;
  5359. if (!opts.raws) {
  5360. opts.raws = {};
  5361. }
  5362. if (opts.raws.value === undefined) {
  5363. opts.raws.value = opts.value;
  5364. }
  5365. opts.value = unescaped;
  5366. opts.quoteMark = quoteMark;
  5367. return opts;
  5368. }
  5369. var Attribute = /*#__PURE__*/function (_Namespace) {
  5370. _inheritsLoose(Attribute, _Namespace);
  5371. function Attribute(opts) {
  5372. var _this;
  5373. if (opts === void 0) {
  5374. opts = {};
  5375. }
  5376. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5377. _this.type = _types.ATTRIBUTE;
  5378. _this.raws = _this.raws || {};
  5379. Object.defineProperty(_this.raws, 'unquoted', {
  5380. get: deprecate(function () {
  5381. return _this.value;
  5382. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5383. set: deprecate(function () {
  5384. return _this.value;
  5385. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5386. });
  5387. _this._constructed = true;
  5388. return _this;
  5389. }
  5390. /**
  5391. * Returns the Attribute's value quoted such that it would be legal to use
  5392. * in the value of a css file. The original value's quotation setting
  5393. * used for stringification is left unchanged. See `setValue(value, options)`
  5394. * if you want to control the quote settings of a new value for the attribute.
  5395. *
  5396. * You can also change the quotation used for the current value by setting quoteMark.
  5397. *
  5398. * Options:
  5399. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5400. * option is not set, the original value for quoteMark will be used. If
  5401. * indeterminate, a double quote is used. The legal values are:
  5402. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5403. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5404. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5405. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5406. * over the quoteMark option value.
  5407. * * smart {boolean} - if true, will select a quote mark based on the value
  5408. * and the other options specified here. See the `smartQuoteMark()`
  5409. * method.
  5410. **/
  5411. var _proto = Attribute.prototype;
  5412. _proto.getQuotedValue = function getQuotedValue(options) {
  5413. if (options === void 0) {
  5414. options = {};
  5415. }
  5416. var quoteMark = this._determineQuoteMark(options);
  5417. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5418. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5419. return escaped;
  5420. };
  5421. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5422. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5423. }
  5424. /**
  5425. * Set the unescaped value with the specified quotation options. The value
  5426. * provided must not include any wrapping quote marks -- those quotes will
  5427. * be interpreted as part of the value and escaped accordingly.
  5428. */;
  5429. _proto.setValue = function setValue(value, options) {
  5430. if (options === void 0) {
  5431. options = {};
  5432. }
  5433. this._value = value;
  5434. this._quoteMark = this._determineQuoteMark(options);
  5435. this._syncRawValue();
  5436. }
  5437. /**
  5438. * Intelligently select a quoteMark value based on the value's contents. If
  5439. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5440. * mark will be picked that minimizes the number of escapes.
  5441. *
  5442. * If there's no clear winner, the quote mark from these options is used,
  5443. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5444. * true). If the quoteMark is unspecified, a double quote is used.
  5445. *
  5446. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5447. * from the quoteValue method.
  5448. */;
  5449. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5450. var v = this.value;
  5451. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5452. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5453. if (numSingleQuotes + numDoubleQuotes === 0) {
  5454. var escaped = (0, _cssesc["default"])(v, {
  5455. isIdentifier: true
  5456. });
  5457. if (escaped === v) {
  5458. return Attribute.NO_QUOTE;
  5459. } else {
  5460. var pref = this.preferredQuoteMark(options);
  5461. if (pref === Attribute.NO_QUOTE) {
  5462. // pick a quote mark that isn't none and see if it's smaller
  5463. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5464. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5465. var quoteValue = (0, _cssesc["default"])(v, opts);
  5466. if (quoteValue.length < escaped.length) {
  5467. return quote;
  5468. }
  5469. }
  5470. return pref;
  5471. }
  5472. } else if (numDoubleQuotes === numSingleQuotes) {
  5473. return this.preferredQuoteMark(options);
  5474. } else if (numDoubleQuotes < numSingleQuotes) {
  5475. return Attribute.DOUBLE_QUOTE;
  5476. } else {
  5477. return Attribute.SINGLE_QUOTE;
  5478. }
  5479. }
  5480. /**
  5481. * Selects the preferred quote mark based on the options and the current quote mark value.
  5482. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5483. * instead.
  5484. */;
  5485. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5486. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5487. if (quoteMark === undefined) {
  5488. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5489. }
  5490. if (quoteMark === undefined) {
  5491. quoteMark = Attribute.DOUBLE_QUOTE;
  5492. }
  5493. return quoteMark;
  5494. };
  5495. _proto._syncRawValue = function _syncRawValue() {
  5496. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5497. if (rawValue === this._value) {
  5498. if (this.raws) {
  5499. delete this.raws.value;
  5500. }
  5501. } else {
  5502. this.raws.value = rawValue;
  5503. }
  5504. };
  5505. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5506. if (this._constructed) {
  5507. var escaped = (0, _cssesc["default"])(value, {
  5508. isIdentifier: true
  5509. });
  5510. if (escaped !== value) {
  5511. this.raws[prop] = escaped;
  5512. } else {
  5513. delete this.raws[prop];
  5514. }
  5515. }
  5516. };
  5517. _proto._spacesFor = function _spacesFor(name) {
  5518. var attrSpaces = {
  5519. before: '',
  5520. after: ''
  5521. };
  5522. var spaces = this.spaces[name] || {};
  5523. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5524. return Object.assign(attrSpaces, spaces, rawSpaces);
  5525. };
  5526. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5527. if (spaceName === void 0) {
  5528. spaceName = name;
  5529. }
  5530. if (concat === void 0) {
  5531. concat = defaultAttrConcat;
  5532. }
  5533. var attrSpaces = this._spacesFor(spaceName);
  5534. return concat(this.stringifyProperty(name), attrSpaces);
  5535. }
  5536. /**
  5537. * returns the offset of the attribute part specified relative to the
  5538. * start of the node of the output string.
  5539. *
  5540. * * "ns" - alias for "namespace"
  5541. * * "namespace" - the namespace if it exists.
  5542. * * "attribute" - the attribute name
  5543. * * "attributeNS" - the start of the attribute or its namespace
  5544. * * "operator" - the match operator of the attribute
  5545. * * "value" - The value (string or identifier)
  5546. * * "insensitive" - the case insensitivity flag;
  5547. * @param part One of the possible values inside an attribute.
  5548. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5549. */;
  5550. _proto.offsetOf = function offsetOf(name) {
  5551. var count = 1;
  5552. var attributeSpaces = this._spacesFor("attribute");
  5553. count += attributeSpaces.before.length;
  5554. if (name === "namespace" || name === "ns") {
  5555. return this.namespace ? count : -1;
  5556. }
  5557. if (name === "attributeNS") {
  5558. return count;
  5559. }
  5560. count += this.namespaceString.length;
  5561. if (this.namespace) {
  5562. count += 1;
  5563. }
  5564. if (name === "attribute") {
  5565. return count;
  5566. }
  5567. count += this.stringifyProperty("attribute").length;
  5568. count += attributeSpaces.after.length;
  5569. var operatorSpaces = this._spacesFor("operator");
  5570. count += operatorSpaces.before.length;
  5571. var operator = this.stringifyProperty("operator");
  5572. if (name === "operator") {
  5573. return operator ? count : -1;
  5574. }
  5575. count += operator.length;
  5576. count += operatorSpaces.after.length;
  5577. var valueSpaces = this._spacesFor("value");
  5578. count += valueSpaces.before.length;
  5579. var value = this.stringifyProperty("value");
  5580. if (name === "value") {
  5581. return value ? count : -1;
  5582. }
  5583. count += value.length;
  5584. count += valueSpaces.after.length;
  5585. var insensitiveSpaces = this._spacesFor("insensitive");
  5586. count += insensitiveSpaces.before.length;
  5587. if (name === "insensitive") {
  5588. return this.insensitive ? count : -1;
  5589. }
  5590. return -1;
  5591. };
  5592. _proto.toString = function toString() {
  5593. var _this2 = this;
  5594. var selector = [this.rawSpaceBefore, '['];
  5595. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5596. if (this.operator && (this.value || this.value === '')) {
  5597. selector.push(this._stringFor('operator'));
  5598. selector.push(this._stringFor('value'));
  5599. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5600. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5601. attrSpaces.before = " ";
  5602. }
  5603. return defaultAttrConcat(attrValue, attrSpaces);
  5604. }));
  5605. }
  5606. selector.push(']');
  5607. selector.push(this.rawSpaceAfter);
  5608. return selector.join('');
  5609. };
  5610. _createClass(Attribute, [{
  5611. key: "quoted",
  5612. get: function get() {
  5613. var qm = this.quoteMark;
  5614. return qm === "'" || qm === '"';
  5615. },
  5616. set: function set(value) {
  5617. warnOfDeprecatedQuotedAssignment();
  5618. }
  5619. /**
  5620. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5621. * returns `null` if the value is not quoted.
  5622. * returns `undefined` if the quotation state is unknown (this can happen when
  5623. * the attribute is constructed without specifying a quote mark.)
  5624. */
  5625. }, {
  5626. key: "quoteMark",
  5627. get: function get() {
  5628. return this._quoteMark;
  5629. }
  5630. /**
  5631. * Set the quote mark to be used by this attribute's value.
  5632. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5633. * value is updated accordingly.
  5634. *
  5635. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5636. */,
  5637. set: function set(quoteMark) {
  5638. if (!this._constructed) {
  5639. this._quoteMark = quoteMark;
  5640. return;
  5641. }
  5642. if (this._quoteMark !== quoteMark) {
  5643. this._quoteMark = quoteMark;
  5644. this._syncRawValue();
  5645. }
  5646. }
  5647. }, {
  5648. key: "qualifiedAttribute",
  5649. get: function get() {
  5650. return this.qualifiedName(this.raws.attribute || this.attribute);
  5651. }
  5652. }, {
  5653. key: "insensitiveFlag",
  5654. get: function get() {
  5655. return this.insensitive ? 'i' : '';
  5656. }
  5657. }, {
  5658. key: "value",
  5659. get: function get() {
  5660. return this._value;
  5661. },
  5662. set:
  5663. /**
  5664. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5665. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5666. * is unescaped during parsing and any quote marks are removed.
  5667. *
  5668. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5669. * a deprecation warning is raised when the new value contains any characters that would
  5670. * require escaping (including if it contains wrapped quotes).
  5671. *
  5672. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5673. * how the new value is quoted.
  5674. */
  5675. function set(v) {
  5676. if (this._constructed) {
  5677. var _unescapeValue2 = unescapeValue(v),
  5678. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5679. unescaped = _unescapeValue2.unescaped,
  5680. quoteMark = _unescapeValue2.quoteMark;
  5681. if (deprecatedUsage) {
  5682. warnOfDeprecatedValueAssignment();
  5683. }
  5684. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5685. return;
  5686. }
  5687. this._value = unescaped;
  5688. this._quoteMark = quoteMark;
  5689. this._syncRawValue();
  5690. } else {
  5691. this._value = v;
  5692. }
  5693. }
  5694. }, {
  5695. key: "insensitive",
  5696. get: function get() {
  5697. return this._insensitive;
  5698. }
  5699. /**
  5700. * Set the case insensitive flag.
  5701. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5702. * of the attribute is updated accordingly.
  5703. *
  5704. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5705. */,
  5706. set: function set(insensitive) {
  5707. if (!insensitive) {
  5708. this._insensitive = false;
  5709. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5710. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5711. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5712. this.raws.insensitiveFlag = undefined;
  5713. }
  5714. }
  5715. this._insensitive = insensitive;
  5716. }
  5717. }, {
  5718. key: "attribute",
  5719. get: function get() {
  5720. return this._attribute;
  5721. },
  5722. set: function set(name) {
  5723. this._handleEscapes("attribute", name);
  5724. this._attribute = name;
  5725. }
  5726. }]);
  5727. return Attribute;
  5728. }(_namespace["default"]);
  5729. exports["default"] = Attribute;
  5730. Attribute.NO_QUOTE = null;
  5731. Attribute.SINGLE_QUOTE = "'";
  5732. Attribute.DOUBLE_QUOTE = '"';
  5733. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5734. "'": {
  5735. quotes: 'single',
  5736. wrap: true
  5737. },
  5738. '"': {
  5739. quotes: 'double',
  5740. wrap: true
  5741. }
  5742. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5743. isIdentifier: true
  5744. }, _CSSESC_QUOTE_OPTIONS);
  5745. function defaultAttrConcat(attrValue, attrSpaces) {
  5746. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5747. }
  5748. } (attribute$1));
  5749. return attribute$1;
  5750. }
  5751. var universal$1 = {exports: {}};
  5752. var hasRequiredUniversal$1;
  5753. function requireUniversal$1 () {
  5754. if (hasRequiredUniversal$1) return universal$1.exports;
  5755. hasRequiredUniversal$1 = 1;
  5756. (function (module, exports) {
  5757. exports.__esModule = true;
  5758. exports["default"] = void 0;
  5759. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5760. var _types = /*@__PURE__*/ requireTypes$1();
  5761. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5762. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5763. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5764. var Universal = /*#__PURE__*/function (_Namespace) {
  5765. _inheritsLoose(Universal, _Namespace);
  5766. function Universal(opts) {
  5767. var _this;
  5768. _this = _Namespace.call(this, opts) || this;
  5769. _this.type = _types.UNIVERSAL;
  5770. _this.value = '*';
  5771. return _this;
  5772. }
  5773. return Universal;
  5774. }(_namespace["default"]);
  5775. exports["default"] = Universal;
  5776. module.exports = exports.default;
  5777. } (universal$1, universal$1.exports));
  5778. return universal$1.exports;
  5779. }
  5780. var combinator$1 = {exports: {}};
  5781. var hasRequiredCombinator$1;
  5782. function requireCombinator$1 () {
  5783. if (hasRequiredCombinator$1) return combinator$1.exports;
  5784. hasRequiredCombinator$1 = 1;
  5785. (function (module, exports) {
  5786. exports.__esModule = true;
  5787. exports["default"] = void 0;
  5788. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5789. var _types = /*@__PURE__*/ requireTypes$1();
  5790. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5791. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5792. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5793. var Combinator = /*#__PURE__*/function (_Node) {
  5794. _inheritsLoose(Combinator, _Node);
  5795. function Combinator(opts) {
  5796. var _this;
  5797. _this = _Node.call(this, opts) || this;
  5798. _this.type = _types.COMBINATOR;
  5799. return _this;
  5800. }
  5801. return Combinator;
  5802. }(_node["default"]);
  5803. exports["default"] = Combinator;
  5804. module.exports = exports.default;
  5805. } (combinator$1, combinator$1.exports));
  5806. return combinator$1.exports;
  5807. }
  5808. var nesting$1 = {exports: {}};
  5809. var hasRequiredNesting$1;
  5810. function requireNesting$1 () {
  5811. if (hasRequiredNesting$1) return nesting$1.exports;
  5812. hasRequiredNesting$1 = 1;
  5813. (function (module, exports) {
  5814. exports.__esModule = true;
  5815. exports["default"] = void 0;
  5816. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5817. var _types = /*@__PURE__*/ requireTypes$1();
  5818. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5819. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5820. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5821. var Nesting = /*#__PURE__*/function (_Node) {
  5822. _inheritsLoose(Nesting, _Node);
  5823. function Nesting(opts) {
  5824. var _this;
  5825. _this = _Node.call(this, opts) || this;
  5826. _this.type = _types.NESTING;
  5827. _this.value = '&';
  5828. return _this;
  5829. }
  5830. return Nesting;
  5831. }(_node["default"]);
  5832. exports["default"] = Nesting;
  5833. module.exports = exports.default;
  5834. } (nesting$1, nesting$1.exports));
  5835. return nesting$1.exports;
  5836. }
  5837. var sortAscending$1 = {exports: {}};
  5838. var hasRequiredSortAscending$1;
  5839. function requireSortAscending$1 () {
  5840. if (hasRequiredSortAscending$1) return sortAscending$1.exports;
  5841. hasRequiredSortAscending$1 = 1;
  5842. (function (module, exports) {
  5843. exports.__esModule = true;
  5844. exports["default"] = sortAscending;
  5845. function sortAscending(list) {
  5846. return list.sort(function (a, b) {
  5847. return a - b;
  5848. });
  5849. }
  5850. module.exports = exports.default;
  5851. } (sortAscending$1, sortAscending$1.exports));
  5852. return sortAscending$1.exports;
  5853. }
  5854. var tokenize$1 = {};
  5855. var tokenTypes$1 = {};
  5856. var hasRequiredTokenTypes$1;
  5857. function requireTokenTypes$1 () {
  5858. if (hasRequiredTokenTypes$1) return tokenTypes$1;
  5859. hasRequiredTokenTypes$1 = 1;
  5860. tokenTypes$1.__esModule = true;
  5861. tokenTypes$1.word = tokenTypes$1.tilde = tokenTypes$1.tab = tokenTypes$1.str = tokenTypes$1.space = tokenTypes$1.slash = tokenTypes$1.singleQuote = tokenTypes$1.semicolon = tokenTypes$1.plus = tokenTypes$1.pipe = tokenTypes$1.openSquare = tokenTypes$1.openParenthesis = tokenTypes$1.newline = tokenTypes$1.greaterThan = tokenTypes$1.feed = tokenTypes$1.equals = tokenTypes$1.doubleQuote = tokenTypes$1.dollar = tokenTypes$1.cr = tokenTypes$1.comment = tokenTypes$1.comma = tokenTypes$1.combinator = tokenTypes$1.colon = tokenTypes$1.closeSquare = tokenTypes$1.closeParenthesis = tokenTypes$1.caret = tokenTypes$1.bang = tokenTypes$1.backslash = tokenTypes$1.at = tokenTypes$1.asterisk = tokenTypes$1.ampersand = void 0;
  5862. var ampersand = 38; // `&`.charCodeAt(0);
  5863. tokenTypes$1.ampersand = ampersand;
  5864. var asterisk = 42; // `*`.charCodeAt(0);
  5865. tokenTypes$1.asterisk = asterisk;
  5866. var at = 64; // `@`.charCodeAt(0);
  5867. tokenTypes$1.at = at;
  5868. var comma = 44; // `,`.charCodeAt(0);
  5869. tokenTypes$1.comma = comma;
  5870. var colon = 58; // `:`.charCodeAt(0);
  5871. tokenTypes$1.colon = colon;
  5872. var semicolon = 59; // `;`.charCodeAt(0);
  5873. tokenTypes$1.semicolon = semicolon;
  5874. var openParenthesis = 40; // `(`.charCodeAt(0);
  5875. tokenTypes$1.openParenthesis = openParenthesis;
  5876. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5877. tokenTypes$1.closeParenthesis = closeParenthesis;
  5878. var openSquare = 91; // `[`.charCodeAt(0);
  5879. tokenTypes$1.openSquare = openSquare;
  5880. var closeSquare = 93; // `]`.charCodeAt(0);
  5881. tokenTypes$1.closeSquare = closeSquare;
  5882. var dollar = 36; // `$`.charCodeAt(0);
  5883. tokenTypes$1.dollar = dollar;
  5884. var tilde = 126; // `~`.charCodeAt(0);
  5885. tokenTypes$1.tilde = tilde;
  5886. var caret = 94; // `^`.charCodeAt(0);
  5887. tokenTypes$1.caret = caret;
  5888. var plus = 43; // `+`.charCodeAt(0);
  5889. tokenTypes$1.plus = plus;
  5890. var equals = 61; // `=`.charCodeAt(0);
  5891. tokenTypes$1.equals = equals;
  5892. var pipe = 124; // `|`.charCodeAt(0);
  5893. tokenTypes$1.pipe = pipe;
  5894. var greaterThan = 62; // `>`.charCodeAt(0);
  5895. tokenTypes$1.greaterThan = greaterThan;
  5896. var space = 32; // ` `.charCodeAt(0);
  5897. tokenTypes$1.space = space;
  5898. var singleQuote = 39; // `'`.charCodeAt(0);
  5899. tokenTypes$1.singleQuote = singleQuote;
  5900. var doubleQuote = 34; // `"`.charCodeAt(0);
  5901. tokenTypes$1.doubleQuote = doubleQuote;
  5902. var slash = 47; // `/`.charCodeAt(0);
  5903. tokenTypes$1.slash = slash;
  5904. var bang = 33; // `!`.charCodeAt(0);
  5905. tokenTypes$1.bang = bang;
  5906. var backslash = 92; // '\\'.charCodeAt(0);
  5907. tokenTypes$1.backslash = backslash;
  5908. var cr = 13; // '\r'.charCodeAt(0);
  5909. tokenTypes$1.cr = cr;
  5910. var feed = 12; // '\f'.charCodeAt(0);
  5911. tokenTypes$1.feed = feed;
  5912. var newline = 10; // '\n'.charCodeAt(0);
  5913. tokenTypes$1.newline = newline;
  5914. var tab = 9; // '\t'.charCodeAt(0);
  5915. // Expose aliases primarily for readability.
  5916. tokenTypes$1.tab = tab;
  5917. var str = singleQuote;
  5918. // No good single character representation!
  5919. tokenTypes$1.str = str;
  5920. var comment = -1;
  5921. tokenTypes$1.comment = comment;
  5922. var word = -2;
  5923. tokenTypes$1.word = word;
  5924. var combinator = -3;
  5925. tokenTypes$1.combinator = combinator;
  5926. return tokenTypes$1;
  5927. }
  5928. var hasRequiredTokenize$1;
  5929. function requireTokenize$1 () {
  5930. if (hasRequiredTokenize$1) return tokenize$1;
  5931. hasRequiredTokenize$1 = 1;
  5932. (function (exports) {
  5933. exports.__esModule = true;
  5934. exports.FIELDS = void 0;
  5935. exports["default"] = tokenize;
  5936. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  5937. var _unescapable, _wordDelimiters;
  5938. 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); }
  5939. function _interopRequireWildcard(obj, nodeInterop) { if (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; }
  5940. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5941. 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);
  5942. var hex = {};
  5943. var hexChars = "0123456789abcdefABCDEF";
  5944. for (var i = 0; i < hexChars.length; i++) {
  5945. hex[hexChars.charCodeAt(i)] = true;
  5946. }
  5947. /**
  5948. * Returns the last index of the bar css word
  5949. * @param {string} css The string in which the word begins
  5950. * @param {number} start The index into the string where word's first letter occurs
  5951. */
  5952. function consumeWord(css, start) {
  5953. var next = start;
  5954. var code;
  5955. do {
  5956. code = css.charCodeAt(next);
  5957. if (wordDelimiters[code]) {
  5958. return next - 1;
  5959. } else if (code === t.backslash) {
  5960. next = consumeEscape(css, next) + 1;
  5961. } else {
  5962. // All other characters are part of the word
  5963. next++;
  5964. }
  5965. } while (next < css.length);
  5966. return next - 1;
  5967. }
  5968. /**
  5969. * Returns the last index of the escape sequence
  5970. * @param {string} css The string in which the sequence begins
  5971. * @param {number} start The index into the string where escape character (`\`) occurs.
  5972. */
  5973. function consumeEscape(css, start) {
  5974. var next = start;
  5975. var code = css.charCodeAt(next + 1);
  5976. if (unescapable[code]) ; else if (hex[code]) {
  5977. var hexDigits = 0;
  5978. // consume up to 6 hex chars
  5979. do {
  5980. next++;
  5981. hexDigits++;
  5982. code = css.charCodeAt(next + 1);
  5983. } while (hex[code] && hexDigits < 6);
  5984. // if fewer than 6 hex chars, a trailing space ends the escape
  5985. if (hexDigits < 6 && code === t.space) {
  5986. next++;
  5987. }
  5988. } else {
  5989. // the next char is part of the current word
  5990. next++;
  5991. }
  5992. return next;
  5993. }
  5994. var FIELDS = {
  5995. TYPE: 0,
  5996. START_LINE: 1,
  5997. START_COL: 2,
  5998. END_LINE: 3,
  5999. END_COL: 4,
  6000. START_POS: 5,
  6001. END_POS: 6
  6002. };
  6003. exports.FIELDS = FIELDS;
  6004. function tokenize(input) {
  6005. var tokens = [];
  6006. var css = input.css.valueOf();
  6007. var _css = css,
  6008. length = _css.length;
  6009. var offset = -1;
  6010. var line = 1;
  6011. var start = 0;
  6012. var end = 0;
  6013. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  6014. function unclosed(what, fix) {
  6015. if (input.safe) {
  6016. // fyi: this is never set to true.
  6017. css += fix;
  6018. next = css.length - 1;
  6019. } else {
  6020. throw input.error('Unclosed ' + what, line, start - offset, start);
  6021. }
  6022. }
  6023. while (start < length) {
  6024. code = css.charCodeAt(start);
  6025. if (code === t.newline) {
  6026. offset = start;
  6027. line += 1;
  6028. }
  6029. switch (code) {
  6030. case t.space:
  6031. case t.tab:
  6032. case t.newline:
  6033. case t.cr:
  6034. case t.feed:
  6035. next = start;
  6036. do {
  6037. next += 1;
  6038. code = css.charCodeAt(next);
  6039. if (code === t.newline) {
  6040. offset = next;
  6041. line += 1;
  6042. }
  6043. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  6044. tokenType = t.space;
  6045. endLine = line;
  6046. endColumn = next - offset - 1;
  6047. end = next;
  6048. break;
  6049. case t.plus:
  6050. case t.greaterThan:
  6051. case t.tilde:
  6052. case t.pipe:
  6053. next = start;
  6054. do {
  6055. next += 1;
  6056. code = css.charCodeAt(next);
  6057. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  6058. tokenType = t.combinator;
  6059. endLine = line;
  6060. endColumn = start - offset;
  6061. end = next;
  6062. break;
  6063. // Consume these characters as single tokens.
  6064. case t.asterisk:
  6065. case t.ampersand:
  6066. case t.bang:
  6067. case t.comma:
  6068. case t.equals:
  6069. case t.dollar:
  6070. case t.caret:
  6071. case t.openSquare:
  6072. case t.closeSquare:
  6073. case t.colon:
  6074. case t.semicolon:
  6075. case t.openParenthesis:
  6076. case t.closeParenthesis:
  6077. next = start;
  6078. tokenType = code;
  6079. endLine = line;
  6080. endColumn = start - offset;
  6081. end = next + 1;
  6082. break;
  6083. case t.singleQuote:
  6084. case t.doubleQuote:
  6085. quote = code === t.singleQuote ? "'" : '"';
  6086. next = start;
  6087. do {
  6088. escaped = false;
  6089. next = css.indexOf(quote, next + 1);
  6090. if (next === -1) {
  6091. unclosed('quote', quote);
  6092. }
  6093. escapePos = next;
  6094. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6095. escapePos -= 1;
  6096. escaped = !escaped;
  6097. }
  6098. } while (escaped);
  6099. tokenType = t.str;
  6100. endLine = line;
  6101. endColumn = start - offset;
  6102. end = next + 1;
  6103. break;
  6104. default:
  6105. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6106. next = css.indexOf('*/', start + 2) + 1;
  6107. if (next === 0) {
  6108. unclosed('comment', '*/');
  6109. }
  6110. content = css.slice(start, next + 1);
  6111. lines = content.split('\n');
  6112. last = lines.length - 1;
  6113. if (last > 0) {
  6114. nextLine = line + last;
  6115. nextOffset = next - lines[last].length;
  6116. } else {
  6117. nextLine = line;
  6118. nextOffset = offset;
  6119. }
  6120. tokenType = t.comment;
  6121. line = nextLine;
  6122. endLine = nextLine;
  6123. endColumn = next - nextOffset;
  6124. } else if (code === t.slash) {
  6125. next = start;
  6126. tokenType = code;
  6127. endLine = line;
  6128. endColumn = start - offset;
  6129. end = next + 1;
  6130. } else {
  6131. next = consumeWord(css, start);
  6132. tokenType = t.word;
  6133. endLine = line;
  6134. endColumn = next - offset;
  6135. }
  6136. end = next + 1;
  6137. break;
  6138. }
  6139. // Ensure that the token structure remains consistent
  6140. tokens.push([tokenType,
  6141. // [0] Token type
  6142. line,
  6143. // [1] Starting line
  6144. start - offset,
  6145. // [2] Starting column
  6146. endLine,
  6147. // [3] Ending line
  6148. endColumn,
  6149. // [4] Ending column
  6150. start,
  6151. // [5] Start position / Source index
  6152. end // [6] End position
  6153. ]);
  6154. // Reset offset for the next token
  6155. if (nextOffset) {
  6156. offset = nextOffset;
  6157. nextOffset = null;
  6158. }
  6159. start = end;
  6160. }
  6161. return tokens;
  6162. }
  6163. } (tokenize$1));
  6164. return tokenize$1;
  6165. }
  6166. var hasRequiredParser$2;
  6167. function requireParser$2 () {
  6168. if (hasRequiredParser$2) return parser$1.exports;
  6169. hasRequiredParser$2 = 1;
  6170. (function (module, exports) {
  6171. exports.__esModule = true;
  6172. exports["default"] = void 0;
  6173. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  6174. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  6175. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  6176. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  6177. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  6178. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  6179. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  6180. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  6181. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute$1());
  6182. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  6183. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  6184. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  6185. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending$1());
  6186. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize$1());
  6187. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  6188. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  6189. var _util = /*@__PURE__*/ requireUtil$2();
  6190. var _WHITESPACE_TOKENS, _Object$assign;
  6191. 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); }
  6192. function _interopRequireWildcard(obj, nodeInterop) { if (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; }
  6193. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6194. 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); } }
  6195. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6196. 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);
  6197. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6198. function tokenStart(token) {
  6199. return {
  6200. line: token[_tokenize.FIELDS.START_LINE],
  6201. column: token[_tokenize.FIELDS.START_COL]
  6202. };
  6203. }
  6204. function tokenEnd(token) {
  6205. return {
  6206. line: token[_tokenize.FIELDS.END_LINE],
  6207. column: token[_tokenize.FIELDS.END_COL]
  6208. };
  6209. }
  6210. function getSource(startLine, startColumn, endLine, endColumn) {
  6211. return {
  6212. start: {
  6213. line: startLine,
  6214. column: startColumn
  6215. },
  6216. end: {
  6217. line: endLine,
  6218. column: endColumn
  6219. }
  6220. };
  6221. }
  6222. function getTokenSource(token) {
  6223. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6224. }
  6225. function getTokenSourceSpan(startToken, endToken) {
  6226. if (!startToken) {
  6227. return undefined;
  6228. }
  6229. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6230. }
  6231. function unescapeProp(node, prop) {
  6232. var value = node[prop];
  6233. if (typeof value !== "string") {
  6234. return;
  6235. }
  6236. if (value.indexOf("\\") !== -1) {
  6237. (0, _util.ensureObject)(node, 'raws');
  6238. node[prop] = (0, _util.unesc)(value);
  6239. if (node.raws[prop] === undefined) {
  6240. node.raws[prop] = value;
  6241. }
  6242. }
  6243. return node;
  6244. }
  6245. function indexesOf(array, item) {
  6246. var i = -1;
  6247. var indexes = [];
  6248. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6249. indexes.push(i);
  6250. }
  6251. return indexes;
  6252. }
  6253. function uniqs() {
  6254. var list = Array.prototype.concat.apply([], arguments);
  6255. return list.filter(function (item, i) {
  6256. return i === list.indexOf(item);
  6257. });
  6258. }
  6259. var Parser = /*#__PURE__*/function () {
  6260. function Parser(rule, options) {
  6261. if (options === void 0) {
  6262. options = {};
  6263. }
  6264. this.rule = rule;
  6265. this.options = Object.assign({
  6266. lossy: false,
  6267. safe: false
  6268. }, options);
  6269. this.position = 0;
  6270. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6271. this.tokens = (0, _tokenize["default"])({
  6272. css: this.css,
  6273. error: this._errorGenerator(),
  6274. safe: this.options.safe
  6275. });
  6276. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6277. this.root = new _root["default"]({
  6278. source: rootSource
  6279. });
  6280. this.root.errorGenerator = this._errorGenerator();
  6281. var selector = new _selector["default"]({
  6282. source: {
  6283. start: {
  6284. line: 1,
  6285. column: 1
  6286. }
  6287. },
  6288. sourceIndex: 0
  6289. });
  6290. this.root.append(selector);
  6291. this.current = selector;
  6292. this.loop();
  6293. }
  6294. var _proto = Parser.prototype;
  6295. _proto._errorGenerator = function _errorGenerator() {
  6296. var _this = this;
  6297. return function (message, errorOptions) {
  6298. if (typeof _this.rule === 'string') {
  6299. return new Error(message);
  6300. }
  6301. return _this.rule.error(message, errorOptions);
  6302. };
  6303. };
  6304. _proto.attribute = function attribute() {
  6305. var attr = [];
  6306. var startingToken = this.currToken;
  6307. this.position++;
  6308. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6309. attr.push(this.currToken);
  6310. this.position++;
  6311. }
  6312. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6313. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6314. }
  6315. var len = attr.length;
  6316. var node = {
  6317. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6318. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6319. };
  6320. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6321. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6322. }
  6323. var pos = 0;
  6324. var spaceBefore = '';
  6325. var commentBefore = '';
  6326. var lastAdded = null;
  6327. var spaceAfterMeaningfulToken = false;
  6328. while (pos < len) {
  6329. var token = attr[pos];
  6330. var content = this.content(token);
  6331. var next = attr[pos + 1];
  6332. switch (token[_tokenize.FIELDS.TYPE]) {
  6333. case tokens.space:
  6334. // if (
  6335. // len === 1 ||
  6336. // pos === 0 && this.content(next) === '|'
  6337. // ) {
  6338. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6339. // }
  6340. spaceAfterMeaningfulToken = true;
  6341. if (this.options.lossy) {
  6342. break;
  6343. }
  6344. if (lastAdded) {
  6345. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6346. var prevContent = node.spaces[lastAdded].after || '';
  6347. node.spaces[lastAdded].after = prevContent + content;
  6348. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6349. if (existingComment) {
  6350. node.raws.spaces[lastAdded].after = existingComment + content;
  6351. }
  6352. } else {
  6353. spaceBefore = spaceBefore + content;
  6354. commentBefore = commentBefore + content;
  6355. }
  6356. break;
  6357. case tokens.asterisk:
  6358. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6359. node.operator = content;
  6360. lastAdded = 'operator';
  6361. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6362. if (spaceBefore) {
  6363. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6364. node.spaces.attribute.before = spaceBefore;
  6365. spaceBefore = '';
  6366. }
  6367. if (commentBefore) {
  6368. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6369. node.raws.spaces.attribute.before = spaceBefore;
  6370. commentBefore = '';
  6371. }
  6372. node.namespace = (node.namespace || "") + content;
  6373. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6374. if (rawValue) {
  6375. node.raws.namespace += content;
  6376. }
  6377. lastAdded = 'namespace';
  6378. }
  6379. spaceAfterMeaningfulToken = false;
  6380. break;
  6381. case tokens.dollar:
  6382. if (lastAdded === "value") {
  6383. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6384. node.value += "$";
  6385. if (oldRawValue) {
  6386. node.raws.value = oldRawValue + "$";
  6387. }
  6388. break;
  6389. }
  6390. // Falls through
  6391. case tokens.caret:
  6392. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6393. node.operator = content;
  6394. lastAdded = 'operator';
  6395. }
  6396. spaceAfterMeaningfulToken = false;
  6397. break;
  6398. case tokens.combinator:
  6399. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6400. node.operator = content;
  6401. lastAdded = 'operator';
  6402. }
  6403. if (content !== '|') {
  6404. spaceAfterMeaningfulToken = false;
  6405. break;
  6406. }
  6407. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6408. node.operator = content;
  6409. lastAdded = 'operator';
  6410. } else if (!node.namespace && !node.attribute) {
  6411. node.namespace = true;
  6412. }
  6413. spaceAfterMeaningfulToken = false;
  6414. break;
  6415. case tokens.word:
  6416. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6417. // this look-ahead probably fails with comment nodes involved.
  6418. !node.operator && !node.namespace) {
  6419. node.namespace = content;
  6420. lastAdded = 'namespace';
  6421. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6422. if (spaceBefore) {
  6423. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6424. node.spaces.attribute.before = spaceBefore;
  6425. spaceBefore = '';
  6426. }
  6427. if (commentBefore) {
  6428. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6429. node.raws.spaces.attribute.before = commentBefore;
  6430. commentBefore = '';
  6431. }
  6432. node.attribute = (node.attribute || "") + content;
  6433. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6434. if (_rawValue) {
  6435. node.raws.attribute += content;
  6436. }
  6437. lastAdded = 'attribute';
  6438. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6439. var _unescaped = (0, _util.unesc)(content);
  6440. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6441. var oldValue = node.value || '';
  6442. node.value = oldValue + _unescaped;
  6443. node.quoteMark = null;
  6444. if (_unescaped !== content || _oldRawValue) {
  6445. (0, _util.ensureObject)(node, 'raws');
  6446. node.raws.value = (_oldRawValue || oldValue) + content;
  6447. }
  6448. lastAdded = 'value';
  6449. } else {
  6450. var insensitive = content === 'i' || content === "I";
  6451. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6452. node.insensitive = insensitive;
  6453. if (!insensitive || content === "I") {
  6454. (0, _util.ensureObject)(node, 'raws');
  6455. node.raws.insensitiveFlag = content;
  6456. }
  6457. lastAdded = 'insensitive';
  6458. if (spaceBefore) {
  6459. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6460. node.spaces.insensitive.before = spaceBefore;
  6461. spaceBefore = '';
  6462. }
  6463. if (commentBefore) {
  6464. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6465. node.raws.spaces.insensitive.before = commentBefore;
  6466. commentBefore = '';
  6467. }
  6468. } else if (node.value || node.value === '') {
  6469. lastAdded = 'value';
  6470. node.value += content;
  6471. if (node.raws.value) {
  6472. node.raws.value += content;
  6473. }
  6474. }
  6475. }
  6476. spaceAfterMeaningfulToken = false;
  6477. break;
  6478. case tokens.str:
  6479. if (!node.attribute || !node.operator) {
  6480. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6481. index: token[_tokenize.FIELDS.START_POS]
  6482. });
  6483. }
  6484. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6485. unescaped = _unescapeValue.unescaped,
  6486. quoteMark = _unescapeValue.quoteMark;
  6487. node.value = unescaped;
  6488. node.quoteMark = quoteMark;
  6489. lastAdded = 'value';
  6490. (0, _util.ensureObject)(node, 'raws');
  6491. node.raws.value = content;
  6492. spaceAfterMeaningfulToken = false;
  6493. break;
  6494. case tokens.equals:
  6495. if (!node.attribute) {
  6496. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6497. }
  6498. if (node.value) {
  6499. return this.error('Unexpected "=" found; an operator was already defined.', {
  6500. index: token[_tokenize.FIELDS.START_POS]
  6501. });
  6502. }
  6503. node.operator = node.operator ? node.operator + content : content;
  6504. lastAdded = 'operator';
  6505. spaceAfterMeaningfulToken = false;
  6506. break;
  6507. case tokens.comment:
  6508. if (lastAdded) {
  6509. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6510. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6511. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6512. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6513. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6514. } else {
  6515. var lastValue = node[lastAdded] || '';
  6516. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6517. (0, _util.ensureObject)(node, 'raws');
  6518. node.raws[lastAdded] = rawLastValue + content;
  6519. }
  6520. } else {
  6521. commentBefore = commentBefore + content;
  6522. }
  6523. break;
  6524. default:
  6525. return this.error("Unexpected \"" + content + "\" found.", {
  6526. index: token[_tokenize.FIELDS.START_POS]
  6527. });
  6528. }
  6529. pos++;
  6530. }
  6531. unescapeProp(node, "attribute");
  6532. unescapeProp(node, "namespace");
  6533. this.newNode(new _attribute["default"](node));
  6534. this.position++;
  6535. }
  6536. /**
  6537. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6538. * if the token position is negative, all remaining tokens are consumed.
  6539. *
  6540. * This returns an array containing a single string node if all whitespace,
  6541. * otherwise an array of comment nodes with space before and after.
  6542. *
  6543. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6544. * a previous node's space metadata.
  6545. *
  6546. * In lossy mode, this returns only comments.
  6547. */;
  6548. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6549. if (stopPosition < 0) {
  6550. stopPosition = this.tokens.length;
  6551. }
  6552. var startPosition = this.position;
  6553. var nodes = [];
  6554. var space = "";
  6555. var lastComment = undefined;
  6556. do {
  6557. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6558. if (!this.options.lossy) {
  6559. space += this.content();
  6560. }
  6561. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6562. var spaces = {};
  6563. if (space) {
  6564. spaces.before = space;
  6565. space = "";
  6566. }
  6567. lastComment = new _comment["default"]({
  6568. value: this.content(),
  6569. source: getTokenSource(this.currToken),
  6570. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6571. spaces: spaces
  6572. });
  6573. nodes.push(lastComment);
  6574. }
  6575. } while (++this.position < stopPosition);
  6576. if (space) {
  6577. if (lastComment) {
  6578. lastComment.spaces.after = space;
  6579. } else if (!this.options.lossy) {
  6580. var firstToken = this.tokens[startPosition];
  6581. var lastToken = this.tokens[this.position - 1];
  6582. nodes.push(new _string["default"]({
  6583. value: '',
  6584. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6585. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6586. spaces: {
  6587. before: space,
  6588. after: ''
  6589. }
  6590. }));
  6591. }
  6592. }
  6593. return nodes;
  6594. }
  6595. /**
  6596. *
  6597. * @param {*} nodes
  6598. */;
  6599. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6600. var _this2 = this;
  6601. if (requiredSpace === void 0) {
  6602. requiredSpace = false;
  6603. }
  6604. var space = "";
  6605. var rawSpace = "";
  6606. nodes.forEach(function (n) {
  6607. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6608. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6609. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6610. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6611. });
  6612. if (rawSpace === space) {
  6613. rawSpace = undefined;
  6614. }
  6615. var result = {
  6616. space: space,
  6617. rawSpace: rawSpace
  6618. };
  6619. return result;
  6620. };
  6621. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6622. if (position === void 0) {
  6623. position = this.position;
  6624. }
  6625. 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;
  6626. };
  6627. _proto.namedCombinator = function namedCombinator() {
  6628. if (this.isNamedCombinator()) {
  6629. var nameRaw = this.content(this.tokens[this.position + 1]);
  6630. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6631. var raws = {};
  6632. if (name !== nameRaw) {
  6633. raws.value = "/" + nameRaw + "/";
  6634. }
  6635. var node = new _combinator["default"]({
  6636. value: "/" + name + "/",
  6637. 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]),
  6638. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6639. raws: raws
  6640. });
  6641. this.position = this.position + 3;
  6642. return node;
  6643. } else {
  6644. this.unexpected();
  6645. }
  6646. };
  6647. _proto.combinator = function combinator() {
  6648. var _this3 = this;
  6649. if (this.content() === '|') {
  6650. return this.namespace();
  6651. }
  6652. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6653. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6654. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6655. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6656. if (nodes.length > 0) {
  6657. var last = this.current.last;
  6658. if (last) {
  6659. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6660. space = _this$convertWhitespa.space,
  6661. rawSpace = _this$convertWhitespa.rawSpace;
  6662. if (rawSpace !== undefined) {
  6663. last.rawSpaceAfter += rawSpace;
  6664. }
  6665. last.spaces.after += space;
  6666. } else {
  6667. nodes.forEach(function (n) {
  6668. return _this3.newNode(n);
  6669. });
  6670. }
  6671. }
  6672. return;
  6673. }
  6674. var firstToken = this.currToken;
  6675. var spaceOrDescendantSelectorNodes = undefined;
  6676. if (nextSigTokenPos > this.position) {
  6677. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6678. }
  6679. var node;
  6680. if (this.isNamedCombinator()) {
  6681. node = this.namedCombinator();
  6682. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6683. node = new _combinator["default"]({
  6684. value: this.content(),
  6685. source: getTokenSource(this.currToken),
  6686. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6687. });
  6688. this.position++;
  6689. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6690. this.unexpected();
  6691. }
  6692. if (node) {
  6693. if (spaceOrDescendantSelectorNodes) {
  6694. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6695. _space = _this$convertWhitespa2.space,
  6696. _rawSpace = _this$convertWhitespa2.rawSpace;
  6697. node.spaces.before = _space;
  6698. node.rawSpaceBefore = _rawSpace;
  6699. }
  6700. } else {
  6701. // descendant combinator
  6702. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6703. _space2 = _this$convertWhitespa3.space,
  6704. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6705. if (!_rawSpace2) {
  6706. _rawSpace2 = _space2;
  6707. }
  6708. var spaces = {};
  6709. var raws = {
  6710. spaces: {}
  6711. };
  6712. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6713. spaces.before = _space2.slice(0, _space2.length - 1);
  6714. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6715. } else if (_space2[0] === ' ' && _rawSpace2[0] === ' ') {
  6716. spaces.after = _space2.slice(1);
  6717. raws.spaces.after = _rawSpace2.slice(1);
  6718. } else {
  6719. raws.value = _rawSpace2;
  6720. }
  6721. node = new _combinator["default"]({
  6722. value: ' ',
  6723. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6724. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6725. spaces: spaces,
  6726. raws: raws
  6727. });
  6728. }
  6729. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6730. node.spaces.after = this.optionalSpace(this.content());
  6731. this.position++;
  6732. }
  6733. return this.newNode(node);
  6734. };
  6735. _proto.comma = function comma() {
  6736. if (this.position === this.tokens.length - 1) {
  6737. this.root.trailingComma = true;
  6738. this.position++;
  6739. return;
  6740. }
  6741. this.current._inferEndPosition();
  6742. var selector = new _selector["default"]({
  6743. source: {
  6744. start: tokenStart(this.tokens[this.position + 1])
  6745. },
  6746. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6747. });
  6748. this.current.parent.append(selector);
  6749. this.current = selector;
  6750. this.position++;
  6751. };
  6752. _proto.comment = function comment() {
  6753. var current = this.currToken;
  6754. this.newNode(new _comment["default"]({
  6755. value: this.content(),
  6756. source: getTokenSource(current),
  6757. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6758. }));
  6759. this.position++;
  6760. };
  6761. _proto.error = function error(message, opts) {
  6762. throw this.root.error(message, opts);
  6763. };
  6764. _proto.missingBackslash = function missingBackslash() {
  6765. return this.error('Expected a backslash preceding the semicolon.', {
  6766. index: this.currToken[_tokenize.FIELDS.START_POS]
  6767. });
  6768. };
  6769. _proto.missingParenthesis = function missingParenthesis() {
  6770. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6771. };
  6772. _proto.missingSquareBracket = function missingSquareBracket() {
  6773. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6774. };
  6775. _proto.unexpected = function unexpected() {
  6776. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6777. };
  6778. _proto.unexpectedPipe = function unexpectedPipe() {
  6779. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6780. };
  6781. _proto.namespace = function namespace() {
  6782. var before = this.prevToken && this.content(this.prevToken) || true;
  6783. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6784. this.position++;
  6785. return this.word(before);
  6786. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6787. this.position++;
  6788. return this.universal(before);
  6789. }
  6790. this.unexpectedPipe();
  6791. };
  6792. _proto.nesting = function nesting() {
  6793. if (this.nextToken) {
  6794. var nextContent = this.content(this.nextToken);
  6795. if (nextContent === "|") {
  6796. this.position++;
  6797. return;
  6798. }
  6799. }
  6800. var current = this.currToken;
  6801. this.newNode(new _nesting["default"]({
  6802. value: this.content(),
  6803. source: getTokenSource(current),
  6804. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6805. }));
  6806. this.position++;
  6807. };
  6808. _proto.parentheses = function parentheses() {
  6809. var last = this.current.last;
  6810. var unbalanced = 1;
  6811. this.position++;
  6812. if (last && last.type === types.PSEUDO) {
  6813. var selector = new _selector["default"]({
  6814. source: {
  6815. start: tokenStart(this.tokens[this.position])
  6816. },
  6817. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6818. });
  6819. var cache = this.current;
  6820. last.append(selector);
  6821. this.current = selector;
  6822. while (this.position < this.tokens.length && unbalanced) {
  6823. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6824. unbalanced++;
  6825. }
  6826. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6827. unbalanced--;
  6828. }
  6829. if (unbalanced) {
  6830. this.parse();
  6831. } else {
  6832. this.current.source.end = tokenEnd(this.currToken);
  6833. this.current.parent.source.end = tokenEnd(this.currToken);
  6834. this.position++;
  6835. }
  6836. }
  6837. this.current = cache;
  6838. } else {
  6839. // I think this case should be an error. It's used to implement a basic parse of media queries
  6840. // but I don't think it's a good idea.
  6841. var parenStart = this.currToken;
  6842. var parenValue = "(";
  6843. var parenEnd;
  6844. while (this.position < this.tokens.length && unbalanced) {
  6845. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6846. unbalanced++;
  6847. }
  6848. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6849. unbalanced--;
  6850. }
  6851. parenEnd = this.currToken;
  6852. parenValue += this.parseParenthesisToken(this.currToken);
  6853. this.position++;
  6854. }
  6855. if (last) {
  6856. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6857. } else {
  6858. this.newNode(new _string["default"]({
  6859. value: parenValue,
  6860. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6861. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6862. }));
  6863. }
  6864. }
  6865. if (unbalanced) {
  6866. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6867. }
  6868. };
  6869. _proto.pseudo = function pseudo() {
  6870. var _this4 = this;
  6871. var pseudoStr = '';
  6872. var startingToken = this.currToken;
  6873. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6874. pseudoStr += this.content();
  6875. this.position++;
  6876. }
  6877. if (!this.currToken) {
  6878. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6879. }
  6880. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6881. this.splitWord(false, function (first, length) {
  6882. pseudoStr += first;
  6883. _this4.newNode(new _pseudo["default"]({
  6884. value: pseudoStr,
  6885. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6886. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6887. }));
  6888. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6889. _this4.error('Misplaced parenthesis.', {
  6890. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6891. });
  6892. }
  6893. });
  6894. } else {
  6895. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6896. }
  6897. };
  6898. _proto.space = function space() {
  6899. var content = this.content();
  6900. // Handle space before and after the selector
  6901. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6902. return node.type === 'comment';
  6903. })) {
  6904. this.spaces = this.optionalSpace(content);
  6905. this.position++;
  6906. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6907. this.current.last.spaces.after = this.optionalSpace(content);
  6908. this.position++;
  6909. } else {
  6910. this.combinator();
  6911. }
  6912. };
  6913. _proto.string = function string() {
  6914. var current = this.currToken;
  6915. this.newNode(new _string["default"]({
  6916. value: this.content(),
  6917. source: getTokenSource(current),
  6918. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6919. }));
  6920. this.position++;
  6921. };
  6922. _proto.universal = function universal(namespace) {
  6923. var nextToken = this.nextToken;
  6924. if (nextToken && this.content(nextToken) === '|') {
  6925. this.position++;
  6926. return this.namespace();
  6927. }
  6928. var current = this.currToken;
  6929. this.newNode(new _universal["default"]({
  6930. value: this.content(),
  6931. source: getTokenSource(current),
  6932. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6933. }), namespace);
  6934. this.position++;
  6935. };
  6936. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6937. var _this5 = this;
  6938. var nextToken = this.nextToken;
  6939. var word = this.content();
  6940. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6941. this.position++;
  6942. var current = this.content();
  6943. word += current;
  6944. if (current.lastIndexOf('\\') === current.length - 1) {
  6945. var next = this.nextToken;
  6946. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6947. word += this.requiredSpace(this.content(next));
  6948. this.position++;
  6949. }
  6950. }
  6951. nextToken = this.nextToken;
  6952. }
  6953. var hasClass = indexesOf(word, '.').filter(function (i) {
  6954. // Allow escaped dot within class name
  6955. var escapedDot = word[i - 1] === '\\';
  6956. // Allow decimal numbers percent in @keyframes
  6957. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6958. return !escapedDot && !isKeyframesPercent;
  6959. });
  6960. var hasId = indexesOf(word, '#').filter(function (i) {
  6961. return word[i - 1] !== '\\';
  6962. });
  6963. // Eliminate Sass interpolations from the list of id indexes
  6964. var interpolations = indexesOf(word, '#{');
  6965. if (interpolations.length) {
  6966. hasId = hasId.filter(function (hashIndex) {
  6967. return !~interpolations.indexOf(hashIndex);
  6968. });
  6969. }
  6970. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6971. indices.forEach(function (ind, i) {
  6972. var index = indices[i + 1] || word.length;
  6973. var value = word.slice(ind, index);
  6974. if (i === 0 && firstCallback) {
  6975. return firstCallback.call(_this5, value, indices.length);
  6976. }
  6977. var node;
  6978. var current = _this5.currToken;
  6979. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6980. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6981. if (~hasClass.indexOf(ind)) {
  6982. var classNameOpts = {
  6983. value: value.slice(1),
  6984. source: source,
  6985. sourceIndex: sourceIndex
  6986. };
  6987. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6988. } else if (~hasId.indexOf(ind)) {
  6989. var idOpts = {
  6990. value: value.slice(1),
  6991. source: source,
  6992. sourceIndex: sourceIndex
  6993. };
  6994. node = new _id["default"](unescapeProp(idOpts, "value"));
  6995. } else {
  6996. var tagOpts = {
  6997. value: value,
  6998. source: source,
  6999. sourceIndex: sourceIndex
  7000. };
  7001. unescapeProp(tagOpts, "value");
  7002. node = new _tag["default"](tagOpts);
  7003. }
  7004. _this5.newNode(node, namespace);
  7005. // Ensure that the namespace is used only once
  7006. namespace = null;
  7007. });
  7008. this.position++;
  7009. };
  7010. _proto.word = function word(namespace) {
  7011. var nextToken = this.nextToken;
  7012. if (nextToken && this.content(nextToken) === '|') {
  7013. this.position++;
  7014. return this.namespace();
  7015. }
  7016. return this.splitWord(namespace);
  7017. };
  7018. _proto.loop = function loop() {
  7019. while (this.position < this.tokens.length) {
  7020. this.parse(true);
  7021. }
  7022. this.current._inferEndPosition();
  7023. return this.root;
  7024. };
  7025. _proto.parse = function parse(throwOnParenthesis) {
  7026. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  7027. case tokens.space:
  7028. this.space();
  7029. break;
  7030. case tokens.comment:
  7031. this.comment();
  7032. break;
  7033. case tokens.openParenthesis:
  7034. this.parentheses();
  7035. break;
  7036. case tokens.closeParenthesis:
  7037. if (throwOnParenthesis) {
  7038. this.missingParenthesis();
  7039. }
  7040. break;
  7041. case tokens.openSquare:
  7042. this.attribute();
  7043. break;
  7044. case tokens.dollar:
  7045. case tokens.caret:
  7046. case tokens.equals:
  7047. case tokens.word:
  7048. this.word();
  7049. break;
  7050. case tokens.colon:
  7051. this.pseudo();
  7052. break;
  7053. case tokens.comma:
  7054. this.comma();
  7055. break;
  7056. case tokens.asterisk:
  7057. this.universal();
  7058. break;
  7059. case tokens.ampersand:
  7060. this.nesting();
  7061. break;
  7062. case tokens.slash:
  7063. case tokens.combinator:
  7064. this.combinator();
  7065. break;
  7066. case tokens.str:
  7067. this.string();
  7068. break;
  7069. // These cases throw; no break needed.
  7070. case tokens.closeSquare:
  7071. this.missingSquareBracket();
  7072. case tokens.semicolon:
  7073. this.missingBackslash();
  7074. default:
  7075. this.unexpected();
  7076. }
  7077. }
  7078. /**
  7079. * Helpers
  7080. */;
  7081. _proto.expected = function expected(description, index, found) {
  7082. if (Array.isArray(description)) {
  7083. var last = description.pop();
  7084. description = description.join(', ') + " or " + last;
  7085. }
  7086. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  7087. if (!found) {
  7088. return this.error("Expected " + an + " " + description + ".", {
  7089. index: index
  7090. });
  7091. }
  7092. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  7093. index: index
  7094. });
  7095. };
  7096. _proto.requiredSpace = function requiredSpace(space) {
  7097. return this.options.lossy ? ' ' : space;
  7098. };
  7099. _proto.optionalSpace = function optionalSpace(space) {
  7100. return this.options.lossy ? '' : space;
  7101. };
  7102. _proto.lossySpace = function lossySpace(space, required) {
  7103. if (this.options.lossy) {
  7104. return required ? ' ' : '';
  7105. } else {
  7106. return space;
  7107. }
  7108. };
  7109. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  7110. var content = this.content(token);
  7111. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  7112. return this.requiredSpace(content);
  7113. } else {
  7114. return content;
  7115. }
  7116. };
  7117. _proto.newNode = function newNode(node, namespace) {
  7118. if (namespace) {
  7119. if (/^ +$/.test(namespace)) {
  7120. if (!this.options.lossy) {
  7121. this.spaces = (this.spaces || '') + namespace;
  7122. }
  7123. namespace = true;
  7124. }
  7125. node.namespace = namespace;
  7126. unescapeProp(node, "namespace");
  7127. }
  7128. if (this.spaces) {
  7129. node.spaces.before = this.spaces;
  7130. this.spaces = '';
  7131. }
  7132. return this.current.append(node);
  7133. };
  7134. _proto.content = function content(token) {
  7135. if (token === void 0) {
  7136. token = this.currToken;
  7137. }
  7138. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  7139. };
  7140. /**
  7141. * returns the index of the next non-whitespace, non-comment token.
  7142. * returns -1 if no meaningful token is found.
  7143. */
  7144. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  7145. if (startPosition === void 0) {
  7146. startPosition = this.position + 1;
  7147. }
  7148. var searchPosition = startPosition;
  7149. while (searchPosition < this.tokens.length) {
  7150. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  7151. searchPosition++;
  7152. continue;
  7153. } else {
  7154. return searchPosition;
  7155. }
  7156. }
  7157. return -1;
  7158. };
  7159. _createClass(Parser, [{
  7160. key: "currToken",
  7161. get: function get() {
  7162. return this.tokens[this.position];
  7163. }
  7164. }, {
  7165. key: "nextToken",
  7166. get: function get() {
  7167. return this.tokens[this.position + 1];
  7168. }
  7169. }, {
  7170. key: "prevToken",
  7171. get: function get() {
  7172. return this.tokens[this.position - 1];
  7173. }
  7174. }]);
  7175. return Parser;
  7176. }();
  7177. exports["default"] = Parser;
  7178. module.exports = exports.default;
  7179. } (parser$1, parser$1.exports));
  7180. return parser$1.exports;
  7181. }
  7182. var hasRequiredProcessor$1;
  7183. function requireProcessor$1 () {
  7184. if (hasRequiredProcessor$1) return processor$1.exports;
  7185. hasRequiredProcessor$1 = 1;
  7186. (function (module, exports) {
  7187. exports.__esModule = true;
  7188. exports["default"] = void 0;
  7189. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser$2());
  7190. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7191. var Processor = /*#__PURE__*/function () {
  7192. function Processor(func, options) {
  7193. this.func = func || function noop() {};
  7194. this.funcRes = null;
  7195. this.options = options;
  7196. }
  7197. var _proto = Processor.prototype;
  7198. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7199. if (options === void 0) {
  7200. options = {};
  7201. }
  7202. var merged = Object.assign({}, this.options, options);
  7203. if (merged.updateSelector === false) {
  7204. return false;
  7205. } else {
  7206. return typeof rule !== "string";
  7207. }
  7208. };
  7209. _proto._isLossy = function _isLossy(options) {
  7210. if (options === void 0) {
  7211. options = {};
  7212. }
  7213. var merged = Object.assign({}, this.options, options);
  7214. if (merged.lossless === false) {
  7215. return true;
  7216. } else {
  7217. return false;
  7218. }
  7219. };
  7220. _proto._root = function _root(rule, options) {
  7221. if (options === void 0) {
  7222. options = {};
  7223. }
  7224. var parser = new _parser["default"](rule, this._parseOptions(options));
  7225. return parser.root;
  7226. };
  7227. _proto._parseOptions = function _parseOptions(options) {
  7228. return {
  7229. lossy: this._isLossy(options)
  7230. };
  7231. };
  7232. _proto._run = function _run(rule, options) {
  7233. var _this = this;
  7234. if (options === void 0) {
  7235. options = {};
  7236. }
  7237. return new Promise(function (resolve, reject) {
  7238. try {
  7239. var root = _this._root(rule, options);
  7240. Promise.resolve(_this.func(root)).then(function (transform) {
  7241. var string = undefined;
  7242. if (_this._shouldUpdateSelector(rule, options)) {
  7243. string = root.toString();
  7244. rule.selector = string;
  7245. }
  7246. return {
  7247. transform: transform,
  7248. root: root,
  7249. string: string
  7250. };
  7251. }).then(resolve, reject);
  7252. } catch (e) {
  7253. reject(e);
  7254. return;
  7255. }
  7256. });
  7257. };
  7258. _proto._runSync = function _runSync(rule, options) {
  7259. if (options === void 0) {
  7260. options = {};
  7261. }
  7262. var root = this._root(rule, options);
  7263. var transform = this.func(root);
  7264. if (transform && typeof transform.then === "function") {
  7265. throw new Error("Selector processor returned a promise to a synchronous call.");
  7266. }
  7267. var string = undefined;
  7268. if (options.updateSelector && typeof rule !== "string") {
  7269. string = root.toString();
  7270. rule.selector = string;
  7271. }
  7272. return {
  7273. transform: transform,
  7274. root: root,
  7275. string: string
  7276. };
  7277. }
  7278. /**
  7279. * Process rule into a selector AST.
  7280. *
  7281. * @param rule {postcss.Rule | string} The css selector to be processed
  7282. * @param options The options for processing
  7283. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7284. */;
  7285. _proto.ast = function ast(rule, options) {
  7286. return this._run(rule, options).then(function (result) {
  7287. return result.root;
  7288. });
  7289. }
  7290. /**
  7291. * Process rule into a selector AST synchronously.
  7292. *
  7293. * @param rule {postcss.Rule | string} The css selector to be processed
  7294. * @param options The options for processing
  7295. * @returns {parser.Root} The AST of the selector after processing it.
  7296. */;
  7297. _proto.astSync = function astSync(rule, options) {
  7298. return this._runSync(rule, options).root;
  7299. }
  7300. /**
  7301. * Process a selector into a transformed value asynchronously
  7302. *
  7303. * @param rule {postcss.Rule | string} The css selector to be processed
  7304. * @param options The options for processing
  7305. * @returns {Promise<any>} The value returned by the processor.
  7306. */;
  7307. _proto.transform = function transform(rule, options) {
  7308. return this._run(rule, options).then(function (result) {
  7309. return result.transform;
  7310. });
  7311. }
  7312. /**
  7313. * Process a selector into a transformed value synchronously.
  7314. *
  7315. * @param rule {postcss.Rule | string} The css selector to be processed
  7316. * @param options The options for processing
  7317. * @returns {any} The value returned by the processor.
  7318. */;
  7319. _proto.transformSync = function transformSync(rule, options) {
  7320. return this._runSync(rule, options).transform;
  7321. }
  7322. /**
  7323. * Process a selector into a new selector string asynchronously.
  7324. *
  7325. * @param rule {postcss.Rule | string} The css selector to be processed
  7326. * @param options The options for processing
  7327. * @returns {string} the selector after processing.
  7328. */;
  7329. _proto.process = function process(rule, options) {
  7330. return this._run(rule, options).then(function (result) {
  7331. return result.string || result.root.toString();
  7332. });
  7333. }
  7334. /**
  7335. * Process a selector into a new selector string synchronously.
  7336. *
  7337. * @param rule {postcss.Rule | string} The css selector to be processed
  7338. * @param options The options for processing
  7339. * @returns {string} the selector after processing.
  7340. */;
  7341. _proto.processSync = function processSync(rule, options) {
  7342. var result = this._runSync(rule, options);
  7343. return result.string || result.root.toString();
  7344. };
  7345. return Processor;
  7346. }();
  7347. exports["default"] = Processor;
  7348. module.exports = exports.default;
  7349. } (processor$1, processor$1.exports));
  7350. return processor$1.exports;
  7351. }
  7352. var selectors$1 = {};
  7353. var constructors$1 = {};
  7354. var hasRequiredConstructors$1;
  7355. function requireConstructors$1 () {
  7356. if (hasRequiredConstructors$1) return constructors$1;
  7357. hasRequiredConstructors$1 = 1;
  7358. constructors$1.__esModule = true;
  7359. constructors$1.universal = constructors$1.tag = constructors$1.string = constructors$1.selector = constructors$1.root = constructors$1.pseudo = constructors$1.nesting = constructors$1.id = constructors$1.comment = constructors$1.combinator = constructors$1.className = constructors$1.attribute = void 0;
  7360. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute$1());
  7361. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  7362. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  7363. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  7364. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  7365. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  7366. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  7367. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  7368. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  7369. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  7370. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  7371. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  7372. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7373. var attribute = function attribute(opts) {
  7374. return new _attribute["default"](opts);
  7375. };
  7376. constructors$1.attribute = attribute;
  7377. var className = function className(opts) {
  7378. return new _className["default"](opts);
  7379. };
  7380. constructors$1.className = className;
  7381. var combinator = function combinator(opts) {
  7382. return new _combinator["default"](opts);
  7383. };
  7384. constructors$1.combinator = combinator;
  7385. var comment = function comment(opts) {
  7386. return new _comment["default"](opts);
  7387. };
  7388. constructors$1.comment = comment;
  7389. var id = function id(opts) {
  7390. return new _id["default"](opts);
  7391. };
  7392. constructors$1.id = id;
  7393. var nesting = function nesting(opts) {
  7394. return new _nesting["default"](opts);
  7395. };
  7396. constructors$1.nesting = nesting;
  7397. var pseudo = function pseudo(opts) {
  7398. return new _pseudo["default"](opts);
  7399. };
  7400. constructors$1.pseudo = pseudo;
  7401. var root = function root(opts) {
  7402. return new _root["default"](opts);
  7403. };
  7404. constructors$1.root = root;
  7405. var selector = function selector(opts) {
  7406. return new _selector["default"](opts);
  7407. };
  7408. constructors$1.selector = selector;
  7409. var string = function string(opts) {
  7410. return new _string["default"](opts);
  7411. };
  7412. constructors$1.string = string;
  7413. var tag = function tag(opts) {
  7414. return new _tag["default"](opts);
  7415. };
  7416. constructors$1.tag = tag;
  7417. var universal = function universal(opts) {
  7418. return new _universal["default"](opts);
  7419. };
  7420. constructors$1.universal = universal;
  7421. return constructors$1;
  7422. }
  7423. var guards$1 = {};
  7424. var hasRequiredGuards$1;
  7425. function requireGuards$1 () {
  7426. if (hasRequiredGuards$1) return guards$1;
  7427. hasRequiredGuards$1 = 1;
  7428. guards$1.__esModule = true;
  7429. guards$1.isComment = guards$1.isCombinator = guards$1.isClassName = guards$1.isAttribute = void 0;
  7430. guards$1.isContainer = isContainer;
  7431. guards$1.isIdentifier = void 0;
  7432. guards$1.isNamespace = isNamespace;
  7433. guards$1.isNesting = void 0;
  7434. guards$1.isNode = isNode;
  7435. guards$1.isPseudo = void 0;
  7436. guards$1.isPseudoClass = isPseudoClass;
  7437. guards$1.isPseudoElement = isPseudoElement;
  7438. guards$1.isUniversal = guards$1.isTag = guards$1.isString = guards$1.isSelector = guards$1.isRoot = void 0;
  7439. var _types = /*@__PURE__*/ requireTypes$1();
  7440. var _IS_TYPE;
  7441. 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);
  7442. function isNode(node) {
  7443. return typeof node === "object" && IS_TYPE[node.type];
  7444. }
  7445. function isNodeType(type, node) {
  7446. return isNode(node) && node.type === type;
  7447. }
  7448. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7449. guards$1.isAttribute = isAttribute;
  7450. var isClassName = isNodeType.bind(null, _types.CLASS);
  7451. guards$1.isClassName = isClassName;
  7452. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7453. guards$1.isCombinator = isCombinator;
  7454. var isComment = isNodeType.bind(null, _types.COMMENT);
  7455. guards$1.isComment = isComment;
  7456. var isIdentifier = isNodeType.bind(null, _types.ID);
  7457. guards$1.isIdentifier = isIdentifier;
  7458. var isNesting = isNodeType.bind(null, _types.NESTING);
  7459. guards$1.isNesting = isNesting;
  7460. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7461. guards$1.isPseudo = isPseudo;
  7462. var isRoot = isNodeType.bind(null, _types.ROOT);
  7463. guards$1.isRoot = isRoot;
  7464. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7465. guards$1.isSelector = isSelector;
  7466. var isString = isNodeType.bind(null, _types.STRING);
  7467. guards$1.isString = isString;
  7468. var isTag = isNodeType.bind(null, _types.TAG);
  7469. guards$1.isTag = isTag;
  7470. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7471. guards$1.isUniversal = isUniversal;
  7472. function isPseudoElement(node) {
  7473. 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");
  7474. }
  7475. function isPseudoClass(node) {
  7476. return isPseudo(node) && !isPseudoElement(node);
  7477. }
  7478. function isContainer(node) {
  7479. return !!(isNode(node) && node.walk);
  7480. }
  7481. function isNamespace(node) {
  7482. return isAttribute(node) || isTag(node);
  7483. }
  7484. return guards$1;
  7485. }
  7486. var hasRequiredSelectors$1;
  7487. function requireSelectors$1 () {
  7488. if (hasRequiredSelectors$1) return selectors$1;
  7489. hasRequiredSelectors$1 = 1;
  7490. (function (exports) {
  7491. exports.__esModule = true;
  7492. var _types = /*@__PURE__*/ requireTypes$1();
  7493. Object.keys(_types).forEach(function (key) {
  7494. if (key === "default" || key === "__esModule") return;
  7495. if (key in exports && exports[key] === _types[key]) return;
  7496. exports[key] = _types[key];
  7497. });
  7498. var _constructors = /*@__PURE__*/ requireConstructors$1();
  7499. Object.keys(_constructors).forEach(function (key) {
  7500. if (key === "default" || key === "__esModule") return;
  7501. if (key in exports && exports[key] === _constructors[key]) return;
  7502. exports[key] = _constructors[key];
  7503. });
  7504. var _guards = /*@__PURE__*/ requireGuards$1();
  7505. Object.keys(_guards).forEach(function (key) {
  7506. if (key === "default" || key === "__esModule") return;
  7507. if (key in exports && exports[key] === _guards[key]) return;
  7508. exports[key] = _guards[key];
  7509. });
  7510. } (selectors$1));
  7511. return selectors$1;
  7512. }
  7513. var hasRequiredDist$1;
  7514. function requireDist$1 () {
  7515. if (hasRequiredDist$1) return dist$1.exports;
  7516. hasRequiredDist$1 = 1;
  7517. (function (module, exports) {
  7518. exports.__esModule = true;
  7519. exports["default"] = void 0;
  7520. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor$1());
  7521. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors$1());
  7522. 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); }
  7523. function _interopRequireWildcard(obj, nodeInterop) { if (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; }
  7524. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7525. var parser = function parser(processor) {
  7526. return new _processor["default"](processor);
  7527. };
  7528. Object.assign(parser, selectors);
  7529. delete parser.__esModule;
  7530. var _default = parser;
  7531. exports["default"] = _default;
  7532. module.exports = exports.default;
  7533. } (dist$1, dist$1.exports));
  7534. return dist$1.exports;
  7535. }
  7536. var distExports = /*@__PURE__*/ requireDist$1();
  7537. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7538. const animationNameRE = /^(?:-\w+-)?animation-name$/;
  7539. const animationRE = /^(?:-\w+-)?animation$/;
  7540. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  7541. const scopedPlugin = (id = "") => {
  7542. const keyframes = /* @__PURE__ */ Object.create(null);
  7543. const shortId = id.replace(/^data-v-/, "");
  7544. return {
  7545. postcssPlugin: "vue-sfc-scoped",
  7546. Rule(rule) {
  7547. processRule(id, rule);
  7548. },
  7549. AtRule(node) {
  7550. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7551. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7552. }
  7553. },
  7554. OnceExit(root) {
  7555. if (Object.keys(keyframes).length) {
  7556. root.walkDecls((decl) => {
  7557. if (animationNameRE.test(decl.prop)) {
  7558. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7559. }
  7560. if (animationRE.test(decl.prop)) {
  7561. decl.value = decl.value.split(",").map((v) => {
  7562. const vals = v.trim().split(/\s+/);
  7563. const i = vals.findIndex((val) => keyframes[val]);
  7564. if (i !== -1) {
  7565. vals.splice(i, 1, keyframes[vals[i]]);
  7566. return vals.join(" ");
  7567. } else {
  7568. return v;
  7569. }
  7570. }).join(",");
  7571. }
  7572. });
  7573. }
  7574. }
  7575. };
  7576. };
  7577. const processedRules = /* @__PURE__ */ new WeakSet();
  7578. function processRule(id, rule) {
  7579. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  7580. return;
  7581. }
  7582. processedRules.add(rule);
  7583. let deep = false;
  7584. let parent = rule.parent;
  7585. while (parent && parent.type !== "root") {
  7586. if (parent.__deep) {
  7587. deep = true;
  7588. break;
  7589. }
  7590. parent = parent.parent;
  7591. }
  7592. rule.selector = selectorParser((selectorRoot) => {
  7593. selectorRoot.each((selector) => {
  7594. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7595. });
  7596. }).processSync(rule.selector);
  7597. }
  7598. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7599. let node = null;
  7600. let shouldInject = !deep;
  7601. let hasNestedDeep = false;
  7602. let splitForNestedDeep = false;
  7603. selector.each((n) => {
  7604. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7605. n.value = " ";
  7606. n.spaces.before = n.spaces.after = "";
  7607. warn(
  7608. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7609. );
  7610. return false;
  7611. }
  7612. if (n.type === "pseudo") {
  7613. const { value } = n;
  7614. if (isDeepContainerPseudo(n)) {
  7615. const hasDeepSelectors = n.nodes.some(
  7616. (selector2) => selector2.some(isDeepSelector)
  7617. );
  7618. if (hasDeepSelectors) {
  7619. const hasScopeAnchor = !!node;
  7620. const hasMixedSelectors = n.nodes.some(
  7621. (selector2) => !selector2.some(isDeepSelector)
  7622. );
  7623. const hasTrailingNodes = selector.index(n) < selector.length - 1;
  7624. if (canSplitDeepContainerPseudo(n) && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  7625. splitSelectorForNestedDeep(
  7626. id,
  7627. rule,
  7628. selector,
  7629. selectorRoot,
  7630. n,
  7631. deep,
  7632. slotted
  7633. );
  7634. splitForNestedDeep = true;
  7635. return false;
  7636. }
  7637. if (value === ":not" && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  7638. return;
  7639. }
  7640. n.nodes.forEach(
  7641. (selector2) => rewriteSelector(
  7642. id,
  7643. rule,
  7644. selector2,
  7645. selectorRoot,
  7646. deep || hasScopeAnchor,
  7647. slotted
  7648. )
  7649. );
  7650. if (!hasScopeAnchor) {
  7651. node = n;
  7652. shouldInject = false;
  7653. }
  7654. hasNestedDeep = true;
  7655. }
  7656. }
  7657. if (value === ":deep" || value === "::v-deep") {
  7658. rule.__deep = true;
  7659. if (n.nodes.length) {
  7660. let last = n;
  7661. n.nodes[0].each((ss) => {
  7662. selector.insertAfter(last, ss);
  7663. last = ss;
  7664. });
  7665. const prev = selector.at(selector.index(n) - 1);
  7666. if (!prev || !isSpaceCombinator(prev)) {
  7667. selector.insertAfter(
  7668. n,
  7669. selectorParser.combinator({
  7670. value: " "
  7671. })
  7672. );
  7673. }
  7674. selector.removeChild(n);
  7675. } else {
  7676. warn(
  7677. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7678. );
  7679. const prev = selector.at(selector.index(n) - 1);
  7680. if (prev && isSpaceCombinator(prev)) {
  7681. selector.removeChild(prev);
  7682. }
  7683. selector.removeChild(n);
  7684. }
  7685. return false;
  7686. }
  7687. if (value === ":slotted" || value === "::v-slotted") {
  7688. rewriteSelector(
  7689. id,
  7690. rule,
  7691. n.nodes[0],
  7692. selectorRoot,
  7693. deep,
  7694. true
  7695. );
  7696. let last = n;
  7697. n.nodes[0].each((ss) => {
  7698. selector.insertAfter(last, ss);
  7699. last = ss;
  7700. });
  7701. selector.removeChild(n);
  7702. shouldInject = false;
  7703. return false;
  7704. }
  7705. if (value === ":global" || value === "::v-global") {
  7706. selector.replaceWith(n.nodes[0]);
  7707. return false;
  7708. }
  7709. }
  7710. if (n.type === "universal") {
  7711. const prev = selector.at(selector.index(n) - 1);
  7712. const next = selector.at(selector.index(n) + 1);
  7713. if (!prev) {
  7714. if (next) {
  7715. if (next.type === "combinator" && next.value === " ") {
  7716. selector.removeChild(next);
  7717. }
  7718. selector.removeChild(n);
  7719. return;
  7720. } else {
  7721. node = selectorParser.combinator({
  7722. value: ""
  7723. });
  7724. selector.insertBefore(n, node);
  7725. selector.removeChild(n);
  7726. return false;
  7727. }
  7728. }
  7729. if (node) return;
  7730. }
  7731. if (!hasNestedDeep && (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node)) {
  7732. node = n;
  7733. }
  7734. });
  7735. if (splitForNestedDeep) {
  7736. return;
  7737. }
  7738. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7739. const deep2 = rule.__deep;
  7740. if (!deep2) {
  7741. extractAndWrapNodes(rule);
  7742. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7743. for (const atnode of atruleNodes) {
  7744. extractAndWrapNodes(atnode);
  7745. }
  7746. }
  7747. shouldInject = deep2;
  7748. }
  7749. if (node && !hasNestedDeep) {
  7750. const { type, value } = node;
  7751. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7752. node.nodes.forEach(
  7753. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7754. );
  7755. shouldInject = false;
  7756. }
  7757. }
  7758. if (node) {
  7759. node.spaces.after = "";
  7760. } else {
  7761. selector.first.spaces.before = "";
  7762. }
  7763. if (shouldInject) {
  7764. const idToAdd = slotted ? id + "-s" : id;
  7765. selector.insertAfter(
  7766. // If node is null it means we need to inject [id] at the start
  7767. // insertAfter can handle `null` here
  7768. node,
  7769. selectorParser.attribute({
  7770. attribute: idToAdd,
  7771. value: idToAdd,
  7772. raws: {},
  7773. quoteMark: `"`
  7774. })
  7775. );
  7776. }
  7777. }
  7778. function isSpaceCombinator(node) {
  7779. return node.type === "combinator" && /^\s+$/.test(node.value);
  7780. }
  7781. function isDeepSelector(node) {
  7782. var _a;
  7783. if (node.type === "pseudo" && (node.value === ":deep" || node.value === "::v-deep")) {
  7784. return true;
  7785. }
  7786. return !!((_a = node.nodes) == null ? void 0 : _a.some((child) => isDeepSelector(child)));
  7787. }
  7788. function isDeepContainerPseudo(node) {
  7789. return node.type === "pseudo" && (node.value === ":is" || node.value === ":where" || node.value === ":has" || node.value === ":not");
  7790. }
  7791. function canSplitDeepContainerPseudo(node) {
  7792. return node.value === ":is" || node.value === ":where" || node.value === ":has";
  7793. }
  7794. function splitSelectorForNestedDeep(id, rule, selector, selectorRoot, pseudo, deep, slotted) {
  7795. const pseudoIndex = selector.index(pseudo);
  7796. const selectors = pseudo.nodes.map((branch, index) => {
  7797. const branchSelector = selector.clone();
  7798. if (branchSelector.first) {
  7799. branchSelector.first.spaces.before = index === 0 ? selector.first.spaces.before : " ";
  7800. }
  7801. const branchPseudo = branchSelector.at(pseudoIndex);
  7802. const branchClone = branch.clone();
  7803. if (branchClone.first) {
  7804. branchClone.first.spaces.before = "";
  7805. }
  7806. branchPseudo.removeAll();
  7807. branchPseudo.append(branchClone);
  7808. rewriteSelector(id, rule, branchSelector, selectorRoot, deep, slotted);
  7809. return branchSelector;
  7810. });
  7811. selector.replaceWith(...selectors);
  7812. }
  7813. function extractAndWrapNodes(parentNode) {
  7814. if (!parentNode.nodes) return;
  7815. const nodes = parentNode.nodes.filter(
  7816. (node) => node.type === "decl" || node.type === "comment"
  7817. );
  7818. if (nodes.length) {
  7819. for (const node of nodes) {
  7820. parentNode.removeChild(node);
  7821. }
  7822. const wrappedRule = new require$$0$1.Rule({
  7823. nodes,
  7824. selector: "&"
  7825. });
  7826. parentNode.prepend(wrappedRule);
  7827. }
  7828. }
  7829. scopedPlugin.postcss = true;
  7830. var sourceMap = {};
  7831. var sourceMapGenerator = {};
  7832. var base64Vlq = {};
  7833. var base64 = {};
  7834. /* -*- Mode: js; js-indent-level: 2; -*- */
  7835. var hasRequiredBase64;
  7836. function requireBase64 () {
  7837. if (hasRequiredBase64) return base64;
  7838. hasRequiredBase64 = 1;
  7839. /*
  7840. * Copyright 2011 Mozilla Foundation and contributors
  7841. * Licensed under the New BSD license. See LICENSE or:
  7842. * http://opensource.org/licenses/BSD-3-Clause
  7843. */
  7844. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7845. /**
  7846. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7847. */
  7848. base64.encode = function (number) {
  7849. if (0 <= number && number < intToCharMap.length) {
  7850. return intToCharMap[number];
  7851. }
  7852. throw new TypeError("Must be between 0 and 63: " + number);
  7853. };
  7854. /**
  7855. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7856. * failure.
  7857. */
  7858. base64.decode = function (charCode) {
  7859. var bigA = 65; // 'A'
  7860. var bigZ = 90; // 'Z'
  7861. var littleA = 97; // 'a'
  7862. var littleZ = 122; // 'z'
  7863. var zero = 48; // '0'
  7864. var nine = 57; // '9'
  7865. var plus = 43; // '+'
  7866. var slash = 47; // '/'
  7867. var littleOffset = 26;
  7868. var numberOffset = 52;
  7869. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7870. if (bigA <= charCode && charCode <= bigZ) {
  7871. return (charCode - bigA);
  7872. }
  7873. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7874. if (littleA <= charCode && charCode <= littleZ) {
  7875. return (charCode - littleA + littleOffset);
  7876. }
  7877. // 52 - 61: 0123456789
  7878. if (zero <= charCode && charCode <= nine) {
  7879. return (charCode - zero + numberOffset);
  7880. }
  7881. // 62: +
  7882. if (charCode == plus) {
  7883. return 62;
  7884. }
  7885. // 63: /
  7886. if (charCode == slash) {
  7887. return 63;
  7888. }
  7889. // Invalid base64 digit.
  7890. return -1;
  7891. };
  7892. return base64;
  7893. }
  7894. /* -*- Mode: js; js-indent-level: 2; -*- */
  7895. var hasRequiredBase64Vlq;
  7896. function requireBase64Vlq () {
  7897. if (hasRequiredBase64Vlq) return base64Vlq;
  7898. hasRequiredBase64Vlq = 1;
  7899. /*
  7900. * Copyright 2011 Mozilla Foundation and contributors
  7901. * Licensed under the New BSD license. See LICENSE or:
  7902. * http://opensource.org/licenses/BSD-3-Clause
  7903. *
  7904. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7905. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7906. *
  7907. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7908. * Redistribution and use in source and binary forms, with or without
  7909. * modification, are permitted provided that the following conditions are
  7910. * met:
  7911. *
  7912. * * Redistributions of source code must retain the above copyright
  7913. * notice, this list of conditions and the following disclaimer.
  7914. * * Redistributions in binary form must reproduce the above
  7915. * copyright notice, this list of conditions and the following
  7916. * disclaimer in the documentation and/or other materials provided
  7917. * with the distribution.
  7918. * * Neither the name of Google Inc. nor the names of its
  7919. * contributors may be used to endorse or promote products derived
  7920. * from this software without specific prior written permission.
  7921. *
  7922. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7923. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7924. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7925. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7926. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7927. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7928. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7929. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7930. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7931. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7932. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7933. */
  7934. var base64 = /*@__PURE__*/ requireBase64();
  7935. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7936. // length quantities we use in the source map spec, the first bit is the sign,
  7937. // the next four bits are the actual value, and the 6th bit is the
  7938. // continuation bit. The continuation bit tells us whether there are more
  7939. // digits in this value following this digit.
  7940. //
  7941. // Continuation
  7942. // | Sign
  7943. // | |
  7944. // V V
  7945. // 101011
  7946. var VLQ_BASE_SHIFT = 5;
  7947. // binary: 100000
  7948. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7949. // binary: 011111
  7950. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7951. // binary: 100000
  7952. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7953. /**
  7954. * Converts from a two-complement value to a value where the sign bit is
  7955. * placed in the least significant bit. For example, as decimals:
  7956. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7957. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7958. */
  7959. function toVLQSigned(aValue) {
  7960. return aValue < 0
  7961. ? ((-aValue) << 1) + 1
  7962. : (aValue << 1) + 0;
  7963. }
  7964. /**
  7965. * Converts to a two-complement value from a value where the sign bit is
  7966. * placed in the least significant bit. For example, as decimals:
  7967. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7968. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7969. */
  7970. function fromVLQSigned(aValue) {
  7971. var isNegative = (aValue & 1) === 1;
  7972. var shifted = aValue >> 1;
  7973. return isNegative
  7974. ? -shifted
  7975. : shifted;
  7976. }
  7977. /**
  7978. * Returns the base 64 VLQ encoded value.
  7979. */
  7980. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7981. var encoded = "";
  7982. var digit;
  7983. var vlq = toVLQSigned(aValue);
  7984. do {
  7985. digit = vlq & VLQ_BASE_MASK;
  7986. vlq >>>= VLQ_BASE_SHIFT;
  7987. if (vlq > 0) {
  7988. // There are still more digits in this value, so we must make sure the
  7989. // continuation bit is marked.
  7990. digit |= VLQ_CONTINUATION_BIT;
  7991. }
  7992. encoded += base64.encode(digit);
  7993. } while (vlq > 0);
  7994. return encoded;
  7995. };
  7996. /**
  7997. * Decodes the next base 64 VLQ value from the given string and returns the
  7998. * value and the rest of the string via the out parameter.
  7999. */
  8000. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  8001. var strLen = aStr.length;
  8002. var result = 0;
  8003. var shift = 0;
  8004. var continuation, digit;
  8005. do {
  8006. if (aIndex >= strLen) {
  8007. throw new Error("Expected more digits in base 64 VLQ value.");
  8008. }
  8009. digit = base64.decode(aStr.charCodeAt(aIndex++));
  8010. if (digit === -1) {
  8011. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  8012. }
  8013. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  8014. digit &= VLQ_BASE_MASK;
  8015. result = result + (digit << shift);
  8016. shift += VLQ_BASE_SHIFT;
  8017. } while (continuation);
  8018. aOutParam.value = fromVLQSigned(result);
  8019. aOutParam.rest = aIndex;
  8020. };
  8021. return base64Vlq;
  8022. }
  8023. var util$1 = {};
  8024. /* -*- Mode: js; js-indent-level: 2; -*- */
  8025. var hasRequiredUtil$1;
  8026. function requireUtil$1 () {
  8027. if (hasRequiredUtil$1) return util$1;
  8028. hasRequiredUtil$1 = 1;
  8029. (function (exports) {
  8030. /*
  8031. * Copyright 2011 Mozilla Foundation and contributors
  8032. * Licensed under the New BSD license. See LICENSE or:
  8033. * http://opensource.org/licenses/BSD-3-Clause
  8034. */
  8035. /**
  8036. * This is a helper function for getting values from parameter/options
  8037. * objects.
  8038. *
  8039. * @param args The object we are extracting values from
  8040. * @param name The name of the property we are getting.
  8041. * @param defaultValue An optional value to return if the property is missing
  8042. * from the object. If this is not specified and the property is missing, an
  8043. * error will be thrown.
  8044. */
  8045. function getArg(aArgs, aName, aDefaultValue) {
  8046. if (aName in aArgs) {
  8047. return aArgs[aName];
  8048. } else if (arguments.length === 3) {
  8049. return aDefaultValue;
  8050. } else {
  8051. throw new Error('"' + aName + '" is a required argument.');
  8052. }
  8053. }
  8054. exports.getArg = getArg;
  8055. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  8056. var dataUrlRegexp = /^data:.+\,.+$/;
  8057. function urlParse(aUrl) {
  8058. var match = aUrl.match(urlRegexp);
  8059. if (!match) {
  8060. return null;
  8061. }
  8062. return {
  8063. scheme: match[1],
  8064. auth: match[2],
  8065. host: match[3],
  8066. port: match[4],
  8067. path: match[5]
  8068. };
  8069. }
  8070. exports.urlParse = urlParse;
  8071. function urlGenerate(aParsedUrl) {
  8072. var url = '';
  8073. if (aParsedUrl.scheme) {
  8074. url += aParsedUrl.scheme + ':';
  8075. }
  8076. url += '//';
  8077. if (aParsedUrl.auth) {
  8078. url += aParsedUrl.auth + '@';
  8079. }
  8080. if (aParsedUrl.host) {
  8081. url += aParsedUrl.host;
  8082. }
  8083. if (aParsedUrl.port) {
  8084. url += ":" + aParsedUrl.port;
  8085. }
  8086. if (aParsedUrl.path) {
  8087. url += aParsedUrl.path;
  8088. }
  8089. return url;
  8090. }
  8091. exports.urlGenerate = urlGenerate;
  8092. /**
  8093. * Normalizes a path, or the path portion of a URL:
  8094. *
  8095. * - Replaces consecutive slashes with one slash.
  8096. * - Removes unnecessary '.' parts.
  8097. * - Removes unnecessary '<dir>/..' parts.
  8098. *
  8099. * Based on code in the Node.js 'path' core module.
  8100. *
  8101. * @param aPath The path or url to normalize.
  8102. */
  8103. function normalize(aPath) {
  8104. var path = aPath;
  8105. var url = urlParse(aPath);
  8106. if (url) {
  8107. if (!url.path) {
  8108. return aPath;
  8109. }
  8110. path = url.path;
  8111. }
  8112. var isAbsolute = exports.isAbsolute(path);
  8113. var parts = path.split(/\/+/);
  8114. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  8115. part = parts[i];
  8116. if (part === '.') {
  8117. parts.splice(i, 1);
  8118. } else if (part === '..') {
  8119. up++;
  8120. } else if (up > 0) {
  8121. if (part === '') {
  8122. // The first part is blank if the path is absolute. Trying to go
  8123. // above the root is a no-op. Therefore we can remove all '..' parts
  8124. // directly after the root.
  8125. parts.splice(i + 1, up);
  8126. up = 0;
  8127. } else {
  8128. parts.splice(i, 2);
  8129. up--;
  8130. }
  8131. }
  8132. }
  8133. path = parts.join('/');
  8134. if (path === '') {
  8135. path = isAbsolute ? '/' : '.';
  8136. }
  8137. if (url) {
  8138. url.path = path;
  8139. return urlGenerate(url);
  8140. }
  8141. return path;
  8142. }
  8143. exports.normalize = normalize;
  8144. /**
  8145. * Joins two paths/URLs.
  8146. *
  8147. * @param aRoot The root path or URL.
  8148. * @param aPath The path or URL to be joined with the root.
  8149. *
  8150. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  8151. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  8152. * first.
  8153. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  8154. * is updated with the result and aRoot is returned. Otherwise the result
  8155. * is returned.
  8156. * - If aPath is absolute, the result is aPath.
  8157. * - Otherwise the two paths are joined with a slash.
  8158. * - Joining for example 'http://' and 'www.example.com' is also supported.
  8159. */
  8160. function join(aRoot, aPath) {
  8161. if (aRoot === "") {
  8162. aRoot = ".";
  8163. }
  8164. if (aPath === "") {
  8165. aPath = ".";
  8166. }
  8167. var aPathUrl = urlParse(aPath);
  8168. var aRootUrl = urlParse(aRoot);
  8169. if (aRootUrl) {
  8170. aRoot = aRootUrl.path || '/';
  8171. }
  8172. // `join(foo, '//www.example.org')`
  8173. if (aPathUrl && !aPathUrl.scheme) {
  8174. if (aRootUrl) {
  8175. aPathUrl.scheme = aRootUrl.scheme;
  8176. }
  8177. return urlGenerate(aPathUrl);
  8178. }
  8179. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8180. return aPath;
  8181. }
  8182. // `join('http://', 'www.example.com')`
  8183. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8184. aRootUrl.host = aPath;
  8185. return urlGenerate(aRootUrl);
  8186. }
  8187. var joined = aPath.charAt(0) === '/'
  8188. ? aPath
  8189. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8190. if (aRootUrl) {
  8191. aRootUrl.path = joined;
  8192. return urlGenerate(aRootUrl);
  8193. }
  8194. return joined;
  8195. }
  8196. exports.join = join;
  8197. exports.isAbsolute = function (aPath) {
  8198. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8199. };
  8200. /**
  8201. * Make a path relative to a URL or another path.
  8202. *
  8203. * @param aRoot The root path or URL.
  8204. * @param aPath The path or URL to be made relative to aRoot.
  8205. */
  8206. function relative(aRoot, aPath) {
  8207. if (aRoot === "") {
  8208. aRoot = ".";
  8209. }
  8210. aRoot = aRoot.replace(/\/$/, '');
  8211. // It is possible for the path to be above the root. In this case, simply
  8212. // checking whether the root is a prefix of the path won't work. Instead, we
  8213. // need to remove components from the root one by one, until either we find
  8214. // a prefix that fits, or we run out of components to remove.
  8215. var level = 0;
  8216. while (aPath.indexOf(aRoot + '/') !== 0) {
  8217. var index = aRoot.lastIndexOf("/");
  8218. if (index < 0) {
  8219. return aPath;
  8220. }
  8221. // If the only part of the root that is left is the scheme (i.e. http://,
  8222. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8223. // have exhausted all components, so the path is not relative to the root.
  8224. aRoot = aRoot.slice(0, index);
  8225. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8226. return aPath;
  8227. }
  8228. ++level;
  8229. }
  8230. // Make sure we add a "../" for each component we removed from the root.
  8231. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8232. }
  8233. exports.relative = relative;
  8234. var supportsNullProto = (function () {
  8235. var obj = Object.create(null);
  8236. return !('__proto__' in obj);
  8237. }());
  8238. function identity (s) {
  8239. return s;
  8240. }
  8241. /**
  8242. * Because behavior goes wacky when you set `__proto__` on objects, we
  8243. * have to prefix all the strings in our set with an arbitrary character.
  8244. *
  8245. * See https://github.com/mozilla/source-map/pull/31 and
  8246. * https://github.com/mozilla/source-map/issues/30
  8247. *
  8248. * @param String aStr
  8249. */
  8250. function toSetString(aStr) {
  8251. if (isProtoString(aStr)) {
  8252. return '$' + aStr;
  8253. }
  8254. return aStr;
  8255. }
  8256. exports.toSetString = supportsNullProto ? identity : toSetString;
  8257. function fromSetString(aStr) {
  8258. if (isProtoString(aStr)) {
  8259. return aStr.slice(1);
  8260. }
  8261. return aStr;
  8262. }
  8263. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  8264. function isProtoString(s) {
  8265. if (!s) {
  8266. return false;
  8267. }
  8268. var length = s.length;
  8269. if (length < 9 /* "__proto__".length */) {
  8270. return false;
  8271. }
  8272. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8273. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8274. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8275. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8276. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8277. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8278. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8279. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8280. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8281. return false;
  8282. }
  8283. for (var i = length - 10; i >= 0; i--) {
  8284. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8285. return false;
  8286. }
  8287. }
  8288. return true;
  8289. }
  8290. /**
  8291. * Comparator between two mappings where the original positions are compared.
  8292. *
  8293. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8294. * mappings with the same original source/line/column, but different generated
  8295. * line and column the same. Useful when searching for a mapping with a
  8296. * stubbed out mapping.
  8297. */
  8298. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8299. var cmp = strcmp(mappingA.source, mappingB.source);
  8300. if (cmp !== 0) {
  8301. return cmp;
  8302. }
  8303. cmp = mappingA.originalLine - mappingB.originalLine;
  8304. if (cmp !== 0) {
  8305. return cmp;
  8306. }
  8307. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8308. if (cmp !== 0 || onlyCompareOriginal) {
  8309. return cmp;
  8310. }
  8311. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8312. if (cmp !== 0) {
  8313. return cmp;
  8314. }
  8315. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8316. if (cmp !== 0) {
  8317. return cmp;
  8318. }
  8319. return strcmp(mappingA.name, mappingB.name);
  8320. }
  8321. exports.compareByOriginalPositions = compareByOriginalPositions;
  8322. /**
  8323. * Comparator between two mappings with deflated source and name indices where
  8324. * the generated positions are compared.
  8325. *
  8326. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8327. * mappings with the same generated line and column, but different
  8328. * source/name/original line and column the same. Useful when searching for a
  8329. * mapping with a stubbed out mapping.
  8330. */
  8331. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8332. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8333. if (cmp !== 0) {
  8334. return cmp;
  8335. }
  8336. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8337. if (cmp !== 0 || onlyCompareGenerated) {
  8338. return cmp;
  8339. }
  8340. cmp = strcmp(mappingA.source, mappingB.source);
  8341. if (cmp !== 0) {
  8342. return cmp;
  8343. }
  8344. cmp = mappingA.originalLine - mappingB.originalLine;
  8345. if (cmp !== 0) {
  8346. return cmp;
  8347. }
  8348. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8349. if (cmp !== 0) {
  8350. return cmp;
  8351. }
  8352. return strcmp(mappingA.name, mappingB.name);
  8353. }
  8354. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8355. function strcmp(aStr1, aStr2) {
  8356. if (aStr1 === aStr2) {
  8357. return 0;
  8358. }
  8359. if (aStr1 === null) {
  8360. return 1; // aStr2 !== null
  8361. }
  8362. if (aStr2 === null) {
  8363. return -1; // aStr1 !== null
  8364. }
  8365. if (aStr1 > aStr2) {
  8366. return 1;
  8367. }
  8368. return -1;
  8369. }
  8370. /**
  8371. * Comparator between two mappings with inflated source and name strings where
  8372. * the generated positions are compared.
  8373. */
  8374. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8375. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8376. if (cmp !== 0) {
  8377. return cmp;
  8378. }
  8379. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8380. if (cmp !== 0) {
  8381. return cmp;
  8382. }
  8383. cmp = strcmp(mappingA.source, mappingB.source);
  8384. if (cmp !== 0) {
  8385. return cmp;
  8386. }
  8387. cmp = mappingA.originalLine - mappingB.originalLine;
  8388. if (cmp !== 0) {
  8389. return cmp;
  8390. }
  8391. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8392. if (cmp !== 0) {
  8393. return cmp;
  8394. }
  8395. return strcmp(mappingA.name, mappingB.name);
  8396. }
  8397. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8398. /**
  8399. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8400. * in the source maps specification), and then parse the string as
  8401. * JSON.
  8402. */
  8403. function parseSourceMapInput(str) {
  8404. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8405. }
  8406. exports.parseSourceMapInput = parseSourceMapInput;
  8407. /**
  8408. * Compute the URL of a source given the the source root, the source's
  8409. * URL, and the source map's URL.
  8410. */
  8411. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8412. sourceURL = sourceURL || '';
  8413. if (sourceRoot) {
  8414. // This follows what Chrome does.
  8415. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8416. sourceRoot += '/';
  8417. }
  8418. // The spec says:
  8419. // Line 4: An optional source root, useful for relocating source
  8420. // files on a server or removing repeated values in the
  8421. // “sources” entry. This value is prepended to the individual
  8422. // entries in the “source” field.
  8423. sourceURL = sourceRoot + sourceURL;
  8424. }
  8425. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8426. // a parameter. This mode is still somewhat supported, which is why
  8427. // this code block is conditional. However, it's preferable to pass
  8428. // the source map URL to SourceMapConsumer, so that this function
  8429. // can implement the source URL resolution algorithm as outlined in
  8430. // the spec. This block is basically the equivalent of:
  8431. // new URL(sourceURL, sourceMapURL).toString()
  8432. // ... except it avoids using URL, which wasn't available in the
  8433. // older releases of node still supported by this library.
  8434. //
  8435. // The spec says:
  8436. // If the sources are not absolute URLs after prepending of the
  8437. // “sourceRoot”, the sources are resolved relative to the
  8438. // SourceMap (like resolving script src in a html document).
  8439. if (sourceMapURL) {
  8440. var parsed = urlParse(sourceMapURL);
  8441. if (!parsed) {
  8442. throw new Error("sourceMapURL could not be parsed");
  8443. }
  8444. if (parsed.path) {
  8445. // Strip the last path component, but keep the "/".
  8446. var index = parsed.path.lastIndexOf('/');
  8447. if (index >= 0) {
  8448. parsed.path = parsed.path.substring(0, index + 1);
  8449. }
  8450. }
  8451. sourceURL = join(urlGenerate(parsed), sourceURL);
  8452. }
  8453. return normalize(sourceURL);
  8454. }
  8455. exports.computeSourceURL = computeSourceURL;
  8456. } (util$1));
  8457. return util$1;
  8458. }
  8459. var arraySet = {};
  8460. /* -*- Mode: js; js-indent-level: 2; -*- */
  8461. var hasRequiredArraySet;
  8462. function requireArraySet () {
  8463. if (hasRequiredArraySet) return arraySet;
  8464. hasRequiredArraySet = 1;
  8465. /*
  8466. * Copyright 2011 Mozilla Foundation and contributors
  8467. * Licensed under the New BSD license. See LICENSE or:
  8468. * http://opensource.org/licenses/BSD-3-Clause
  8469. */
  8470. var util = /*@__PURE__*/ requireUtil$1();
  8471. var has = Object.prototype.hasOwnProperty;
  8472. var hasNativeMap = typeof Map !== "undefined";
  8473. /**
  8474. * A data structure which is a combination of an array and a set. Adding a new
  8475. * member is O(1), testing for membership is O(1), and finding the index of an
  8476. * element is O(1). Removing elements from the set is not supported. Only
  8477. * strings are supported for membership.
  8478. */
  8479. function ArraySet() {
  8480. this._array = [];
  8481. this._set = hasNativeMap ? new Map() : Object.create(null);
  8482. }
  8483. /**
  8484. * Static method for creating ArraySet instances from an existing array.
  8485. */
  8486. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8487. var set = new ArraySet();
  8488. for (var i = 0, len = aArray.length; i < len; i++) {
  8489. set.add(aArray[i], aAllowDuplicates);
  8490. }
  8491. return set;
  8492. };
  8493. /**
  8494. * Return how many unique items are in this ArraySet. If duplicates have been
  8495. * added, than those do not count towards the size.
  8496. *
  8497. * @returns Number
  8498. */
  8499. ArraySet.prototype.size = function ArraySet_size() {
  8500. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8501. };
  8502. /**
  8503. * Add the given string to this set.
  8504. *
  8505. * @param String aStr
  8506. */
  8507. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8508. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8509. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8510. var idx = this._array.length;
  8511. if (!isDuplicate || aAllowDuplicates) {
  8512. this._array.push(aStr);
  8513. }
  8514. if (!isDuplicate) {
  8515. if (hasNativeMap) {
  8516. this._set.set(aStr, idx);
  8517. } else {
  8518. this._set[sStr] = idx;
  8519. }
  8520. }
  8521. };
  8522. /**
  8523. * Is the given string a member of this set?
  8524. *
  8525. * @param String aStr
  8526. */
  8527. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8528. if (hasNativeMap) {
  8529. return this._set.has(aStr);
  8530. } else {
  8531. var sStr = util.toSetString(aStr);
  8532. return has.call(this._set, sStr);
  8533. }
  8534. };
  8535. /**
  8536. * What is the index of the given string in the array?
  8537. *
  8538. * @param String aStr
  8539. */
  8540. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8541. if (hasNativeMap) {
  8542. var idx = this._set.get(aStr);
  8543. if (idx >= 0) {
  8544. return idx;
  8545. }
  8546. } else {
  8547. var sStr = util.toSetString(aStr);
  8548. if (has.call(this._set, sStr)) {
  8549. return this._set[sStr];
  8550. }
  8551. }
  8552. throw new Error('"' + aStr + '" is not in the set.');
  8553. };
  8554. /**
  8555. * What is the element at the given index?
  8556. *
  8557. * @param Number aIdx
  8558. */
  8559. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8560. if (aIdx >= 0 && aIdx < this._array.length) {
  8561. return this._array[aIdx];
  8562. }
  8563. throw new Error('No element indexed by ' + aIdx);
  8564. };
  8565. /**
  8566. * Returns the array representation of this set (which has the proper indices
  8567. * indicated by indexOf). Note that this is a copy of the internal array used
  8568. * for storing the members so that no one can mess with internal state.
  8569. */
  8570. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8571. return this._array.slice();
  8572. };
  8573. arraySet.ArraySet = ArraySet;
  8574. return arraySet;
  8575. }
  8576. var mappingList = {};
  8577. /* -*- Mode: js; js-indent-level: 2; -*- */
  8578. var hasRequiredMappingList;
  8579. function requireMappingList () {
  8580. if (hasRequiredMappingList) return mappingList;
  8581. hasRequiredMappingList = 1;
  8582. /*
  8583. * Copyright 2014 Mozilla Foundation and contributors
  8584. * Licensed under the New BSD license. See LICENSE or:
  8585. * http://opensource.org/licenses/BSD-3-Clause
  8586. */
  8587. var util = /*@__PURE__*/ requireUtil$1();
  8588. /**
  8589. * Determine whether mappingB is after mappingA with respect to generated
  8590. * position.
  8591. */
  8592. function generatedPositionAfter(mappingA, mappingB) {
  8593. // Optimized for most common case
  8594. var lineA = mappingA.generatedLine;
  8595. var lineB = mappingB.generatedLine;
  8596. var columnA = mappingA.generatedColumn;
  8597. var columnB = mappingB.generatedColumn;
  8598. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8599. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8600. }
  8601. /**
  8602. * A data structure to provide a sorted view of accumulated mappings in a
  8603. * performance conscious manner. It trades a neglibable overhead in general
  8604. * case for a large speedup in case of mappings being added in order.
  8605. */
  8606. function MappingList() {
  8607. this._array = [];
  8608. this._sorted = true;
  8609. // Serves as infimum
  8610. this._last = {generatedLine: -1, generatedColumn: 0};
  8611. }
  8612. /**
  8613. * Iterate through internal items. This method takes the same arguments that
  8614. * `Array.prototype.forEach` takes.
  8615. *
  8616. * NOTE: The order of the mappings is NOT guaranteed.
  8617. */
  8618. MappingList.prototype.unsortedForEach =
  8619. function MappingList_forEach(aCallback, aThisArg) {
  8620. this._array.forEach(aCallback, aThisArg);
  8621. };
  8622. /**
  8623. * Add the given source mapping.
  8624. *
  8625. * @param Object aMapping
  8626. */
  8627. MappingList.prototype.add = function MappingList_add(aMapping) {
  8628. if (generatedPositionAfter(this._last, aMapping)) {
  8629. this._last = aMapping;
  8630. this._array.push(aMapping);
  8631. } else {
  8632. this._sorted = false;
  8633. this._array.push(aMapping);
  8634. }
  8635. };
  8636. /**
  8637. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8638. * generated position.
  8639. *
  8640. * WARNING: This method returns internal data without copying, for
  8641. * performance. The return value must NOT be mutated, and should be treated as
  8642. * an immutable borrow. If you want to take ownership, you must make your own
  8643. * copy.
  8644. */
  8645. MappingList.prototype.toArray = function MappingList_toArray() {
  8646. if (!this._sorted) {
  8647. this._array.sort(util.compareByGeneratedPositionsInflated);
  8648. this._sorted = true;
  8649. }
  8650. return this._array;
  8651. };
  8652. mappingList.MappingList = MappingList;
  8653. return mappingList;
  8654. }
  8655. /* -*- Mode: js; js-indent-level: 2; -*- */
  8656. var hasRequiredSourceMapGenerator;
  8657. function requireSourceMapGenerator () {
  8658. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8659. hasRequiredSourceMapGenerator = 1;
  8660. /*
  8661. * Copyright 2011 Mozilla Foundation and contributors
  8662. * Licensed under the New BSD license. See LICENSE or:
  8663. * http://opensource.org/licenses/BSD-3-Clause
  8664. */
  8665. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8666. var util = /*@__PURE__*/ requireUtil$1();
  8667. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8668. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8669. /**
  8670. * An instance of the SourceMapGenerator represents a source map which is
  8671. * being built incrementally. You may pass an object with the following
  8672. * properties:
  8673. *
  8674. * - file: The filename of the generated source.
  8675. * - sourceRoot: A root for all relative URLs in this source map.
  8676. */
  8677. function SourceMapGenerator(aArgs) {
  8678. if (!aArgs) {
  8679. aArgs = {};
  8680. }
  8681. this._file = util.getArg(aArgs, 'file', null);
  8682. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8683. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8684. this._sources = new ArraySet();
  8685. this._names = new ArraySet();
  8686. this._mappings = new MappingList();
  8687. this._sourcesContents = null;
  8688. }
  8689. SourceMapGenerator.prototype._version = 3;
  8690. /**
  8691. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8692. *
  8693. * @param aSourceMapConsumer The SourceMap.
  8694. */
  8695. SourceMapGenerator.fromSourceMap =
  8696. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8697. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8698. var generator = new SourceMapGenerator({
  8699. file: aSourceMapConsumer.file,
  8700. sourceRoot: sourceRoot
  8701. });
  8702. aSourceMapConsumer.eachMapping(function (mapping) {
  8703. var newMapping = {
  8704. generated: {
  8705. line: mapping.generatedLine,
  8706. column: mapping.generatedColumn
  8707. }
  8708. };
  8709. if (mapping.source != null) {
  8710. newMapping.source = mapping.source;
  8711. if (sourceRoot != null) {
  8712. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8713. }
  8714. newMapping.original = {
  8715. line: mapping.originalLine,
  8716. column: mapping.originalColumn
  8717. };
  8718. if (mapping.name != null) {
  8719. newMapping.name = mapping.name;
  8720. }
  8721. }
  8722. generator.addMapping(newMapping);
  8723. });
  8724. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8725. var sourceRelative = sourceFile;
  8726. if (sourceRoot !== null) {
  8727. sourceRelative = util.relative(sourceRoot, sourceFile);
  8728. }
  8729. if (!generator._sources.has(sourceRelative)) {
  8730. generator._sources.add(sourceRelative);
  8731. }
  8732. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8733. if (content != null) {
  8734. generator.setSourceContent(sourceFile, content);
  8735. }
  8736. });
  8737. return generator;
  8738. };
  8739. /**
  8740. * Add a single mapping from original source line and column to the generated
  8741. * source's line and column for this source map being created. The mapping
  8742. * object should have the following properties:
  8743. *
  8744. * - generated: An object with the generated line and column positions.
  8745. * - original: An object with the original line and column positions.
  8746. * - source: The original source file (relative to the sourceRoot).
  8747. * - name: An optional original token name for this mapping.
  8748. */
  8749. SourceMapGenerator.prototype.addMapping =
  8750. function SourceMapGenerator_addMapping(aArgs) {
  8751. var generated = util.getArg(aArgs, 'generated');
  8752. var original = util.getArg(aArgs, 'original', null);
  8753. var source = util.getArg(aArgs, 'source', null);
  8754. var name = util.getArg(aArgs, 'name', null);
  8755. if (!this._skipValidation) {
  8756. this._validateMapping(generated, original, source, name);
  8757. }
  8758. if (source != null) {
  8759. source = String(source);
  8760. if (!this._sources.has(source)) {
  8761. this._sources.add(source);
  8762. }
  8763. }
  8764. if (name != null) {
  8765. name = String(name);
  8766. if (!this._names.has(name)) {
  8767. this._names.add(name);
  8768. }
  8769. }
  8770. this._mappings.add({
  8771. generatedLine: generated.line,
  8772. generatedColumn: generated.column,
  8773. originalLine: original != null && original.line,
  8774. originalColumn: original != null && original.column,
  8775. source: source,
  8776. name: name
  8777. });
  8778. };
  8779. /**
  8780. * Set the source content for a source file.
  8781. */
  8782. SourceMapGenerator.prototype.setSourceContent =
  8783. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8784. var source = aSourceFile;
  8785. if (this._sourceRoot != null) {
  8786. source = util.relative(this._sourceRoot, source);
  8787. }
  8788. if (aSourceContent != null) {
  8789. // Add the source content to the _sourcesContents map.
  8790. // Create a new _sourcesContents map if the property is null.
  8791. if (!this._sourcesContents) {
  8792. this._sourcesContents = Object.create(null);
  8793. }
  8794. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8795. } else if (this._sourcesContents) {
  8796. // Remove the source file from the _sourcesContents map.
  8797. // If the _sourcesContents map is empty, set the property to null.
  8798. delete this._sourcesContents[util.toSetString(source)];
  8799. if (Object.keys(this._sourcesContents).length === 0) {
  8800. this._sourcesContents = null;
  8801. }
  8802. }
  8803. };
  8804. /**
  8805. * Applies the mappings of a sub-source-map for a specific source file to the
  8806. * source map being generated. Each mapping to the supplied source file is
  8807. * rewritten using the supplied source map. Note: The resolution for the
  8808. * resulting mappings is the minimium of this map and the supplied map.
  8809. *
  8810. * @param aSourceMapConsumer The source map to be applied.
  8811. * @param aSourceFile Optional. The filename of the source file.
  8812. * If omitted, SourceMapConsumer's file property will be used.
  8813. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8814. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8815. * This parameter is needed when the two source maps aren't in the same
  8816. * directory, and the source map to be applied contains relative source
  8817. * paths. If so, those relative source paths need to be rewritten
  8818. * relative to the SourceMapGenerator.
  8819. */
  8820. SourceMapGenerator.prototype.applySourceMap =
  8821. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8822. var sourceFile = aSourceFile;
  8823. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8824. if (aSourceFile == null) {
  8825. if (aSourceMapConsumer.file == null) {
  8826. throw new Error(
  8827. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8828. 'or the source map\'s "file" property. Both were omitted.'
  8829. );
  8830. }
  8831. sourceFile = aSourceMapConsumer.file;
  8832. }
  8833. var sourceRoot = this._sourceRoot;
  8834. // Make "sourceFile" relative if an absolute Url is passed.
  8835. if (sourceRoot != null) {
  8836. sourceFile = util.relative(sourceRoot, sourceFile);
  8837. }
  8838. // Applying the SourceMap can add and remove items from the sources and
  8839. // the names array.
  8840. var newSources = new ArraySet();
  8841. var newNames = new ArraySet();
  8842. // Find mappings for the "sourceFile"
  8843. this._mappings.unsortedForEach(function (mapping) {
  8844. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8845. // Check if it can be mapped by the source map, then update the mapping.
  8846. var original = aSourceMapConsumer.originalPositionFor({
  8847. line: mapping.originalLine,
  8848. column: mapping.originalColumn
  8849. });
  8850. if (original.source != null) {
  8851. // Copy mapping
  8852. mapping.source = original.source;
  8853. if (aSourceMapPath != null) {
  8854. mapping.source = util.join(aSourceMapPath, mapping.source);
  8855. }
  8856. if (sourceRoot != null) {
  8857. mapping.source = util.relative(sourceRoot, mapping.source);
  8858. }
  8859. mapping.originalLine = original.line;
  8860. mapping.originalColumn = original.column;
  8861. if (original.name != null) {
  8862. mapping.name = original.name;
  8863. }
  8864. }
  8865. }
  8866. var source = mapping.source;
  8867. if (source != null && !newSources.has(source)) {
  8868. newSources.add(source);
  8869. }
  8870. var name = mapping.name;
  8871. if (name != null && !newNames.has(name)) {
  8872. newNames.add(name);
  8873. }
  8874. }, this);
  8875. this._sources = newSources;
  8876. this._names = newNames;
  8877. // Copy sourcesContents of applied map.
  8878. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8879. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8880. if (content != null) {
  8881. if (aSourceMapPath != null) {
  8882. sourceFile = util.join(aSourceMapPath, sourceFile);
  8883. }
  8884. if (sourceRoot != null) {
  8885. sourceFile = util.relative(sourceRoot, sourceFile);
  8886. }
  8887. this.setSourceContent(sourceFile, content);
  8888. }
  8889. }, this);
  8890. };
  8891. /**
  8892. * A mapping can have one of the three levels of data:
  8893. *
  8894. * 1. Just the generated position.
  8895. * 2. The Generated position, original position, and original source.
  8896. * 3. Generated and original position, original source, as well as a name
  8897. * token.
  8898. *
  8899. * To maintain consistency, we validate that any new mapping being added falls
  8900. * in to one of these categories.
  8901. */
  8902. SourceMapGenerator.prototype._validateMapping =
  8903. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8904. aName) {
  8905. // When aOriginal is truthy but has empty values for .line and .column,
  8906. // it is most likely a programmer error. In this case we throw a very
  8907. // specific error message to try to guide them the right way.
  8908. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8909. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8910. throw new Error(
  8911. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8912. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8913. 'null for the original mapping instead of an object with empty or null values.'
  8914. );
  8915. }
  8916. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8917. && aGenerated.line > 0 && aGenerated.column >= 0
  8918. && !aOriginal && !aSource && !aName) {
  8919. // Case 1.
  8920. return;
  8921. }
  8922. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8923. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8924. && aGenerated.line > 0 && aGenerated.column >= 0
  8925. && aOriginal.line > 0 && aOriginal.column >= 0
  8926. && aSource) {
  8927. // Cases 2 and 3.
  8928. return;
  8929. }
  8930. else {
  8931. throw new Error('Invalid mapping: ' + JSON.stringify({
  8932. generated: aGenerated,
  8933. source: aSource,
  8934. original: aOriginal,
  8935. name: aName
  8936. }));
  8937. }
  8938. };
  8939. /**
  8940. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8941. * specified by the source map format.
  8942. */
  8943. SourceMapGenerator.prototype._serializeMappings =
  8944. function SourceMapGenerator_serializeMappings() {
  8945. var previousGeneratedColumn = 0;
  8946. var previousGeneratedLine = 1;
  8947. var previousOriginalColumn = 0;
  8948. var previousOriginalLine = 0;
  8949. var previousName = 0;
  8950. var previousSource = 0;
  8951. var result = '';
  8952. var next;
  8953. var mapping;
  8954. var nameIdx;
  8955. var sourceIdx;
  8956. var mappings = this._mappings.toArray();
  8957. for (var i = 0, len = mappings.length; i < len; i++) {
  8958. mapping = mappings[i];
  8959. next = '';
  8960. if (mapping.generatedLine !== previousGeneratedLine) {
  8961. previousGeneratedColumn = 0;
  8962. while (mapping.generatedLine !== previousGeneratedLine) {
  8963. next += ';';
  8964. previousGeneratedLine++;
  8965. }
  8966. }
  8967. else {
  8968. if (i > 0) {
  8969. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8970. continue;
  8971. }
  8972. next += ',';
  8973. }
  8974. }
  8975. next += base64VLQ.encode(mapping.generatedColumn
  8976. - previousGeneratedColumn);
  8977. previousGeneratedColumn = mapping.generatedColumn;
  8978. if (mapping.source != null) {
  8979. sourceIdx = this._sources.indexOf(mapping.source);
  8980. next += base64VLQ.encode(sourceIdx - previousSource);
  8981. previousSource = sourceIdx;
  8982. // lines are stored 0-based in SourceMap spec version 3
  8983. next += base64VLQ.encode(mapping.originalLine - 1
  8984. - previousOriginalLine);
  8985. previousOriginalLine = mapping.originalLine - 1;
  8986. next += base64VLQ.encode(mapping.originalColumn
  8987. - previousOriginalColumn);
  8988. previousOriginalColumn = mapping.originalColumn;
  8989. if (mapping.name != null) {
  8990. nameIdx = this._names.indexOf(mapping.name);
  8991. next += base64VLQ.encode(nameIdx - previousName);
  8992. previousName = nameIdx;
  8993. }
  8994. }
  8995. result += next;
  8996. }
  8997. return result;
  8998. };
  8999. SourceMapGenerator.prototype._generateSourcesContent =
  9000. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  9001. return aSources.map(function (source) {
  9002. if (!this._sourcesContents) {
  9003. return null;
  9004. }
  9005. if (aSourceRoot != null) {
  9006. source = util.relative(aSourceRoot, source);
  9007. }
  9008. var key = util.toSetString(source);
  9009. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  9010. ? this._sourcesContents[key]
  9011. : null;
  9012. }, this);
  9013. };
  9014. /**
  9015. * Externalize the source map.
  9016. */
  9017. SourceMapGenerator.prototype.toJSON =
  9018. function SourceMapGenerator_toJSON() {
  9019. var map = {
  9020. version: this._version,
  9021. sources: this._sources.toArray(),
  9022. names: this._names.toArray(),
  9023. mappings: this._serializeMappings()
  9024. };
  9025. if (this._file != null) {
  9026. map.file = this._file;
  9027. }
  9028. if (this._sourceRoot != null) {
  9029. map.sourceRoot = this._sourceRoot;
  9030. }
  9031. if (this._sourcesContents) {
  9032. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  9033. }
  9034. return map;
  9035. };
  9036. /**
  9037. * Render the source map being generated to a string.
  9038. */
  9039. SourceMapGenerator.prototype.toString =
  9040. function SourceMapGenerator_toString() {
  9041. return JSON.stringify(this.toJSON());
  9042. };
  9043. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  9044. return sourceMapGenerator;
  9045. }
  9046. var sourceMapConsumer = {};
  9047. var binarySearch = {};
  9048. /* -*- Mode: js; js-indent-level: 2; -*- */
  9049. var hasRequiredBinarySearch;
  9050. function requireBinarySearch () {
  9051. if (hasRequiredBinarySearch) return binarySearch;
  9052. hasRequiredBinarySearch = 1;
  9053. (function (exports) {
  9054. /*
  9055. * Copyright 2011 Mozilla Foundation and contributors
  9056. * Licensed under the New BSD license. See LICENSE or:
  9057. * http://opensource.org/licenses/BSD-3-Clause
  9058. */
  9059. exports.GREATEST_LOWER_BOUND = 1;
  9060. exports.LEAST_UPPER_BOUND = 2;
  9061. /**
  9062. * Recursive implementation of binary search.
  9063. *
  9064. * @param aLow Indices here and lower do not contain the needle.
  9065. * @param aHigh Indices here and higher do not contain the needle.
  9066. * @param aNeedle The element being searched for.
  9067. * @param aHaystack The non-empty array being searched.
  9068. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  9069. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9070. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9071. * closest element that is smaller than or greater than the one we are
  9072. * searching for, respectively, if the exact element cannot be found.
  9073. */
  9074. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  9075. // This function terminates when one of the following is true:
  9076. //
  9077. // 1. We find the exact element we are looking for.
  9078. //
  9079. // 2. We did not find the exact element, but we can return the index of
  9080. // the next-closest element.
  9081. //
  9082. // 3. We did not find the exact element, and there is no next-closest
  9083. // element than the one we are searching for, so we return -1.
  9084. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  9085. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  9086. if (cmp === 0) {
  9087. // Found the element we are looking for.
  9088. return mid;
  9089. }
  9090. else if (cmp > 0) {
  9091. // Our needle is greater than aHaystack[mid].
  9092. if (aHigh - mid > 1) {
  9093. // The element is in the upper half.
  9094. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  9095. }
  9096. // The exact needle element was not found in this haystack. Determine if
  9097. // we are in termination case (3) or (2) and return the appropriate thing.
  9098. if (aBias == exports.LEAST_UPPER_BOUND) {
  9099. return aHigh < aHaystack.length ? aHigh : -1;
  9100. } else {
  9101. return mid;
  9102. }
  9103. }
  9104. else {
  9105. // Our needle is less than aHaystack[mid].
  9106. if (mid - aLow > 1) {
  9107. // The element is in the lower half.
  9108. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  9109. }
  9110. // we are in termination case (3) or (2) and return the appropriate thing.
  9111. if (aBias == exports.LEAST_UPPER_BOUND) {
  9112. return mid;
  9113. } else {
  9114. return aLow < 0 ? -1 : aLow;
  9115. }
  9116. }
  9117. }
  9118. /**
  9119. * This is an implementation of binary search which will always try and return
  9120. * the index of the closest element if there is no exact hit. This is because
  9121. * mappings between original and generated line/col pairs are single points,
  9122. * and there is an implicit region between each of them, so a miss just means
  9123. * that you aren't on the very start of a region.
  9124. *
  9125. * @param aNeedle The element you are looking for.
  9126. * @param aHaystack The array that is being searched.
  9127. * @param aCompare A function which takes the needle and an element in the
  9128. * array and returns -1, 0, or 1 depending on whether the needle is less
  9129. * than, equal to, or greater than the element, respectively.
  9130. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9131. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9132. * closest element that is smaller than or greater than the one we are
  9133. * searching for, respectively, if the exact element cannot be found.
  9134. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  9135. */
  9136. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  9137. if (aHaystack.length === 0) {
  9138. return -1;
  9139. }
  9140. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  9141. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  9142. if (index < 0) {
  9143. return -1;
  9144. }
  9145. // We have found either the exact element, or the next-closest element than
  9146. // the one we are searching for. However, there may be more than one such
  9147. // element. Make sure we always return the smallest of these.
  9148. while (index - 1 >= 0) {
  9149. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  9150. break;
  9151. }
  9152. --index;
  9153. }
  9154. return index;
  9155. };
  9156. } (binarySearch));
  9157. return binarySearch;
  9158. }
  9159. var quickSort = {};
  9160. /* -*- Mode: js; js-indent-level: 2; -*- */
  9161. var hasRequiredQuickSort;
  9162. function requireQuickSort () {
  9163. if (hasRequiredQuickSort) return quickSort;
  9164. hasRequiredQuickSort = 1;
  9165. /*
  9166. * Copyright 2011 Mozilla Foundation and contributors
  9167. * Licensed under the New BSD license. See LICENSE or:
  9168. * http://opensource.org/licenses/BSD-3-Clause
  9169. */
  9170. // It turns out that some (most?) JavaScript engines don't self-host
  9171. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9172. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9173. // custom comparator function, calling back and forth between the VM's C++ and
  9174. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9175. // worse generated code for the comparator function than would be optimal. In
  9176. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9177. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9178. // a ~3500ms mean speed-up in `bench/bench.html`.
  9179. /**
  9180. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9181. *
  9182. * @param {Array} ary
  9183. * The array.
  9184. * @param {Number} x
  9185. * The index of the first item.
  9186. * @param {Number} y
  9187. * The index of the second item.
  9188. */
  9189. function swap(ary, x, y) {
  9190. var temp = ary[x];
  9191. ary[x] = ary[y];
  9192. ary[y] = temp;
  9193. }
  9194. /**
  9195. * Returns a random integer within the range `low .. high` inclusive.
  9196. *
  9197. * @param {Number} low
  9198. * The lower bound on the range.
  9199. * @param {Number} high
  9200. * The upper bound on the range.
  9201. */
  9202. function randomIntInRange(low, high) {
  9203. return Math.round(low + (Math.random() * (high - low)));
  9204. }
  9205. /**
  9206. * The Quick Sort algorithm.
  9207. *
  9208. * @param {Array} ary
  9209. * An array to sort.
  9210. * @param {function} comparator
  9211. * Function to use to compare two items.
  9212. * @param {Number} p
  9213. * Start index of the array
  9214. * @param {Number} r
  9215. * End index of the array
  9216. */
  9217. function doQuickSort(ary, comparator, p, r) {
  9218. // If our lower bound is less than our upper bound, we (1) partition the
  9219. // array into two pieces and (2) recurse on each half. If it is not, this is
  9220. // the empty array and our base case.
  9221. if (p < r) {
  9222. // (1) Partitioning.
  9223. //
  9224. // The partitioning chooses a pivot between `p` and `r` and moves all
  9225. // elements that are less than or equal to the pivot to the before it, and
  9226. // all the elements that are greater than it after it. The effect is that
  9227. // once partition is done, the pivot is in the exact place it will be when
  9228. // the array is put in sorted order, and it will not need to be moved
  9229. // again. This runs in O(n) time.
  9230. // Always choose a random pivot so that an input array which is reverse
  9231. // sorted does not cause O(n^2) running time.
  9232. var pivotIndex = randomIntInRange(p, r);
  9233. var i = p - 1;
  9234. swap(ary, pivotIndex, r);
  9235. var pivot = ary[r];
  9236. // Immediately after `j` is incremented in this loop, the following hold
  9237. // true:
  9238. //
  9239. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9240. //
  9241. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9242. for (var j = p; j < r; j++) {
  9243. if (comparator(ary[j], pivot) <= 0) {
  9244. i += 1;
  9245. swap(ary, i, j);
  9246. }
  9247. }
  9248. swap(ary, i + 1, j);
  9249. var q = i + 1;
  9250. // (2) Recurse on each half.
  9251. doQuickSort(ary, comparator, p, q - 1);
  9252. doQuickSort(ary, comparator, q + 1, r);
  9253. }
  9254. }
  9255. /**
  9256. * Sort the given array in-place with the given comparator function.
  9257. *
  9258. * @param {Array} ary
  9259. * An array to sort.
  9260. * @param {function} comparator
  9261. * Function to use to compare two items.
  9262. */
  9263. quickSort.quickSort = function (ary, comparator) {
  9264. doQuickSort(ary, comparator, 0, ary.length - 1);
  9265. };
  9266. return quickSort;
  9267. }
  9268. /* -*- Mode: js; js-indent-level: 2; -*- */
  9269. var hasRequiredSourceMapConsumer;
  9270. function requireSourceMapConsumer () {
  9271. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9272. hasRequiredSourceMapConsumer = 1;
  9273. /*
  9274. * Copyright 2011 Mozilla Foundation and contributors
  9275. * Licensed under the New BSD license. See LICENSE or:
  9276. * http://opensource.org/licenses/BSD-3-Clause
  9277. */
  9278. var util = /*@__PURE__*/ requireUtil$1();
  9279. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9280. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9281. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9282. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9283. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9284. var sourceMap = aSourceMap;
  9285. if (typeof aSourceMap === 'string') {
  9286. sourceMap = util.parseSourceMapInput(aSourceMap);
  9287. }
  9288. return sourceMap.sections != null
  9289. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9290. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9291. }
  9292. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9293. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9294. };
  9295. /**
  9296. * The version of the source mapping spec that we are consuming.
  9297. */
  9298. SourceMapConsumer.prototype._version = 3;
  9299. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9300. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9301. // are lazily instantiated, accessed via the `_generatedMappings` and
  9302. // `_originalMappings` getters respectively, and we only parse the mappings
  9303. // and create these arrays once queried for a source location. We jump through
  9304. // these hoops because there can be many thousands of mappings, and parsing
  9305. // them is expensive, so we only want to do it if we must.
  9306. //
  9307. // Each object in the arrays is of the form:
  9308. //
  9309. // {
  9310. // generatedLine: The line number in the generated code,
  9311. // generatedColumn: The column number in the generated code,
  9312. // source: The path to the original source file that generated this
  9313. // chunk of code,
  9314. // originalLine: The line number in the original source that
  9315. // corresponds to this chunk of generated code,
  9316. // originalColumn: The column number in the original source that
  9317. // corresponds to this chunk of generated code,
  9318. // name: The name of the original symbol which generated this chunk of
  9319. // code.
  9320. // }
  9321. //
  9322. // All properties except for `generatedLine` and `generatedColumn` can be
  9323. // `null`.
  9324. //
  9325. // `_generatedMappings` is ordered by the generated positions.
  9326. //
  9327. // `_originalMappings` is ordered by the original positions.
  9328. SourceMapConsumer.prototype.__generatedMappings = null;
  9329. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9330. configurable: true,
  9331. enumerable: true,
  9332. get: function () {
  9333. if (!this.__generatedMappings) {
  9334. this._parseMappings(this._mappings, this.sourceRoot);
  9335. }
  9336. return this.__generatedMappings;
  9337. }
  9338. });
  9339. SourceMapConsumer.prototype.__originalMappings = null;
  9340. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9341. configurable: true,
  9342. enumerable: true,
  9343. get: function () {
  9344. if (!this.__originalMappings) {
  9345. this._parseMappings(this._mappings, this.sourceRoot);
  9346. }
  9347. return this.__originalMappings;
  9348. }
  9349. });
  9350. SourceMapConsumer.prototype._charIsMappingSeparator =
  9351. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9352. var c = aStr.charAt(index);
  9353. return c === ";" || c === ",";
  9354. };
  9355. /**
  9356. * Parse the mappings in a string in to a data structure which we can easily
  9357. * query (the ordered arrays in the `this.__generatedMappings` and
  9358. * `this.__originalMappings` properties).
  9359. */
  9360. SourceMapConsumer.prototype._parseMappings =
  9361. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9362. throw new Error("Subclasses must implement _parseMappings");
  9363. };
  9364. SourceMapConsumer.GENERATED_ORDER = 1;
  9365. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9366. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9367. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9368. /**
  9369. * Iterate over each mapping between an original source/line/column and a
  9370. * generated line/column in this source map.
  9371. *
  9372. * @param Function aCallback
  9373. * The function that is called with each mapping.
  9374. * @param Object aContext
  9375. * Optional. If specified, this object will be the value of `this` every
  9376. * time that `aCallback` is called.
  9377. * @param aOrder
  9378. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9379. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9380. * iterate over the mappings sorted by the generated file's line/column
  9381. * order or the original's source/line/column order, respectively. Defaults to
  9382. * `SourceMapConsumer.GENERATED_ORDER`.
  9383. */
  9384. SourceMapConsumer.prototype.eachMapping =
  9385. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9386. var context = aContext || null;
  9387. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9388. var mappings;
  9389. switch (order) {
  9390. case SourceMapConsumer.GENERATED_ORDER:
  9391. mappings = this._generatedMappings;
  9392. break;
  9393. case SourceMapConsumer.ORIGINAL_ORDER:
  9394. mappings = this._originalMappings;
  9395. break;
  9396. default:
  9397. throw new Error("Unknown order of iteration.");
  9398. }
  9399. var sourceRoot = this.sourceRoot;
  9400. mappings.map(function (mapping) {
  9401. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9402. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9403. return {
  9404. source: source,
  9405. generatedLine: mapping.generatedLine,
  9406. generatedColumn: mapping.generatedColumn,
  9407. originalLine: mapping.originalLine,
  9408. originalColumn: mapping.originalColumn,
  9409. name: mapping.name === null ? null : this._names.at(mapping.name)
  9410. };
  9411. }, this).forEach(aCallback, context);
  9412. };
  9413. /**
  9414. * Returns all generated line and column information for the original source,
  9415. * line, and column provided. If no column is provided, returns all mappings
  9416. * corresponding to a either the line we are searching for or the next
  9417. * closest line that has any mappings. Otherwise, returns all mappings
  9418. * corresponding to the given line and either the column we are searching for
  9419. * or the next closest column that has any offsets.
  9420. *
  9421. * The only argument is an object with the following properties:
  9422. *
  9423. * - source: The filename of the original source.
  9424. * - line: The line number in the original source. The line number is 1-based.
  9425. * - column: Optional. the column number in the original source.
  9426. * The column number is 0-based.
  9427. *
  9428. * and an array of objects is returned, each with the following properties:
  9429. *
  9430. * - line: The line number in the generated source, or null. The
  9431. * line number is 1-based.
  9432. * - column: The column number in the generated source, or null.
  9433. * The column number is 0-based.
  9434. */
  9435. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9436. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9437. var line = util.getArg(aArgs, 'line');
  9438. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9439. // returns the index of the closest mapping less than the needle. By
  9440. // setting needle.originalColumn to 0, we thus find the last mapping for
  9441. // the given line, provided such a mapping exists.
  9442. var needle = {
  9443. source: util.getArg(aArgs, 'source'),
  9444. originalLine: line,
  9445. originalColumn: util.getArg(aArgs, 'column', 0)
  9446. };
  9447. needle.source = this._findSourceIndex(needle.source);
  9448. if (needle.source < 0) {
  9449. return [];
  9450. }
  9451. var mappings = [];
  9452. var index = this._findMapping(needle,
  9453. this._originalMappings,
  9454. "originalLine",
  9455. "originalColumn",
  9456. util.compareByOriginalPositions,
  9457. binarySearch.LEAST_UPPER_BOUND);
  9458. if (index >= 0) {
  9459. var mapping = this._originalMappings[index];
  9460. if (aArgs.column === undefined) {
  9461. var originalLine = mapping.originalLine;
  9462. // Iterate until either we run out of mappings, or we run into
  9463. // a mapping for a different line than the one we found. Since
  9464. // mappings are sorted, this is guaranteed to find all mappings for
  9465. // the line we found.
  9466. while (mapping && mapping.originalLine === originalLine) {
  9467. mappings.push({
  9468. line: util.getArg(mapping, 'generatedLine', null),
  9469. column: util.getArg(mapping, 'generatedColumn', null),
  9470. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9471. });
  9472. mapping = this._originalMappings[++index];
  9473. }
  9474. } else {
  9475. var originalColumn = mapping.originalColumn;
  9476. // Iterate until either we run out of mappings, or we run into
  9477. // a mapping for a different line than the one we were searching for.
  9478. // Since mappings are sorted, this is guaranteed to find all mappings for
  9479. // the line we are searching for.
  9480. while (mapping &&
  9481. mapping.originalLine === line &&
  9482. mapping.originalColumn == originalColumn) {
  9483. mappings.push({
  9484. line: util.getArg(mapping, 'generatedLine', null),
  9485. column: util.getArg(mapping, 'generatedColumn', null),
  9486. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9487. });
  9488. mapping = this._originalMappings[++index];
  9489. }
  9490. }
  9491. }
  9492. return mappings;
  9493. };
  9494. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9495. /**
  9496. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9497. * query for information about the original file positions by giving it a file
  9498. * position in the generated source.
  9499. *
  9500. * The first parameter is the raw source map (either as a JSON string, or
  9501. * already parsed to an object). According to the spec, source maps have the
  9502. * following attributes:
  9503. *
  9504. * - version: Which version of the source map spec this map is following.
  9505. * - sources: An array of URLs to the original source files.
  9506. * - names: An array of identifiers which can be referrenced by individual mappings.
  9507. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9508. * - sourcesContent: Optional. An array of contents of the original source files.
  9509. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9510. * - file: Optional. The generated file this source map is associated with.
  9511. *
  9512. * Here is an example source map, taken from the source map spec[0]:
  9513. *
  9514. * {
  9515. * version : 3,
  9516. * file: "out.js",
  9517. * sourceRoot : "",
  9518. * sources: ["foo.js", "bar.js"],
  9519. * names: ["src", "maps", "are", "fun"],
  9520. * mappings: "AA,AB;;ABCDE;"
  9521. * }
  9522. *
  9523. * The second parameter, if given, is a string whose value is the URL
  9524. * at which the source map was found. This URL is used to compute the
  9525. * sources array.
  9526. *
  9527. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9528. */
  9529. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9530. var sourceMap = aSourceMap;
  9531. if (typeof aSourceMap === 'string') {
  9532. sourceMap = util.parseSourceMapInput(aSourceMap);
  9533. }
  9534. var version = util.getArg(sourceMap, 'version');
  9535. var sources = util.getArg(sourceMap, 'sources');
  9536. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9537. // requires the array) to play nice here.
  9538. var names = util.getArg(sourceMap, 'names', []);
  9539. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9540. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9541. var mappings = util.getArg(sourceMap, 'mappings');
  9542. var file = util.getArg(sourceMap, 'file', null);
  9543. // Once again, Sass deviates from the spec and supplies the version as a
  9544. // string rather than a number, so we use loose equality checking here.
  9545. if (version != this._version) {
  9546. throw new Error('Unsupported version: ' + version);
  9547. }
  9548. if (sourceRoot) {
  9549. sourceRoot = util.normalize(sourceRoot);
  9550. }
  9551. sources = sources
  9552. .map(String)
  9553. // Some source maps produce relative source paths like "./foo.js" instead of
  9554. // "foo.js". Normalize these first so that future comparisons will succeed.
  9555. // See bugzil.la/1090768.
  9556. .map(util.normalize)
  9557. // Always ensure that absolute sources are internally stored relative to
  9558. // the source root, if the source root is absolute. Not doing this would
  9559. // be particularly problematic when the source root is a prefix of the
  9560. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9561. .map(function (source) {
  9562. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9563. ? util.relative(sourceRoot, source)
  9564. : source;
  9565. });
  9566. // Pass `true` below to allow duplicate names and sources. While source maps
  9567. // are intended to be compressed and deduplicated, the TypeScript compiler
  9568. // sometimes generates source maps with duplicates in them. See Github issue
  9569. // #72 and bugzil.la/889492.
  9570. this._names = ArraySet.fromArray(names.map(String), true);
  9571. this._sources = ArraySet.fromArray(sources, true);
  9572. this._absoluteSources = this._sources.toArray().map(function (s) {
  9573. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9574. });
  9575. this.sourceRoot = sourceRoot;
  9576. this.sourcesContent = sourcesContent;
  9577. this._mappings = mappings;
  9578. this._sourceMapURL = aSourceMapURL;
  9579. this.file = file;
  9580. }
  9581. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9582. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9583. /**
  9584. * Utility function to find the index of a source. Returns -1 if not
  9585. * found.
  9586. */
  9587. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9588. var relativeSource = aSource;
  9589. if (this.sourceRoot != null) {
  9590. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9591. }
  9592. if (this._sources.has(relativeSource)) {
  9593. return this._sources.indexOf(relativeSource);
  9594. }
  9595. // Maybe aSource is an absolute URL as returned by |sources|. In
  9596. // this case we can't simply undo the transform.
  9597. var i;
  9598. for (i = 0; i < this._absoluteSources.length; ++i) {
  9599. if (this._absoluteSources[i] == aSource) {
  9600. return i;
  9601. }
  9602. }
  9603. return -1;
  9604. };
  9605. /**
  9606. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9607. *
  9608. * @param SourceMapGenerator aSourceMap
  9609. * The source map that will be consumed.
  9610. * @param String aSourceMapURL
  9611. * The URL at which the source map can be found (optional)
  9612. * @returns BasicSourceMapConsumer
  9613. */
  9614. BasicSourceMapConsumer.fromSourceMap =
  9615. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9616. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9617. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9618. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9619. smc.sourceRoot = aSourceMap._sourceRoot;
  9620. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9621. smc.sourceRoot);
  9622. smc.file = aSourceMap._file;
  9623. smc._sourceMapURL = aSourceMapURL;
  9624. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9625. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9626. });
  9627. // Because we are modifying the entries (by converting string sources and
  9628. // names to indices into the sources and names ArraySets), we have to make
  9629. // a copy of the entry or else bad things happen. Shared mutable state
  9630. // strikes again! See github issue #191.
  9631. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9632. var destGeneratedMappings = smc.__generatedMappings = [];
  9633. var destOriginalMappings = smc.__originalMappings = [];
  9634. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9635. var srcMapping = generatedMappings[i];
  9636. var destMapping = new Mapping;
  9637. destMapping.generatedLine = srcMapping.generatedLine;
  9638. destMapping.generatedColumn = srcMapping.generatedColumn;
  9639. if (srcMapping.source) {
  9640. destMapping.source = sources.indexOf(srcMapping.source);
  9641. destMapping.originalLine = srcMapping.originalLine;
  9642. destMapping.originalColumn = srcMapping.originalColumn;
  9643. if (srcMapping.name) {
  9644. destMapping.name = names.indexOf(srcMapping.name);
  9645. }
  9646. destOriginalMappings.push(destMapping);
  9647. }
  9648. destGeneratedMappings.push(destMapping);
  9649. }
  9650. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9651. return smc;
  9652. };
  9653. /**
  9654. * The version of the source mapping spec that we are consuming.
  9655. */
  9656. BasicSourceMapConsumer.prototype._version = 3;
  9657. /**
  9658. * The list of original sources.
  9659. */
  9660. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9661. get: function () {
  9662. return this._absoluteSources.slice();
  9663. }
  9664. });
  9665. /**
  9666. * Provide the JIT with a nice shape / hidden class.
  9667. */
  9668. function Mapping() {
  9669. this.generatedLine = 0;
  9670. this.generatedColumn = 0;
  9671. this.source = null;
  9672. this.originalLine = null;
  9673. this.originalColumn = null;
  9674. this.name = null;
  9675. }
  9676. /**
  9677. * Parse the mappings in a string in to a data structure which we can easily
  9678. * query (the ordered arrays in the `this.__generatedMappings` and
  9679. * `this.__originalMappings` properties).
  9680. */
  9681. BasicSourceMapConsumer.prototype._parseMappings =
  9682. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9683. var generatedLine = 1;
  9684. var previousGeneratedColumn = 0;
  9685. var previousOriginalLine = 0;
  9686. var previousOriginalColumn = 0;
  9687. var previousSource = 0;
  9688. var previousName = 0;
  9689. var length = aStr.length;
  9690. var index = 0;
  9691. var cachedSegments = {};
  9692. var temp = {};
  9693. var originalMappings = [];
  9694. var generatedMappings = [];
  9695. var mapping, str, segment, end, value;
  9696. while (index < length) {
  9697. if (aStr.charAt(index) === ';') {
  9698. generatedLine++;
  9699. index++;
  9700. previousGeneratedColumn = 0;
  9701. }
  9702. else if (aStr.charAt(index) === ',') {
  9703. index++;
  9704. }
  9705. else {
  9706. mapping = new Mapping();
  9707. mapping.generatedLine = generatedLine;
  9708. // Because each offset is encoded relative to the previous one,
  9709. // many segments often have the same encoding. We can exploit this
  9710. // fact by caching the parsed variable length fields of each segment,
  9711. // allowing us to avoid a second parse if we encounter the same
  9712. // segment again.
  9713. for (end = index; end < length; end++) {
  9714. if (this._charIsMappingSeparator(aStr, end)) {
  9715. break;
  9716. }
  9717. }
  9718. str = aStr.slice(index, end);
  9719. segment = cachedSegments[str];
  9720. if (segment) {
  9721. index += str.length;
  9722. } else {
  9723. segment = [];
  9724. while (index < end) {
  9725. base64VLQ.decode(aStr, index, temp);
  9726. value = temp.value;
  9727. index = temp.rest;
  9728. segment.push(value);
  9729. }
  9730. if (segment.length === 2) {
  9731. throw new Error('Found a source, but no line and column');
  9732. }
  9733. if (segment.length === 3) {
  9734. throw new Error('Found a source and line, but no column');
  9735. }
  9736. cachedSegments[str] = segment;
  9737. }
  9738. // Generated column.
  9739. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9740. previousGeneratedColumn = mapping.generatedColumn;
  9741. if (segment.length > 1) {
  9742. // Original source.
  9743. mapping.source = previousSource + segment[1];
  9744. previousSource += segment[1];
  9745. // Original line.
  9746. mapping.originalLine = previousOriginalLine + segment[2];
  9747. previousOriginalLine = mapping.originalLine;
  9748. // Lines are stored 0-based
  9749. mapping.originalLine += 1;
  9750. // Original column.
  9751. mapping.originalColumn = previousOriginalColumn + segment[3];
  9752. previousOriginalColumn = mapping.originalColumn;
  9753. if (segment.length > 4) {
  9754. // Original name.
  9755. mapping.name = previousName + segment[4];
  9756. previousName += segment[4];
  9757. }
  9758. }
  9759. generatedMappings.push(mapping);
  9760. if (typeof mapping.originalLine === 'number') {
  9761. originalMappings.push(mapping);
  9762. }
  9763. }
  9764. }
  9765. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9766. this.__generatedMappings = generatedMappings;
  9767. quickSort(originalMappings, util.compareByOriginalPositions);
  9768. this.__originalMappings = originalMappings;
  9769. };
  9770. /**
  9771. * Find the mapping that best matches the hypothetical "needle" mapping that
  9772. * we are searching for in the given "haystack" of mappings.
  9773. */
  9774. BasicSourceMapConsumer.prototype._findMapping =
  9775. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9776. aColumnName, aComparator, aBias) {
  9777. // To return the position we are searching for, we must first find the
  9778. // mapping for the given position and then return the opposite position it
  9779. // points to. Because the mappings are sorted, we can use binary search to
  9780. // find the best mapping.
  9781. if (aNeedle[aLineName] <= 0) {
  9782. throw new TypeError('Line must be greater than or equal to 1, got '
  9783. + aNeedle[aLineName]);
  9784. }
  9785. if (aNeedle[aColumnName] < 0) {
  9786. throw new TypeError('Column must be greater than or equal to 0, got '
  9787. + aNeedle[aColumnName]);
  9788. }
  9789. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9790. };
  9791. /**
  9792. * Compute the last column for each generated mapping. The last column is
  9793. * inclusive.
  9794. */
  9795. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9796. function SourceMapConsumer_computeColumnSpans() {
  9797. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9798. var mapping = this._generatedMappings[index];
  9799. // Mappings do not contain a field for the last generated columnt. We
  9800. // can come up with an optimistic estimate, however, by assuming that
  9801. // mappings are contiguous (i.e. given two consecutive mappings, the
  9802. // first mapping ends where the second one starts).
  9803. if (index + 1 < this._generatedMappings.length) {
  9804. var nextMapping = this._generatedMappings[index + 1];
  9805. if (mapping.generatedLine === nextMapping.generatedLine) {
  9806. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9807. continue;
  9808. }
  9809. }
  9810. // The last mapping for each line spans the entire line.
  9811. mapping.lastGeneratedColumn = Infinity;
  9812. }
  9813. };
  9814. /**
  9815. * Returns the original source, line, and column information for the generated
  9816. * source's line and column positions provided. The only argument is an object
  9817. * with the following properties:
  9818. *
  9819. * - line: The line number in the generated source. The line number
  9820. * is 1-based.
  9821. * - column: The column number in the generated source. The column
  9822. * number is 0-based.
  9823. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9824. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9825. * closest element that is smaller than or greater than the one we are
  9826. * searching for, respectively, if the exact element cannot be found.
  9827. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9828. *
  9829. * and an object is returned with the following properties:
  9830. *
  9831. * - source: The original source file, or null.
  9832. * - line: The line number in the original source, or null. The
  9833. * line number is 1-based.
  9834. * - column: The column number in the original source, or null. The
  9835. * column number is 0-based.
  9836. * - name: The original identifier, or null.
  9837. */
  9838. BasicSourceMapConsumer.prototype.originalPositionFor =
  9839. function SourceMapConsumer_originalPositionFor(aArgs) {
  9840. var needle = {
  9841. generatedLine: util.getArg(aArgs, 'line'),
  9842. generatedColumn: util.getArg(aArgs, 'column')
  9843. };
  9844. var index = this._findMapping(
  9845. needle,
  9846. this._generatedMappings,
  9847. "generatedLine",
  9848. "generatedColumn",
  9849. util.compareByGeneratedPositionsDeflated,
  9850. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9851. );
  9852. if (index >= 0) {
  9853. var mapping = this._generatedMappings[index];
  9854. if (mapping.generatedLine === needle.generatedLine) {
  9855. var source = util.getArg(mapping, 'source', null);
  9856. if (source !== null) {
  9857. source = this._sources.at(source);
  9858. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9859. }
  9860. var name = util.getArg(mapping, 'name', null);
  9861. if (name !== null) {
  9862. name = this._names.at(name);
  9863. }
  9864. return {
  9865. source: source,
  9866. line: util.getArg(mapping, 'originalLine', null),
  9867. column: util.getArg(mapping, 'originalColumn', null),
  9868. name: name
  9869. };
  9870. }
  9871. }
  9872. return {
  9873. source: null,
  9874. line: null,
  9875. column: null,
  9876. name: null
  9877. };
  9878. };
  9879. /**
  9880. * Return true if we have the source content for every source in the source
  9881. * map, false otherwise.
  9882. */
  9883. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9884. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9885. if (!this.sourcesContent) {
  9886. return false;
  9887. }
  9888. return this.sourcesContent.length >= this._sources.size() &&
  9889. !this.sourcesContent.some(function (sc) { return sc == null; });
  9890. };
  9891. /**
  9892. * Returns the original source content. The only argument is the url of the
  9893. * original source file. Returns null if no original source content is
  9894. * available.
  9895. */
  9896. BasicSourceMapConsumer.prototype.sourceContentFor =
  9897. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9898. if (!this.sourcesContent) {
  9899. return null;
  9900. }
  9901. var index = this._findSourceIndex(aSource);
  9902. if (index >= 0) {
  9903. return this.sourcesContent[index];
  9904. }
  9905. var relativeSource = aSource;
  9906. if (this.sourceRoot != null) {
  9907. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9908. }
  9909. var url;
  9910. if (this.sourceRoot != null
  9911. && (url = util.urlParse(this.sourceRoot))) {
  9912. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9913. // many users. We can help them out when they expect file:// URIs to
  9914. // behave like it would if they were running a local HTTP server. See
  9915. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9916. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9917. if (url.scheme == "file"
  9918. && this._sources.has(fileUriAbsPath)) {
  9919. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9920. }
  9921. if ((!url.path || url.path == "/")
  9922. && this._sources.has("/" + relativeSource)) {
  9923. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9924. }
  9925. }
  9926. // This function is used recursively from
  9927. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9928. // don't want to throw if we can't find the source - we just want to
  9929. // return null, so we provide a flag to exit gracefully.
  9930. if (nullOnMissing) {
  9931. return null;
  9932. }
  9933. else {
  9934. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9935. }
  9936. };
  9937. /**
  9938. * Returns the generated line and column information for the original source,
  9939. * line, and column positions provided. The only argument is an object with
  9940. * the following properties:
  9941. *
  9942. * - source: The filename of the original source.
  9943. * - line: The line number in the original source. The line number
  9944. * is 1-based.
  9945. * - column: The column number in the original source. The column
  9946. * number is 0-based.
  9947. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9948. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9949. * closest element that is smaller than or greater than the one we are
  9950. * searching for, respectively, if the exact element cannot be found.
  9951. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9952. *
  9953. * and an object is returned with the following properties:
  9954. *
  9955. * - line: The line number in the generated source, or null. The
  9956. * line number is 1-based.
  9957. * - column: The column number in the generated source, or null.
  9958. * The column number is 0-based.
  9959. */
  9960. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9961. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9962. var source = util.getArg(aArgs, 'source');
  9963. source = this._findSourceIndex(source);
  9964. if (source < 0) {
  9965. return {
  9966. line: null,
  9967. column: null,
  9968. lastColumn: null
  9969. };
  9970. }
  9971. var needle = {
  9972. source: source,
  9973. originalLine: util.getArg(aArgs, 'line'),
  9974. originalColumn: util.getArg(aArgs, 'column')
  9975. };
  9976. var index = this._findMapping(
  9977. needle,
  9978. this._originalMappings,
  9979. "originalLine",
  9980. "originalColumn",
  9981. util.compareByOriginalPositions,
  9982. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9983. );
  9984. if (index >= 0) {
  9985. var mapping = this._originalMappings[index];
  9986. if (mapping.source === needle.source) {
  9987. return {
  9988. line: util.getArg(mapping, 'generatedLine', null),
  9989. column: util.getArg(mapping, 'generatedColumn', null),
  9990. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9991. };
  9992. }
  9993. }
  9994. return {
  9995. line: null,
  9996. column: null,
  9997. lastColumn: null
  9998. };
  9999. };
  10000. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  10001. /**
  10002. * An IndexedSourceMapConsumer instance represents a parsed source map which
  10003. * we can query for information. It differs from BasicSourceMapConsumer in
  10004. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  10005. * input.
  10006. *
  10007. * The first parameter is a raw source map (either as a JSON string, or already
  10008. * parsed to an object). According to the spec for indexed source maps, they
  10009. * have the following attributes:
  10010. *
  10011. * - version: Which version of the source map spec this map is following.
  10012. * - file: Optional. The generated file this source map is associated with.
  10013. * - sections: A list of section definitions.
  10014. *
  10015. * Each value under the "sections" field has two fields:
  10016. * - offset: The offset into the original specified at which this section
  10017. * begins to apply, defined as an object with a "line" and "column"
  10018. * field.
  10019. * - map: A source map definition. This source map could also be indexed,
  10020. * but doesn't have to be.
  10021. *
  10022. * Instead of the "map" field, it's also possible to have a "url" field
  10023. * specifying a URL to retrieve a source map from, but that's currently
  10024. * unsupported.
  10025. *
  10026. * Here's an example source map, taken from the source map spec[0], but
  10027. * modified to omit a section which uses the "url" field.
  10028. *
  10029. * {
  10030. * version : 3,
  10031. * file: "app.js",
  10032. * sections: [{
  10033. * offset: {line:100, column:10},
  10034. * map: {
  10035. * version : 3,
  10036. * file: "section.js",
  10037. * sources: ["foo.js", "bar.js"],
  10038. * names: ["src", "maps", "are", "fun"],
  10039. * mappings: "AAAA,E;;ABCDE;"
  10040. * }
  10041. * }],
  10042. * }
  10043. *
  10044. * The second parameter, if given, is a string whose value is the URL
  10045. * at which the source map was found. This URL is used to compute the
  10046. * sources array.
  10047. *
  10048. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  10049. */
  10050. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  10051. var sourceMap = aSourceMap;
  10052. if (typeof aSourceMap === 'string') {
  10053. sourceMap = util.parseSourceMapInput(aSourceMap);
  10054. }
  10055. var version = util.getArg(sourceMap, 'version');
  10056. var sections = util.getArg(sourceMap, 'sections');
  10057. if (version != this._version) {
  10058. throw new Error('Unsupported version: ' + version);
  10059. }
  10060. this._sources = new ArraySet();
  10061. this._names = new ArraySet();
  10062. var lastOffset = {
  10063. line: -1,
  10064. column: 0
  10065. };
  10066. this._sections = sections.map(function (s) {
  10067. if (s.url) {
  10068. // The url field will require support for asynchronicity.
  10069. // See https://github.com/mozilla/source-map/issues/16
  10070. throw new Error('Support for url field in sections not implemented.');
  10071. }
  10072. var offset = util.getArg(s, 'offset');
  10073. var offsetLine = util.getArg(offset, 'line');
  10074. var offsetColumn = util.getArg(offset, 'column');
  10075. if (offsetLine < lastOffset.line ||
  10076. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  10077. throw new Error('Section offsets must be ordered and non-overlapping.');
  10078. }
  10079. lastOffset = offset;
  10080. return {
  10081. generatedOffset: {
  10082. // The offset fields are 0-based, but we use 1-based indices when
  10083. // encoding/decoding from VLQ.
  10084. generatedLine: offsetLine + 1,
  10085. generatedColumn: offsetColumn + 1
  10086. },
  10087. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  10088. }
  10089. });
  10090. }
  10091. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10092. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  10093. /**
  10094. * The version of the source mapping spec that we are consuming.
  10095. */
  10096. IndexedSourceMapConsumer.prototype._version = 3;
  10097. /**
  10098. * The list of original sources.
  10099. */
  10100. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  10101. get: function () {
  10102. var sources = [];
  10103. for (var i = 0; i < this._sections.length; i++) {
  10104. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  10105. sources.push(this._sections[i].consumer.sources[j]);
  10106. }
  10107. }
  10108. return sources;
  10109. }
  10110. });
  10111. /**
  10112. * Returns the original source, line, and column information for the generated
  10113. * source's line and column positions provided. The only argument is an object
  10114. * with the following properties:
  10115. *
  10116. * - line: The line number in the generated source. The line number
  10117. * is 1-based.
  10118. * - column: The column number in the generated source. The column
  10119. * number is 0-based.
  10120. *
  10121. * and an object is returned with the following properties:
  10122. *
  10123. * - source: The original source file, or null.
  10124. * - line: The line number in the original source, or null. The
  10125. * line number is 1-based.
  10126. * - column: The column number in the original source, or null. The
  10127. * column number is 0-based.
  10128. * - name: The original identifier, or null.
  10129. */
  10130. IndexedSourceMapConsumer.prototype.originalPositionFor =
  10131. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  10132. var needle = {
  10133. generatedLine: util.getArg(aArgs, 'line'),
  10134. generatedColumn: util.getArg(aArgs, 'column')
  10135. };
  10136. // Find the section containing the generated position we're trying to map
  10137. // to an original position.
  10138. var sectionIndex = binarySearch.search(needle, this._sections,
  10139. function(needle, section) {
  10140. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  10141. if (cmp) {
  10142. return cmp;
  10143. }
  10144. return (needle.generatedColumn -
  10145. section.generatedOffset.generatedColumn);
  10146. });
  10147. var section = this._sections[sectionIndex];
  10148. if (!section) {
  10149. return {
  10150. source: null,
  10151. line: null,
  10152. column: null,
  10153. name: null
  10154. };
  10155. }
  10156. return section.consumer.originalPositionFor({
  10157. line: needle.generatedLine -
  10158. (section.generatedOffset.generatedLine - 1),
  10159. column: needle.generatedColumn -
  10160. (section.generatedOffset.generatedLine === needle.generatedLine
  10161. ? section.generatedOffset.generatedColumn - 1
  10162. : 0),
  10163. bias: aArgs.bias
  10164. });
  10165. };
  10166. /**
  10167. * Return true if we have the source content for every source in the source
  10168. * map, false otherwise.
  10169. */
  10170. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10171. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10172. return this._sections.every(function (s) {
  10173. return s.consumer.hasContentsOfAllSources();
  10174. });
  10175. };
  10176. /**
  10177. * Returns the original source content. The only argument is the url of the
  10178. * original source file. Returns null if no original source content is
  10179. * available.
  10180. */
  10181. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10182. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10183. for (var i = 0; i < this._sections.length; i++) {
  10184. var section = this._sections[i];
  10185. var content = section.consumer.sourceContentFor(aSource, true);
  10186. if (content) {
  10187. return content;
  10188. }
  10189. }
  10190. if (nullOnMissing) {
  10191. return null;
  10192. }
  10193. else {
  10194. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10195. }
  10196. };
  10197. /**
  10198. * Returns the generated line and column information for the original source,
  10199. * line, and column positions provided. The only argument is an object with
  10200. * the following properties:
  10201. *
  10202. * - source: The filename of the original source.
  10203. * - line: The line number in the original source. The line number
  10204. * is 1-based.
  10205. * - column: The column number in the original source. The column
  10206. * number is 0-based.
  10207. *
  10208. * and an object is returned with the following properties:
  10209. *
  10210. * - line: The line number in the generated source, or null. The
  10211. * line number is 1-based.
  10212. * - column: The column number in the generated source, or null.
  10213. * The column number is 0-based.
  10214. */
  10215. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10216. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10217. for (var i = 0; i < this._sections.length; i++) {
  10218. var section = this._sections[i];
  10219. // Only consider this section if the requested source is in the list of
  10220. // sources of the consumer.
  10221. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10222. continue;
  10223. }
  10224. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10225. if (generatedPosition) {
  10226. var ret = {
  10227. line: generatedPosition.line +
  10228. (section.generatedOffset.generatedLine - 1),
  10229. column: generatedPosition.column +
  10230. (section.generatedOffset.generatedLine === generatedPosition.line
  10231. ? section.generatedOffset.generatedColumn - 1
  10232. : 0)
  10233. };
  10234. return ret;
  10235. }
  10236. }
  10237. return {
  10238. line: null,
  10239. column: null
  10240. };
  10241. };
  10242. /**
  10243. * Parse the mappings in a string in to a data structure which we can easily
  10244. * query (the ordered arrays in the `this.__generatedMappings` and
  10245. * `this.__originalMappings` properties).
  10246. */
  10247. IndexedSourceMapConsumer.prototype._parseMappings =
  10248. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10249. this.__generatedMappings = [];
  10250. this.__originalMappings = [];
  10251. for (var i = 0; i < this._sections.length; i++) {
  10252. var section = this._sections[i];
  10253. var sectionMappings = section.consumer._generatedMappings;
  10254. for (var j = 0; j < sectionMappings.length; j++) {
  10255. var mapping = sectionMappings[j];
  10256. var source = section.consumer._sources.at(mapping.source);
  10257. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10258. this._sources.add(source);
  10259. source = this._sources.indexOf(source);
  10260. var name = null;
  10261. if (mapping.name) {
  10262. name = section.consumer._names.at(mapping.name);
  10263. this._names.add(name);
  10264. name = this._names.indexOf(name);
  10265. }
  10266. // The mappings coming from the consumer for the section have
  10267. // generated positions relative to the start of the section, so we
  10268. // need to offset them to be relative to the start of the concatenated
  10269. // generated file.
  10270. var adjustedMapping = {
  10271. source: source,
  10272. generatedLine: mapping.generatedLine +
  10273. (section.generatedOffset.generatedLine - 1),
  10274. generatedColumn: mapping.generatedColumn +
  10275. (section.generatedOffset.generatedLine === mapping.generatedLine
  10276. ? section.generatedOffset.generatedColumn - 1
  10277. : 0),
  10278. originalLine: mapping.originalLine,
  10279. originalColumn: mapping.originalColumn,
  10280. name: name
  10281. };
  10282. this.__generatedMappings.push(adjustedMapping);
  10283. if (typeof adjustedMapping.originalLine === 'number') {
  10284. this.__originalMappings.push(adjustedMapping);
  10285. }
  10286. }
  10287. }
  10288. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10289. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10290. };
  10291. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10292. return sourceMapConsumer;
  10293. }
  10294. var sourceNode = {};
  10295. /* -*- Mode: js; js-indent-level: 2; -*- */
  10296. var hasRequiredSourceNode;
  10297. function requireSourceNode () {
  10298. if (hasRequiredSourceNode) return sourceNode;
  10299. hasRequiredSourceNode = 1;
  10300. /*
  10301. * Copyright 2011 Mozilla Foundation and contributors
  10302. * Licensed under the New BSD license. See LICENSE or:
  10303. * http://opensource.org/licenses/BSD-3-Clause
  10304. */
  10305. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10306. var util = /*@__PURE__*/ requireUtil$1();
  10307. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10308. // operating systems these days (capturing the result).
  10309. var REGEX_NEWLINE = /(\r?\n)/;
  10310. // Newline character code for charCodeAt() comparisons
  10311. var NEWLINE_CODE = 10;
  10312. // Private symbol for identifying `SourceNode`s when multiple versions of
  10313. // the source-map library are loaded. This MUST NOT CHANGE across
  10314. // versions!
  10315. var isSourceNode = "$$$isSourceNode$$$";
  10316. /**
  10317. * SourceNodes provide a way to abstract over interpolating/concatenating
  10318. * snippets of generated JavaScript source code while maintaining the line and
  10319. * column information associated with the original source code.
  10320. *
  10321. * @param aLine The original line number.
  10322. * @param aColumn The original column number.
  10323. * @param aSource The original source's filename.
  10324. * @param aChunks Optional. An array of strings which are snippets of
  10325. * generated JS, or other SourceNodes.
  10326. * @param aName The original identifier.
  10327. */
  10328. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10329. this.children = [];
  10330. this.sourceContents = {};
  10331. this.line = aLine == null ? null : aLine;
  10332. this.column = aColumn == null ? null : aColumn;
  10333. this.source = aSource == null ? null : aSource;
  10334. this.name = aName == null ? null : aName;
  10335. this[isSourceNode] = true;
  10336. if (aChunks != null) this.add(aChunks);
  10337. }
  10338. /**
  10339. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10340. *
  10341. * @param aGeneratedCode The generated code
  10342. * @param aSourceMapConsumer The SourceMap for the generated code
  10343. * @param aRelativePath Optional. The path that relative sources in the
  10344. * SourceMapConsumer should be relative to.
  10345. */
  10346. SourceNode.fromStringWithSourceMap =
  10347. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10348. // The SourceNode we want to fill with the generated code
  10349. // and the SourceMap
  10350. var node = new SourceNode();
  10351. // All even indices of this array are one line of the generated code,
  10352. // while all odd indices are the newlines between two adjacent lines
  10353. // (since `REGEX_NEWLINE` captures its match).
  10354. // Processed fragments are accessed by calling `shiftNextLine`.
  10355. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10356. var remainingLinesIndex = 0;
  10357. var shiftNextLine = function() {
  10358. var lineContents = getNextLine();
  10359. // The last line of a file might not have a newline.
  10360. var newLine = getNextLine() || "";
  10361. return lineContents + newLine;
  10362. function getNextLine() {
  10363. return remainingLinesIndex < remainingLines.length ?
  10364. remainingLines[remainingLinesIndex++] : undefined;
  10365. }
  10366. };
  10367. // We need to remember the position of "remainingLines"
  10368. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10369. // The generate SourceNodes we need a code range.
  10370. // To extract it current and last mapping is used.
  10371. // Here we store the last mapping.
  10372. var lastMapping = null;
  10373. aSourceMapConsumer.eachMapping(function (mapping) {
  10374. if (lastMapping !== null) {
  10375. // We add the code from "lastMapping" to "mapping":
  10376. // First check if there is a new line in between.
  10377. if (lastGeneratedLine < mapping.generatedLine) {
  10378. // Associate first line with "lastMapping"
  10379. addMappingWithCode(lastMapping, shiftNextLine());
  10380. lastGeneratedLine++;
  10381. lastGeneratedColumn = 0;
  10382. // The remaining code is added without mapping
  10383. } else {
  10384. // There is no new line in between.
  10385. // Associate the code between "lastGeneratedColumn" and
  10386. // "mapping.generatedColumn" with "lastMapping"
  10387. var nextLine = remainingLines[remainingLinesIndex] || '';
  10388. var code = nextLine.substr(0, mapping.generatedColumn -
  10389. lastGeneratedColumn);
  10390. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10391. lastGeneratedColumn);
  10392. lastGeneratedColumn = mapping.generatedColumn;
  10393. addMappingWithCode(lastMapping, code);
  10394. // No more remaining code, continue
  10395. lastMapping = mapping;
  10396. return;
  10397. }
  10398. }
  10399. // We add the generated code until the first mapping
  10400. // to the SourceNode without any mapping.
  10401. // Each line is added as separate string.
  10402. while (lastGeneratedLine < mapping.generatedLine) {
  10403. node.add(shiftNextLine());
  10404. lastGeneratedLine++;
  10405. }
  10406. if (lastGeneratedColumn < mapping.generatedColumn) {
  10407. var nextLine = remainingLines[remainingLinesIndex] || '';
  10408. node.add(nextLine.substr(0, mapping.generatedColumn));
  10409. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10410. lastGeneratedColumn = mapping.generatedColumn;
  10411. }
  10412. lastMapping = mapping;
  10413. }, this);
  10414. // We have processed all mappings.
  10415. if (remainingLinesIndex < remainingLines.length) {
  10416. if (lastMapping) {
  10417. // Associate the remaining code in the current line with "lastMapping"
  10418. addMappingWithCode(lastMapping, shiftNextLine());
  10419. }
  10420. // and add the remaining lines without any mapping
  10421. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10422. }
  10423. // Copy sourcesContent into SourceNode
  10424. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10425. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10426. if (content != null) {
  10427. if (aRelativePath != null) {
  10428. sourceFile = util.join(aRelativePath, sourceFile);
  10429. }
  10430. node.setSourceContent(sourceFile, content);
  10431. }
  10432. });
  10433. return node;
  10434. function addMappingWithCode(mapping, code) {
  10435. if (mapping === null || mapping.source === undefined) {
  10436. node.add(code);
  10437. } else {
  10438. var source = aRelativePath
  10439. ? util.join(aRelativePath, mapping.source)
  10440. : mapping.source;
  10441. node.add(new SourceNode(mapping.originalLine,
  10442. mapping.originalColumn,
  10443. source,
  10444. code,
  10445. mapping.name));
  10446. }
  10447. }
  10448. };
  10449. /**
  10450. * Add a chunk of generated JS to this source node.
  10451. *
  10452. * @param aChunk A string snippet of generated JS code, another instance of
  10453. * SourceNode, or an array where each member is one of those things.
  10454. */
  10455. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10456. if (Array.isArray(aChunk)) {
  10457. aChunk.forEach(function (chunk) {
  10458. this.add(chunk);
  10459. }, this);
  10460. }
  10461. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10462. if (aChunk) {
  10463. this.children.push(aChunk);
  10464. }
  10465. }
  10466. else {
  10467. throw new TypeError(
  10468. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10469. );
  10470. }
  10471. return this;
  10472. };
  10473. /**
  10474. * Add a chunk of generated JS to the beginning of this source node.
  10475. *
  10476. * @param aChunk A string snippet of generated JS code, another instance of
  10477. * SourceNode, or an array where each member is one of those things.
  10478. */
  10479. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10480. if (Array.isArray(aChunk)) {
  10481. for (var i = aChunk.length-1; i >= 0; i--) {
  10482. this.prepend(aChunk[i]);
  10483. }
  10484. }
  10485. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10486. this.children.unshift(aChunk);
  10487. }
  10488. else {
  10489. throw new TypeError(
  10490. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10491. );
  10492. }
  10493. return this;
  10494. };
  10495. /**
  10496. * Walk over the tree of JS snippets in this node and its children. The
  10497. * walking function is called once for each snippet of JS and is passed that
  10498. * snippet and the its original associated source's line/column location.
  10499. *
  10500. * @param aFn The traversal function.
  10501. */
  10502. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10503. var chunk;
  10504. for (var i = 0, len = this.children.length; i < len; i++) {
  10505. chunk = this.children[i];
  10506. if (chunk[isSourceNode]) {
  10507. chunk.walk(aFn);
  10508. }
  10509. else {
  10510. if (chunk !== '') {
  10511. aFn(chunk, { source: this.source,
  10512. line: this.line,
  10513. column: this.column,
  10514. name: this.name });
  10515. }
  10516. }
  10517. }
  10518. };
  10519. /**
  10520. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10521. * each of `this.children`.
  10522. *
  10523. * @param aSep The separator.
  10524. */
  10525. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10526. var newChildren;
  10527. var i;
  10528. var len = this.children.length;
  10529. if (len > 0) {
  10530. newChildren = [];
  10531. for (i = 0; i < len-1; i++) {
  10532. newChildren.push(this.children[i]);
  10533. newChildren.push(aSep);
  10534. }
  10535. newChildren.push(this.children[i]);
  10536. this.children = newChildren;
  10537. }
  10538. return this;
  10539. };
  10540. /**
  10541. * Call String.prototype.replace on the very right-most source snippet. Useful
  10542. * for trimming whitespace from the end of a source node, etc.
  10543. *
  10544. * @param aPattern The pattern to replace.
  10545. * @param aReplacement The thing to replace the pattern with.
  10546. */
  10547. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10548. var lastChild = this.children[this.children.length - 1];
  10549. if (lastChild[isSourceNode]) {
  10550. lastChild.replaceRight(aPattern, aReplacement);
  10551. }
  10552. else if (typeof lastChild === 'string') {
  10553. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10554. }
  10555. else {
  10556. this.children.push(''.replace(aPattern, aReplacement));
  10557. }
  10558. return this;
  10559. };
  10560. /**
  10561. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10562. * in the sourcesContent field.
  10563. *
  10564. * @param aSourceFile The filename of the source file
  10565. * @param aSourceContent The content of the source file
  10566. */
  10567. SourceNode.prototype.setSourceContent =
  10568. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10569. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10570. };
  10571. /**
  10572. * Walk over the tree of SourceNodes. The walking function is called for each
  10573. * source file content and is passed the filename and source content.
  10574. *
  10575. * @param aFn The traversal function.
  10576. */
  10577. SourceNode.prototype.walkSourceContents =
  10578. function SourceNode_walkSourceContents(aFn) {
  10579. for (var i = 0, len = this.children.length; i < len; i++) {
  10580. if (this.children[i][isSourceNode]) {
  10581. this.children[i].walkSourceContents(aFn);
  10582. }
  10583. }
  10584. var sources = Object.keys(this.sourceContents);
  10585. for (var i = 0, len = sources.length; i < len; i++) {
  10586. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10587. }
  10588. };
  10589. /**
  10590. * Return the string representation of this source node. Walks over the tree
  10591. * and concatenates all the various snippets together to one string.
  10592. */
  10593. SourceNode.prototype.toString = function SourceNode_toString() {
  10594. var str = "";
  10595. this.walk(function (chunk) {
  10596. str += chunk;
  10597. });
  10598. return str;
  10599. };
  10600. /**
  10601. * Returns the string representation of this source node along with a source
  10602. * map.
  10603. */
  10604. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10605. var generated = {
  10606. code: "",
  10607. line: 1,
  10608. column: 0
  10609. };
  10610. var map = new SourceMapGenerator(aArgs);
  10611. var sourceMappingActive = false;
  10612. var lastOriginalSource = null;
  10613. var lastOriginalLine = null;
  10614. var lastOriginalColumn = null;
  10615. var lastOriginalName = null;
  10616. this.walk(function (chunk, original) {
  10617. generated.code += chunk;
  10618. if (original.source !== null
  10619. && original.line !== null
  10620. && original.column !== null) {
  10621. if(lastOriginalSource !== original.source
  10622. || lastOriginalLine !== original.line
  10623. || lastOriginalColumn !== original.column
  10624. || lastOriginalName !== original.name) {
  10625. map.addMapping({
  10626. source: original.source,
  10627. original: {
  10628. line: original.line,
  10629. column: original.column
  10630. },
  10631. generated: {
  10632. line: generated.line,
  10633. column: generated.column
  10634. },
  10635. name: original.name
  10636. });
  10637. }
  10638. lastOriginalSource = original.source;
  10639. lastOriginalLine = original.line;
  10640. lastOriginalColumn = original.column;
  10641. lastOriginalName = original.name;
  10642. sourceMappingActive = true;
  10643. } else if (sourceMappingActive) {
  10644. map.addMapping({
  10645. generated: {
  10646. line: generated.line,
  10647. column: generated.column
  10648. }
  10649. });
  10650. lastOriginalSource = null;
  10651. sourceMappingActive = false;
  10652. }
  10653. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10654. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10655. generated.line++;
  10656. generated.column = 0;
  10657. // Mappings end at eol
  10658. if (idx + 1 === length) {
  10659. lastOriginalSource = null;
  10660. sourceMappingActive = false;
  10661. } else if (sourceMappingActive) {
  10662. map.addMapping({
  10663. source: original.source,
  10664. original: {
  10665. line: original.line,
  10666. column: original.column
  10667. },
  10668. generated: {
  10669. line: generated.line,
  10670. column: generated.column
  10671. },
  10672. name: original.name
  10673. });
  10674. }
  10675. } else {
  10676. generated.column++;
  10677. }
  10678. }
  10679. });
  10680. this.walkSourceContents(function (sourceFile, sourceContent) {
  10681. map.setSourceContent(sourceFile, sourceContent);
  10682. });
  10683. return { code: generated.code, map: map };
  10684. };
  10685. sourceNode.SourceNode = SourceNode;
  10686. return sourceNode;
  10687. }
  10688. /*
  10689. * Copyright 2009-2011 Mozilla Foundation and contributors
  10690. * Licensed under the New BSD license. See LICENSE.txt or:
  10691. * http://opensource.org/licenses/BSD-3-Clause
  10692. */
  10693. var hasRequiredSourceMap;
  10694. function requireSourceMap () {
  10695. if (hasRequiredSourceMap) return sourceMap;
  10696. hasRequiredSourceMap = 1;
  10697. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10698. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10699. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10700. return sourceMap;
  10701. }
  10702. var mergeSourceMap;
  10703. var hasRequiredMergeSourceMap;
  10704. function requireMergeSourceMap () {
  10705. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10706. hasRequiredMergeSourceMap = 1;
  10707. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10708. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10709. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10710. mergeSourceMap = merge;
  10711. /**
  10712. * Merge old source map and new source map and return merged.
  10713. * If old or new source map value is falsy, return another one as it is.
  10714. *
  10715. * @param {object|string} [oldMap] old source map object
  10716. * @param {object|string} [newmap] new source map object
  10717. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10718. */
  10719. function merge(oldMap, newMap) {
  10720. if (!oldMap) return newMap
  10721. if (!newMap) return oldMap
  10722. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10723. var newMapConsumer = new SourceMapConsumer(newMap);
  10724. var mergedMapGenerator = new SourceMapGenerator();
  10725. // iterate on new map and overwrite original position of new map with one of old map
  10726. newMapConsumer.eachMapping(function(m) {
  10727. // pass when `originalLine` is null.
  10728. // It occurs in case that the node does not have origin in original code.
  10729. if (m.originalLine == null) return
  10730. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10731. line: m.originalLine,
  10732. column: m.originalColumn
  10733. });
  10734. if (origPosInOldMap.source == null) return
  10735. mergedMapGenerator.addMapping({
  10736. original: {
  10737. line: origPosInOldMap.line,
  10738. column: origPosInOldMap.column
  10739. },
  10740. generated: {
  10741. line: m.generatedLine,
  10742. column: m.generatedColumn
  10743. },
  10744. source: origPosInOldMap.source,
  10745. name: origPosInOldMap.name
  10746. });
  10747. });
  10748. var consumers = [oldMapConsumer, newMapConsumer];
  10749. consumers.forEach(function(consumer) {
  10750. consumer.sources.forEach(function(sourceFile) {
  10751. mergedMapGenerator._sources.add(sourceFile);
  10752. var sourceContent = consumer.sourceContentFor(sourceFile);
  10753. if (sourceContent != null) {
  10754. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10755. }
  10756. });
  10757. });
  10758. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10759. mergedMapGenerator._file = oldMap.file;
  10760. return JSON.parse(mergedMapGenerator.toString())
  10761. }
  10762. return mergeSourceMap;
  10763. }
  10764. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10765. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10766. const scss = (source, map, options, load = require) => {
  10767. const nodeSass = load("sass");
  10768. const { compileString, renderSync } = nodeSass;
  10769. const data = getSource(source, options.filename, options.additionalData);
  10770. let css;
  10771. let dependencies;
  10772. let sourceMap;
  10773. try {
  10774. if (compileString) {
  10775. const { pathToFileURL, fileURLToPath } = load("url");
  10776. const result = compileString(data, {
  10777. ...options,
  10778. url: pathToFileURL(options.filename),
  10779. sourceMap: !!map
  10780. });
  10781. css = result.css;
  10782. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10783. sourceMap = map ? result.sourceMap : void 0;
  10784. } else {
  10785. const result = renderSync({
  10786. ...options,
  10787. data,
  10788. file: options.filename,
  10789. outFile: options.filename,
  10790. sourceMap: !!map
  10791. });
  10792. css = result.css.toString();
  10793. dependencies = result.stats.includedFiles;
  10794. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10795. }
  10796. if (map) {
  10797. return {
  10798. code: css,
  10799. errors: [],
  10800. dependencies,
  10801. map: merge(map, sourceMap)
  10802. };
  10803. }
  10804. return { code: css, errors: [], dependencies };
  10805. } catch (e) {
  10806. return { code: "", errors: [e], dependencies: [] };
  10807. }
  10808. };
  10809. const sass = (source, map, options, load) => scss(
  10810. source,
  10811. map,
  10812. {
  10813. ...options,
  10814. indentedSyntax: true
  10815. },
  10816. load
  10817. );
  10818. const less = (source, map, options, load = require) => {
  10819. const nodeLess = load("less");
  10820. let result;
  10821. let error = null;
  10822. nodeLess.render(
  10823. getSource(source, options.filename, options.additionalData),
  10824. { ...options, syncImport: true },
  10825. (err, output) => {
  10826. error = err;
  10827. result = output;
  10828. }
  10829. );
  10830. if (error) return { code: "", errors: [error], dependencies: [] };
  10831. const dependencies = result.imports;
  10832. if (map) {
  10833. return {
  10834. code: result.css.toString(),
  10835. map: merge(map, result.map),
  10836. errors: [],
  10837. dependencies
  10838. };
  10839. }
  10840. return {
  10841. code: result.css.toString(),
  10842. errors: [],
  10843. dependencies
  10844. };
  10845. };
  10846. const styl = (source, map, options, load = require) => {
  10847. const nodeStylus = load("stylus");
  10848. try {
  10849. const ref = nodeStylus(source, options);
  10850. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10851. const result = ref.render();
  10852. const dependencies = ref.deps();
  10853. if (map) {
  10854. return {
  10855. code: result,
  10856. map: merge(map, ref.sourcemap),
  10857. errors: [],
  10858. dependencies
  10859. };
  10860. }
  10861. return { code: result, errors: [], dependencies };
  10862. } catch (e) {
  10863. return { code: "", errors: [e], dependencies: [] };
  10864. }
  10865. };
  10866. function getSource(source, filename, additionalData) {
  10867. if (!additionalData) return source;
  10868. if (shared.isFunction(additionalData)) {
  10869. return additionalData(source, filename);
  10870. }
  10871. return additionalData + source;
  10872. }
  10873. const processors = {
  10874. less,
  10875. sass,
  10876. scss,
  10877. styl,
  10878. stylus: styl
  10879. };
  10880. var build = {exports: {}};
  10881. var fs = {};
  10882. var hasRequiredFs;
  10883. function requireFs () {
  10884. if (hasRequiredFs) return fs;
  10885. hasRequiredFs = 1;
  10886. Object.defineProperty(fs, "__esModule", {
  10887. value: true
  10888. });
  10889. fs.getFileSystem = getFileSystem;
  10890. fs.setFileSystem = setFileSystem;
  10891. let fileSystem = {
  10892. readFile: () => {
  10893. throw Error("readFile not implemented");
  10894. },
  10895. writeFile: () => {
  10896. throw Error("writeFile not implemented");
  10897. }
  10898. };
  10899. function setFileSystem(fs) {
  10900. fileSystem.readFile = fs.readFile;
  10901. fileSystem.writeFile = fs.writeFile;
  10902. }
  10903. function getFileSystem() {
  10904. return fileSystem;
  10905. }
  10906. return fs;
  10907. }
  10908. var pluginFactory = {};
  10909. var unquote = {};
  10910. var hasRequiredUnquote;
  10911. function requireUnquote () {
  10912. if (hasRequiredUnquote) return unquote;
  10913. hasRequiredUnquote = 1;
  10914. Object.defineProperty(unquote, "__esModule", {
  10915. value: true
  10916. });
  10917. unquote.default = unquote$1;
  10918. // copied from https://github.com/lakenen/node-unquote
  10919. const reg = /['"]/;
  10920. function unquote$1(str) {
  10921. if (!str) {
  10922. return "";
  10923. }
  10924. if (reg.test(str.charAt(0))) {
  10925. str = str.substr(1);
  10926. }
  10927. if (reg.test(str.charAt(str.length - 1))) {
  10928. str = str.substr(0, str.length - 1);
  10929. }
  10930. return str;
  10931. }
  10932. return unquote;
  10933. }
  10934. var Parser = {};
  10935. var replaceValueSymbols_1;
  10936. var hasRequiredReplaceValueSymbols;
  10937. function requireReplaceValueSymbols () {
  10938. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10939. hasRequiredReplaceValueSymbols = 1;
  10940. const matchValueName = /[$]?[\w-]+/g;
  10941. const replaceValueSymbols = (value, replacements) => {
  10942. let matches;
  10943. while ((matches = matchValueName.exec(value))) {
  10944. const replacement = replacements[matches[0]];
  10945. if (replacement) {
  10946. value =
  10947. value.slice(0, matches.index) +
  10948. replacement +
  10949. value.slice(matchValueName.lastIndex);
  10950. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10951. }
  10952. }
  10953. return value;
  10954. };
  10955. replaceValueSymbols_1 = replaceValueSymbols;
  10956. return replaceValueSymbols_1;
  10957. }
  10958. var replaceSymbols_1;
  10959. var hasRequiredReplaceSymbols;
  10960. function requireReplaceSymbols () {
  10961. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10962. hasRequiredReplaceSymbols = 1;
  10963. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10964. const replaceSymbols = (css, replacements) => {
  10965. css.walk((node) => {
  10966. if (node.type === "decl" && node.value) {
  10967. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10968. } else if (node.type === "rule" && node.selector) {
  10969. node.selector = replaceValueSymbols(
  10970. node.selector.toString(),
  10971. replacements
  10972. );
  10973. } else if (node.type === "atrule" && node.params) {
  10974. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10975. }
  10976. });
  10977. };
  10978. replaceSymbols_1 = replaceSymbols;
  10979. return replaceSymbols_1;
  10980. }
  10981. var extractICSS_1;
  10982. var hasRequiredExtractICSS;
  10983. function requireExtractICSS () {
  10984. if (hasRequiredExtractICSS) return extractICSS_1;
  10985. hasRequiredExtractICSS = 1;
  10986. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10987. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10988. const getDeclsObject = (rule) => {
  10989. const object = {};
  10990. rule.walkDecls((decl) => {
  10991. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10992. object[before + decl.prop] = decl.value;
  10993. });
  10994. return object;
  10995. };
  10996. /**
  10997. *
  10998. * @param {string} css
  10999. * @param {boolean} removeRules
  11000. * @param {'auto' | 'rule' | 'at-rule'} mode
  11001. */
  11002. const extractICSS = (css, removeRules = true, mode = "auto") => {
  11003. const icssImports = {};
  11004. const icssExports = {};
  11005. function addImports(node, path) {
  11006. const unquoted = path.replace(/'|"/g, "");
  11007. icssImports[unquoted] = Object.assign(
  11008. icssImports[unquoted] || {},
  11009. getDeclsObject(node)
  11010. );
  11011. if (removeRules) {
  11012. node.remove();
  11013. }
  11014. }
  11015. function addExports(node) {
  11016. Object.assign(icssExports, getDeclsObject(node));
  11017. if (removeRules) {
  11018. node.remove();
  11019. }
  11020. }
  11021. css.each((node) => {
  11022. if (node.type === "rule" && mode !== "at-rule") {
  11023. if (node.selector.slice(0, 7) === ":import") {
  11024. const matches = importPattern.exec(node.selector);
  11025. if (matches) {
  11026. addImports(node, matches[1]);
  11027. }
  11028. }
  11029. if (node.selector === ":export") {
  11030. addExports(node);
  11031. }
  11032. }
  11033. if (node.type === "atrule" && mode !== "rule") {
  11034. if (node.name === "icss-import") {
  11035. const matches = balancedQuotes.exec(node.params);
  11036. if (matches) {
  11037. addImports(node, matches[1]);
  11038. }
  11039. }
  11040. if (node.name === "icss-export") {
  11041. addExports(node);
  11042. }
  11043. }
  11044. });
  11045. return { icssImports, icssExports };
  11046. };
  11047. extractICSS_1 = extractICSS;
  11048. return extractICSS_1;
  11049. }
  11050. var createICSSRules_1;
  11051. var hasRequiredCreateICSSRules;
  11052. function requireCreateICSSRules () {
  11053. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  11054. hasRequiredCreateICSSRules = 1;
  11055. const createImports = (imports, postcss, mode = "rule") => {
  11056. return Object.keys(imports).map((path) => {
  11057. const aliases = imports[path];
  11058. const declarations = Object.keys(aliases).map((key) =>
  11059. postcss.decl({
  11060. prop: key,
  11061. value: aliases[key],
  11062. raws: { before: "\n " },
  11063. })
  11064. );
  11065. const hasDeclarations = declarations.length > 0;
  11066. const rule =
  11067. mode === "rule"
  11068. ? postcss.rule({
  11069. selector: `:import('${path}')`,
  11070. raws: { after: hasDeclarations ? "\n" : "" },
  11071. })
  11072. : postcss.atRule({
  11073. name: "icss-import",
  11074. params: `'${path}'`,
  11075. raws: { after: hasDeclarations ? "\n" : "" },
  11076. });
  11077. if (hasDeclarations) {
  11078. rule.append(declarations);
  11079. }
  11080. return rule;
  11081. });
  11082. };
  11083. const createExports = (exports, postcss, mode = "rule") => {
  11084. const declarations = Object.keys(exports).map((key) =>
  11085. postcss.decl({
  11086. prop: key,
  11087. value: exports[key],
  11088. raws: { before: "\n " },
  11089. })
  11090. );
  11091. if (declarations.length === 0) {
  11092. return [];
  11093. }
  11094. const rule =
  11095. mode === "rule"
  11096. ? postcss.rule({
  11097. selector: `:export`,
  11098. raws: { after: "\n" },
  11099. })
  11100. : postcss.atRule({
  11101. name: "icss-export",
  11102. raws: { after: "\n" },
  11103. });
  11104. rule.append(declarations);
  11105. return [rule];
  11106. };
  11107. const createICSSRules = (imports, exports, postcss, mode) => [
  11108. ...createImports(imports, postcss, mode),
  11109. ...createExports(exports, postcss, mode),
  11110. ];
  11111. createICSSRules_1 = createICSSRules;
  11112. return createICSSRules_1;
  11113. }
  11114. var src$4;
  11115. var hasRequiredSrc$4;
  11116. function requireSrc$4 () {
  11117. if (hasRequiredSrc$4) return src$4;
  11118. hasRequiredSrc$4 = 1;
  11119. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  11120. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  11121. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  11122. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  11123. src$4 = {
  11124. replaceValueSymbols,
  11125. replaceSymbols,
  11126. extractICSS,
  11127. createICSSRules,
  11128. };
  11129. return src$4;
  11130. }
  11131. var hasRequiredParser$1;
  11132. function requireParser$1 () {
  11133. if (hasRequiredParser$1) return Parser;
  11134. hasRequiredParser$1 = 1;
  11135. Object.defineProperty(Parser, "__esModule", {
  11136. value: true
  11137. });
  11138. Parser.default = void 0;
  11139. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  11140. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11141. const importRegexp = /^:import\((.+)\)$/;
  11142. let Parser$1 = class Parser {
  11143. constructor(pathFetcher, trace) {
  11144. this.pathFetcher = pathFetcher;
  11145. this.plugin = this.plugin.bind(this);
  11146. this.exportTokens = {};
  11147. this.translations = {};
  11148. this.trace = trace;
  11149. }
  11150. plugin() {
  11151. const parser = this;
  11152. return {
  11153. postcssPlugin: "css-modules-parser",
  11154. async OnceExit(css) {
  11155. await Promise.all(parser.fetchAllImports(css));
  11156. parser.linkImportedSymbols(css);
  11157. return parser.extractExports(css);
  11158. }
  11159. };
  11160. }
  11161. fetchAllImports(css) {
  11162. let imports = [];
  11163. css.each(node => {
  11164. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11165. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11166. }
  11167. });
  11168. return imports;
  11169. }
  11170. linkImportedSymbols(css) {
  11171. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11172. }
  11173. extractExports(css) {
  11174. css.each(node => {
  11175. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11176. });
  11177. }
  11178. handleExport(exportNode) {
  11179. exportNode.each(decl => {
  11180. if (decl.type == "decl") {
  11181. Object.keys(this.translations).forEach(translation => {
  11182. decl.value = decl.value.replace(translation, this.translations[translation]);
  11183. });
  11184. this.exportTokens[decl.prop] = decl.value;
  11185. }
  11186. });
  11187. exportNode.remove();
  11188. }
  11189. async fetchImport(importNode, relativeTo, depNr) {
  11190. const file = importNode.selector.match(importRegexp)[1];
  11191. const depTrace = this.trace + String.fromCharCode(depNr);
  11192. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  11193. try {
  11194. importNode.each(decl => {
  11195. if (decl.type == "decl") {
  11196. this.translations[decl.prop] = exports[decl.value];
  11197. }
  11198. });
  11199. importNode.remove();
  11200. } catch (err) {
  11201. console.log(err);
  11202. }
  11203. }
  11204. };
  11205. Parser.default = Parser$1;
  11206. return Parser;
  11207. }
  11208. var saveJSON = {};
  11209. var hasRequiredSaveJSON;
  11210. function requireSaveJSON () {
  11211. if (hasRequiredSaveJSON) return saveJSON;
  11212. hasRequiredSaveJSON = 1;
  11213. Object.defineProperty(saveJSON, "__esModule", {
  11214. value: true
  11215. });
  11216. saveJSON.default = saveJSON$1;
  11217. var _fs = /*@__PURE__*/ requireFs();
  11218. function saveJSON$1(cssFile, json) {
  11219. return new Promise((resolve, reject) => {
  11220. const {
  11221. writeFile
  11222. } = (0, _fs.getFileSystem)();
  11223. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11224. });
  11225. }
  11226. return saveJSON;
  11227. }
  11228. var localsConvention = {};
  11229. /**
  11230. * lodash (Custom Build) <https://lodash.com/>
  11231. * Build: `lodash modularize exports="npm" -o ./`
  11232. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11233. * Released under MIT license <https://lodash.com/license>
  11234. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11235. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11236. */
  11237. var lodash_camelcase;
  11238. var hasRequiredLodash_camelcase;
  11239. function requireLodash_camelcase () {
  11240. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11241. hasRequiredLodash_camelcase = 1;
  11242. /** `Object#toString` result references. */
  11243. var symbolTag = '[object Symbol]';
  11244. /** Used to match words composed of alphanumeric characters. */
  11245. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11246. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11247. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11248. /** Used to compose unicode character classes. */
  11249. var rsAstralRange = '\\ud800-\\udfff',
  11250. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11251. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11252. rsDingbatRange = '\\u2700-\\u27bf',
  11253. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11254. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11255. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11256. rsPunctuationRange = '\\u2000-\\u206f',
  11257. 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',
  11258. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11259. rsVarRange = '\\ufe0e\\ufe0f',
  11260. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11261. /** Used to compose unicode capture groups. */
  11262. var rsApos = "['\u2019]",
  11263. rsAstral = '[' + rsAstralRange + ']',
  11264. rsBreak = '[' + rsBreakRange + ']',
  11265. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11266. rsDigits = '\\d+',
  11267. rsDingbat = '[' + rsDingbatRange + ']',
  11268. rsLower = '[' + rsLowerRange + ']',
  11269. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11270. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11271. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11272. rsNonAstral = '[^' + rsAstralRange + ']',
  11273. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11274. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11275. rsUpper = '[' + rsUpperRange + ']',
  11276. rsZWJ = '\\u200d';
  11277. /** Used to compose unicode regexes. */
  11278. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11279. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11280. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11281. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11282. reOptMod = rsModifier + '?',
  11283. rsOptVar = '[' + rsVarRange + ']?',
  11284. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11285. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11286. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11287. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11288. /** Used to match apostrophes. */
  11289. var reApos = RegExp(rsApos, 'g');
  11290. /**
  11291. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11292. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11293. */
  11294. var reComboMark = RegExp(rsCombo, 'g');
  11295. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11296. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11297. /** Used to match complex or compound words. */
  11298. var reUnicodeWord = RegExp([
  11299. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11300. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11301. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11302. rsUpper + '+' + rsOptUpperContr,
  11303. rsDigits,
  11304. rsEmoji
  11305. ].join('|'), 'g');
  11306. /** 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/). */
  11307. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11308. /** Used to detect strings that need a more robust regexp to match words. */
  11309. 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 ]/;
  11310. /** Used to map Latin Unicode letters to basic Latin letters. */
  11311. var deburredLetters = {
  11312. // Latin-1 Supplement block.
  11313. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11314. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11315. '\xc7': 'C', '\xe7': 'c',
  11316. '\xd0': 'D', '\xf0': 'd',
  11317. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11318. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11319. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11320. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11321. '\xd1': 'N', '\xf1': 'n',
  11322. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11323. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11324. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11325. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11326. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11327. '\xc6': 'Ae', '\xe6': 'ae',
  11328. '\xde': 'Th', '\xfe': 'th',
  11329. '\xdf': 'ss',
  11330. // Latin Extended-A block.
  11331. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11332. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11333. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11334. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11335. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11336. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11337. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11338. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11339. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11340. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11341. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11342. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11343. '\u0134': 'J', '\u0135': 'j',
  11344. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11345. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11346. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11347. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11348. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11349. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11350. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11351. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11352. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11353. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11354. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11355. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11356. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11357. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11358. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11359. '\u0174': 'W', '\u0175': 'w',
  11360. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11361. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11362. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11363. '\u0132': 'IJ', '\u0133': 'ij',
  11364. '\u0152': 'Oe', '\u0153': 'oe',
  11365. '\u0149': "'n", '\u017f': 'ss'
  11366. };
  11367. /** Detect free variable `global` from Node.js. */
  11368. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11369. /** Detect free variable `self`. */
  11370. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11371. /** Used as a reference to the global object. */
  11372. var root = freeGlobal || freeSelf || Function('return this')();
  11373. /**
  11374. * A specialized version of `_.reduce` for arrays without support for
  11375. * iteratee shorthands.
  11376. *
  11377. * @private
  11378. * @param {Array} [array] The array to iterate over.
  11379. * @param {Function} iteratee The function invoked per iteration.
  11380. * @param {*} [accumulator] The initial value.
  11381. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11382. * the initial value.
  11383. * @returns {*} Returns the accumulated value.
  11384. */
  11385. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11386. var index = -1,
  11387. length = array ? array.length : 0;
  11388. while (++index < length) {
  11389. accumulator = iteratee(accumulator, array[index], index, array);
  11390. }
  11391. return accumulator;
  11392. }
  11393. /**
  11394. * Converts an ASCII `string` to an array.
  11395. *
  11396. * @private
  11397. * @param {string} string The string to convert.
  11398. * @returns {Array} Returns the converted array.
  11399. */
  11400. function asciiToArray(string) {
  11401. return string.split('');
  11402. }
  11403. /**
  11404. * Splits an ASCII `string` into an array of its words.
  11405. *
  11406. * @private
  11407. * @param {string} The string to inspect.
  11408. * @returns {Array} Returns the words of `string`.
  11409. */
  11410. function asciiWords(string) {
  11411. return string.match(reAsciiWord) || [];
  11412. }
  11413. /**
  11414. * The base implementation of `_.propertyOf` without support for deep paths.
  11415. *
  11416. * @private
  11417. * @param {Object} object The object to query.
  11418. * @returns {Function} Returns the new accessor function.
  11419. */
  11420. function basePropertyOf(object) {
  11421. return function(key) {
  11422. return object == null ? undefined : object[key];
  11423. };
  11424. }
  11425. /**
  11426. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11427. * letters to basic Latin letters.
  11428. *
  11429. * @private
  11430. * @param {string} letter The matched letter to deburr.
  11431. * @returns {string} Returns the deburred letter.
  11432. */
  11433. var deburrLetter = basePropertyOf(deburredLetters);
  11434. /**
  11435. * Checks if `string` contains Unicode symbols.
  11436. *
  11437. * @private
  11438. * @param {string} string The string to inspect.
  11439. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11440. */
  11441. function hasUnicode(string) {
  11442. return reHasUnicode.test(string);
  11443. }
  11444. /**
  11445. * Checks if `string` contains a word composed of Unicode symbols.
  11446. *
  11447. * @private
  11448. * @param {string} string The string to inspect.
  11449. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11450. */
  11451. function hasUnicodeWord(string) {
  11452. return reHasUnicodeWord.test(string);
  11453. }
  11454. /**
  11455. * Converts `string` to an array.
  11456. *
  11457. * @private
  11458. * @param {string} string The string to convert.
  11459. * @returns {Array} Returns the converted array.
  11460. */
  11461. function stringToArray(string) {
  11462. return hasUnicode(string)
  11463. ? unicodeToArray(string)
  11464. : asciiToArray(string);
  11465. }
  11466. /**
  11467. * Converts a Unicode `string` to an array.
  11468. *
  11469. * @private
  11470. * @param {string} string The string to convert.
  11471. * @returns {Array} Returns the converted array.
  11472. */
  11473. function unicodeToArray(string) {
  11474. return string.match(reUnicode) || [];
  11475. }
  11476. /**
  11477. * Splits a Unicode `string` into an array of its words.
  11478. *
  11479. * @private
  11480. * @param {string} The string to inspect.
  11481. * @returns {Array} Returns the words of `string`.
  11482. */
  11483. function unicodeWords(string) {
  11484. return string.match(reUnicodeWord) || [];
  11485. }
  11486. /** Used for built-in method references. */
  11487. var objectProto = Object.prototype;
  11488. /**
  11489. * Used to resolve the
  11490. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11491. * of values.
  11492. */
  11493. var objectToString = objectProto.toString;
  11494. /** Built-in value references. */
  11495. var Symbol = root.Symbol;
  11496. /** Used to convert symbols to primitives and strings. */
  11497. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11498. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11499. /**
  11500. * The base implementation of `_.slice` without an iteratee call guard.
  11501. *
  11502. * @private
  11503. * @param {Array} array The array to slice.
  11504. * @param {number} [start=0] The start position.
  11505. * @param {number} [end=array.length] The end position.
  11506. * @returns {Array} Returns the slice of `array`.
  11507. */
  11508. function baseSlice(array, start, end) {
  11509. var index = -1,
  11510. length = array.length;
  11511. if (start < 0) {
  11512. start = -start > length ? 0 : (length + start);
  11513. }
  11514. end = end > length ? length : end;
  11515. if (end < 0) {
  11516. end += length;
  11517. }
  11518. length = start > end ? 0 : ((end - start) >>> 0);
  11519. start >>>= 0;
  11520. var result = Array(length);
  11521. while (++index < length) {
  11522. result[index] = array[index + start];
  11523. }
  11524. return result;
  11525. }
  11526. /**
  11527. * The base implementation of `_.toString` which doesn't convert nullish
  11528. * values to empty strings.
  11529. *
  11530. * @private
  11531. * @param {*} value The value to process.
  11532. * @returns {string} Returns the string.
  11533. */
  11534. function baseToString(value) {
  11535. // Exit early for strings to avoid a performance hit in some environments.
  11536. if (typeof value == 'string') {
  11537. return value;
  11538. }
  11539. if (isSymbol(value)) {
  11540. return symbolToString ? symbolToString.call(value) : '';
  11541. }
  11542. var result = (value + '');
  11543. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  11544. }
  11545. /**
  11546. * Casts `array` to a slice if it's needed.
  11547. *
  11548. * @private
  11549. * @param {Array} array The array to inspect.
  11550. * @param {number} start The start position.
  11551. * @param {number} [end=array.length] The end position.
  11552. * @returns {Array} Returns the cast slice.
  11553. */
  11554. function castSlice(array, start, end) {
  11555. var length = array.length;
  11556. end = end === undefined ? length : end;
  11557. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11558. }
  11559. /**
  11560. * Creates a function like `_.lowerFirst`.
  11561. *
  11562. * @private
  11563. * @param {string} methodName The name of the `String` case method to use.
  11564. * @returns {Function} Returns the new case function.
  11565. */
  11566. function createCaseFirst(methodName) {
  11567. return function(string) {
  11568. string = toString(string);
  11569. var strSymbols = hasUnicode(string)
  11570. ? stringToArray(string)
  11571. : undefined;
  11572. var chr = strSymbols
  11573. ? strSymbols[0]
  11574. : string.charAt(0);
  11575. var trailing = strSymbols
  11576. ? castSlice(strSymbols, 1).join('')
  11577. : string.slice(1);
  11578. return chr[methodName]() + trailing;
  11579. };
  11580. }
  11581. /**
  11582. * Creates a function like `_.camelCase`.
  11583. *
  11584. * @private
  11585. * @param {Function} callback The function to combine each word.
  11586. * @returns {Function} Returns the new compounder function.
  11587. */
  11588. function createCompounder(callback) {
  11589. return function(string) {
  11590. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11591. };
  11592. }
  11593. /**
  11594. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11595. * and has a `typeof` result of "object".
  11596. *
  11597. * @static
  11598. * @memberOf _
  11599. * @since 4.0.0
  11600. * @category Lang
  11601. * @param {*} value The value to check.
  11602. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11603. * @example
  11604. *
  11605. * _.isObjectLike({});
  11606. * // => true
  11607. *
  11608. * _.isObjectLike([1, 2, 3]);
  11609. * // => true
  11610. *
  11611. * _.isObjectLike(_.noop);
  11612. * // => false
  11613. *
  11614. * _.isObjectLike(null);
  11615. * // => false
  11616. */
  11617. function isObjectLike(value) {
  11618. return !!value && typeof value == 'object';
  11619. }
  11620. /**
  11621. * Checks if `value` is classified as a `Symbol` primitive or object.
  11622. *
  11623. * @static
  11624. * @memberOf _
  11625. * @since 4.0.0
  11626. * @category Lang
  11627. * @param {*} value The value to check.
  11628. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11629. * @example
  11630. *
  11631. * _.isSymbol(Symbol.iterator);
  11632. * // => true
  11633. *
  11634. * _.isSymbol('abc');
  11635. * // => false
  11636. */
  11637. function isSymbol(value) {
  11638. return typeof value == 'symbol' ||
  11639. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11640. }
  11641. /**
  11642. * Converts `value` to a string. An empty string is returned for `null`
  11643. * and `undefined` values. The sign of `-0` is preserved.
  11644. *
  11645. * @static
  11646. * @memberOf _
  11647. * @since 4.0.0
  11648. * @category Lang
  11649. * @param {*} value The value to process.
  11650. * @returns {string} Returns the string.
  11651. * @example
  11652. *
  11653. * _.toString(null);
  11654. * // => ''
  11655. *
  11656. * _.toString(-0);
  11657. * // => '-0'
  11658. *
  11659. * _.toString([1, 2, 3]);
  11660. * // => '1,2,3'
  11661. */
  11662. function toString(value) {
  11663. return value == null ? '' : baseToString(value);
  11664. }
  11665. /**
  11666. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11667. *
  11668. * @static
  11669. * @memberOf _
  11670. * @since 3.0.0
  11671. * @category String
  11672. * @param {string} [string=''] The string to convert.
  11673. * @returns {string} Returns the camel cased string.
  11674. * @example
  11675. *
  11676. * _.camelCase('Foo Bar');
  11677. * // => 'fooBar'
  11678. *
  11679. * _.camelCase('--foo-bar--');
  11680. * // => 'fooBar'
  11681. *
  11682. * _.camelCase('__FOO_BAR__');
  11683. * // => 'fooBar'
  11684. */
  11685. var camelCase = createCompounder(function(result, word, index) {
  11686. word = word.toLowerCase();
  11687. return result + (index ? capitalize(word) : word);
  11688. });
  11689. /**
  11690. * Converts the first character of `string` to upper case and the remaining
  11691. * to lower case.
  11692. *
  11693. * @static
  11694. * @memberOf _
  11695. * @since 3.0.0
  11696. * @category String
  11697. * @param {string} [string=''] The string to capitalize.
  11698. * @returns {string} Returns the capitalized string.
  11699. * @example
  11700. *
  11701. * _.capitalize('FRED');
  11702. * // => 'Fred'
  11703. */
  11704. function capitalize(string) {
  11705. return upperFirst(toString(string).toLowerCase());
  11706. }
  11707. /**
  11708. * Deburrs `string` by converting
  11709. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11710. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11711. * letters to basic Latin letters and removing
  11712. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11713. *
  11714. * @static
  11715. * @memberOf _
  11716. * @since 3.0.0
  11717. * @category String
  11718. * @param {string} [string=''] The string to deburr.
  11719. * @returns {string} Returns the deburred string.
  11720. * @example
  11721. *
  11722. * _.deburr('déjà vu');
  11723. * // => 'deja vu'
  11724. */
  11725. function deburr(string) {
  11726. string = toString(string);
  11727. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11728. }
  11729. /**
  11730. * Converts the first character of `string` to upper case.
  11731. *
  11732. * @static
  11733. * @memberOf _
  11734. * @since 4.0.0
  11735. * @category String
  11736. * @param {string} [string=''] The string to convert.
  11737. * @returns {string} Returns the converted string.
  11738. * @example
  11739. *
  11740. * _.upperFirst('fred');
  11741. * // => 'Fred'
  11742. *
  11743. * _.upperFirst('FRED');
  11744. * // => 'FRED'
  11745. */
  11746. var upperFirst = createCaseFirst('toUpperCase');
  11747. /**
  11748. * Splits `string` into an array of its words.
  11749. *
  11750. * @static
  11751. * @memberOf _
  11752. * @since 3.0.0
  11753. * @category String
  11754. * @param {string} [string=''] The string to inspect.
  11755. * @param {RegExp|string} [pattern] The pattern to match words.
  11756. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11757. * @returns {Array} Returns the words of `string`.
  11758. * @example
  11759. *
  11760. * _.words('fred, barney, & pebbles');
  11761. * // => ['fred', 'barney', 'pebbles']
  11762. *
  11763. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11764. * // => ['fred', 'barney', '&', 'pebbles']
  11765. */
  11766. function words(string, pattern, guard) {
  11767. string = toString(string);
  11768. pattern = pattern;
  11769. if (pattern === undefined) {
  11770. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11771. }
  11772. return string.match(pattern) || [];
  11773. }
  11774. lodash_camelcase = camelCase;
  11775. return lodash_camelcase;
  11776. }
  11777. var hasRequiredLocalsConvention;
  11778. function requireLocalsConvention () {
  11779. if (hasRequiredLocalsConvention) return localsConvention;
  11780. hasRequiredLocalsConvention = 1;
  11781. Object.defineProperty(localsConvention, "__esModule", {
  11782. value: true
  11783. });
  11784. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11785. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11786. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11787. function dashesCamelCase(string) {
  11788. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11789. }
  11790. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11791. const isFunc = typeof localsConvention === "function";
  11792. return (tokens, [className, value]) => {
  11793. if (isFunc) {
  11794. const convention = localsConvention(className, value, inputFile);
  11795. tokens[convention] = value;
  11796. return tokens;
  11797. }
  11798. switch (localsConvention) {
  11799. case "camelCase":
  11800. tokens[className] = value;
  11801. tokens[(0, _lodash.default)(className)] = value;
  11802. break;
  11803. case "camelCaseOnly":
  11804. tokens[(0, _lodash.default)(className)] = value;
  11805. break;
  11806. case "dashes":
  11807. tokens[className] = value;
  11808. tokens[dashesCamelCase(className)] = value;
  11809. break;
  11810. case "dashesOnly":
  11811. tokens[dashesCamelCase(className)] = value;
  11812. break;
  11813. }
  11814. return tokens;
  11815. };
  11816. }
  11817. return localsConvention;
  11818. }
  11819. var FileSystemLoader = {};
  11820. var hasRequiredFileSystemLoader;
  11821. function requireFileSystemLoader () {
  11822. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11823. hasRequiredFileSystemLoader = 1;
  11824. Object.defineProperty(FileSystemLoader, "__esModule", {
  11825. value: true
  11826. });
  11827. FileSystemLoader.default = void 0;
  11828. var _postcss = _interopRequireDefault(require$$0$1);
  11829. var _path = _interopRequireDefault(path$1);
  11830. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  11831. var _fs = /*@__PURE__*/ requireFs();
  11832. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11833. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11834. class Core {
  11835. constructor(plugins) {
  11836. this.plugins = plugins || Core.defaultPlugins;
  11837. }
  11838. async load(sourceString, sourcePath, trace, pathFetcher) {
  11839. const parser = new _Parser.default(pathFetcher, trace);
  11840. const plugins = this.plugins.concat([parser.plugin()]);
  11841. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11842. from: sourcePath
  11843. });
  11844. return {
  11845. injectableSource: result.css,
  11846. exportTokens: parser.exportTokens
  11847. };
  11848. }
  11849. } // Sorts dependencies in the following way:
  11850. // AAA comes before AA and A
  11851. // AB comes after AA and before A
  11852. // All Bs come after all As
  11853. // This ensures that the files are always returned in the following order:
  11854. // - In the order they were required, except
  11855. // - After all their dependencies
  11856. const traceKeySorter = (a, b) => {
  11857. if (a.length < b.length) {
  11858. return a < b.substring(0, a.length) ? -1 : 1;
  11859. }
  11860. if (a.length > b.length) {
  11861. return a.substring(0, b.length) <= b ? -1 : 1;
  11862. }
  11863. return a < b ? -1 : 1;
  11864. };
  11865. let FileSystemLoader$1 = class FileSystemLoader {
  11866. constructor(root, plugins, fileResolve) {
  11867. if (root === "/" && process.platform === "win32") {
  11868. const cwdDrive = process.cwd().slice(0, 3);
  11869. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11870. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11871. }
  11872. root = cwdDrive;
  11873. }
  11874. this.root = root;
  11875. this.fileResolve = fileResolve;
  11876. this.sources = {};
  11877. this.traces = {};
  11878. this.importNr = 0;
  11879. this.core = new Core(plugins);
  11880. this.tokensByFile = {};
  11881. this.fs = (0, _fs.getFileSystem)();
  11882. }
  11883. async fetch(_newPath, relativeTo, _trace) {
  11884. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11885. const trace = _trace || String.fromCharCode(this.importNr++);
  11886. const useFileResolve = typeof this.fileResolve === "function";
  11887. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11888. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11889. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11890. }
  11891. const relativeDir = _path.default.dirname(relativeTo);
  11892. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11893. 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
  11894. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11895. try {
  11896. fileRelativePath = require.resolve(newPath);
  11897. } catch (e) {// noop
  11898. }
  11899. }
  11900. const tokens = this.tokensByFile[fileRelativePath];
  11901. if (tokens) return tokens;
  11902. return new Promise((resolve, reject) => {
  11903. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11904. if (err) reject(err);
  11905. const {
  11906. injectableSource,
  11907. exportTokens
  11908. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11909. this.sources[fileRelativePath] = injectableSource;
  11910. this.traces[trace] = fileRelativePath;
  11911. this.tokensByFile[fileRelativePath] = exportTokens;
  11912. resolve(exportTokens);
  11913. });
  11914. });
  11915. }
  11916. get finalSource() {
  11917. const traces = this.traces;
  11918. const sources = this.sources;
  11919. let written = new Set();
  11920. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11921. const filename = traces[key];
  11922. if (written.has(filename)) {
  11923. return null;
  11924. }
  11925. written.add(filename);
  11926. return sources[filename];
  11927. }).join("");
  11928. }
  11929. };
  11930. FileSystemLoader.default = FileSystemLoader$1;
  11931. return FileSystemLoader;
  11932. }
  11933. var scoping = {};
  11934. var src$3 = {exports: {}};
  11935. var topologicalSort_1;
  11936. var hasRequiredTopologicalSort;
  11937. function requireTopologicalSort () {
  11938. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11939. hasRequiredTopologicalSort = 1;
  11940. const PERMANENT_MARKER = 2;
  11941. const TEMPORARY_MARKER = 1;
  11942. function createError(node, graph) {
  11943. const er = new Error("Nondeterministic import's order");
  11944. const related = graph[node];
  11945. const relatedNode = related.find(
  11946. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11947. );
  11948. er.nodes = [node, relatedNode];
  11949. return er;
  11950. }
  11951. function walkGraph(node, graph, state, result, strict) {
  11952. if (state[node] === PERMANENT_MARKER) {
  11953. return;
  11954. }
  11955. if (state[node] === TEMPORARY_MARKER) {
  11956. if (strict) {
  11957. return createError(node, graph);
  11958. }
  11959. return;
  11960. }
  11961. state[node] = TEMPORARY_MARKER;
  11962. const children = graph[node];
  11963. const length = children.length;
  11964. for (let i = 0; i < length; ++i) {
  11965. const error = walkGraph(children[i], graph, state, result, strict);
  11966. if (error instanceof Error) {
  11967. return error;
  11968. }
  11969. }
  11970. state[node] = PERMANENT_MARKER;
  11971. result.push(node);
  11972. }
  11973. function topologicalSort(graph, strict) {
  11974. const result = [];
  11975. const state = {};
  11976. const nodes = Object.keys(graph);
  11977. const length = nodes.length;
  11978. for (let i = 0; i < length; ++i) {
  11979. const er = walkGraph(nodes[i], graph, state, result, strict);
  11980. if (er instanceof Error) {
  11981. return er;
  11982. }
  11983. }
  11984. return result;
  11985. }
  11986. topologicalSort_1 = topologicalSort;
  11987. return topologicalSort_1;
  11988. }
  11989. var hasRequiredSrc$3;
  11990. function requireSrc$3 () {
  11991. if (hasRequiredSrc$3) return src$3.exports;
  11992. hasRequiredSrc$3 = 1;
  11993. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  11994. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11995. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11996. const VISITED_MARKER = 1;
  11997. /**
  11998. * :import('G') {}
  11999. *
  12000. * Rule
  12001. * composes: ... from 'A'
  12002. * composes: ... from 'B'
  12003. * Rule
  12004. * composes: ... from 'A'
  12005. * composes: ... from 'A'
  12006. * composes: ... from 'C'
  12007. *
  12008. * Results in:
  12009. *
  12010. * graph: {
  12011. * G: [],
  12012. * A: [],
  12013. * B: ['A'],
  12014. * C: ['A'],
  12015. * }
  12016. */
  12017. function addImportToGraph(importId, parentId, graph, visited) {
  12018. const siblingsId = parentId + "_" + "siblings";
  12019. const visitedId = parentId + "_" + importId;
  12020. if (visited[visitedId] !== VISITED_MARKER) {
  12021. if (!Array.isArray(visited[siblingsId])) {
  12022. visited[siblingsId] = [];
  12023. }
  12024. const siblings = visited[siblingsId];
  12025. if (Array.isArray(graph[importId])) {
  12026. graph[importId] = graph[importId].concat(siblings);
  12027. } else {
  12028. graph[importId] = siblings.slice();
  12029. }
  12030. visited[visitedId] = VISITED_MARKER;
  12031. siblings.push(importId);
  12032. }
  12033. }
  12034. src$3.exports = (options = {}) => {
  12035. let importIndex = 0;
  12036. const createImportedName =
  12037. typeof options.createImportedName !== "function"
  12038. ? (importName /*, path*/) =>
  12039. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  12040. : options.createImportedName;
  12041. const failOnWrongOrder = options.failOnWrongOrder;
  12042. return {
  12043. postcssPlugin: "postcss-modules-extract-imports",
  12044. prepare() {
  12045. const graph = {};
  12046. const visited = {};
  12047. const existingImports = {};
  12048. const importDecls = {};
  12049. const imports = {};
  12050. return {
  12051. Once(root, postcss) {
  12052. // Check the existing imports order and save refs
  12053. root.walkRules((rule) => {
  12054. const matches = icssImport.exec(rule.selector);
  12055. if (matches) {
  12056. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  12057. const importPath = doubleQuotePath || singleQuotePath;
  12058. addImportToGraph(importPath, "root", graph, visited);
  12059. existingImports[importPath] = rule;
  12060. }
  12061. });
  12062. root.walkDecls(/^composes$/, (declaration) => {
  12063. const multiple = declaration.value.split(",");
  12064. const values = [];
  12065. multiple.forEach((value) => {
  12066. const matches = value.trim().match(matchImports);
  12067. if (!matches) {
  12068. values.push(value);
  12069. return;
  12070. }
  12071. let tmpSymbols;
  12072. let [
  12073. ,
  12074. /*match*/ symbols,
  12075. doubleQuotePath,
  12076. singleQuotePath,
  12077. global,
  12078. ] = matches;
  12079. if (global) {
  12080. // Composing globals simply means changing these classes to wrap them in global(name)
  12081. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  12082. } else {
  12083. const importPath = doubleQuotePath || singleQuotePath;
  12084. let parent = declaration.parent;
  12085. let parentIndexes = "";
  12086. while (parent.type !== "root") {
  12087. parentIndexes =
  12088. parent.parent.index(parent) + "_" + parentIndexes;
  12089. parent = parent.parent;
  12090. }
  12091. const { selector } = declaration.parent;
  12092. const parentRule = `_${parentIndexes}${selector}`;
  12093. addImportToGraph(importPath, parentRule, graph, visited);
  12094. importDecls[importPath] = declaration;
  12095. imports[importPath] = imports[importPath] || {};
  12096. tmpSymbols = symbols.split(/\s+/).map((s) => {
  12097. if (!imports[importPath][s]) {
  12098. imports[importPath][s] = createImportedName(s, importPath);
  12099. }
  12100. return imports[importPath][s];
  12101. });
  12102. }
  12103. values.push(tmpSymbols.join(" "));
  12104. });
  12105. declaration.value = values.join(", ");
  12106. });
  12107. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  12108. if (importsOrder instanceof Error) {
  12109. const importPath = importsOrder.nodes.find((importPath) =>
  12110. // eslint-disable-next-line no-prototype-builtins
  12111. importDecls.hasOwnProperty(importPath)
  12112. );
  12113. const decl = importDecls[importPath];
  12114. throw decl.error(
  12115. "Failed to resolve order of composed modules " +
  12116. importsOrder.nodes
  12117. .map((importPath) => "`" + importPath + "`")
  12118. .join(", ") +
  12119. ".",
  12120. {
  12121. plugin: "postcss-modules-extract-imports",
  12122. word: "composes",
  12123. }
  12124. );
  12125. }
  12126. let lastImportRule;
  12127. importsOrder.forEach((path) => {
  12128. const importedSymbols = imports[path];
  12129. let rule = existingImports[path];
  12130. if (!rule && importedSymbols) {
  12131. rule = postcss.rule({
  12132. selector: `:import("${path}")`,
  12133. raws: { after: "\n" },
  12134. });
  12135. if (lastImportRule) {
  12136. root.insertAfter(lastImportRule, rule);
  12137. } else {
  12138. root.prepend(rule);
  12139. }
  12140. }
  12141. lastImportRule = rule;
  12142. if (!importedSymbols) {
  12143. return;
  12144. }
  12145. Object.keys(importedSymbols).forEach((importedSymbol) => {
  12146. rule.append(
  12147. postcss.decl({
  12148. value: importedSymbol,
  12149. prop: importedSymbols[importedSymbol],
  12150. raws: { before: "\n " },
  12151. })
  12152. );
  12153. });
  12154. });
  12155. },
  12156. };
  12157. },
  12158. };
  12159. };
  12160. src$3.exports.postcss = true;
  12161. return src$3.exports;
  12162. }
  12163. var wasmHash = {exports: {}};
  12164. /*
  12165. MIT License http://www.opensource.org/licenses/mit-license.php
  12166. Author Tobias Koppers @sokra
  12167. */
  12168. var hasRequiredWasmHash;
  12169. function requireWasmHash () {
  12170. if (hasRequiredWasmHash) return wasmHash.exports;
  12171. hasRequiredWasmHash = 1;
  12172. // 65536 is the size of a wasm memory page
  12173. // 64 is the maximum chunk size for every possible wasm hash implementation
  12174. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12175. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12176. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
  12177. class WasmHash {
  12178. /**
  12179. * @param {WebAssembly.Instance} instance wasm instance
  12180. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12181. * @param {number} chunkSize size of data chunks passed to wasm
  12182. * @param {number} digestSize size of digest returned by wasm
  12183. */
  12184. constructor(instance, instancesPool, chunkSize, digestSize) {
  12185. const exports = /** @type {any} */ (instance.exports);
  12186. exports.init();
  12187. this.exports = exports;
  12188. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  12189. this.buffered = 0;
  12190. this.instancesPool = instancesPool;
  12191. this.chunkSize = chunkSize;
  12192. this.digestSize = digestSize;
  12193. }
  12194. reset() {
  12195. this.buffered = 0;
  12196. this.exports.init();
  12197. }
  12198. /**
  12199. * @param {Buffer | string} data data
  12200. * @param {BufferEncoding=} encoding encoding
  12201. * @returns {this} itself
  12202. */
  12203. update(data, encoding) {
  12204. if (typeof data === "string") {
  12205. while (data.length > MAX_SHORT_STRING) {
  12206. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12207. data = data.slice(MAX_SHORT_STRING);
  12208. }
  12209. this._updateWithShortString(data, encoding);
  12210. return this;
  12211. }
  12212. this._updateWithBuffer(data);
  12213. return this;
  12214. }
  12215. /**
  12216. * @param {string} data data
  12217. * @param {BufferEncoding=} encoding encoding
  12218. * @returns {void}
  12219. */
  12220. _updateWithShortString(data, encoding) {
  12221. const { exports, buffered, mem, chunkSize } = this;
  12222. let endPos;
  12223. if (data.length < 70) {
  12224. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12225. endPos = buffered;
  12226. for (let i = 0; i < data.length; i++) {
  12227. const cc = data.charCodeAt(i);
  12228. if (cc < 0x80) {
  12229. mem[endPos++] = cc;
  12230. } else if (cc < 0x800) {
  12231. mem[endPos] = (cc >> 6) | 0xc0;
  12232. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12233. endPos += 2;
  12234. } else {
  12235. // bail-out for weird chars
  12236. endPos += mem.write(data.slice(i), endPos, encoding);
  12237. break;
  12238. }
  12239. }
  12240. } else if (encoding === "latin1") {
  12241. endPos = buffered;
  12242. for (let i = 0; i < data.length; i++) {
  12243. const cc = data.charCodeAt(i);
  12244. mem[endPos++] = cc;
  12245. }
  12246. } else {
  12247. endPos = buffered + mem.write(data, buffered, encoding);
  12248. }
  12249. } else {
  12250. endPos = buffered + mem.write(data, buffered, encoding);
  12251. }
  12252. if (endPos < chunkSize) {
  12253. this.buffered = endPos;
  12254. } else {
  12255. const l = endPos & ~(this.chunkSize - 1);
  12256. exports.update(l);
  12257. const newBuffered = endPos - l;
  12258. this.buffered = newBuffered;
  12259. if (newBuffered > 0) {
  12260. mem.copyWithin(0, l, endPos);
  12261. }
  12262. }
  12263. }
  12264. /**
  12265. * @param {Buffer} data data
  12266. * @returns {void}
  12267. */
  12268. _updateWithBuffer(data) {
  12269. const { exports, buffered, mem } = this;
  12270. const length = data.length;
  12271. if (buffered + length < this.chunkSize) {
  12272. data.copy(mem, buffered, 0, length);
  12273. this.buffered += length;
  12274. } else {
  12275. const l = (buffered + length) & ~(this.chunkSize - 1);
  12276. if (l > 65536) {
  12277. let i = 65536 - buffered;
  12278. data.copy(mem, buffered, 0, i);
  12279. exports.update(65536);
  12280. const stop = l - buffered - 65536;
  12281. while (i < stop) {
  12282. data.copy(mem, 0, i, i + 65536);
  12283. exports.update(65536);
  12284. i += 65536;
  12285. }
  12286. data.copy(mem, 0, i, l - buffered);
  12287. exports.update(l - buffered - i);
  12288. } else {
  12289. data.copy(mem, buffered, 0, l - buffered);
  12290. exports.update(l);
  12291. }
  12292. const newBuffered = length + buffered - l;
  12293. this.buffered = newBuffered;
  12294. if (newBuffered > 0) {
  12295. data.copy(mem, 0, length - newBuffered, length);
  12296. }
  12297. }
  12298. }
  12299. digest(type) {
  12300. const { exports, buffered, mem, digestSize } = this;
  12301. exports.final(buffered);
  12302. this.instancesPool.push(this);
  12303. const hex = mem.toString("latin1", 0, digestSize);
  12304. if (type === "hex") {
  12305. return hex;
  12306. }
  12307. if (type === "binary" || !type) {
  12308. return Buffer.from(hex, "hex");
  12309. }
  12310. return Buffer.from(hex, "hex").toString(type);
  12311. }
  12312. }
  12313. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12314. if (instancesPool.length > 0) {
  12315. const old = instancesPool.pop();
  12316. old.reset();
  12317. return old;
  12318. } else {
  12319. return new WasmHash(
  12320. new WebAssembly.Instance(wasmModule),
  12321. instancesPool,
  12322. chunkSize,
  12323. digestSize
  12324. );
  12325. }
  12326. };
  12327. wasmHash.exports = create;
  12328. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12329. return wasmHash.exports;
  12330. }
  12331. /*
  12332. MIT License http://www.opensource.org/licenses/mit-license.php
  12333. Author Tobias Koppers @sokra
  12334. */
  12335. var xxhash64_1;
  12336. var hasRequiredXxhash64;
  12337. function requireXxhash64 () {
  12338. if (hasRequiredXxhash64) return xxhash64_1;
  12339. hasRequiredXxhash64 = 1;
  12340. const create = /*@__PURE__*/ requireWasmHash();
  12341. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12342. const xxhash64 = new WebAssembly.Module(
  12343. Buffer.from(
  12344. // 1173 bytes
  12345. "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",
  12346. "base64"
  12347. )
  12348. );
  12349. //#endregion
  12350. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12351. return xxhash64_1;
  12352. }
  12353. var BatchedHash_1;
  12354. var hasRequiredBatchedHash;
  12355. function requireBatchedHash () {
  12356. if (hasRequiredBatchedHash) return BatchedHash_1;
  12357. hasRequiredBatchedHash = 1;
  12358. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12359. class BatchedHash {
  12360. constructor(hash) {
  12361. this.string = undefined;
  12362. this.encoding = undefined;
  12363. this.hash = hash;
  12364. }
  12365. /**
  12366. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12367. * @param {string|Buffer} data data
  12368. * @param {string=} inputEncoding data encoding
  12369. * @returns {this} updated hash
  12370. */
  12371. update(data, inputEncoding) {
  12372. if (this.string !== undefined) {
  12373. if (
  12374. typeof data === "string" &&
  12375. inputEncoding === this.encoding &&
  12376. this.string.length + data.length < MAX_SHORT_STRING
  12377. ) {
  12378. this.string += data;
  12379. return this;
  12380. }
  12381. this.hash.update(this.string, this.encoding);
  12382. this.string = undefined;
  12383. }
  12384. if (typeof data === "string") {
  12385. if (
  12386. data.length < MAX_SHORT_STRING &&
  12387. // base64 encoding is not valid since it may contain padding chars
  12388. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12389. ) {
  12390. this.string = data;
  12391. this.encoding = inputEncoding;
  12392. } else {
  12393. this.hash.update(data, inputEncoding);
  12394. }
  12395. } else {
  12396. this.hash.update(data);
  12397. }
  12398. return this;
  12399. }
  12400. /**
  12401. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12402. * @param {string=} encoding encoding of the return value
  12403. * @returns {string|Buffer} digest
  12404. */
  12405. digest(encoding) {
  12406. if (this.string !== undefined) {
  12407. this.hash.update(this.string, this.encoding);
  12408. }
  12409. return this.hash.digest(encoding);
  12410. }
  12411. }
  12412. BatchedHash_1 = BatchedHash;
  12413. return BatchedHash_1;
  12414. }
  12415. /*
  12416. MIT License http://www.opensource.org/licenses/mit-license.php
  12417. Author Tobias Koppers @sokra
  12418. */
  12419. var md4_1;
  12420. var hasRequiredMd4;
  12421. function requireMd4 () {
  12422. if (hasRequiredMd4) return md4_1;
  12423. hasRequiredMd4 = 1;
  12424. const create = /*@__PURE__*/ requireWasmHash();
  12425. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12426. const md4 = new WebAssembly.Module(
  12427. Buffer.from(
  12428. // 2150 bytes
  12429. "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=",
  12430. "base64"
  12431. )
  12432. );
  12433. //#endregion
  12434. md4_1 = create.bind(null, md4, [], 64, 32);
  12435. return md4_1;
  12436. }
  12437. var BulkUpdateDecorator_1;
  12438. var hasRequiredBulkUpdateDecorator;
  12439. function requireBulkUpdateDecorator () {
  12440. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12441. hasRequiredBulkUpdateDecorator = 1;
  12442. const BULK_SIZE = 2000;
  12443. // We are using an object instead of a Map as this will stay static during the runtime
  12444. // so access to it can be optimized by v8
  12445. const digestCaches = {};
  12446. class BulkUpdateDecorator {
  12447. /**
  12448. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12449. * @param {string=} hashKey key for caching
  12450. */
  12451. constructor(hashOrFactory, hashKey) {
  12452. this.hashKey = hashKey;
  12453. if (typeof hashOrFactory === "function") {
  12454. this.hashFactory = hashOrFactory;
  12455. this.hash = undefined;
  12456. } else {
  12457. this.hashFactory = undefined;
  12458. this.hash = hashOrFactory;
  12459. }
  12460. this.buffer = "";
  12461. }
  12462. /**
  12463. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12464. * @param {string|Buffer} data data
  12465. * @param {string=} inputEncoding data encoding
  12466. * @returns {this} updated hash
  12467. */
  12468. update(data, inputEncoding) {
  12469. if (
  12470. inputEncoding !== undefined ||
  12471. typeof data !== "string" ||
  12472. data.length > BULK_SIZE
  12473. ) {
  12474. if (this.hash === undefined) {
  12475. this.hash = this.hashFactory();
  12476. }
  12477. if (this.buffer.length > 0) {
  12478. this.hash.update(this.buffer);
  12479. this.buffer = "";
  12480. }
  12481. this.hash.update(data, inputEncoding);
  12482. } else {
  12483. this.buffer += data;
  12484. if (this.buffer.length > BULK_SIZE) {
  12485. if (this.hash === undefined) {
  12486. this.hash = this.hashFactory();
  12487. }
  12488. this.hash.update(this.buffer);
  12489. this.buffer = "";
  12490. }
  12491. }
  12492. return this;
  12493. }
  12494. /**
  12495. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12496. * @param {string=} encoding encoding of the return value
  12497. * @returns {string|Buffer} digest
  12498. */
  12499. digest(encoding) {
  12500. let digestCache;
  12501. const buffer = this.buffer;
  12502. if (this.hash === undefined) {
  12503. // short data for hash, we can use caching
  12504. const cacheKey = `${this.hashKey}-${encoding}`;
  12505. digestCache = digestCaches[cacheKey];
  12506. if (digestCache === undefined) {
  12507. digestCache = digestCaches[cacheKey] = new Map();
  12508. }
  12509. const cacheEntry = digestCache.get(buffer);
  12510. if (cacheEntry !== undefined) {
  12511. return cacheEntry;
  12512. }
  12513. this.hash = this.hashFactory();
  12514. }
  12515. if (buffer.length > 0) {
  12516. this.hash.update(buffer);
  12517. }
  12518. const digestResult = this.hash.digest(encoding);
  12519. if (digestCache !== undefined) {
  12520. digestCache.set(buffer, digestResult);
  12521. }
  12522. return digestResult;
  12523. }
  12524. }
  12525. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12526. return BulkUpdateDecorator_1;
  12527. }
  12528. var getHashDigest_1;
  12529. var hasRequiredGetHashDigest;
  12530. function requireGetHashDigest () {
  12531. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12532. hasRequiredGetHashDigest = 1;
  12533. const baseEncodeTables = {
  12534. 26: "abcdefghijklmnopqrstuvwxyz",
  12535. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12536. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12537. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12538. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12539. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12540. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12541. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12542. };
  12543. /**
  12544. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12545. * @param {number} divisor The divisor
  12546. * @return {number} Modulo (remainder) of the division
  12547. */
  12548. function divmod32(uint32Array, divisor) {
  12549. let carry = 0;
  12550. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12551. const value = carry * 0x100000000 + uint32Array[i];
  12552. carry = value % divisor;
  12553. uint32Array[i] = Math.floor(value / divisor);
  12554. }
  12555. return carry;
  12556. }
  12557. function encodeBufferToBase(buffer, base, length) {
  12558. const encodeTable = baseEncodeTables[base];
  12559. if (!encodeTable) {
  12560. throw new Error("Unknown encoding base" + base);
  12561. }
  12562. // Input bits are only enough to generate this many characters
  12563. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12564. length = Math.min(length, limit);
  12565. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12566. // Fewer numbers in the array means faster math.
  12567. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12568. // Make sure the input buffer data is copied and is not mutated by reference.
  12569. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12570. buffer.copy(Buffer.from(uint32Array.buffer));
  12571. let output = "";
  12572. for (let i = 0; i < length; i++) {
  12573. output = encodeTable[divmod32(uint32Array, base)] + output;
  12574. }
  12575. return output;
  12576. }
  12577. let crypto = undefined;
  12578. let createXXHash64 = undefined;
  12579. let createMd4 = undefined;
  12580. let BatchedHash = undefined;
  12581. let BulkUpdateDecorator = undefined;
  12582. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12583. algorithm = algorithm || "xxhash64";
  12584. maxLength = maxLength || 9999;
  12585. let hash;
  12586. if (algorithm === "xxhash64") {
  12587. if (createXXHash64 === undefined) {
  12588. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12589. if (BatchedHash === undefined) {
  12590. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12591. }
  12592. }
  12593. hash = new BatchedHash(createXXHash64());
  12594. } else if (algorithm === "md4") {
  12595. if (createMd4 === undefined) {
  12596. createMd4 = /*@__PURE__*/ requireMd4();
  12597. if (BatchedHash === undefined) {
  12598. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12599. }
  12600. }
  12601. hash = new BatchedHash(createMd4());
  12602. } else if (algorithm === "native-md4") {
  12603. if (typeof crypto === "undefined") {
  12604. crypto = require("crypto");
  12605. if (BulkUpdateDecorator === undefined) {
  12606. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12607. }
  12608. }
  12609. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12610. } else {
  12611. if (typeof crypto === "undefined") {
  12612. crypto = require("crypto");
  12613. if (BulkUpdateDecorator === undefined) {
  12614. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12615. }
  12616. }
  12617. hash = new BulkUpdateDecorator(
  12618. () => crypto.createHash(algorithm),
  12619. algorithm
  12620. );
  12621. }
  12622. hash.update(buffer);
  12623. if (
  12624. digestType === "base26" ||
  12625. digestType === "base32" ||
  12626. digestType === "base36" ||
  12627. digestType === "base49" ||
  12628. digestType === "base52" ||
  12629. digestType === "base58" ||
  12630. digestType === "base62" ||
  12631. digestType === "base64safe"
  12632. ) {
  12633. return encodeBufferToBase(
  12634. hash.digest(),
  12635. digestType === "base64safe" ? 64 : digestType.substr(4),
  12636. maxLength
  12637. );
  12638. }
  12639. return hash.digest(digestType || "hex").substr(0, maxLength);
  12640. }
  12641. getHashDigest_1 = getHashDigest;
  12642. return getHashDigest_1;
  12643. }
  12644. var interpolateName_1;
  12645. var hasRequiredInterpolateName;
  12646. function requireInterpolateName () {
  12647. if (hasRequiredInterpolateName) return interpolateName_1;
  12648. hasRequiredInterpolateName = 1;
  12649. const path = path$1;
  12650. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12651. function interpolateName(loaderContext, name, options = {}) {
  12652. let filename;
  12653. const hasQuery =
  12654. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12655. if (typeof name === "function") {
  12656. filename = name(
  12657. loaderContext.resourcePath,
  12658. hasQuery ? loaderContext.resourceQuery : undefined
  12659. );
  12660. } else {
  12661. filename = name || "[hash].[ext]";
  12662. }
  12663. const context = options.context;
  12664. const content = options.content;
  12665. const regExp = options.regExp;
  12666. let ext = "bin";
  12667. let basename = "file";
  12668. let directory = "";
  12669. let folder = "";
  12670. let query = "";
  12671. if (loaderContext.resourcePath) {
  12672. const parsed = path.parse(loaderContext.resourcePath);
  12673. let resourcePath = loaderContext.resourcePath;
  12674. if (parsed.ext) {
  12675. ext = parsed.ext.substr(1);
  12676. }
  12677. if (parsed.dir) {
  12678. basename = parsed.name;
  12679. resourcePath = parsed.dir + path.sep;
  12680. }
  12681. if (typeof context !== "undefined") {
  12682. directory = path
  12683. .relative(context, resourcePath + "_")
  12684. .replace(/\\/g, "/")
  12685. .replace(/\.\.(\/)?/g, "_$1");
  12686. directory = directory.substr(0, directory.length - 1);
  12687. } else {
  12688. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12689. }
  12690. if (directory.length <= 1) {
  12691. directory = "";
  12692. } else {
  12693. // directory.length > 1
  12694. folder = path.basename(directory);
  12695. }
  12696. }
  12697. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12698. query = loaderContext.resourceQuery;
  12699. const hashIdx = query.indexOf("#");
  12700. if (hashIdx >= 0) {
  12701. query = query.substr(0, hashIdx);
  12702. }
  12703. }
  12704. let url = filename;
  12705. if (content) {
  12706. // Match hash template
  12707. url = url
  12708. // `hash` and `contenthash` are same in `loader-utils` context
  12709. // let's keep `hash` for backward compatibility
  12710. .replace(
  12711. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12712. (all, hashType, digestType, maxLength) =>
  12713. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12714. );
  12715. }
  12716. url = url
  12717. .replace(/\[ext\]/gi, () => ext)
  12718. .replace(/\[name\]/gi, () => basename)
  12719. .replace(/\[path\]/gi, () => directory)
  12720. .replace(/\[folder\]/gi, () => folder)
  12721. .replace(/\[query\]/gi, () => query);
  12722. if (regExp && loaderContext.resourcePath) {
  12723. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12724. match &&
  12725. match.forEach((matched, i) => {
  12726. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12727. });
  12728. }
  12729. if (
  12730. typeof loaderContext.options === "object" &&
  12731. typeof loaderContext.options.customInterpolateName === "function"
  12732. ) {
  12733. url = loaderContext.options.customInterpolateName.call(
  12734. loaderContext,
  12735. url,
  12736. name,
  12737. options
  12738. );
  12739. }
  12740. return url;
  12741. }
  12742. interpolateName_1 = interpolateName;
  12743. return interpolateName_1;
  12744. }
  12745. var genericNames;
  12746. var hasRequiredGenericNames;
  12747. function requireGenericNames () {
  12748. if (hasRequiredGenericNames) return genericNames;
  12749. hasRequiredGenericNames = 1;
  12750. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12751. var path = path$1;
  12752. /**
  12753. * @param {string} pattern
  12754. * @param {object} options
  12755. * @param {string} options.context
  12756. * @param {string} options.hashPrefix
  12757. * @return {function}
  12758. */
  12759. genericNames = function createGenerator(pattern, options) {
  12760. options = options || {};
  12761. var context =
  12762. options && typeof options.context === "string"
  12763. ? options.context
  12764. : process.cwd();
  12765. var hashPrefix =
  12766. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12767. /**
  12768. * @param {string} localName Usually a class name
  12769. * @param {string} filepath Absolute path
  12770. * @return {string}
  12771. */
  12772. return function generate(localName, filepath) {
  12773. var name = pattern.replace(/\[local\]/gi, localName);
  12774. var loaderContext = {
  12775. resourcePath: filepath,
  12776. };
  12777. var loaderOptions = {
  12778. content:
  12779. hashPrefix +
  12780. path.relative(context, filepath).replace(/\\/g, "/") +
  12781. "\x00" +
  12782. localName,
  12783. context: context,
  12784. };
  12785. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12786. return genericName
  12787. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12788. .replace(/^((-?[0-9])|--)/, "_$1");
  12789. };
  12790. };
  12791. return genericNames;
  12792. }
  12793. var src$2 = {exports: {}};
  12794. var dist = {exports: {}};
  12795. var processor = {exports: {}};
  12796. var parser = {exports: {}};
  12797. var root = {exports: {}};
  12798. var container = {exports: {}};
  12799. var node = {exports: {}};
  12800. var util = {};
  12801. var unesc = {exports: {}};
  12802. var hasRequiredUnesc;
  12803. function requireUnesc () {
  12804. if (hasRequiredUnesc) return unesc.exports;
  12805. hasRequiredUnesc = 1;
  12806. (function (module, exports) {
  12807. exports.__esModule = true;
  12808. exports["default"] = unesc;
  12809. // Many thanks for this post which made this migration much easier.
  12810. // https://mathiasbynens.be/notes/css-escapes
  12811. /**
  12812. *
  12813. * @param {string} str
  12814. * @returns {[string, number]|undefined}
  12815. */
  12816. function gobbleHex(str) {
  12817. var lower = str.toLowerCase();
  12818. var hex = '';
  12819. var spaceTerminated = false;
  12820. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  12821. var code = lower.charCodeAt(i);
  12822. // check to see if we are dealing with a valid hex char [a-f|0-9]
  12823. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  12824. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  12825. spaceTerminated = code === 32;
  12826. if (!valid) {
  12827. break;
  12828. }
  12829. hex += lower[i];
  12830. }
  12831. if (hex.length === 0) {
  12832. return undefined;
  12833. }
  12834. var codePoint = parseInt(hex, 16);
  12835. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  12836. // Add special case for
  12837. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  12838. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  12839. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  12840. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  12841. }
  12842. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  12843. }
  12844. var CONTAINS_ESCAPE = /\\/;
  12845. function unesc(str) {
  12846. var needToProcess = CONTAINS_ESCAPE.test(str);
  12847. if (!needToProcess) {
  12848. return str;
  12849. }
  12850. var ret = "";
  12851. for (var i = 0; i < str.length; i++) {
  12852. if (str[i] === "\\") {
  12853. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  12854. if (gobbled !== undefined) {
  12855. ret += gobbled[0];
  12856. i += gobbled[1];
  12857. continue;
  12858. }
  12859. // Retain a pair of \\ if double escaped `\\\\`
  12860. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  12861. if (str[i + 1] === "\\") {
  12862. ret += "\\";
  12863. i++;
  12864. continue;
  12865. }
  12866. // if \\ is at the end of the string retain it
  12867. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  12868. if (str.length === i + 1) {
  12869. ret += str[i];
  12870. }
  12871. continue;
  12872. }
  12873. ret += str[i];
  12874. }
  12875. return ret;
  12876. }
  12877. module.exports = exports.default;
  12878. } (unesc, unesc.exports));
  12879. return unesc.exports;
  12880. }
  12881. var getProp = {exports: {}};
  12882. var hasRequiredGetProp;
  12883. function requireGetProp () {
  12884. if (hasRequiredGetProp) return getProp.exports;
  12885. hasRequiredGetProp = 1;
  12886. (function (module, exports) {
  12887. exports.__esModule = true;
  12888. exports["default"] = getProp;
  12889. function getProp(obj) {
  12890. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12891. props[_key - 1] = arguments[_key];
  12892. }
  12893. while (props.length > 0) {
  12894. var prop = props.shift();
  12895. if (!obj[prop]) {
  12896. return undefined;
  12897. }
  12898. obj = obj[prop];
  12899. }
  12900. return obj;
  12901. }
  12902. module.exports = exports.default;
  12903. } (getProp, getProp.exports));
  12904. return getProp.exports;
  12905. }
  12906. var ensureObject = {exports: {}};
  12907. var hasRequiredEnsureObject;
  12908. function requireEnsureObject () {
  12909. if (hasRequiredEnsureObject) return ensureObject.exports;
  12910. hasRequiredEnsureObject = 1;
  12911. (function (module, exports) {
  12912. exports.__esModule = true;
  12913. exports["default"] = ensureObject;
  12914. function ensureObject(obj) {
  12915. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12916. props[_key - 1] = arguments[_key];
  12917. }
  12918. while (props.length > 0) {
  12919. var prop = props.shift();
  12920. if (!obj[prop]) {
  12921. obj[prop] = {};
  12922. }
  12923. obj = obj[prop];
  12924. }
  12925. }
  12926. module.exports = exports.default;
  12927. } (ensureObject, ensureObject.exports));
  12928. return ensureObject.exports;
  12929. }
  12930. var stripComments = {exports: {}};
  12931. var hasRequiredStripComments;
  12932. function requireStripComments () {
  12933. if (hasRequiredStripComments) return stripComments.exports;
  12934. hasRequiredStripComments = 1;
  12935. (function (module, exports) {
  12936. exports.__esModule = true;
  12937. exports["default"] = stripComments;
  12938. function stripComments(str) {
  12939. var s = "";
  12940. var commentStart = str.indexOf("/*");
  12941. var lastEnd = 0;
  12942. while (commentStart >= 0) {
  12943. s = s + str.slice(lastEnd, commentStart);
  12944. var commentEnd = str.indexOf("*/", commentStart + 2);
  12945. if (commentEnd < 0) {
  12946. return s;
  12947. }
  12948. lastEnd = commentEnd + 2;
  12949. commentStart = str.indexOf("/*", lastEnd);
  12950. }
  12951. s = s + str.slice(lastEnd);
  12952. return s;
  12953. }
  12954. module.exports = exports.default;
  12955. } (stripComments, stripComments.exports));
  12956. return stripComments.exports;
  12957. }
  12958. var hasRequiredUtil;
  12959. function requireUtil () {
  12960. if (hasRequiredUtil) return util;
  12961. hasRequiredUtil = 1;
  12962. util.__esModule = true;
  12963. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  12964. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  12965. util.unesc = _unesc["default"];
  12966. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  12967. util.getProp = _getProp["default"];
  12968. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  12969. util.ensureObject = _ensureObject["default"];
  12970. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  12971. util.stripComments = _stripComments["default"];
  12972. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  12973. return util;
  12974. }
  12975. var hasRequiredNode;
  12976. function requireNode () {
  12977. if (hasRequiredNode) return node.exports;
  12978. hasRequiredNode = 1;
  12979. (function (module, exports) {
  12980. exports.__esModule = true;
  12981. exports["default"] = void 0;
  12982. var _util = /*@__PURE__*/ requireUtil();
  12983. 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); } }
  12984. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12985. var cloneNode = function cloneNode(obj, parent) {
  12986. if (typeof obj !== 'object' || obj === null) {
  12987. return obj;
  12988. }
  12989. var cloned = new obj.constructor();
  12990. for (var i in obj) {
  12991. if (!obj.hasOwnProperty(i)) {
  12992. continue;
  12993. }
  12994. var value = obj[i];
  12995. var type = typeof value;
  12996. if (i === 'parent' && type === 'object') {
  12997. if (parent) {
  12998. cloned[i] = parent;
  12999. }
  13000. } else if (value instanceof Array) {
  13001. cloned[i] = value.map(function (j) {
  13002. return cloneNode(j, cloned);
  13003. });
  13004. } else {
  13005. cloned[i] = cloneNode(value, cloned);
  13006. }
  13007. }
  13008. return cloned;
  13009. };
  13010. var Node = /*#__PURE__*/function () {
  13011. function Node(opts) {
  13012. if (opts === void 0) {
  13013. opts = {};
  13014. }
  13015. Object.assign(this, opts);
  13016. this.spaces = this.spaces || {};
  13017. this.spaces.before = this.spaces.before || '';
  13018. this.spaces.after = this.spaces.after || '';
  13019. }
  13020. var _proto = Node.prototype;
  13021. _proto.remove = function remove() {
  13022. if (this.parent) {
  13023. this.parent.removeChild(this);
  13024. }
  13025. this.parent = undefined;
  13026. return this;
  13027. };
  13028. _proto.replaceWith = function replaceWith() {
  13029. if (this.parent) {
  13030. for (var index in arguments) {
  13031. this.parent.insertBefore(this, arguments[index]);
  13032. }
  13033. this.remove();
  13034. }
  13035. return this;
  13036. };
  13037. _proto.next = function next() {
  13038. return this.parent.at(this.parent.index(this) + 1);
  13039. };
  13040. _proto.prev = function prev() {
  13041. return this.parent.at(this.parent.index(this) - 1);
  13042. };
  13043. _proto.clone = function clone(overrides) {
  13044. if (overrides === void 0) {
  13045. overrides = {};
  13046. }
  13047. var cloned = cloneNode(this);
  13048. for (var name in overrides) {
  13049. cloned[name] = overrides[name];
  13050. }
  13051. return cloned;
  13052. }
  13053. /**
  13054. * Some non-standard syntax doesn't follow normal escaping rules for css.
  13055. * This allows non standard syntax to be appended to an existing property
  13056. * by specifying the escaped value. By specifying the escaped value,
  13057. * illegal characters are allowed to be directly inserted into css output.
  13058. * @param {string} name the property to set
  13059. * @param {any} value the unescaped value of the property
  13060. * @param {string} valueEscaped optional. the escaped value of the property.
  13061. */;
  13062. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  13063. if (!this.raws) {
  13064. this.raws = {};
  13065. }
  13066. var originalValue = this[name];
  13067. var originalEscaped = this.raws[name];
  13068. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  13069. if (originalEscaped || valueEscaped !== value) {
  13070. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  13071. } else {
  13072. delete this.raws[name]; // delete any escaped value that was created by the setter.
  13073. }
  13074. }
  13075. /**
  13076. * Some non-standard syntax doesn't follow normal escaping rules for css.
  13077. * This allows the escaped value to be specified directly, allowing illegal
  13078. * characters to be directly inserted into css output.
  13079. * @param {string} name the property to set
  13080. * @param {any} value the unescaped value of the property
  13081. * @param {string} valueEscaped the escaped value of the property.
  13082. */;
  13083. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  13084. if (!this.raws) {
  13085. this.raws = {};
  13086. }
  13087. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13088. this.raws[name] = valueEscaped;
  13089. }
  13090. /**
  13091. * When you want a value to passed through to CSS directly. This method
  13092. * deletes the corresponding raw value causing the stringifier to fallback
  13093. * to the unescaped value.
  13094. * @param {string} name the property to set.
  13095. * @param {any} value The value that is both escaped and unescaped.
  13096. */;
  13097. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  13098. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13099. if (this.raws) {
  13100. delete this.raws[name];
  13101. }
  13102. }
  13103. /**
  13104. *
  13105. * @param {number} line The number (starting with 1)
  13106. * @param {number} column The column number (starting with 1)
  13107. */;
  13108. _proto.isAtPosition = function isAtPosition(line, column) {
  13109. if (this.source && this.source.start && this.source.end) {
  13110. if (this.source.start.line > line) {
  13111. return false;
  13112. }
  13113. if (this.source.end.line < line) {
  13114. return false;
  13115. }
  13116. if (this.source.start.line === line && this.source.start.column > column) {
  13117. return false;
  13118. }
  13119. if (this.source.end.line === line && this.source.end.column < column) {
  13120. return false;
  13121. }
  13122. return true;
  13123. }
  13124. return undefined;
  13125. };
  13126. _proto.stringifyProperty = function stringifyProperty(name) {
  13127. return this.raws && this.raws[name] || this[name];
  13128. };
  13129. _proto.valueToString = function valueToString() {
  13130. return String(this.stringifyProperty("value"));
  13131. };
  13132. _proto.toString = function toString() {
  13133. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  13134. };
  13135. _createClass(Node, [{
  13136. key: "rawSpaceBefore",
  13137. get: function get() {
  13138. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  13139. if (rawSpace === undefined) {
  13140. rawSpace = this.spaces && this.spaces.before;
  13141. }
  13142. return rawSpace || "";
  13143. },
  13144. set: function set(raw) {
  13145. (0, _util.ensureObject)(this, "raws", "spaces");
  13146. this.raws.spaces.before = raw;
  13147. }
  13148. }, {
  13149. key: "rawSpaceAfter",
  13150. get: function get() {
  13151. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  13152. if (rawSpace === undefined) {
  13153. rawSpace = this.spaces.after;
  13154. }
  13155. return rawSpace || "";
  13156. },
  13157. set: function set(raw) {
  13158. (0, _util.ensureObject)(this, "raws", "spaces");
  13159. this.raws.spaces.after = raw;
  13160. }
  13161. }]);
  13162. return Node;
  13163. }();
  13164. exports["default"] = Node;
  13165. module.exports = exports.default;
  13166. } (node, node.exports));
  13167. return node.exports;
  13168. }
  13169. var types$1 = {};
  13170. var hasRequiredTypes;
  13171. function requireTypes () {
  13172. if (hasRequiredTypes) return types$1;
  13173. hasRequiredTypes = 1;
  13174. types$1.__esModule = true;
  13175. 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;
  13176. var TAG = 'tag';
  13177. types$1.TAG = TAG;
  13178. var STRING = 'string';
  13179. types$1.STRING = STRING;
  13180. var SELECTOR = 'selector';
  13181. types$1.SELECTOR = SELECTOR;
  13182. var ROOT = 'root';
  13183. types$1.ROOT = ROOT;
  13184. var PSEUDO = 'pseudo';
  13185. types$1.PSEUDO = PSEUDO;
  13186. var NESTING = 'nesting';
  13187. types$1.NESTING = NESTING;
  13188. var ID = 'id';
  13189. types$1.ID = ID;
  13190. var COMMENT = 'comment';
  13191. types$1.COMMENT = COMMENT;
  13192. var COMBINATOR = 'combinator';
  13193. types$1.COMBINATOR = COMBINATOR;
  13194. var CLASS = 'class';
  13195. types$1.CLASS = CLASS;
  13196. var ATTRIBUTE = 'attribute';
  13197. types$1.ATTRIBUTE = ATTRIBUTE;
  13198. var UNIVERSAL = 'universal';
  13199. types$1.UNIVERSAL = UNIVERSAL;
  13200. return types$1;
  13201. }
  13202. var hasRequiredContainer;
  13203. function requireContainer () {
  13204. if (hasRequiredContainer) return container.exports;
  13205. hasRequiredContainer = 1;
  13206. (function (module, exports) {
  13207. exports.__esModule = true;
  13208. exports["default"] = void 0;
  13209. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13210. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13211. 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); }
  13212. function _interopRequireWildcard(obj, nodeInterop) { if (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; }
  13213. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13214. 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) { 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."); }
  13215. 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); }
  13216. 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; }
  13217. 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); } }
  13218. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13219. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13220. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13221. var Container = /*#__PURE__*/function (_Node) {
  13222. _inheritsLoose(Container, _Node);
  13223. function Container(opts) {
  13224. var _this;
  13225. _this = _Node.call(this, opts) || this;
  13226. if (!_this.nodes) {
  13227. _this.nodes = [];
  13228. }
  13229. return _this;
  13230. }
  13231. var _proto = Container.prototype;
  13232. _proto.append = function append(selector) {
  13233. selector.parent = this;
  13234. this.nodes.push(selector);
  13235. return this;
  13236. };
  13237. _proto.prepend = function prepend(selector) {
  13238. selector.parent = this;
  13239. this.nodes.unshift(selector);
  13240. return this;
  13241. };
  13242. _proto.at = function at(index) {
  13243. return this.nodes[index];
  13244. };
  13245. _proto.index = function index(child) {
  13246. if (typeof child === 'number') {
  13247. return child;
  13248. }
  13249. return this.nodes.indexOf(child);
  13250. };
  13251. _proto.removeChild = function removeChild(child) {
  13252. child = this.index(child);
  13253. this.at(child).parent = undefined;
  13254. this.nodes.splice(child, 1);
  13255. var index;
  13256. for (var id in this.indexes) {
  13257. index = this.indexes[id];
  13258. if (index >= child) {
  13259. this.indexes[id] = index - 1;
  13260. }
  13261. }
  13262. return this;
  13263. };
  13264. _proto.removeAll = function removeAll() {
  13265. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13266. var node = _step.value;
  13267. node.parent = undefined;
  13268. }
  13269. this.nodes = [];
  13270. return this;
  13271. };
  13272. _proto.empty = function empty() {
  13273. return this.removeAll();
  13274. };
  13275. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13276. newNode.parent = this;
  13277. var oldIndex = this.index(oldNode);
  13278. this.nodes.splice(oldIndex + 1, 0, newNode);
  13279. newNode.parent = this;
  13280. var index;
  13281. for (var id in this.indexes) {
  13282. index = this.indexes[id];
  13283. if (oldIndex <= index) {
  13284. this.indexes[id] = index + 1;
  13285. }
  13286. }
  13287. return this;
  13288. };
  13289. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13290. newNode.parent = this;
  13291. var oldIndex = this.index(oldNode);
  13292. this.nodes.splice(oldIndex, 0, newNode);
  13293. newNode.parent = this;
  13294. var index;
  13295. for (var id in this.indexes) {
  13296. index = this.indexes[id];
  13297. if (index <= oldIndex) {
  13298. this.indexes[id] = index + 1;
  13299. }
  13300. }
  13301. return this;
  13302. };
  13303. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13304. var found = undefined;
  13305. this.each(function (node) {
  13306. if (node.atPosition) {
  13307. var foundChild = node.atPosition(line, col);
  13308. if (foundChild) {
  13309. found = foundChild;
  13310. return false;
  13311. }
  13312. } else if (node.isAtPosition(line, col)) {
  13313. found = node;
  13314. return false;
  13315. }
  13316. });
  13317. return found;
  13318. }
  13319. /**
  13320. * Return the most specific node at the line and column number given.
  13321. * The source location is based on the original parsed location, locations aren't
  13322. * updated as selector nodes are mutated.
  13323. *
  13324. * Note that this location is relative to the location of the first character
  13325. * of the selector, and not the location of the selector in the overall document
  13326. * when used in conjunction with postcss.
  13327. *
  13328. * If not found, returns undefined.
  13329. * @param {number} line The line number of the node to find. (1-based index)
  13330. * @param {number} col The column number of the node to find. (1-based index)
  13331. */;
  13332. _proto.atPosition = function atPosition(line, col) {
  13333. if (this.isAtPosition(line, col)) {
  13334. return this._findChildAtPosition(line, col) || this;
  13335. } else {
  13336. return undefined;
  13337. }
  13338. };
  13339. _proto._inferEndPosition = function _inferEndPosition() {
  13340. if (this.last && this.last.source && this.last.source.end) {
  13341. this.source = this.source || {};
  13342. this.source.end = this.source.end || {};
  13343. Object.assign(this.source.end, this.last.source.end);
  13344. }
  13345. };
  13346. _proto.each = function each(callback) {
  13347. if (!this.lastEach) {
  13348. this.lastEach = 0;
  13349. }
  13350. if (!this.indexes) {
  13351. this.indexes = {};
  13352. }
  13353. this.lastEach++;
  13354. var id = this.lastEach;
  13355. this.indexes[id] = 0;
  13356. if (!this.length) {
  13357. return undefined;
  13358. }
  13359. var index, result;
  13360. while (this.indexes[id] < this.length) {
  13361. index = this.indexes[id];
  13362. result = callback(this.at(index), index);
  13363. if (result === false) {
  13364. break;
  13365. }
  13366. this.indexes[id] += 1;
  13367. }
  13368. delete this.indexes[id];
  13369. if (result === false) {
  13370. return false;
  13371. }
  13372. };
  13373. _proto.walk = function walk(callback) {
  13374. return this.each(function (node, i) {
  13375. var result = callback(node, i);
  13376. if (result !== false && node.length) {
  13377. result = node.walk(callback);
  13378. }
  13379. if (result === false) {
  13380. return false;
  13381. }
  13382. });
  13383. };
  13384. _proto.walkAttributes = function walkAttributes(callback) {
  13385. var _this2 = this;
  13386. return this.walk(function (selector) {
  13387. if (selector.type === types.ATTRIBUTE) {
  13388. return callback.call(_this2, selector);
  13389. }
  13390. });
  13391. };
  13392. _proto.walkClasses = function walkClasses(callback) {
  13393. var _this3 = this;
  13394. return this.walk(function (selector) {
  13395. if (selector.type === types.CLASS) {
  13396. return callback.call(_this3, selector);
  13397. }
  13398. });
  13399. };
  13400. _proto.walkCombinators = function walkCombinators(callback) {
  13401. var _this4 = this;
  13402. return this.walk(function (selector) {
  13403. if (selector.type === types.COMBINATOR) {
  13404. return callback.call(_this4, selector);
  13405. }
  13406. });
  13407. };
  13408. _proto.walkComments = function walkComments(callback) {
  13409. var _this5 = this;
  13410. return this.walk(function (selector) {
  13411. if (selector.type === types.COMMENT) {
  13412. return callback.call(_this5, selector);
  13413. }
  13414. });
  13415. };
  13416. _proto.walkIds = function walkIds(callback) {
  13417. var _this6 = this;
  13418. return this.walk(function (selector) {
  13419. if (selector.type === types.ID) {
  13420. return callback.call(_this6, selector);
  13421. }
  13422. });
  13423. };
  13424. _proto.walkNesting = function walkNesting(callback) {
  13425. var _this7 = this;
  13426. return this.walk(function (selector) {
  13427. if (selector.type === types.NESTING) {
  13428. return callback.call(_this7, selector);
  13429. }
  13430. });
  13431. };
  13432. _proto.walkPseudos = function walkPseudos(callback) {
  13433. var _this8 = this;
  13434. return this.walk(function (selector) {
  13435. if (selector.type === types.PSEUDO) {
  13436. return callback.call(_this8, selector);
  13437. }
  13438. });
  13439. };
  13440. _proto.walkTags = function walkTags(callback) {
  13441. var _this9 = this;
  13442. return this.walk(function (selector) {
  13443. if (selector.type === types.TAG) {
  13444. return callback.call(_this9, selector);
  13445. }
  13446. });
  13447. };
  13448. _proto.walkUniversals = function walkUniversals(callback) {
  13449. var _this10 = this;
  13450. return this.walk(function (selector) {
  13451. if (selector.type === types.UNIVERSAL) {
  13452. return callback.call(_this10, selector);
  13453. }
  13454. });
  13455. };
  13456. _proto.split = function split(callback) {
  13457. var _this11 = this;
  13458. var current = [];
  13459. return this.reduce(function (memo, node, index) {
  13460. var split = callback.call(_this11, node);
  13461. current.push(node);
  13462. if (split) {
  13463. memo.push(current);
  13464. current = [];
  13465. } else if (index === _this11.length - 1) {
  13466. memo.push(current);
  13467. }
  13468. return memo;
  13469. }, []);
  13470. };
  13471. _proto.map = function map(callback) {
  13472. return this.nodes.map(callback);
  13473. };
  13474. _proto.reduce = function reduce(callback, memo) {
  13475. return this.nodes.reduce(callback, memo);
  13476. };
  13477. _proto.every = function every(callback) {
  13478. return this.nodes.every(callback);
  13479. };
  13480. _proto.some = function some(callback) {
  13481. return this.nodes.some(callback);
  13482. };
  13483. _proto.filter = function filter(callback) {
  13484. return this.nodes.filter(callback);
  13485. };
  13486. _proto.sort = function sort(callback) {
  13487. return this.nodes.sort(callback);
  13488. };
  13489. _proto.toString = function toString() {
  13490. return this.map(String).join('');
  13491. };
  13492. _createClass(Container, [{
  13493. key: "first",
  13494. get: function get() {
  13495. return this.at(0);
  13496. }
  13497. }, {
  13498. key: "last",
  13499. get: function get() {
  13500. return this.at(this.length - 1);
  13501. }
  13502. }, {
  13503. key: "length",
  13504. get: function get() {
  13505. return this.nodes.length;
  13506. }
  13507. }]);
  13508. return Container;
  13509. }(_node["default"]);
  13510. exports["default"] = Container;
  13511. module.exports = exports.default;
  13512. } (container, container.exports));
  13513. return container.exports;
  13514. }
  13515. var hasRequiredRoot;
  13516. function requireRoot () {
  13517. if (hasRequiredRoot) return root.exports;
  13518. hasRequiredRoot = 1;
  13519. (function (module, exports) {
  13520. exports.__esModule = true;
  13521. exports["default"] = void 0;
  13522. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13523. var _types = /*@__PURE__*/ requireTypes();
  13524. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13525. 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); } }
  13526. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13527. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13528. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13529. var Root = /*#__PURE__*/function (_Container) {
  13530. _inheritsLoose(Root, _Container);
  13531. function Root(opts) {
  13532. var _this;
  13533. _this = _Container.call(this, opts) || this;
  13534. _this.type = _types.ROOT;
  13535. return _this;
  13536. }
  13537. var _proto = Root.prototype;
  13538. _proto.toString = function toString() {
  13539. var str = this.reduce(function (memo, selector) {
  13540. memo.push(String(selector));
  13541. return memo;
  13542. }, []).join(',');
  13543. return this.trailingComma ? str + ',' : str;
  13544. };
  13545. _proto.error = function error(message, options) {
  13546. if (this._error) {
  13547. return this._error(message, options);
  13548. } else {
  13549. return new Error(message);
  13550. }
  13551. };
  13552. _createClass(Root, [{
  13553. key: "errorGenerator",
  13554. set: function set(handler) {
  13555. this._error = handler;
  13556. }
  13557. }]);
  13558. return Root;
  13559. }(_container["default"]);
  13560. exports["default"] = Root;
  13561. module.exports = exports.default;
  13562. } (root, root.exports));
  13563. return root.exports;
  13564. }
  13565. var selector = {exports: {}};
  13566. var hasRequiredSelector;
  13567. function requireSelector () {
  13568. if (hasRequiredSelector) return selector.exports;
  13569. hasRequiredSelector = 1;
  13570. (function (module, exports) {
  13571. exports.__esModule = true;
  13572. exports["default"] = void 0;
  13573. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13574. var _types = /*@__PURE__*/ requireTypes();
  13575. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13576. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13577. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13578. var Selector = /*#__PURE__*/function (_Container) {
  13579. _inheritsLoose(Selector, _Container);
  13580. function Selector(opts) {
  13581. var _this;
  13582. _this = _Container.call(this, opts) || this;
  13583. _this.type = _types.SELECTOR;
  13584. return _this;
  13585. }
  13586. return Selector;
  13587. }(_container["default"]);
  13588. exports["default"] = Selector;
  13589. module.exports = exports.default;
  13590. } (selector, selector.exports));
  13591. return selector.exports;
  13592. }
  13593. var className = {exports: {}};
  13594. var hasRequiredClassName;
  13595. function requireClassName () {
  13596. if (hasRequiredClassName) return className.exports;
  13597. hasRequiredClassName = 1;
  13598. (function (module, exports) {
  13599. exports.__esModule = true;
  13600. exports["default"] = void 0;
  13601. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13602. var _util = /*@__PURE__*/ requireUtil();
  13603. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13604. var _types = /*@__PURE__*/ requireTypes();
  13605. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13606. 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); } }
  13607. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13608. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13609. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13610. var ClassName = /*#__PURE__*/function (_Node) {
  13611. _inheritsLoose(ClassName, _Node);
  13612. function ClassName(opts) {
  13613. var _this;
  13614. _this = _Node.call(this, opts) || this;
  13615. _this.type = _types.CLASS;
  13616. _this._constructed = true;
  13617. return _this;
  13618. }
  13619. var _proto = ClassName.prototype;
  13620. _proto.valueToString = function valueToString() {
  13621. return '.' + _Node.prototype.valueToString.call(this);
  13622. };
  13623. _createClass(ClassName, [{
  13624. key: "value",
  13625. get: function get() {
  13626. return this._value;
  13627. },
  13628. set: function set(v) {
  13629. if (this._constructed) {
  13630. var escaped = (0, _cssesc["default"])(v, {
  13631. isIdentifier: true
  13632. });
  13633. if (escaped !== v) {
  13634. (0, _util.ensureObject)(this, "raws");
  13635. this.raws.value = escaped;
  13636. } else if (this.raws) {
  13637. delete this.raws.value;
  13638. }
  13639. }
  13640. this._value = v;
  13641. }
  13642. }]);
  13643. return ClassName;
  13644. }(_node["default"]);
  13645. exports["default"] = ClassName;
  13646. module.exports = exports.default;
  13647. } (className, className.exports));
  13648. return className.exports;
  13649. }
  13650. var comment = {exports: {}};
  13651. var hasRequiredComment;
  13652. function requireComment () {
  13653. if (hasRequiredComment) return comment.exports;
  13654. hasRequiredComment = 1;
  13655. (function (module, exports) {
  13656. exports.__esModule = true;
  13657. exports["default"] = void 0;
  13658. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13659. var _types = /*@__PURE__*/ requireTypes();
  13660. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13661. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13662. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13663. var Comment = /*#__PURE__*/function (_Node) {
  13664. _inheritsLoose(Comment, _Node);
  13665. function Comment(opts) {
  13666. var _this;
  13667. _this = _Node.call(this, opts) || this;
  13668. _this.type = _types.COMMENT;
  13669. return _this;
  13670. }
  13671. return Comment;
  13672. }(_node["default"]);
  13673. exports["default"] = Comment;
  13674. module.exports = exports.default;
  13675. } (comment, comment.exports));
  13676. return comment.exports;
  13677. }
  13678. var id = {exports: {}};
  13679. var hasRequiredId;
  13680. function requireId () {
  13681. if (hasRequiredId) return id.exports;
  13682. hasRequiredId = 1;
  13683. (function (module, exports) {
  13684. exports.__esModule = true;
  13685. exports["default"] = void 0;
  13686. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13687. var _types = /*@__PURE__*/ requireTypes();
  13688. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13689. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13690. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13691. var ID = /*#__PURE__*/function (_Node) {
  13692. _inheritsLoose(ID, _Node);
  13693. function ID(opts) {
  13694. var _this;
  13695. _this = _Node.call(this, opts) || this;
  13696. _this.type = _types.ID;
  13697. return _this;
  13698. }
  13699. var _proto = ID.prototype;
  13700. _proto.valueToString = function valueToString() {
  13701. return '#' + _Node.prototype.valueToString.call(this);
  13702. };
  13703. return ID;
  13704. }(_node["default"]);
  13705. exports["default"] = ID;
  13706. module.exports = exports.default;
  13707. } (id, id.exports));
  13708. return id.exports;
  13709. }
  13710. var tag = {exports: {}};
  13711. var namespace = {exports: {}};
  13712. var hasRequiredNamespace;
  13713. function requireNamespace () {
  13714. if (hasRequiredNamespace) return namespace.exports;
  13715. hasRequiredNamespace = 1;
  13716. (function (module, exports) {
  13717. exports.__esModule = true;
  13718. exports["default"] = void 0;
  13719. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13720. var _util = /*@__PURE__*/ requireUtil();
  13721. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13722. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13723. 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); } }
  13724. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13725. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13726. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13727. var Namespace = /*#__PURE__*/function (_Node) {
  13728. _inheritsLoose(Namespace, _Node);
  13729. function Namespace() {
  13730. return _Node.apply(this, arguments) || this;
  13731. }
  13732. var _proto = Namespace.prototype;
  13733. _proto.qualifiedName = function qualifiedName(value) {
  13734. if (this.namespace) {
  13735. return this.namespaceString + "|" + value;
  13736. } else {
  13737. return value;
  13738. }
  13739. };
  13740. _proto.valueToString = function valueToString() {
  13741. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  13742. };
  13743. _createClass(Namespace, [{
  13744. key: "namespace",
  13745. get: function get() {
  13746. return this._namespace;
  13747. },
  13748. set: function set(namespace) {
  13749. if (namespace === true || namespace === "*" || namespace === "&") {
  13750. this._namespace = namespace;
  13751. if (this.raws) {
  13752. delete this.raws.namespace;
  13753. }
  13754. return;
  13755. }
  13756. var escaped = (0, _cssesc["default"])(namespace, {
  13757. isIdentifier: true
  13758. });
  13759. this._namespace = namespace;
  13760. if (escaped !== namespace) {
  13761. (0, _util.ensureObject)(this, "raws");
  13762. this.raws.namespace = escaped;
  13763. } else if (this.raws) {
  13764. delete this.raws.namespace;
  13765. }
  13766. }
  13767. }, {
  13768. key: "ns",
  13769. get: function get() {
  13770. return this._namespace;
  13771. },
  13772. set: function set(namespace) {
  13773. this.namespace = namespace;
  13774. }
  13775. }, {
  13776. key: "namespaceString",
  13777. get: function get() {
  13778. if (this.namespace) {
  13779. var ns = this.stringifyProperty("namespace");
  13780. if (ns === true) {
  13781. return '';
  13782. } else {
  13783. return ns;
  13784. }
  13785. } else {
  13786. return '';
  13787. }
  13788. }
  13789. }]);
  13790. return Namespace;
  13791. }(_node["default"]);
  13792. exports["default"] = Namespace;
  13793. module.exports = exports.default;
  13794. } (namespace, namespace.exports));
  13795. return namespace.exports;
  13796. }
  13797. var hasRequiredTag;
  13798. function requireTag () {
  13799. if (hasRequiredTag) return tag.exports;
  13800. hasRequiredTag = 1;
  13801. (function (module, exports) {
  13802. exports.__esModule = true;
  13803. exports["default"] = void 0;
  13804. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13805. var _types = /*@__PURE__*/ requireTypes();
  13806. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13807. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13808. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13809. var Tag = /*#__PURE__*/function (_Namespace) {
  13810. _inheritsLoose(Tag, _Namespace);
  13811. function Tag(opts) {
  13812. var _this;
  13813. _this = _Namespace.call(this, opts) || this;
  13814. _this.type = _types.TAG;
  13815. return _this;
  13816. }
  13817. return Tag;
  13818. }(_namespace["default"]);
  13819. exports["default"] = Tag;
  13820. module.exports = exports.default;
  13821. } (tag, tag.exports));
  13822. return tag.exports;
  13823. }
  13824. var string = {exports: {}};
  13825. var hasRequiredString;
  13826. function requireString () {
  13827. if (hasRequiredString) return string.exports;
  13828. hasRequiredString = 1;
  13829. (function (module, exports) {
  13830. exports.__esModule = true;
  13831. exports["default"] = void 0;
  13832. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13833. var _types = /*@__PURE__*/ requireTypes();
  13834. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13835. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13836. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13837. var String = /*#__PURE__*/function (_Node) {
  13838. _inheritsLoose(String, _Node);
  13839. function String(opts) {
  13840. var _this;
  13841. _this = _Node.call(this, opts) || this;
  13842. _this.type = _types.STRING;
  13843. return _this;
  13844. }
  13845. return String;
  13846. }(_node["default"]);
  13847. exports["default"] = String;
  13848. module.exports = exports.default;
  13849. } (string, string.exports));
  13850. return string.exports;
  13851. }
  13852. var pseudo = {exports: {}};
  13853. var hasRequiredPseudo;
  13854. function requirePseudo () {
  13855. if (hasRequiredPseudo) return pseudo.exports;
  13856. hasRequiredPseudo = 1;
  13857. (function (module, exports) {
  13858. exports.__esModule = true;
  13859. exports["default"] = void 0;
  13860. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13861. var _types = /*@__PURE__*/ requireTypes();
  13862. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13863. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13864. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13865. var Pseudo = /*#__PURE__*/function (_Container) {
  13866. _inheritsLoose(Pseudo, _Container);
  13867. function Pseudo(opts) {
  13868. var _this;
  13869. _this = _Container.call(this, opts) || this;
  13870. _this.type = _types.PSEUDO;
  13871. return _this;
  13872. }
  13873. var _proto = Pseudo.prototype;
  13874. _proto.toString = function toString() {
  13875. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  13876. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  13877. };
  13878. return Pseudo;
  13879. }(_container["default"]);
  13880. exports["default"] = Pseudo;
  13881. module.exports = exports.default;
  13882. } (pseudo, pseudo.exports));
  13883. return pseudo.exports;
  13884. }
  13885. var attribute = {};
  13886. var hasRequiredAttribute;
  13887. function requireAttribute () {
  13888. if (hasRequiredAttribute) return attribute;
  13889. hasRequiredAttribute = 1;
  13890. (function (exports) {
  13891. exports.__esModule = true;
  13892. exports["default"] = void 0;
  13893. exports.unescapeValue = unescapeValue;
  13894. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13895. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13896. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13897. var _types = /*@__PURE__*/ requireTypes();
  13898. var _CSSESC_QUOTE_OPTIONS;
  13899. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13900. 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); } }
  13901. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13902. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13903. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13904. var deprecate = /*@__PURE__*/ requireNode$1();
  13905. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  13906. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  13907. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  13908. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  13909. function unescapeValue(value) {
  13910. var deprecatedUsage = false;
  13911. var quoteMark = null;
  13912. var unescaped = value;
  13913. var m = unescaped.match(WRAPPED_IN_QUOTES);
  13914. if (m) {
  13915. quoteMark = m[1];
  13916. unescaped = m[2];
  13917. }
  13918. unescaped = (0, _unesc["default"])(unescaped);
  13919. if (unescaped !== value) {
  13920. deprecatedUsage = true;
  13921. }
  13922. return {
  13923. deprecatedUsage: deprecatedUsage,
  13924. unescaped: unescaped,
  13925. quoteMark: quoteMark
  13926. };
  13927. }
  13928. function handleDeprecatedContructorOpts(opts) {
  13929. if (opts.quoteMark !== undefined) {
  13930. return opts;
  13931. }
  13932. if (opts.value === undefined) {
  13933. return opts;
  13934. }
  13935. warnOfDeprecatedConstructor();
  13936. var _unescapeValue = unescapeValue(opts.value),
  13937. quoteMark = _unescapeValue.quoteMark,
  13938. unescaped = _unescapeValue.unescaped;
  13939. if (!opts.raws) {
  13940. opts.raws = {};
  13941. }
  13942. if (opts.raws.value === undefined) {
  13943. opts.raws.value = opts.value;
  13944. }
  13945. opts.value = unescaped;
  13946. opts.quoteMark = quoteMark;
  13947. return opts;
  13948. }
  13949. var Attribute = /*#__PURE__*/function (_Namespace) {
  13950. _inheritsLoose(Attribute, _Namespace);
  13951. function Attribute(opts) {
  13952. var _this;
  13953. if (opts === void 0) {
  13954. opts = {};
  13955. }
  13956. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  13957. _this.type = _types.ATTRIBUTE;
  13958. _this.raws = _this.raws || {};
  13959. Object.defineProperty(_this.raws, 'unquoted', {
  13960. get: deprecate(function () {
  13961. return _this.value;
  13962. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  13963. set: deprecate(function () {
  13964. return _this.value;
  13965. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  13966. });
  13967. _this._constructed = true;
  13968. return _this;
  13969. }
  13970. /**
  13971. * Returns the Attribute's value quoted such that it would be legal to use
  13972. * in the value of a css file. The original value's quotation setting
  13973. * used for stringification is left unchanged. See `setValue(value, options)`
  13974. * if you want to control the quote settings of a new value for the attribute.
  13975. *
  13976. * You can also change the quotation used for the current value by setting quoteMark.
  13977. *
  13978. * Options:
  13979. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  13980. * option is not set, the original value for quoteMark will be used. If
  13981. * indeterminate, a double quote is used. The legal values are:
  13982. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  13983. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  13984. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  13985. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  13986. * over the quoteMark option value.
  13987. * * smart {boolean} - if true, will select a quote mark based on the value
  13988. * and the other options specified here. See the `smartQuoteMark()`
  13989. * method.
  13990. **/
  13991. var _proto = Attribute.prototype;
  13992. _proto.getQuotedValue = function getQuotedValue(options) {
  13993. if (options === void 0) {
  13994. options = {};
  13995. }
  13996. var quoteMark = this._determineQuoteMark(options);
  13997. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  13998. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  13999. return escaped;
  14000. };
  14001. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  14002. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  14003. }
  14004. /**
  14005. * Set the unescaped value with the specified quotation options. The value
  14006. * provided must not include any wrapping quote marks -- those quotes will
  14007. * be interpreted as part of the value and escaped accordingly.
  14008. */;
  14009. _proto.setValue = function setValue(value, options) {
  14010. if (options === void 0) {
  14011. options = {};
  14012. }
  14013. this._value = value;
  14014. this._quoteMark = this._determineQuoteMark(options);
  14015. this._syncRawValue();
  14016. }
  14017. /**
  14018. * Intelligently select a quoteMark value based on the value's contents. If
  14019. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  14020. * mark will be picked that minimizes the number of escapes.
  14021. *
  14022. * If there's no clear winner, the quote mark from these options is used,
  14023. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  14024. * true). If the quoteMark is unspecified, a double quote is used.
  14025. *
  14026. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  14027. * from the quoteValue method.
  14028. */;
  14029. _proto.smartQuoteMark = function smartQuoteMark(options) {
  14030. var v = this.value;
  14031. var numSingleQuotes = v.replace(/[^']/g, '').length;
  14032. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  14033. if (numSingleQuotes + numDoubleQuotes === 0) {
  14034. var escaped = (0, _cssesc["default"])(v, {
  14035. isIdentifier: true
  14036. });
  14037. if (escaped === v) {
  14038. return Attribute.NO_QUOTE;
  14039. } else {
  14040. var pref = this.preferredQuoteMark(options);
  14041. if (pref === Attribute.NO_QUOTE) {
  14042. // pick a quote mark that isn't none and see if it's smaller
  14043. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  14044. var opts = CSSESC_QUOTE_OPTIONS[quote];
  14045. var quoteValue = (0, _cssesc["default"])(v, opts);
  14046. if (quoteValue.length < escaped.length) {
  14047. return quote;
  14048. }
  14049. }
  14050. return pref;
  14051. }
  14052. } else if (numDoubleQuotes === numSingleQuotes) {
  14053. return this.preferredQuoteMark(options);
  14054. } else if (numDoubleQuotes < numSingleQuotes) {
  14055. return Attribute.DOUBLE_QUOTE;
  14056. } else {
  14057. return Attribute.SINGLE_QUOTE;
  14058. }
  14059. }
  14060. /**
  14061. * Selects the preferred quote mark based on the options and the current quote mark value.
  14062. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  14063. * instead.
  14064. */;
  14065. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  14066. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  14067. if (quoteMark === undefined) {
  14068. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  14069. }
  14070. if (quoteMark === undefined) {
  14071. quoteMark = Attribute.DOUBLE_QUOTE;
  14072. }
  14073. return quoteMark;
  14074. };
  14075. _proto._syncRawValue = function _syncRawValue() {
  14076. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  14077. if (rawValue === this._value) {
  14078. if (this.raws) {
  14079. delete this.raws.value;
  14080. }
  14081. } else {
  14082. this.raws.value = rawValue;
  14083. }
  14084. };
  14085. _proto._handleEscapes = function _handleEscapes(prop, value) {
  14086. if (this._constructed) {
  14087. var escaped = (0, _cssesc["default"])(value, {
  14088. isIdentifier: true
  14089. });
  14090. if (escaped !== value) {
  14091. this.raws[prop] = escaped;
  14092. } else {
  14093. delete this.raws[prop];
  14094. }
  14095. }
  14096. };
  14097. _proto._spacesFor = function _spacesFor(name) {
  14098. var attrSpaces = {
  14099. before: '',
  14100. after: ''
  14101. };
  14102. var spaces = this.spaces[name] || {};
  14103. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  14104. return Object.assign(attrSpaces, spaces, rawSpaces);
  14105. };
  14106. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  14107. if (spaceName === void 0) {
  14108. spaceName = name;
  14109. }
  14110. if (concat === void 0) {
  14111. concat = defaultAttrConcat;
  14112. }
  14113. var attrSpaces = this._spacesFor(spaceName);
  14114. return concat(this.stringifyProperty(name), attrSpaces);
  14115. }
  14116. /**
  14117. * returns the offset of the attribute part specified relative to the
  14118. * start of the node of the output string.
  14119. *
  14120. * * "ns" - alias for "namespace"
  14121. * * "namespace" - the namespace if it exists.
  14122. * * "attribute" - the attribute name
  14123. * * "attributeNS" - the start of the attribute or its namespace
  14124. * * "operator" - the match operator of the attribute
  14125. * * "value" - The value (string or identifier)
  14126. * * "insensitive" - the case insensitivity flag;
  14127. * @param part One of the possible values inside an attribute.
  14128. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  14129. */;
  14130. _proto.offsetOf = function offsetOf(name) {
  14131. var count = 1;
  14132. var attributeSpaces = this._spacesFor("attribute");
  14133. count += attributeSpaces.before.length;
  14134. if (name === "namespace" || name === "ns") {
  14135. return this.namespace ? count : -1;
  14136. }
  14137. if (name === "attributeNS") {
  14138. return count;
  14139. }
  14140. count += this.namespaceString.length;
  14141. if (this.namespace) {
  14142. count += 1;
  14143. }
  14144. if (name === "attribute") {
  14145. return count;
  14146. }
  14147. count += this.stringifyProperty("attribute").length;
  14148. count += attributeSpaces.after.length;
  14149. var operatorSpaces = this._spacesFor("operator");
  14150. count += operatorSpaces.before.length;
  14151. var operator = this.stringifyProperty("operator");
  14152. if (name === "operator") {
  14153. return operator ? count : -1;
  14154. }
  14155. count += operator.length;
  14156. count += operatorSpaces.after.length;
  14157. var valueSpaces = this._spacesFor("value");
  14158. count += valueSpaces.before.length;
  14159. var value = this.stringifyProperty("value");
  14160. if (name === "value") {
  14161. return value ? count : -1;
  14162. }
  14163. count += value.length;
  14164. count += valueSpaces.after.length;
  14165. var insensitiveSpaces = this._spacesFor("insensitive");
  14166. count += insensitiveSpaces.before.length;
  14167. if (name === "insensitive") {
  14168. return this.insensitive ? count : -1;
  14169. }
  14170. return -1;
  14171. };
  14172. _proto.toString = function toString() {
  14173. var _this2 = this;
  14174. var selector = [this.rawSpaceBefore, '['];
  14175. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14176. if (this.operator && (this.value || this.value === '')) {
  14177. selector.push(this._stringFor('operator'));
  14178. selector.push(this._stringFor('value'));
  14179. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14180. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14181. attrSpaces.before = " ";
  14182. }
  14183. return defaultAttrConcat(attrValue, attrSpaces);
  14184. }));
  14185. }
  14186. selector.push(']');
  14187. selector.push(this.rawSpaceAfter);
  14188. return selector.join('');
  14189. };
  14190. _createClass(Attribute, [{
  14191. key: "quoted",
  14192. get: function get() {
  14193. var qm = this.quoteMark;
  14194. return qm === "'" || qm === '"';
  14195. },
  14196. set: function set(value) {
  14197. warnOfDeprecatedQuotedAssignment();
  14198. }
  14199. /**
  14200. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14201. * returns `null` if the value is not quoted.
  14202. * returns `undefined` if the quotation state is unknown (this can happen when
  14203. * the attribute is constructed without specifying a quote mark.)
  14204. */
  14205. }, {
  14206. key: "quoteMark",
  14207. get: function get() {
  14208. return this._quoteMark;
  14209. }
  14210. /**
  14211. * Set the quote mark to be used by this attribute's value.
  14212. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14213. * value is updated accordingly.
  14214. *
  14215. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14216. */,
  14217. set: function set(quoteMark) {
  14218. if (!this._constructed) {
  14219. this._quoteMark = quoteMark;
  14220. return;
  14221. }
  14222. if (this._quoteMark !== quoteMark) {
  14223. this._quoteMark = quoteMark;
  14224. this._syncRawValue();
  14225. }
  14226. }
  14227. }, {
  14228. key: "qualifiedAttribute",
  14229. get: function get() {
  14230. return this.qualifiedName(this.raws.attribute || this.attribute);
  14231. }
  14232. }, {
  14233. key: "insensitiveFlag",
  14234. get: function get() {
  14235. return this.insensitive ? 'i' : '';
  14236. }
  14237. }, {
  14238. key: "value",
  14239. get: function get() {
  14240. return this._value;
  14241. },
  14242. set:
  14243. /**
  14244. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14245. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14246. * is unescaped during parsing and any quote marks are removed.
  14247. *
  14248. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14249. * a deprecation warning is raised when the new value contains any characters that would
  14250. * require escaping (including if it contains wrapped quotes).
  14251. *
  14252. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14253. * how the new value is quoted.
  14254. */
  14255. function set(v) {
  14256. if (this._constructed) {
  14257. var _unescapeValue2 = unescapeValue(v),
  14258. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14259. unescaped = _unescapeValue2.unescaped,
  14260. quoteMark = _unescapeValue2.quoteMark;
  14261. if (deprecatedUsage) {
  14262. warnOfDeprecatedValueAssignment();
  14263. }
  14264. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14265. return;
  14266. }
  14267. this._value = unescaped;
  14268. this._quoteMark = quoteMark;
  14269. this._syncRawValue();
  14270. } else {
  14271. this._value = v;
  14272. }
  14273. }
  14274. }, {
  14275. key: "insensitive",
  14276. get: function get() {
  14277. return this._insensitive;
  14278. }
  14279. /**
  14280. * Set the case insensitive flag.
  14281. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14282. * of the attribute is updated accordingly.
  14283. *
  14284. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14285. */,
  14286. set: function set(insensitive) {
  14287. if (!insensitive) {
  14288. this._insensitive = false;
  14289. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14290. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14291. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14292. this.raws.insensitiveFlag = undefined;
  14293. }
  14294. }
  14295. this._insensitive = insensitive;
  14296. }
  14297. }, {
  14298. key: "attribute",
  14299. get: function get() {
  14300. return this._attribute;
  14301. },
  14302. set: function set(name) {
  14303. this._handleEscapes("attribute", name);
  14304. this._attribute = name;
  14305. }
  14306. }]);
  14307. return Attribute;
  14308. }(_namespace["default"]);
  14309. exports["default"] = Attribute;
  14310. Attribute.NO_QUOTE = null;
  14311. Attribute.SINGLE_QUOTE = "'";
  14312. Attribute.DOUBLE_QUOTE = '"';
  14313. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14314. "'": {
  14315. quotes: 'single',
  14316. wrap: true
  14317. },
  14318. '"': {
  14319. quotes: 'double',
  14320. wrap: true
  14321. }
  14322. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14323. isIdentifier: true
  14324. }, _CSSESC_QUOTE_OPTIONS);
  14325. function defaultAttrConcat(attrValue, attrSpaces) {
  14326. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14327. }
  14328. } (attribute));
  14329. return attribute;
  14330. }
  14331. var universal = {exports: {}};
  14332. var hasRequiredUniversal;
  14333. function requireUniversal () {
  14334. if (hasRequiredUniversal) return universal.exports;
  14335. hasRequiredUniversal = 1;
  14336. (function (module, exports) {
  14337. exports.__esModule = true;
  14338. exports["default"] = void 0;
  14339. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14340. var _types = /*@__PURE__*/ requireTypes();
  14341. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14342. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14343. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14344. var Universal = /*#__PURE__*/function (_Namespace) {
  14345. _inheritsLoose(Universal, _Namespace);
  14346. function Universal(opts) {
  14347. var _this;
  14348. _this = _Namespace.call(this, opts) || this;
  14349. _this.type = _types.UNIVERSAL;
  14350. _this.value = '*';
  14351. return _this;
  14352. }
  14353. return Universal;
  14354. }(_namespace["default"]);
  14355. exports["default"] = Universal;
  14356. module.exports = exports.default;
  14357. } (universal, universal.exports));
  14358. return universal.exports;
  14359. }
  14360. var combinator = {exports: {}};
  14361. var hasRequiredCombinator;
  14362. function requireCombinator () {
  14363. if (hasRequiredCombinator) return combinator.exports;
  14364. hasRequiredCombinator = 1;
  14365. (function (module, exports) {
  14366. exports.__esModule = true;
  14367. exports["default"] = void 0;
  14368. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14369. var _types = /*@__PURE__*/ requireTypes();
  14370. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14371. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14372. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14373. var Combinator = /*#__PURE__*/function (_Node) {
  14374. _inheritsLoose(Combinator, _Node);
  14375. function Combinator(opts) {
  14376. var _this;
  14377. _this = _Node.call(this, opts) || this;
  14378. _this.type = _types.COMBINATOR;
  14379. return _this;
  14380. }
  14381. return Combinator;
  14382. }(_node["default"]);
  14383. exports["default"] = Combinator;
  14384. module.exports = exports.default;
  14385. } (combinator, combinator.exports));
  14386. return combinator.exports;
  14387. }
  14388. var nesting = {exports: {}};
  14389. var hasRequiredNesting;
  14390. function requireNesting () {
  14391. if (hasRequiredNesting) return nesting.exports;
  14392. hasRequiredNesting = 1;
  14393. (function (module, exports) {
  14394. exports.__esModule = true;
  14395. exports["default"] = void 0;
  14396. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14397. var _types = /*@__PURE__*/ requireTypes();
  14398. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14399. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14400. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14401. var Nesting = /*#__PURE__*/function (_Node) {
  14402. _inheritsLoose(Nesting, _Node);
  14403. function Nesting(opts) {
  14404. var _this;
  14405. _this = _Node.call(this, opts) || this;
  14406. _this.type = _types.NESTING;
  14407. _this.value = '&';
  14408. return _this;
  14409. }
  14410. return Nesting;
  14411. }(_node["default"]);
  14412. exports["default"] = Nesting;
  14413. module.exports = exports.default;
  14414. } (nesting, nesting.exports));
  14415. return nesting.exports;
  14416. }
  14417. var sortAscending = {exports: {}};
  14418. var hasRequiredSortAscending;
  14419. function requireSortAscending () {
  14420. if (hasRequiredSortAscending) return sortAscending.exports;
  14421. hasRequiredSortAscending = 1;
  14422. (function (module, exports) {
  14423. exports.__esModule = true;
  14424. exports["default"] = sortAscending;
  14425. function sortAscending(list) {
  14426. return list.sort(function (a, b) {
  14427. return a - b;
  14428. });
  14429. }
  14430. module.exports = exports.default;
  14431. } (sortAscending, sortAscending.exports));
  14432. return sortAscending.exports;
  14433. }
  14434. var tokenize = {};
  14435. var tokenTypes = {};
  14436. var hasRequiredTokenTypes;
  14437. function requireTokenTypes () {
  14438. if (hasRequiredTokenTypes) return tokenTypes;
  14439. hasRequiredTokenTypes = 1;
  14440. tokenTypes.__esModule = true;
  14441. 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;
  14442. var ampersand = 38; // `&`.charCodeAt(0);
  14443. tokenTypes.ampersand = ampersand;
  14444. var asterisk = 42; // `*`.charCodeAt(0);
  14445. tokenTypes.asterisk = asterisk;
  14446. var at = 64; // `@`.charCodeAt(0);
  14447. tokenTypes.at = at;
  14448. var comma = 44; // `,`.charCodeAt(0);
  14449. tokenTypes.comma = comma;
  14450. var colon = 58; // `:`.charCodeAt(0);
  14451. tokenTypes.colon = colon;
  14452. var semicolon = 59; // `;`.charCodeAt(0);
  14453. tokenTypes.semicolon = semicolon;
  14454. var openParenthesis = 40; // `(`.charCodeAt(0);
  14455. tokenTypes.openParenthesis = openParenthesis;
  14456. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14457. tokenTypes.closeParenthesis = closeParenthesis;
  14458. var openSquare = 91; // `[`.charCodeAt(0);
  14459. tokenTypes.openSquare = openSquare;
  14460. var closeSquare = 93; // `]`.charCodeAt(0);
  14461. tokenTypes.closeSquare = closeSquare;
  14462. var dollar = 36; // `$`.charCodeAt(0);
  14463. tokenTypes.dollar = dollar;
  14464. var tilde = 126; // `~`.charCodeAt(0);
  14465. tokenTypes.tilde = tilde;
  14466. var caret = 94; // `^`.charCodeAt(0);
  14467. tokenTypes.caret = caret;
  14468. var plus = 43; // `+`.charCodeAt(0);
  14469. tokenTypes.plus = plus;
  14470. var equals = 61; // `=`.charCodeAt(0);
  14471. tokenTypes.equals = equals;
  14472. var pipe = 124; // `|`.charCodeAt(0);
  14473. tokenTypes.pipe = pipe;
  14474. var greaterThan = 62; // `>`.charCodeAt(0);
  14475. tokenTypes.greaterThan = greaterThan;
  14476. var space = 32; // ` `.charCodeAt(0);
  14477. tokenTypes.space = space;
  14478. var singleQuote = 39; // `'`.charCodeAt(0);
  14479. tokenTypes.singleQuote = singleQuote;
  14480. var doubleQuote = 34; // `"`.charCodeAt(0);
  14481. tokenTypes.doubleQuote = doubleQuote;
  14482. var slash = 47; // `/`.charCodeAt(0);
  14483. tokenTypes.slash = slash;
  14484. var bang = 33; // `!`.charCodeAt(0);
  14485. tokenTypes.bang = bang;
  14486. var backslash = 92; // '\\'.charCodeAt(0);
  14487. tokenTypes.backslash = backslash;
  14488. var cr = 13; // '\r'.charCodeAt(0);
  14489. tokenTypes.cr = cr;
  14490. var feed = 12; // '\f'.charCodeAt(0);
  14491. tokenTypes.feed = feed;
  14492. var newline = 10; // '\n'.charCodeAt(0);
  14493. tokenTypes.newline = newline;
  14494. var tab = 9; // '\t'.charCodeAt(0);
  14495. // Expose aliases primarily for readability.
  14496. tokenTypes.tab = tab;
  14497. var str = singleQuote;
  14498. // No good single character representation!
  14499. tokenTypes.str = str;
  14500. var comment = -1;
  14501. tokenTypes.comment = comment;
  14502. var word = -2;
  14503. tokenTypes.word = word;
  14504. var combinator = -3;
  14505. tokenTypes.combinator = combinator;
  14506. return tokenTypes;
  14507. }
  14508. var hasRequiredTokenize;
  14509. function requireTokenize () {
  14510. if (hasRequiredTokenize) return tokenize;
  14511. hasRequiredTokenize = 1;
  14512. (function (exports) {
  14513. exports.__esModule = true;
  14514. exports.FIELDS = void 0;
  14515. exports["default"] = tokenize;
  14516. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14517. var _unescapable, _wordDelimiters;
  14518. 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); }
  14519. function _interopRequireWildcard(obj, nodeInterop) { if (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; }
  14520. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14521. 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);
  14522. var hex = {};
  14523. var hexChars = "0123456789abcdefABCDEF";
  14524. for (var i = 0; i < hexChars.length; i++) {
  14525. hex[hexChars.charCodeAt(i)] = true;
  14526. }
  14527. /**
  14528. * Returns the last index of the bar css word
  14529. * @param {string} css The string in which the word begins
  14530. * @param {number} start The index into the string where word's first letter occurs
  14531. */
  14532. function consumeWord(css, start) {
  14533. var next = start;
  14534. var code;
  14535. do {
  14536. code = css.charCodeAt(next);
  14537. if (wordDelimiters[code]) {
  14538. return next - 1;
  14539. } else if (code === t.backslash) {
  14540. next = consumeEscape(css, next) + 1;
  14541. } else {
  14542. // All other characters are part of the word
  14543. next++;
  14544. }
  14545. } while (next < css.length);
  14546. return next - 1;
  14547. }
  14548. /**
  14549. * Returns the last index of the escape sequence
  14550. * @param {string} css The string in which the sequence begins
  14551. * @param {number} start The index into the string where escape character (`\`) occurs.
  14552. */
  14553. function consumeEscape(css, start) {
  14554. var next = start;
  14555. var code = css.charCodeAt(next + 1);
  14556. if (unescapable[code]) ; else if (hex[code]) {
  14557. var hexDigits = 0;
  14558. // consume up to 6 hex chars
  14559. do {
  14560. next++;
  14561. hexDigits++;
  14562. code = css.charCodeAt(next + 1);
  14563. } while (hex[code] && hexDigits < 6);
  14564. // if fewer than 6 hex chars, a trailing space ends the escape
  14565. if (hexDigits < 6 && code === t.space) {
  14566. next++;
  14567. }
  14568. } else {
  14569. // the next char is part of the current word
  14570. next++;
  14571. }
  14572. return next;
  14573. }
  14574. var FIELDS = {
  14575. TYPE: 0,
  14576. START_LINE: 1,
  14577. START_COL: 2,
  14578. END_LINE: 3,
  14579. END_COL: 4,
  14580. START_POS: 5,
  14581. END_POS: 6
  14582. };
  14583. exports.FIELDS = FIELDS;
  14584. function tokenize(input) {
  14585. var tokens = [];
  14586. var css = input.css.valueOf();
  14587. var _css = css,
  14588. length = _css.length;
  14589. var offset = -1;
  14590. var line = 1;
  14591. var start = 0;
  14592. var end = 0;
  14593. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14594. function unclosed(what, fix) {
  14595. if (input.safe) {
  14596. // fyi: this is never set to true.
  14597. css += fix;
  14598. next = css.length - 1;
  14599. } else {
  14600. throw input.error('Unclosed ' + what, line, start - offset, start);
  14601. }
  14602. }
  14603. while (start < length) {
  14604. code = css.charCodeAt(start);
  14605. if (code === t.newline) {
  14606. offset = start;
  14607. line += 1;
  14608. }
  14609. switch (code) {
  14610. case t.space:
  14611. case t.tab:
  14612. case t.newline:
  14613. case t.cr:
  14614. case t.feed:
  14615. next = start;
  14616. do {
  14617. next += 1;
  14618. code = css.charCodeAt(next);
  14619. if (code === t.newline) {
  14620. offset = next;
  14621. line += 1;
  14622. }
  14623. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  14624. tokenType = t.space;
  14625. endLine = line;
  14626. endColumn = next - offset - 1;
  14627. end = next;
  14628. break;
  14629. case t.plus:
  14630. case t.greaterThan:
  14631. case t.tilde:
  14632. case t.pipe:
  14633. next = start;
  14634. do {
  14635. next += 1;
  14636. code = css.charCodeAt(next);
  14637. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  14638. tokenType = t.combinator;
  14639. endLine = line;
  14640. endColumn = start - offset;
  14641. end = next;
  14642. break;
  14643. // Consume these characters as single tokens.
  14644. case t.asterisk:
  14645. case t.ampersand:
  14646. case t.bang:
  14647. case t.comma:
  14648. case t.equals:
  14649. case t.dollar:
  14650. case t.caret:
  14651. case t.openSquare:
  14652. case t.closeSquare:
  14653. case t.colon:
  14654. case t.semicolon:
  14655. case t.openParenthesis:
  14656. case t.closeParenthesis:
  14657. next = start;
  14658. tokenType = code;
  14659. endLine = line;
  14660. endColumn = start - offset;
  14661. end = next + 1;
  14662. break;
  14663. case t.singleQuote:
  14664. case t.doubleQuote:
  14665. quote = code === t.singleQuote ? "'" : '"';
  14666. next = start;
  14667. do {
  14668. escaped = false;
  14669. next = css.indexOf(quote, next + 1);
  14670. if (next === -1) {
  14671. unclosed('quote', quote);
  14672. }
  14673. escapePos = next;
  14674. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  14675. escapePos -= 1;
  14676. escaped = !escaped;
  14677. }
  14678. } while (escaped);
  14679. tokenType = t.str;
  14680. endLine = line;
  14681. endColumn = start - offset;
  14682. end = next + 1;
  14683. break;
  14684. default:
  14685. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  14686. next = css.indexOf('*/', start + 2) + 1;
  14687. if (next === 0) {
  14688. unclosed('comment', '*/');
  14689. }
  14690. content = css.slice(start, next + 1);
  14691. lines = content.split('\n');
  14692. last = lines.length - 1;
  14693. if (last > 0) {
  14694. nextLine = line + last;
  14695. nextOffset = next - lines[last].length;
  14696. } else {
  14697. nextLine = line;
  14698. nextOffset = offset;
  14699. }
  14700. tokenType = t.comment;
  14701. line = nextLine;
  14702. endLine = nextLine;
  14703. endColumn = next - nextOffset;
  14704. } else if (code === t.slash) {
  14705. next = start;
  14706. tokenType = code;
  14707. endLine = line;
  14708. endColumn = start - offset;
  14709. end = next + 1;
  14710. } else {
  14711. next = consumeWord(css, start);
  14712. tokenType = t.word;
  14713. endLine = line;
  14714. endColumn = next - offset;
  14715. }
  14716. end = next + 1;
  14717. break;
  14718. }
  14719. // Ensure that the token structure remains consistent
  14720. tokens.push([tokenType,
  14721. // [0] Token type
  14722. line,
  14723. // [1] Starting line
  14724. start - offset,
  14725. // [2] Starting column
  14726. endLine,
  14727. // [3] Ending line
  14728. endColumn,
  14729. // [4] Ending column
  14730. start,
  14731. // [5] Start position / Source index
  14732. end // [6] End position
  14733. ]);
  14734. // Reset offset for the next token
  14735. if (nextOffset) {
  14736. offset = nextOffset;
  14737. nextOffset = null;
  14738. }
  14739. start = end;
  14740. }
  14741. return tokens;
  14742. }
  14743. } (tokenize));
  14744. return tokenize;
  14745. }
  14746. var hasRequiredParser;
  14747. function requireParser () {
  14748. if (hasRequiredParser) return parser.exports;
  14749. hasRequiredParser = 1;
  14750. (function (module, exports) {
  14751. exports.__esModule = true;
  14752. exports["default"] = void 0;
  14753. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  14754. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  14755. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  14756. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  14757. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  14758. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  14759. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  14760. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  14761. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  14762. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  14763. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  14764. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  14765. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  14766. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  14767. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14768. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  14769. var _util = /*@__PURE__*/ requireUtil();
  14770. var _WHITESPACE_TOKENS, _Object$assign;
  14771. 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); }
  14772. function _interopRequireWildcard(obj, nodeInterop) { if (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; }
  14773. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14774. 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); } }
  14775. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14776. 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);
  14777. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  14778. function tokenStart(token) {
  14779. return {
  14780. line: token[_tokenize.FIELDS.START_LINE],
  14781. column: token[_tokenize.FIELDS.START_COL]
  14782. };
  14783. }
  14784. function tokenEnd(token) {
  14785. return {
  14786. line: token[_tokenize.FIELDS.END_LINE],
  14787. column: token[_tokenize.FIELDS.END_COL]
  14788. };
  14789. }
  14790. function getSource(startLine, startColumn, endLine, endColumn) {
  14791. return {
  14792. start: {
  14793. line: startLine,
  14794. column: startColumn
  14795. },
  14796. end: {
  14797. line: endLine,
  14798. column: endColumn
  14799. }
  14800. };
  14801. }
  14802. function getTokenSource(token) {
  14803. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  14804. }
  14805. function getTokenSourceSpan(startToken, endToken) {
  14806. if (!startToken) {
  14807. return undefined;
  14808. }
  14809. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  14810. }
  14811. function unescapeProp(node, prop) {
  14812. var value = node[prop];
  14813. if (typeof value !== "string") {
  14814. return;
  14815. }
  14816. if (value.indexOf("\\") !== -1) {
  14817. (0, _util.ensureObject)(node, 'raws');
  14818. node[prop] = (0, _util.unesc)(value);
  14819. if (node.raws[prop] === undefined) {
  14820. node.raws[prop] = value;
  14821. }
  14822. }
  14823. return node;
  14824. }
  14825. function indexesOf(array, item) {
  14826. var i = -1;
  14827. var indexes = [];
  14828. while ((i = array.indexOf(item, i + 1)) !== -1) {
  14829. indexes.push(i);
  14830. }
  14831. return indexes;
  14832. }
  14833. function uniqs() {
  14834. var list = Array.prototype.concat.apply([], arguments);
  14835. return list.filter(function (item, i) {
  14836. return i === list.indexOf(item);
  14837. });
  14838. }
  14839. var Parser = /*#__PURE__*/function () {
  14840. function Parser(rule, options) {
  14841. if (options === void 0) {
  14842. options = {};
  14843. }
  14844. this.rule = rule;
  14845. this.options = Object.assign({
  14846. lossy: false,
  14847. safe: false
  14848. }, options);
  14849. this.position = 0;
  14850. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  14851. this.tokens = (0, _tokenize["default"])({
  14852. css: this.css,
  14853. error: this._errorGenerator(),
  14854. safe: this.options.safe
  14855. });
  14856. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  14857. this.root = new _root["default"]({
  14858. source: rootSource
  14859. });
  14860. this.root.errorGenerator = this._errorGenerator();
  14861. var selector = new _selector["default"]({
  14862. source: {
  14863. start: {
  14864. line: 1,
  14865. column: 1
  14866. }
  14867. },
  14868. sourceIndex: 0
  14869. });
  14870. this.root.append(selector);
  14871. this.current = selector;
  14872. this.loop();
  14873. }
  14874. var _proto = Parser.prototype;
  14875. _proto._errorGenerator = function _errorGenerator() {
  14876. var _this = this;
  14877. return function (message, errorOptions) {
  14878. if (typeof _this.rule === 'string') {
  14879. return new Error(message);
  14880. }
  14881. return _this.rule.error(message, errorOptions);
  14882. };
  14883. };
  14884. _proto.attribute = function attribute() {
  14885. var attr = [];
  14886. var startingToken = this.currToken;
  14887. this.position++;
  14888. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14889. attr.push(this.currToken);
  14890. this.position++;
  14891. }
  14892. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14893. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  14894. }
  14895. var len = attr.length;
  14896. var node = {
  14897. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  14898. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  14899. };
  14900. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  14901. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  14902. }
  14903. var pos = 0;
  14904. var spaceBefore = '';
  14905. var commentBefore = '';
  14906. var lastAdded = null;
  14907. var spaceAfterMeaningfulToken = false;
  14908. while (pos < len) {
  14909. var token = attr[pos];
  14910. var content = this.content(token);
  14911. var next = attr[pos + 1];
  14912. switch (token[_tokenize.FIELDS.TYPE]) {
  14913. case tokens.space:
  14914. // if (
  14915. // len === 1 ||
  14916. // pos === 0 && this.content(next) === '|'
  14917. // ) {
  14918. // return this.expected('attribute', token[TOKEN.START_POS], content);
  14919. // }
  14920. spaceAfterMeaningfulToken = true;
  14921. if (this.options.lossy) {
  14922. break;
  14923. }
  14924. if (lastAdded) {
  14925. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  14926. var prevContent = node.spaces[lastAdded].after || '';
  14927. node.spaces[lastAdded].after = prevContent + content;
  14928. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  14929. if (existingComment) {
  14930. node.raws.spaces[lastAdded].after = existingComment + content;
  14931. }
  14932. } else {
  14933. spaceBefore = spaceBefore + content;
  14934. commentBefore = commentBefore + content;
  14935. }
  14936. break;
  14937. case tokens.asterisk:
  14938. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14939. node.operator = content;
  14940. lastAdded = 'operator';
  14941. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  14942. if (spaceBefore) {
  14943. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14944. node.spaces.attribute.before = spaceBefore;
  14945. spaceBefore = '';
  14946. }
  14947. if (commentBefore) {
  14948. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14949. node.raws.spaces.attribute.before = spaceBefore;
  14950. commentBefore = '';
  14951. }
  14952. node.namespace = (node.namespace || "") + content;
  14953. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  14954. if (rawValue) {
  14955. node.raws.namespace += content;
  14956. }
  14957. lastAdded = 'namespace';
  14958. }
  14959. spaceAfterMeaningfulToken = false;
  14960. break;
  14961. case tokens.dollar:
  14962. if (lastAdded === "value") {
  14963. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  14964. node.value += "$";
  14965. if (oldRawValue) {
  14966. node.raws.value = oldRawValue + "$";
  14967. }
  14968. break;
  14969. }
  14970. // Falls through
  14971. case tokens.caret:
  14972. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14973. node.operator = content;
  14974. lastAdded = 'operator';
  14975. }
  14976. spaceAfterMeaningfulToken = false;
  14977. break;
  14978. case tokens.combinator:
  14979. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14980. node.operator = content;
  14981. lastAdded = 'operator';
  14982. }
  14983. if (content !== '|') {
  14984. spaceAfterMeaningfulToken = false;
  14985. break;
  14986. }
  14987. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14988. node.operator = content;
  14989. lastAdded = 'operator';
  14990. } else if (!node.namespace && !node.attribute) {
  14991. node.namespace = true;
  14992. }
  14993. spaceAfterMeaningfulToken = false;
  14994. break;
  14995. case tokens.word:
  14996. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  14997. // this look-ahead probably fails with comment nodes involved.
  14998. !node.operator && !node.namespace) {
  14999. node.namespace = content;
  15000. lastAdded = 'namespace';
  15001. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  15002. if (spaceBefore) {
  15003. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  15004. node.spaces.attribute.before = spaceBefore;
  15005. spaceBefore = '';
  15006. }
  15007. if (commentBefore) {
  15008. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  15009. node.raws.spaces.attribute.before = commentBefore;
  15010. commentBefore = '';
  15011. }
  15012. node.attribute = (node.attribute || "") + content;
  15013. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  15014. if (_rawValue) {
  15015. node.raws.attribute += content;
  15016. }
  15017. lastAdded = 'attribute';
  15018. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  15019. var _unescaped = (0, _util.unesc)(content);
  15020. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  15021. var oldValue = node.value || '';
  15022. node.value = oldValue + _unescaped;
  15023. node.quoteMark = null;
  15024. if (_unescaped !== content || _oldRawValue) {
  15025. (0, _util.ensureObject)(node, 'raws');
  15026. node.raws.value = (_oldRawValue || oldValue) + content;
  15027. }
  15028. lastAdded = 'value';
  15029. } else {
  15030. var insensitive = content === 'i' || content === "I";
  15031. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  15032. node.insensitive = insensitive;
  15033. if (!insensitive || content === "I") {
  15034. (0, _util.ensureObject)(node, 'raws');
  15035. node.raws.insensitiveFlag = content;
  15036. }
  15037. lastAdded = 'insensitive';
  15038. if (spaceBefore) {
  15039. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  15040. node.spaces.insensitive.before = spaceBefore;
  15041. spaceBefore = '';
  15042. }
  15043. if (commentBefore) {
  15044. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  15045. node.raws.spaces.insensitive.before = commentBefore;
  15046. commentBefore = '';
  15047. }
  15048. } else if (node.value || node.value === '') {
  15049. lastAdded = 'value';
  15050. node.value += content;
  15051. if (node.raws.value) {
  15052. node.raws.value += content;
  15053. }
  15054. }
  15055. }
  15056. spaceAfterMeaningfulToken = false;
  15057. break;
  15058. case tokens.str:
  15059. if (!node.attribute || !node.operator) {
  15060. return this.error("Expected an attribute followed by an operator preceding the string.", {
  15061. index: token[_tokenize.FIELDS.START_POS]
  15062. });
  15063. }
  15064. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  15065. unescaped = _unescapeValue.unescaped,
  15066. quoteMark = _unescapeValue.quoteMark;
  15067. node.value = unescaped;
  15068. node.quoteMark = quoteMark;
  15069. lastAdded = 'value';
  15070. (0, _util.ensureObject)(node, 'raws');
  15071. node.raws.value = content;
  15072. spaceAfterMeaningfulToken = false;
  15073. break;
  15074. case tokens.equals:
  15075. if (!node.attribute) {
  15076. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  15077. }
  15078. if (node.value) {
  15079. return this.error('Unexpected "=" found; an operator was already defined.', {
  15080. index: token[_tokenize.FIELDS.START_POS]
  15081. });
  15082. }
  15083. node.operator = node.operator ? node.operator + content : content;
  15084. lastAdded = 'operator';
  15085. spaceAfterMeaningfulToken = false;
  15086. break;
  15087. case tokens.comment:
  15088. if (lastAdded) {
  15089. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  15090. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  15091. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  15092. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  15093. node.raws.spaces[lastAdded].after = rawLastComment + content;
  15094. } else {
  15095. var lastValue = node[lastAdded] || '';
  15096. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  15097. (0, _util.ensureObject)(node, 'raws');
  15098. node.raws[lastAdded] = rawLastValue + content;
  15099. }
  15100. } else {
  15101. commentBefore = commentBefore + content;
  15102. }
  15103. break;
  15104. default:
  15105. return this.error("Unexpected \"" + content + "\" found.", {
  15106. index: token[_tokenize.FIELDS.START_POS]
  15107. });
  15108. }
  15109. pos++;
  15110. }
  15111. unescapeProp(node, "attribute");
  15112. unescapeProp(node, "namespace");
  15113. this.newNode(new _attribute["default"](node));
  15114. this.position++;
  15115. }
  15116. /**
  15117. * return a node containing meaningless garbage up to (but not including) the specified token position.
  15118. * if the token position is negative, all remaining tokens are consumed.
  15119. *
  15120. * This returns an array containing a single string node if all whitespace,
  15121. * otherwise an array of comment nodes with space before and after.
  15122. *
  15123. * These tokens are not added to the current selector, the caller can add them or use them to amend
  15124. * a previous node's space metadata.
  15125. *
  15126. * In lossy mode, this returns only comments.
  15127. */;
  15128. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  15129. if (stopPosition < 0) {
  15130. stopPosition = this.tokens.length;
  15131. }
  15132. var startPosition = this.position;
  15133. var nodes = [];
  15134. var space = "";
  15135. var lastComment = undefined;
  15136. do {
  15137. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  15138. if (!this.options.lossy) {
  15139. space += this.content();
  15140. }
  15141. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  15142. var spaces = {};
  15143. if (space) {
  15144. spaces.before = space;
  15145. space = "";
  15146. }
  15147. lastComment = new _comment["default"]({
  15148. value: this.content(),
  15149. source: getTokenSource(this.currToken),
  15150. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15151. spaces: spaces
  15152. });
  15153. nodes.push(lastComment);
  15154. }
  15155. } while (++this.position < stopPosition);
  15156. if (space) {
  15157. if (lastComment) {
  15158. lastComment.spaces.after = space;
  15159. } else if (!this.options.lossy) {
  15160. var firstToken = this.tokens[startPosition];
  15161. var lastToken = this.tokens[this.position - 1];
  15162. nodes.push(new _string["default"]({
  15163. value: '',
  15164. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15165. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15166. spaces: {
  15167. before: space,
  15168. after: ''
  15169. }
  15170. }));
  15171. }
  15172. }
  15173. return nodes;
  15174. }
  15175. /**
  15176. *
  15177. * @param {*} nodes
  15178. */;
  15179. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15180. var _this2 = this;
  15181. if (requiredSpace === void 0) {
  15182. requiredSpace = false;
  15183. }
  15184. var space = "";
  15185. var rawSpace = "";
  15186. nodes.forEach(function (n) {
  15187. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15188. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15189. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15190. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15191. });
  15192. if (rawSpace === space) {
  15193. rawSpace = undefined;
  15194. }
  15195. var result = {
  15196. space: space,
  15197. rawSpace: rawSpace
  15198. };
  15199. return result;
  15200. };
  15201. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15202. if (position === void 0) {
  15203. position = this.position;
  15204. }
  15205. 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;
  15206. };
  15207. _proto.namedCombinator = function namedCombinator() {
  15208. if (this.isNamedCombinator()) {
  15209. var nameRaw = this.content(this.tokens[this.position + 1]);
  15210. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15211. var raws = {};
  15212. if (name !== nameRaw) {
  15213. raws.value = "/" + nameRaw + "/";
  15214. }
  15215. var node = new _combinator["default"]({
  15216. value: "/" + name + "/",
  15217. 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]),
  15218. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15219. raws: raws
  15220. });
  15221. this.position = this.position + 3;
  15222. return node;
  15223. } else {
  15224. this.unexpected();
  15225. }
  15226. };
  15227. _proto.combinator = function combinator() {
  15228. var _this3 = this;
  15229. if (this.content() === '|') {
  15230. return this.namespace();
  15231. }
  15232. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15233. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15234. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15235. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15236. if (nodes.length > 0) {
  15237. var last = this.current.last;
  15238. if (last) {
  15239. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15240. space = _this$convertWhitespa.space,
  15241. rawSpace = _this$convertWhitespa.rawSpace;
  15242. if (rawSpace !== undefined) {
  15243. last.rawSpaceAfter += rawSpace;
  15244. }
  15245. last.spaces.after += space;
  15246. } else {
  15247. nodes.forEach(function (n) {
  15248. return _this3.newNode(n);
  15249. });
  15250. }
  15251. }
  15252. return;
  15253. }
  15254. var firstToken = this.currToken;
  15255. var spaceOrDescendantSelectorNodes = undefined;
  15256. if (nextSigTokenPos > this.position) {
  15257. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15258. }
  15259. var node;
  15260. if (this.isNamedCombinator()) {
  15261. node = this.namedCombinator();
  15262. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15263. node = new _combinator["default"]({
  15264. value: this.content(),
  15265. source: getTokenSource(this.currToken),
  15266. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15267. });
  15268. this.position++;
  15269. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15270. this.unexpected();
  15271. }
  15272. if (node) {
  15273. if (spaceOrDescendantSelectorNodes) {
  15274. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15275. _space = _this$convertWhitespa2.space,
  15276. _rawSpace = _this$convertWhitespa2.rawSpace;
  15277. node.spaces.before = _space;
  15278. node.rawSpaceBefore = _rawSpace;
  15279. }
  15280. } else {
  15281. // descendant combinator
  15282. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15283. _space2 = _this$convertWhitespa3.space,
  15284. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15285. if (!_rawSpace2) {
  15286. _rawSpace2 = _space2;
  15287. }
  15288. var spaces = {};
  15289. var raws = {
  15290. spaces: {}
  15291. };
  15292. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15293. spaces.before = _space2.slice(0, _space2.length - 1);
  15294. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15295. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15296. spaces.after = _space2.slice(1);
  15297. raws.spaces.after = _rawSpace2.slice(1);
  15298. } else {
  15299. raws.value = _rawSpace2;
  15300. }
  15301. node = new _combinator["default"]({
  15302. value: ' ',
  15303. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15304. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15305. spaces: spaces,
  15306. raws: raws
  15307. });
  15308. }
  15309. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15310. node.spaces.after = this.optionalSpace(this.content());
  15311. this.position++;
  15312. }
  15313. return this.newNode(node);
  15314. };
  15315. _proto.comma = function comma() {
  15316. if (this.position === this.tokens.length - 1) {
  15317. this.root.trailingComma = true;
  15318. this.position++;
  15319. return;
  15320. }
  15321. this.current._inferEndPosition();
  15322. var selector = new _selector["default"]({
  15323. source: {
  15324. start: tokenStart(this.tokens[this.position + 1])
  15325. },
  15326. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15327. });
  15328. this.current.parent.append(selector);
  15329. this.current = selector;
  15330. this.position++;
  15331. };
  15332. _proto.comment = function comment() {
  15333. var current = this.currToken;
  15334. this.newNode(new _comment["default"]({
  15335. value: this.content(),
  15336. source: getTokenSource(current),
  15337. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15338. }));
  15339. this.position++;
  15340. };
  15341. _proto.error = function error(message, opts) {
  15342. throw this.root.error(message, opts);
  15343. };
  15344. _proto.missingBackslash = function missingBackslash() {
  15345. return this.error('Expected a backslash preceding the semicolon.', {
  15346. index: this.currToken[_tokenize.FIELDS.START_POS]
  15347. });
  15348. };
  15349. _proto.missingParenthesis = function missingParenthesis() {
  15350. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15351. };
  15352. _proto.missingSquareBracket = function missingSquareBracket() {
  15353. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15354. };
  15355. _proto.unexpected = function unexpected() {
  15356. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15357. };
  15358. _proto.unexpectedPipe = function unexpectedPipe() {
  15359. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15360. };
  15361. _proto.namespace = function namespace() {
  15362. var before = this.prevToken && this.content(this.prevToken) || true;
  15363. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15364. this.position++;
  15365. return this.word(before);
  15366. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15367. this.position++;
  15368. return this.universal(before);
  15369. }
  15370. this.unexpectedPipe();
  15371. };
  15372. _proto.nesting = function nesting() {
  15373. if (this.nextToken) {
  15374. var nextContent = this.content(this.nextToken);
  15375. if (nextContent === "|") {
  15376. this.position++;
  15377. return;
  15378. }
  15379. }
  15380. var current = this.currToken;
  15381. this.newNode(new _nesting["default"]({
  15382. value: this.content(),
  15383. source: getTokenSource(current),
  15384. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15385. }));
  15386. this.position++;
  15387. };
  15388. _proto.parentheses = function parentheses() {
  15389. var last = this.current.last;
  15390. var unbalanced = 1;
  15391. this.position++;
  15392. if (last && last.type === types.PSEUDO) {
  15393. var selector = new _selector["default"]({
  15394. source: {
  15395. start: tokenStart(this.tokens[this.position])
  15396. },
  15397. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15398. });
  15399. var cache = this.current;
  15400. last.append(selector);
  15401. this.current = selector;
  15402. while (this.position < this.tokens.length && unbalanced) {
  15403. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15404. unbalanced++;
  15405. }
  15406. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15407. unbalanced--;
  15408. }
  15409. if (unbalanced) {
  15410. this.parse();
  15411. } else {
  15412. this.current.source.end = tokenEnd(this.currToken);
  15413. this.current.parent.source.end = tokenEnd(this.currToken);
  15414. this.position++;
  15415. }
  15416. }
  15417. this.current = cache;
  15418. } else {
  15419. // I think this case should be an error. It's used to implement a basic parse of media queries
  15420. // but I don't think it's a good idea.
  15421. var parenStart = this.currToken;
  15422. var parenValue = "(";
  15423. var parenEnd;
  15424. while (this.position < this.tokens.length && unbalanced) {
  15425. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15426. unbalanced++;
  15427. }
  15428. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15429. unbalanced--;
  15430. }
  15431. parenEnd = this.currToken;
  15432. parenValue += this.parseParenthesisToken(this.currToken);
  15433. this.position++;
  15434. }
  15435. if (last) {
  15436. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15437. } else {
  15438. this.newNode(new _string["default"]({
  15439. value: parenValue,
  15440. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15441. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15442. }));
  15443. }
  15444. }
  15445. if (unbalanced) {
  15446. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15447. }
  15448. };
  15449. _proto.pseudo = function pseudo() {
  15450. var _this4 = this;
  15451. var pseudoStr = '';
  15452. var startingToken = this.currToken;
  15453. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15454. pseudoStr += this.content();
  15455. this.position++;
  15456. }
  15457. if (!this.currToken) {
  15458. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15459. }
  15460. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15461. this.splitWord(false, function (first, length) {
  15462. pseudoStr += first;
  15463. _this4.newNode(new _pseudo["default"]({
  15464. value: pseudoStr,
  15465. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15466. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15467. }));
  15468. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15469. _this4.error('Misplaced parenthesis.', {
  15470. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15471. });
  15472. }
  15473. });
  15474. } else {
  15475. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15476. }
  15477. };
  15478. _proto.space = function space() {
  15479. var content = this.content();
  15480. // Handle space before and after the selector
  15481. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15482. return node.type === 'comment';
  15483. })) {
  15484. this.spaces = this.optionalSpace(content);
  15485. this.position++;
  15486. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15487. this.current.last.spaces.after = this.optionalSpace(content);
  15488. this.position++;
  15489. } else {
  15490. this.combinator();
  15491. }
  15492. };
  15493. _proto.string = function string() {
  15494. var current = this.currToken;
  15495. this.newNode(new _string["default"]({
  15496. value: this.content(),
  15497. source: getTokenSource(current),
  15498. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15499. }));
  15500. this.position++;
  15501. };
  15502. _proto.universal = function universal(namespace) {
  15503. var nextToken = this.nextToken;
  15504. if (nextToken && this.content(nextToken) === '|') {
  15505. this.position++;
  15506. return this.namespace();
  15507. }
  15508. var current = this.currToken;
  15509. this.newNode(new _universal["default"]({
  15510. value: this.content(),
  15511. source: getTokenSource(current),
  15512. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15513. }), namespace);
  15514. this.position++;
  15515. };
  15516. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15517. var _this5 = this;
  15518. var nextToken = this.nextToken;
  15519. var word = this.content();
  15520. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15521. this.position++;
  15522. var current = this.content();
  15523. word += current;
  15524. if (current.lastIndexOf('\\') === current.length - 1) {
  15525. var next = this.nextToken;
  15526. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15527. word += this.requiredSpace(this.content(next));
  15528. this.position++;
  15529. }
  15530. }
  15531. nextToken = this.nextToken;
  15532. }
  15533. var hasClass = indexesOf(word, '.').filter(function (i) {
  15534. // Allow escaped dot within class name
  15535. var escapedDot = word[i - 1] === '\\';
  15536. // Allow decimal numbers percent in @keyframes
  15537. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15538. return !escapedDot && !isKeyframesPercent;
  15539. });
  15540. var hasId = indexesOf(word, '#').filter(function (i) {
  15541. return word[i - 1] !== '\\';
  15542. });
  15543. // Eliminate Sass interpolations from the list of id indexes
  15544. var interpolations = indexesOf(word, '#{');
  15545. if (interpolations.length) {
  15546. hasId = hasId.filter(function (hashIndex) {
  15547. return !~interpolations.indexOf(hashIndex);
  15548. });
  15549. }
  15550. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15551. indices.forEach(function (ind, i) {
  15552. var index = indices[i + 1] || word.length;
  15553. var value = word.slice(ind, index);
  15554. if (i === 0 && firstCallback) {
  15555. return firstCallback.call(_this5, value, indices.length);
  15556. }
  15557. var node;
  15558. var current = _this5.currToken;
  15559. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15560. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15561. if (~hasClass.indexOf(ind)) {
  15562. var classNameOpts = {
  15563. value: value.slice(1),
  15564. source: source,
  15565. sourceIndex: sourceIndex
  15566. };
  15567. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15568. } else if (~hasId.indexOf(ind)) {
  15569. var idOpts = {
  15570. value: value.slice(1),
  15571. source: source,
  15572. sourceIndex: sourceIndex
  15573. };
  15574. node = new _id["default"](unescapeProp(idOpts, "value"));
  15575. } else {
  15576. var tagOpts = {
  15577. value: value,
  15578. source: source,
  15579. sourceIndex: sourceIndex
  15580. };
  15581. unescapeProp(tagOpts, "value");
  15582. node = new _tag["default"](tagOpts);
  15583. }
  15584. _this5.newNode(node, namespace);
  15585. // Ensure that the namespace is used only once
  15586. namespace = null;
  15587. });
  15588. this.position++;
  15589. };
  15590. _proto.word = function word(namespace) {
  15591. var nextToken = this.nextToken;
  15592. if (nextToken && this.content(nextToken) === '|') {
  15593. this.position++;
  15594. return this.namespace();
  15595. }
  15596. return this.splitWord(namespace);
  15597. };
  15598. _proto.loop = function loop() {
  15599. while (this.position < this.tokens.length) {
  15600. this.parse(true);
  15601. }
  15602. this.current._inferEndPosition();
  15603. return this.root;
  15604. };
  15605. _proto.parse = function parse(throwOnParenthesis) {
  15606. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  15607. case tokens.space:
  15608. this.space();
  15609. break;
  15610. case tokens.comment:
  15611. this.comment();
  15612. break;
  15613. case tokens.openParenthesis:
  15614. this.parentheses();
  15615. break;
  15616. case tokens.closeParenthesis:
  15617. if (throwOnParenthesis) {
  15618. this.missingParenthesis();
  15619. }
  15620. break;
  15621. case tokens.openSquare:
  15622. this.attribute();
  15623. break;
  15624. case tokens.dollar:
  15625. case tokens.caret:
  15626. case tokens.equals:
  15627. case tokens.word:
  15628. this.word();
  15629. break;
  15630. case tokens.colon:
  15631. this.pseudo();
  15632. break;
  15633. case tokens.comma:
  15634. this.comma();
  15635. break;
  15636. case tokens.asterisk:
  15637. this.universal();
  15638. break;
  15639. case tokens.ampersand:
  15640. this.nesting();
  15641. break;
  15642. case tokens.slash:
  15643. case tokens.combinator:
  15644. this.combinator();
  15645. break;
  15646. case tokens.str:
  15647. this.string();
  15648. break;
  15649. // These cases throw; no break needed.
  15650. case tokens.closeSquare:
  15651. this.missingSquareBracket();
  15652. case tokens.semicolon:
  15653. this.missingBackslash();
  15654. default:
  15655. this.unexpected();
  15656. }
  15657. }
  15658. /**
  15659. * Helpers
  15660. */;
  15661. _proto.expected = function expected(description, index, found) {
  15662. if (Array.isArray(description)) {
  15663. var last = description.pop();
  15664. description = description.join(', ') + " or " + last;
  15665. }
  15666. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  15667. if (!found) {
  15668. return this.error("Expected " + an + " " + description + ".", {
  15669. index: index
  15670. });
  15671. }
  15672. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  15673. index: index
  15674. });
  15675. };
  15676. _proto.requiredSpace = function requiredSpace(space) {
  15677. return this.options.lossy ? ' ' : space;
  15678. };
  15679. _proto.optionalSpace = function optionalSpace(space) {
  15680. return this.options.lossy ? '' : space;
  15681. };
  15682. _proto.lossySpace = function lossySpace(space, required) {
  15683. if (this.options.lossy) {
  15684. return required ? ' ' : '';
  15685. } else {
  15686. return space;
  15687. }
  15688. };
  15689. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  15690. var content = this.content(token);
  15691. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  15692. return this.requiredSpace(content);
  15693. } else {
  15694. return content;
  15695. }
  15696. };
  15697. _proto.newNode = function newNode(node, namespace) {
  15698. if (namespace) {
  15699. if (/^ +$/.test(namespace)) {
  15700. if (!this.options.lossy) {
  15701. this.spaces = (this.spaces || '') + namespace;
  15702. }
  15703. namespace = true;
  15704. }
  15705. node.namespace = namespace;
  15706. unescapeProp(node, "namespace");
  15707. }
  15708. if (this.spaces) {
  15709. node.spaces.before = this.spaces;
  15710. this.spaces = '';
  15711. }
  15712. return this.current.append(node);
  15713. };
  15714. _proto.content = function content(token) {
  15715. if (token === void 0) {
  15716. token = this.currToken;
  15717. }
  15718. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  15719. };
  15720. /**
  15721. * returns the index of the next non-whitespace, non-comment token.
  15722. * returns -1 if no meaningful token is found.
  15723. */
  15724. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  15725. if (startPosition === void 0) {
  15726. startPosition = this.position + 1;
  15727. }
  15728. var searchPosition = startPosition;
  15729. while (searchPosition < this.tokens.length) {
  15730. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  15731. searchPosition++;
  15732. continue;
  15733. } else {
  15734. return searchPosition;
  15735. }
  15736. }
  15737. return -1;
  15738. };
  15739. _createClass(Parser, [{
  15740. key: "currToken",
  15741. get: function get() {
  15742. return this.tokens[this.position];
  15743. }
  15744. }, {
  15745. key: "nextToken",
  15746. get: function get() {
  15747. return this.tokens[this.position + 1];
  15748. }
  15749. }, {
  15750. key: "prevToken",
  15751. get: function get() {
  15752. return this.tokens[this.position - 1];
  15753. }
  15754. }]);
  15755. return Parser;
  15756. }();
  15757. exports["default"] = Parser;
  15758. module.exports = exports.default;
  15759. } (parser, parser.exports));
  15760. return parser.exports;
  15761. }
  15762. var hasRequiredProcessor;
  15763. function requireProcessor () {
  15764. if (hasRequiredProcessor) return processor.exports;
  15765. hasRequiredProcessor = 1;
  15766. (function (module, exports) {
  15767. exports.__esModule = true;
  15768. exports["default"] = void 0;
  15769. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  15770. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15771. var Processor = /*#__PURE__*/function () {
  15772. function Processor(func, options) {
  15773. this.func = func || function noop() {};
  15774. this.funcRes = null;
  15775. this.options = options;
  15776. }
  15777. var _proto = Processor.prototype;
  15778. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  15779. if (options === void 0) {
  15780. options = {};
  15781. }
  15782. var merged = Object.assign({}, this.options, options);
  15783. if (merged.updateSelector === false) {
  15784. return false;
  15785. } else {
  15786. return typeof rule !== "string";
  15787. }
  15788. };
  15789. _proto._isLossy = function _isLossy(options) {
  15790. if (options === void 0) {
  15791. options = {};
  15792. }
  15793. var merged = Object.assign({}, this.options, options);
  15794. if (merged.lossless === false) {
  15795. return true;
  15796. } else {
  15797. return false;
  15798. }
  15799. };
  15800. _proto._root = function _root(rule, options) {
  15801. if (options === void 0) {
  15802. options = {};
  15803. }
  15804. var parser = new _parser["default"](rule, this._parseOptions(options));
  15805. return parser.root;
  15806. };
  15807. _proto._parseOptions = function _parseOptions(options) {
  15808. return {
  15809. lossy: this._isLossy(options)
  15810. };
  15811. };
  15812. _proto._run = function _run(rule, options) {
  15813. var _this = this;
  15814. if (options === void 0) {
  15815. options = {};
  15816. }
  15817. return new Promise(function (resolve, reject) {
  15818. try {
  15819. var root = _this._root(rule, options);
  15820. Promise.resolve(_this.func(root)).then(function (transform) {
  15821. var string = undefined;
  15822. if (_this._shouldUpdateSelector(rule, options)) {
  15823. string = root.toString();
  15824. rule.selector = string;
  15825. }
  15826. return {
  15827. transform: transform,
  15828. root: root,
  15829. string: string
  15830. };
  15831. }).then(resolve, reject);
  15832. } catch (e) {
  15833. reject(e);
  15834. return;
  15835. }
  15836. });
  15837. };
  15838. _proto._runSync = function _runSync(rule, options) {
  15839. if (options === void 0) {
  15840. options = {};
  15841. }
  15842. var root = this._root(rule, options);
  15843. var transform = this.func(root);
  15844. if (transform && typeof transform.then === "function") {
  15845. throw new Error("Selector processor returned a promise to a synchronous call.");
  15846. }
  15847. var string = undefined;
  15848. if (options.updateSelector && typeof rule !== "string") {
  15849. string = root.toString();
  15850. rule.selector = string;
  15851. }
  15852. return {
  15853. transform: transform,
  15854. root: root,
  15855. string: string
  15856. };
  15857. }
  15858. /**
  15859. * Process rule into a selector AST.
  15860. *
  15861. * @param rule {postcss.Rule | string} The css selector to be processed
  15862. * @param options The options for processing
  15863. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  15864. */;
  15865. _proto.ast = function ast(rule, options) {
  15866. return this._run(rule, options).then(function (result) {
  15867. return result.root;
  15868. });
  15869. }
  15870. /**
  15871. * Process rule into a selector AST synchronously.
  15872. *
  15873. * @param rule {postcss.Rule | string} The css selector to be processed
  15874. * @param options The options for processing
  15875. * @returns {parser.Root} The AST of the selector after processing it.
  15876. */;
  15877. _proto.astSync = function astSync(rule, options) {
  15878. return this._runSync(rule, options).root;
  15879. }
  15880. /**
  15881. * Process a selector into a transformed value asynchronously
  15882. *
  15883. * @param rule {postcss.Rule | string} The css selector to be processed
  15884. * @param options The options for processing
  15885. * @returns {Promise<any>} The value returned by the processor.
  15886. */;
  15887. _proto.transform = function transform(rule, options) {
  15888. return this._run(rule, options).then(function (result) {
  15889. return result.transform;
  15890. });
  15891. }
  15892. /**
  15893. * Process a selector into a transformed value synchronously.
  15894. *
  15895. * @param rule {postcss.Rule | string} The css selector to be processed
  15896. * @param options The options for processing
  15897. * @returns {any} The value returned by the processor.
  15898. */;
  15899. _proto.transformSync = function transformSync(rule, options) {
  15900. return this._runSync(rule, options).transform;
  15901. }
  15902. /**
  15903. * Process a selector into a new selector string asynchronously.
  15904. *
  15905. * @param rule {postcss.Rule | string} The css selector to be processed
  15906. * @param options The options for processing
  15907. * @returns {string} the selector after processing.
  15908. */;
  15909. _proto.process = function process(rule, options) {
  15910. return this._run(rule, options).then(function (result) {
  15911. return result.string || result.root.toString();
  15912. });
  15913. }
  15914. /**
  15915. * Process a selector into a new selector string synchronously.
  15916. *
  15917. * @param rule {postcss.Rule | string} The css selector to be processed
  15918. * @param options The options for processing
  15919. * @returns {string} the selector after processing.
  15920. */;
  15921. _proto.processSync = function processSync(rule, options) {
  15922. var result = this._runSync(rule, options);
  15923. return result.string || result.root.toString();
  15924. };
  15925. return Processor;
  15926. }();
  15927. exports["default"] = Processor;
  15928. module.exports = exports.default;
  15929. } (processor, processor.exports));
  15930. return processor.exports;
  15931. }
  15932. var selectors = {};
  15933. var constructors = {};
  15934. var hasRequiredConstructors;
  15935. function requireConstructors () {
  15936. if (hasRequiredConstructors) return constructors;
  15937. hasRequiredConstructors = 1;
  15938. constructors.__esModule = true;
  15939. 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;
  15940. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  15941. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15942. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15943. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15944. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15945. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15946. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15947. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15948. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15949. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15950. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15951. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15952. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15953. var attribute = function attribute(opts) {
  15954. return new _attribute["default"](opts);
  15955. };
  15956. constructors.attribute = attribute;
  15957. var className = function className(opts) {
  15958. return new _className["default"](opts);
  15959. };
  15960. constructors.className = className;
  15961. var combinator = function combinator(opts) {
  15962. return new _combinator["default"](opts);
  15963. };
  15964. constructors.combinator = combinator;
  15965. var comment = function comment(opts) {
  15966. return new _comment["default"](opts);
  15967. };
  15968. constructors.comment = comment;
  15969. var id = function id(opts) {
  15970. return new _id["default"](opts);
  15971. };
  15972. constructors.id = id;
  15973. var nesting = function nesting(opts) {
  15974. return new _nesting["default"](opts);
  15975. };
  15976. constructors.nesting = nesting;
  15977. var pseudo = function pseudo(opts) {
  15978. return new _pseudo["default"](opts);
  15979. };
  15980. constructors.pseudo = pseudo;
  15981. var root = function root(opts) {
  15982. return new _root["default"](opts);
  15983. };
  15984. constructors.root = root;
  15985. var selector = function selector(opts) {
  15986. return new _selector["default"](opts);
  15987. };
  15988. constructors.selector = selector;
  15989. var string = function string(opts) {
  15990. return new _string["default"](opts);
  15991. };
  15992. constructors.string = string;
  15993. var tag = function tag(opts) {
  15994. return new _tag["default"](opts);
  15995. };
  15996. constructors.tag = tag;
  15997. var universal = function universal(opts) {
  15998. return new _universal["default"](opts);
  15999. };
  16000. constructors.universal = universal;
  16001. return constructors;
  16002. }
  16003. var guards = {};
  16004. var hasRequiredGuards;
  16005. function requireGuards () {
  16006. if (hasRequiredGuards) return guards;
  16007. hasRequiredGuards = 1;
  16008. guards.__esModule = true;
  16009. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  16010. guards.isContainer = isContainer;
  16011. guards.isIdentifier = void 0;
  16012. guards.isNamespace = isNamespace;
  16013. guards.isNesting = void 0;
  16014. guards.isNode = isNode;
  16015. guards.isPseudo = void 0;
  16016. guards.isPseudoClass = isPseudoClass;
  16017. guards.isPseudoElement = isPseudoElement;
  16018. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  16019. var _types = /*@__PURE__*/ requireTypes();
  16020. var _IS_TYPE;
  16021. 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);
  16022. function isNode(node) {
  16023. return typeof node === "object" && IS_TYPE[node.type];
  16024. }
  16025. function isNodeType(type, node) {
  16026. return isNode(node) && node.type === type;
  16027. }
  16028. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  16029. guards.isAttribute = isAttribute;
  16030. var isClassName = isNodeType.bind(null, _types.CLASS);
  16031. guards.isClassName = isClassName;
  16032. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  16033. guards.isCombinator = isCombinator;
  16034. var isComment = isNodeType.bind(null, _types.COMMENT);
  16035. guards.isComment = isComment;
  16036. var isIdentifier = isNodeType.bind(null, _types.ID);
  16037. guards.isIdentifier = isIdentifier;
  16038. var isNesting = isNodeType.bind(null, _types.NESTING);
  16039. guards.isNesting = isNesting;
  16040. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  16041. guards.isPseudo = isPseudo;
  16042. var isRoot = isNodeType.bind(null, _types.ROOT);
  16043. guards.isRoot = isRoot;
  16044. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  16045. guards.isSelector = isSelector;
  16046. var isString = isNodeType.bind(null, _types.STRING);
  16047. guards.isString = isString;
  16048. var isTag = isNodeType.bind(null, _types.TAG);
  16049. guards.isTag = isTag;
  16050. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  16051. guards.isUniversal = isUniversal;
  16052. function isPseudoElement(node) {
  16053. 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");
  16054. }
  16055. function isPseudoClass(node) {
  16056. return isPseudo(node) && !isPseudoElement(node);
  16057. }
  16058. function isContainer(node) {
  16059. return !!(isNode(node) && node.walk);
  16060. }
  16061. function isNamespace(node) {
  16062. return isAttribute(node) || isTag(node);
  16063. }
  16064. return guards;
  16065. }
  16066. var hasRequiredSelectors;
  16067. function requireSelectors () {
  16068. if (hasRequiredSelectors) return selectors;
  16069. hasRequiredSelectors = 1;
  16070. (function (exports) {
  16071. exports.__esModule = true;
  16072. var _types = /*@__PURE__*/ requireTypes();
  16073. Object.keys(_types).forEach(function (key) {
  16074. if (key === "default" || key === "__esModule") return;
  16075. if (key in exports && exports[key] === _types[key]) return;
  16076. exports[key] = _types[key];
  16077. });
  16078. var _constructors = /*@__PURE__*/ requireConstructors();
  16079. Object.keys(_constructors).forEach(function (key) {
  16080. if (key === "default" || key === "__esModule") return;
  16081. if (key in exports && exports[key] === _constructors[key]) return;
  16082. exports[key] = _constructors[key];
  16083. });
  16084. var _guards = /*@__PURE__*/ requireGuards();
  16085. Object.keys(_guards).forEach(function (key) {
  16086. if (key === "default" || key === "__esModule") return;
  16087. if (key in exports && exports[key] === _guards[key]) return;
  16088. exports[key] = _guards[key];
  16089. });
  16090. } (selectors));
  16091. return selectors;
  16092. }
  16093. var hasRequiredDist;
  16094. function requireDist () {
  16095. if (hasRequiredDist) return dist.exports;
  16096. hasRequiredDist = 1;
  16097. (function (module, exports) {
  16098. exports.__esModule = true;
  16099. exports["default"] = void 0;
  16100. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  16101. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  16102. 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); }
  16103. function _interopRequireWildcard(obj, nodeInterop) { if (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; }
  16104. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  16105. var parser = function parser(processor) {
  16106. return new _processor["default"](processor);
  16107. };
  16108. Object.assign(parser, selectors);
  16109. delete parser.__esModule;
  16110. var _default = parser;
  16111. exports["default"] = _default;
  16112. module.exports = exports.default;
  16113. } (dist, dist.exports));
  16114. return dist.exports;
  16115. }
  16116. var parse;
  16117. var hasRequiredParse;
  16118. function requireParse () {
  16119. if (hasRequiredParse) return parse;
  16120. hasRequiredParse = 1;
  16121. var openParentheses = "(".charCodeAt(0);
  16122. var closeParentheses = ")".charCodeAt(0);
  16123. var singleQuote = "'".charCodeAt(0);
  16124. var doubleQuote = '"'.charCodeAt(0);
  16125. var backslash = "\\".charCodeAt(0);
  16126. var slash = "/".charCodeAt(0);
  16127. var comma = ",".charCodeAt(0);
  16128. var colon = ":".charCodeAt(0);
  16129. var star = "*".charCodeAt(0);
  16130. var uLower = "u".charCodeAt(0);
  16131. var uUpper = "U".charCodeAt(0);
  16132. var plus = "+".charCodeAt(0);
  16133. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  16134. parse = function(input) {
  16135. var tokens = [];
  16136. var value = input;
  16137. var next,
  16138. quote,
  16139. prev,
  16140. token,
  16141. escape,
  16142. escapePos,
  16143. whitespacePos,
  16144. parenthesesOpenPos;
  16145. var pos = 0;
  16146. var code = value.charCodeAt(pos);
  16147. var max = value.length;
  16148. var stack = [{ nodes: tokens }];
  16149. var balanced = 0;
  16150. var parent;
  16151. var name = "";
  16152. var before = "";
  16153. var after = "";
  16154. while (pos < max) {
  16155. // Whitespaces
  16156. if (code <= 32) {
  16157. next = pos;
  16158. do {
  16159. next += 1;
  16160. code = value.charCodeAt(next);
  16161. } while (code <= 32);
  16162. token = value.slice(pos, next);
  16163. prev = tokens[tokens.length - 1];
  16164. if (code === closeParentheses && balanced) {
  16165. after = token;
  16166. } else if (prev && prev.type === "div") {
  16167. prev.after = token;
  16168. prev.sourceEndIndex += token.length;
  16169. } else if (
  16170. code === comma ||
  16171. code === colon ||
  16172. (code === slash &&
  16173. value.charCodeAt(next + 1) !== star &&
  16174. (!parent ||
  16175. (parent && parent.type === "function" && parent.value !== "calc")))
  16176. ) {
  16177. before = token;
  16178. } else {
  16179. tokens.push({
  16180. type: "space",
  16181. sourceIndex: pos,
  16182. sourceEndIndex: next,
  16183. value: token
  16184. });
  16185. }
  16186. pos = next;
  16187. // Quotes
  16188. } else if (code === singleQuote || code === doubleQuote) {
  16189. next = pos;
  16190. quote = code === singleQuote ? "'" : '"';
  16191. token = {
  16192. type: "string",
  16193. sourceIndex: pos,
  16194. quote: quote
  16195. };
  16196. do {
  16197. escape = false;
  16198. next = value.indexOf(quote, next + 1);
  16199. if (~next) {
  16200. escapePos = next;
  16201. while (value.charCodeAt(escapePos - 1) === backslash) {
  16202. escapePos -= 1;
  16203. escape = !escape;
  16204. }
  16205. } else {
  16206. value += quote;
  16207. next = value.length - 1;
  16208. token.unclosed = true;
  16209. }
  16210. } while (escape);
  16211. token.value = value.slice(pos + 1, next);
  16212. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16213. tokens.push(token);
  16214. pos = next + 1;
  16215. code = value.charCodeAt(pos);
  16216. // Comments
  16217. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16218. next = value.indexOf("*/", pos);
  16219. token = {
  16220. type: "comment",
  16221. sourceIndex: pos,
  16222. sourceEndIndex: next + 2
  16223. };
  16224. if (next === -1) {
  16225. token.unclosed = true;
  16226. next = value.length;
  16227. token.sourceEndIndex = next;
  16228. }
  16229. token.value = value.slice(pos + 2, next);
  16230. tokens.push(token);
  16231. pos = next + 2;
  16232. code = value.charCodeAt(pos);
  16233. // Operation within calc
  16234. } else if (
  16235. (code === slash || code === star) &&
  16236. parent &&
  16237. parent.type === "function" &&
  16238. parent.value === "calc"
  16239. ) {
  16240. token = value[pos];
  16241. tokens.push({
  16242. type: "word",
  16243. sourceIndex: pos - before.length,
  16244. sourceEndIndex: pos + token.length,
  16245. value: token
  16246. });
  16247. pos += 1;
  16248. code = value.charCodeAt(pos);
  16249. // Dividers
  16250. } else if (code === slash || code === comma || code === colon) {
  16251. token = value[pos];
  16252. tokens.push({
  16253. type: "div",
  16254. sourceIndex: pos - before.length,
  16255. sourceEndIndex: pos + token.length,
  16256. value: token,
  16257. before: before,
  16258. after: ""
  16259. });
  16260. before = "";
  16261. pos += 1;
  16262. code = value.charCodeAt(pos);
  16263. // Open parentheses
  16264. } else if (openParentheses === code) {
  16265. // Whitespaces after open parentheses
  16266. next = pos;
  16267. do {
  16268. next += 1;
  16269. code = value.charCodeAt(next);
  16270. } while (code <= 32);
  16271. parenthesesOpenPos = pos;
  16272. token = {
  16273. type: "function",
  16274. sourceIndex: pos - name.length,
  16275. value: name,
  16276. before: value.slice(parenthesesOpenPos + 1, next)
  16277. };
  16278. pos = next;
  16279. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16280. next -= 1;
  16281. do {
  16282. escape = false;
  16283. next = value.indexOf(")", next + 1);
  16284. if (~next) {
  16285. escapePos = next;
  16286. while (value.charCodeAt(escapePos - 1) === backslash) {
  16287. escapePos -= 1;
  16288. escape = !escape;
  16289. }
  16290. } else {
  16291. value += ")";
  16292. next = value.length - 1;
  16293. token.unclosed = true;
  16294. }
  16295. } while (escape);
  16296. // Whitespaces before closed
  16297. whitespacePos = next;
  16298. do {
  16299. whitespacePos -= 1;
  16300. code = value.charCodeAt(whitespacePos);
  16301. } while (code <= 32);
  16302. if (parenthesesOpenPos < whitespacePos) {
  16303. if (pos !== whitespacePos + 1) {
  16304. token.nodes = [
  16305. {
  16306. type: "word",
  16307. sourceIndex: pos,
  16308. sourceEndIndex: whitespacePos + 1,
  16309. value: value.slice(pos, whitespacePos + 1)
  16310. }
  16311. ];
  16312. } else {
  16313. token.nodes = [];
  16314. }
  16315. if (token.unclosed && whitespacePos + 1 !== next) {
  16316. token.after = "";
  16317. token.nodes.push({
  16318. type: "space",
  16319. sourceIndex: whitespacePos + 1,
  16320. sourceEndIndex: next,
  16321. value: value.slice(whitespacePos + 1, next)
  16322. });
  16323. } else {
  16324. token.after = value.slice(whitespacePos + 1, next);
  16325. token.sourceEndIndex = next;
  16326. }
  16327. } else {
  16328. token.after = "";
  16329. token.nodes = [];
  16330. }
  16331. pos = next + 1;
  16332. token.sourceEndIndex = token.unclosed ? next : pos;
  16333. code = value.charCodeAt(pos);
  16334. tokens.push(token);
  16335. } else {
  16336. balanced += 1;
  16337. token.after = "";
  16338. token.sourceEndIndex = pos + 1;
  16339. tokens.push(token);
  16340. stack.push(token);
  16341. tokens = token.nodes = [];
  16342. parent = token;
  16343. }
  16344. name = "";
  16345. // Close parentheses
  16346. } else if (closeParentheses === code && balanced) {
  16347. pos += 1;
  16348. code = value.charCodeAt(pos);
  16349. parent.after = after;
  16350. parent.sourceEndIndex += after.length;
  16351. after = "";
  16352. balanced -= 1;
  16353. stack[stack.length - 1].sourceEndIndex = pos;
  16354. stack.pop();
  16355. parent = stack[balanced];
  16356. tokens = parent.nodes;
  16357. // Words
  16358. } else {
  16359. next = pos;
  16360. do {
  16361. if (code === backslash) {
  16362. next += 1;
  16363. }
  16364. next += 1;
  16365. code = value.charCodeAt(next);
  16366. } while (
  16367. next < max &&
  16368. !(
  16369. code <= 32 ||
  16370. code === singleQuote ||
  16371. code === doubleQuote ||
  16372. code === comma ||
  16373. code === colon ||
  16374. code === slash ||
  16375. code === openParentheses ||
  16376. (code === star &&
  16377. parent &&
  16378. parent.type === "function" &&
  16379. parent.value === "calc") ||
  16380. (code === slash &&
  16381. parent.type === "function" &&
  16382. parent.value === "calc") ||
  16383. (code === closeParentheses && balanced)
  16384. )
  16385. );
  16386. token = value.slice(pos, next);
  16387. if (openParentheses === code) {
  16388. name = token;
  16389. } else if (
  16390. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16391. plus === token.charCodeAt(1) &&
  16392. isUnicodeRange.test(token.slice(2))
  16393. ) {
  16394. tokens.push({
  16395. type: "unicode-range",
  16396. sourceIndex: pos,
  16397. sourceEndIndex: next,
  16398. value: token
  16399. });
  16400. } else {
  16401. tokens.push({
  16402. type: "word",
  16403. sourceIndex: pos,
  16404. sourceEndIndex: next,
  16405. value: token
  16406. });
  16407. }
  16408. pos = next;
  16409. }
  16410. }
  16411. for (pos = stack.length - 1; pos; pos -= 1) {
  16412. stack[pos].unclosed = true;
  16413. stack[pos].sourceEndIndex = value.length;
  16414. }
  16415. return stack[0].nodes;
  16416. };
  16417. return parse;
  16418. }
  16419. var walk$1;
  16420. var hasRequiredWalk;
  16421. function requireWalk () {
  16422. if (hasRequiredWalk) return walk$1;
  16423. hasRequiredWalk = 1;
  16424. walk$1 = function walk(nodes, cb, bubble) {
  16425. var i, max, node, result;
  16426. for (i = 0, max = nodes.length; i < max; i += 1) {
  16427. node = nodes[i];
  16428. if (!bubble) {
  16429. result = cb(node, i, nodes);
  16430. }
  16431. if (
  16432. result !== false &&
  16433. node.type === "function" &&
  16434. Array.isArray(node.nodes)
  16435. ) {
  16436. walk(node.nodes, cb, bubble);
  16437. }
  16438. if (bubble) {
  16439. cb(node, i, nodes);
  16440. }
  16441. }
  16442. };
  16443. return walk$1;
  16444. }
  16445. var stringify_1;
  16446. var hasRequiredStringify;
  16447. function requireStringify () {
  16448. if (hasRequiredStringify) return stringify_1;
  16449. hasRequiredStringify = 1;
  16450. function stringifyNode(node, custom) {
  16451. var type = node.type;
  16452. var value = node.value;
  16453. var buf;
  16454. var customResult;
  16455. if (custom && (customResult = custom(node)) !== undefined) {
  16456. return customResult;
  16457. } else if (type === "word" || type === "space") {
  16458. return value;
  16459. } else if (type === "string") {
  16460. buf = node.quote || "";
  16461. return buf + value + (node.unclosed ? "" : buf);
  16462. } else if (type === "comment") {
  16463. return "/*" + value + (node.unclosed ? "" : "*/");
  16464. } else if (type === "div") {
  16465. return (node.before || "") + value + (node.after || "");
  16466. } else if (Array.isArray(node.nodes)) {
  16467. buf = stringify(node.nodes, custom);
  16468. if (type !== "function") {
  16469. return buf;
  16470. }
  16471. return (
  16472. value +
  16473. "(" +
  16474. (node.before || "") +
  16475. buf +
  16476. (node.after || "") +
  16477. (node.unclosed ? "" : ")")
  16478. );
  16479. }
  16480. return value;
  16481. }
  16482. function stringify(nodes, custom) {
  16483. var result, i;
  16484. if (Array.isArray(nodes)) {
  16485. result = "";
  16486. for (i = nodes.length - 1; ~i; i -= 1) {
  16487. result = stringifyNode(nodes[i], custom) + result;
  16488. }
  16489. return result;
  16490. }
  16491. return stringifyNode(nodes, custom);
  16492. }
  16493. stringify_1 = stringify;
  16494. return stringify_1;
  16495. }
  16496. var unit;
  16497. var hasRequiredUnit;
  16498. function requireUnit () {
  16499. if (hasRequiredUnit) return unit;
  16500. hasRequiredUnit = 1;
  16501. var minus = "-".charCodeAt(0);
  16502. var plus = "+".charCodeAt(0);
  16503. var dot = ".".charCodeAt(0);
  16504. var exp = "e".charCodeAt(0);
  16505. var EXP = "E".charCodeAt(0);
  16506. // Check if three code points would start a number
  16507. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16508. function likeNumber(value) {
  16509. var code = value.charCodeAt(0);
  16510. var nextCode;
  16511. if (code === plus || code === minus) {
  16512. nextCode = value.charCodeAt(1);
  16513. if (nextCode >= 48 && nextCode <= 57) {
  16514. return true;
  16515. }
  16516. var nextNextCode = value.charCodeAt(2);
  16517. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16518. return true;
  16519. }
  16520. return false;
  16521. }
  16522. if (code === dot) {
  16523. nextCode = value.charCodeAt(1);
  16524. if (nextCode >= 48 && nextCode <= 57) {
  16525. return true;
  16526. }
  16527. return false;
  16528. }
  16529. if (code >= 48 && code <= 57) {
  16530. return true;
  16531. }
  16532. return false;
  16533. }
  16534. // Consume a number
  16535. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16536. unit = function(value) {
  16537. var pos = 0;
  16538. var length = value.length;
  16539. var code;
  16540. var nextCode;
  16541. var nextNextCode;
  16542. if (length === 0 || !likeNumber(value)) {
  16543. return false;
  16544. }
  16545. code = value.charCodeAt(pos);
  16546. if (code === plus || code === minus) {
  16547. pos++;
  16548. }
  16549. while (pos < length) {
  16550. code = value.charCodeAt(pos);
  16551. if (code < 48 || code > 57) {
  16552. break;
  16553. }
  16554. pos += 1;
  16555. }
  16556. code = value.charCodeAt(pos);
  16557. nextCode = value.charCodeAt(pos + 1);
  16558. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16559. pos += 2;
  16560. while (pos < length) {
  16561. code = value.charCodeAt(pos);
  16562. if (code < 48 || code > 57) {
  16563. break;
  16564. }
  16565. pos += 1;
  16566. }
  16567. }
  16568. code = value.charCodeAt(pos);
  16569. nextCode = value.charCodeAt(pos + 1);
  16570. nextNextCode = value.charCodeAt(pos + 2);
  16571. if (
  16572. (code === exp || code === EXP) &&
  16573. ((nextCode >= 48 && nextCode <= 57) ||
  16574. ((nextCode === plus || nextCode === minus) &&
  16575. nextNextCode >= 48 &&
  16576. nextNextCode <= 57))
  16577. ) {
  16578. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16579. while (pos < length) {
  16580. code = value.charCodeAt(pos);
  16581. if (code < 48 || code > 57) {
  16582. break;
  16583. }
  16584. pos += 1;
  16585. }
  16586. }
  16587. return {
  16588. number: value.slice(0, pos),
  16589. unit: value.slice(pos)
  16590. };
  16591. };
  16592. return unit;
  16593. }
  16594. var lib;
  16595. var hasRequiredLib;
  16596. function requireLib () {
  16597. if (hasRequiredLib) return lib;
  16598. hasRequiredLib = 1;
  16599. var parse = /*@__PURE__*/ requireParse();
  16600. var walk = /*@__PURE__*/ requireWalk();
  16601. var stringify = /*@__PURE__*/ requireStringify();
  16602. function ValueParser(value) {
  16603. if (this instanceof ValueParser) {
  16604. this.nodes = parse(value);
  16605. return this;
  16606. }
  16607. return new ValueParser(value);
  16608. }
  16609. ValueParser.prototype.toString = function() {
  16610. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  16611. };
  16612. ValueParser.prototype.walk = function(cb, bubble) {
  16613. walk(this.nodes, cb, bubble);
  16614. return this;
  16615. };
  16616. ValueParser.unit = /*@__PURE__*/ requireUnit();
  16617. ValueParser.walk = walk;
  16618. ValueParser.stringify = stringify;
  16619. lib = ValueParser;
  16620. return lib;
  16621. }
  16622. var hasRequiredSrc$2;
  16623. function requireSrc$2 () {
  16624. if (hasRequiredSrc$2) return src$2.exports;
  16625. hasRequiredSrc$2 = 1;
  16626. const selectorParser = /*@__PURE__*/ requireDist();
  16627. const valueParser = /*@__PURE__*/ requireLib();
  16628. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  16629. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  16630. function normalizeNodeArray(nodes) {
  16631. const array = [];
  16632. nodes.forEach((x) => {
  16633. if (Array.isArray(x)) {
  16634. normalizeNodeArray(x).forEach((item) => {
  16635. array.push(item);
  16636. });
  16637. } else if (x) {
  16638. array.push(x);
  16639. }
  16640. });
  16641. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  16642. array.pop();
  16643. }
  16644. return array;
  16645. }
  16646. function localizeNode(rule, mode, localAliasMap) {
  16647. const transform = (node, context) => {
  16648. if (context.ignoreNextSpacing && !isSpacing(node)) {
  16649. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  16650. }
  16651. if (context.enforceNoSpacing && isSpacing(node)) {
  16652. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  16653. }
  16654. let newNodes;
  16655. switch (node.type) {
  16656. case "root": {
  16657. let resultingGlobal;
  16658. context.hasPureGlobals = false;
  16659. newNodes = node.nodes.map((n) => {
  16660. const nContext = {
  16661. global: context.global,
  16662. lastWasSpacing: true,
  16663. hasLocals: false,
  16664. explicit: false,
  16665. };
  16666. n = transform(n, nContext);
  16667. if (typeof resultingGlobal === "undefined") {
  16668. resultingGlobal = nContext.global;
  16669. } else if (resultingGlobal !== nContext.global) {
  16670. throw new Error(
  16671. 'Inconsistent rule global/local result in rule "' +
  16672. node +
  16673. '" (multiple selectors must result in the same mode for the rule)'
  16674. );
  16675. }
  16676. if (!nContext.hasLocals) {
  16677. context.hasPureGlobals = true;
  16678. }
  16679. return n;
  16680. });
  16681. context.global = resultingGlobal;
  16682. node.nodes = normalizeNodeArray(newNodes);
  16683. break;
  16684. }
  16685. case "selector": {
  16686. newNodes = node.map((childNode) => transform(childNode, context));
  16687. node = node.clone();
  16688. node.nodes = normalizeNodeArray(newNodes);
  16689. break;
  16690. }
  16691. case "combinator": {
  16692. if (isSpacing(node)) {
  16693. if (context.ignoreNextSpacing) {
  16694. context.ignoreNextSpacing = false;
  16695. context.lastWasSpacing = false;
  16696. context.enforceNoSpacing = false;
  16697. return null;
  16698. }
  16699. context.lastWasSpacing = true;
  16700. return node;
  16701. }
  16702. break;
  16703. }
  16704. case "pseudo": {
  16705. let childContext;
  16706. const isNested = !!node.length;
  16707. const isScoped = node.value === ":local" || node.value === ":global";
  16708. const isImportExport =
  16709. node.value === ":import" || node.value === ":export";
  16710. if (isImportExport) {
  16711. context.hasLocals = true;
  16712. // :local(.foo)
  16713. } else if (isNested) {
  16714. if (isScoped) {
  16715. if (node.nodes.length === 0) {
  16716. throw new Error(`${node.value}() can't be empty`);
  16717. }
  16718. if (context.inside) {
  16719. throw new Error(
  16720. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16721. );
  16722. }
  16723. childContext = {
  16724. global: node.value === ":global",
  16725. inside: node.value,
  16726. hasLocals: false,
  16727. explicit: true,
  16728. };
  16729. newNodes = node
  16730. .map((childNode) => transform(childNode, childContext))
  16731. .reduce((acc, next) => acc.concat(next.nodes), []);
  16732. if (newNodes.length) {
  16733. const { before, after } = node.spaces;
  16734. const first = newNodes[0];
  16735. const last = newNodes[newNodes.length - 1];
  16736. first.spaces = { before, after: first.spaces.after };
  16737. last.spaces = { before: last.spaces.before, after };
  16738. }
  16739. node = newNodes;
  16740. break;
  16741. } else {
  16742. childContext = {
  16743. global: context.global,
  16744. inside: context.inside,
  16745. lastWasSpacing: true,
  16746. hasLocals: false,
  16747. explicit: context.explicit,
  16748. };
  16749. newNodes = node.map((childNode) => {
  16750. const newContext = {
  16751. ...childContext,
  16752. enforceNoSpacing: false,
  16753. };
  16754. const result = transform(childNode, newContext);
  16755. childContext.global = newContext.global;
  16756. childContext.hasLocals = newContext.hasLocals;
  16757. return result;
  16758. });
  16759. node = node.clone();
  16760. node.nodes = normalizeNodeArray(newNodes);
  16761. if (childContext.hasLocals) {
  16762. context.hasLocals = true;
  16763. }
  16764. }
  16765. break;
  16766. //:local .foo .bar
  16767. } else if (isScoped) {
  16768. if (context.inside) {
  16769. throw new Error(
  16770. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16771. );
  16772. }
  16773. const addBackSpacing = !!node.spaces.before;
  16774. context.ignoreNextSpacing = context.lastWasSpacing
  16775. ? node.value
  16776. : false;
  16777. context.enforceNoSpacing = context.lastWasSpacing
  16778. ? false
  16779. : node.value;
  16780. context.global = node.value === ":global";
  16781. context.explicit = true;
  16782. // because this node has spacing that is lost when we remove it
  16783. // we make up for it by adding an extra combinator in since adding
  16784. // spacing on the parent selector doesn't work
  16785. return addBackSpacing
  16786. ? selectorParser.combinator({ value: " " })
  16787. : null;
  16788. }
  16789. break;
  16790. }
  16791. case "id":
  16792. case "class": {
  16793. if (!node.value) {
  16794. throw new Error("Invalid class or id selector syntax");
  16795. }
  16796. if (context.global) {
  16797. break;
  16798. }
  16799. const isImportedValue = localAliasMap.has(node.value);
  16800. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  16801. if (!isImportedValue || isImportedWithExplicitScope) {
  16802. const innerNode = node.clone();
  16803. innerNode.spaces = { before: "", after: "" };
  16804. node = selectorParser.pseudo({
  16805. value: ":local",
  16806. nodes: [innerNode],
  16807. spaces: node.spaces,
  16808. });
  16809. context.hasLocals = true;
  16810. }
  16811. break;
  16812. }
  16813. case "nesting": {
  16814. if (node.value === "&") {
  16815. context.hasLocals = true;
  16816. }
  16817. }
  16818. }
  16819. context.lastWasSpacing = false;
  16820. context.ignoreNextSpacing = false;
  16821. context.enforceNoSpacing = false;
  16822. return node;
  16823. };
  16824. const rootContext = {
  16825. global: mode === "global",
  16826. hasPureGlobals: false,
  16827. };
  16828. rootContext.selector = selectorParser((root) => {
  16829. transform(root, rootContext);
  16830. }).processSync(rule, { updateSelector: false, lossless: true });
  16831. return rootContext;
  16832. }
  16833. function localizeDeclNode(node, context) {
  16834. switch (node.type) {
  16835. case "word":
  16836. if (context.localizeNextItem) {
  16837. if (!context.localAliasMap.has(node.value)) {
  16838. node.value = ":local(" + node.value + ")";
  16839. context.localizeNextItem = false;
  16840. }
  16841. }
  16842. break;
  16843. case "function":
  16844. if (
  16845. context.options &&
  16846. context.options.rewriteUrl &&
  16847. node.value.toLowerCase() === "url"
  16848. ) {
  16849. node.nodes.map((nestedNode) => {
  16850. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  16851. return;
  16852. }
  16853. let newUrl = context.options.rewriteUrl(
  16854. context.global,
  16855. nestedNode.value
  16856. );
  16857. switch (nestedNode.type) {
  16858. case "string":
  16859. if (nestedNode.quote === "'") {
  16860. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  16861. }
  16862. if (nestedNode.quote === '"') {
  16863. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  16864. }
  16865. break;
  16866. case "word":
  16867. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  16868. break;
  16869. }
  16870. nestedNode.value = newUrl;
  16871. });
  16872. }
  16873. break;
  16874. }
  16875. return node;
  16876. }
  16877. // `none` is special value, other is global values
  16878. const specialKeywords = [
  16879. "none",
  16880. "inherit",
  16881. "initial",
  16882. "revert",
  16883. "revert-layer",
  16884. "unset",
  16885. ];
  16886. function localizeDeclarationValues(localize, declaration, context) {
  16887. const valueNodes = valueParser(declaration.value);
  16888. valueNodes.walk((node, index, nodes) => {
  16889. if (
  16890. node.type === "function" &&
  16891. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  16892. ) {
  16893. return false;
  16894. }
  16895. if (
  16896. node.type === "word" &&
  16897. specialKeywords.includes(node.value.toLowerCase())
  16898. ) {
  16899. return;
  16900. }
  16901. const subContext = {
  16902. options: context.options,
  16903. global: context.global,
  16904. localizeNextItem: localize && !context.global,
  16905. localAliasMap: context.localAliasMap,
  16906. };
  16907. nodes[index] = localizeDeclNode(node, subContext);
  16908. });
  16909. declaration.value = valueNodes.toString();
  16910. }
  16911. function localizeDeclaration(declaration, context) {
  16912. const isAnimation = /animation$/i.test(declaration.prop);
  16913. if (isAnimation) {
  16914. // letter
  16915. // An uppercase letter or a lowercase letter.
  16916. //
  16917. // ident-start code point
  16918. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  16919. //
  16920. // ident code point
  16921. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  16922. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  16923. const validIdent =
  16924. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  16925. /*
  16926. The spec defines some keywords that you can use to describe properties such as the timing
  16927. function. These are still valid animation names, so as long as there is a property that accepts
  16928. a keyword, it is given priority. Only when all the properties that can take a keyword are
  16929. exhausted can the animation name be set to the keyword. I.e.
  16930. animation: infinite infinite;
  16931. The animation will repeat an infinite number of times from the first argument, and will have an
  16932. animation name of infinite from the second.
  16933. */
  16934. const animationKeywords = {
  16935. // animation-direction
  16936. $normal: 1,
  16937. $reverse: 1,
  16938. $alternate: 1,
  16939. "$alternate-reverse": 1,
  16940. // animation-fill-mode
  16941. $forwards: 1,
  16942. $backwards: 1,
  16943. $both: 1,
  16944. // animation-iteration-count
  16945. $infinite: 1,
  16946. // animation-play-state
  16947. $paused: 1,
  16948. $running: 1,
  16949. // animation-timing-function
  16950. $ease: 1,
  16951. "$ease-in": 1,
  16952. "$ease-out": 1,
  16953. "$ease-in-out": 1,
  16954. $linear: 1,
  16955. "$step-end": 1,
  16956. "$step-start": 1,
  16957. // Special
  16958. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  16959. // Global values
  16960. $initial: Infinity,
  16961. $inherit: Infinity,
  16962. $unset: Infinity,
  16963. $revert: Infinity,
  16964. "$revert-layer": Infinity,
  16965. };
  16966. let parsedAnimationKeywords = {};
  16967. const valueNodes = valueParser(declaration.value).walk((node) => {
  16968. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  16969. if (node.type === "div") {
  16970. parsedAnimationKeywords = {};
  16971. return;
  16972. }
  16973. // Do not handle nested functions
  16974. else if (node.type === "function") {
  16975. return false;
  16976. }
  16977. // Ignore all except word
  16978. else if (node.type !== "word") {
  16979. return;
  16980. }
  16981. const value = node.type === "word" ? node.value.toLowerCase() : null;
  16982. let shouldParseAnimationName = false;
  16983. if (value && validIdent.test(value)) {
  16984. if ("$" + value in animationKeywords) {
  16985. parsedAnimationKeywords["$" + value] =
  16986. "$" + value in parsedAnimationKeywords
  16987. ? parsedAnimationKeywords["$" + value] + 1
  16988. : 0;
  16989. shouldParseAnimationName =
  16990. parsedAnimationKeywords["$" + value] >=
  16991. animationKeywords["$" + value];
  16992. } else {
  16993. shouldParseAnimationName = true;
  16994. }
  16995. }
  16996. const subContext = {
  16997. options: context.options,
  16998. global: context.global,
  16999. localizeNextItem: shouldParseAnimationName && !context.global,
  17000. localAliasMap: context.localAliasMap,
  17001. };
  17002. return localizeDeclNode(node, subContext);
  17003. });
  17004. declaration.value = valueNodes.toString();
  17005. return;
  17006. }
  17007. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  17008. if (isAnimationName) {
  17009. return localizeDeclarationValues(true, declaration, context);
  17010. }
  17011. const hasUrl = /url\(/i.test(declaration.value);
  17012. if (hasUrl) {
  17013. return localizeDeclarationValues(false, declaration, context);
  17014. }
  17015. }
  17016. src$2.exports = (options = {}) => {
  17017. if (
  17018. options &&
  17019. options.mode &&
  17020. options.mode !== "global" &&
  17021. options.mode !== "local" &&
  17022. options.mode !== "pure"
  17023. ) {
  17024. throw new Error(
  17025. 'options.mode must be either "global", "local" or "pure" (default "local")'
  17026. );
  17027. }
  17028. const pureMode = options && options.mode === "pure";
  17029. const globalMode = options && options.mode === "global";
  17030. return {
  17031. postcssPlugin: "postcss-modules-local-by-default",
  17032. prepare() {
  17033. const localAliasMap = new Map();
  17034. return {
  17035. Once(root) {
  17036. const { icssImports } = extractICSS(root, false);
  17037. Object.keys(icssImports).forEach((key) => {
  17038. Object.keys(icssImports[key]).forEach((prop) => {
  17039. localAliasMap.set(prop, icssImports[key][prop]);
  17040. });
  17041. });
  17042. root.walkAtRules((atRule) => {
  17043. if (/keyframes$/i.test(atRule.name)) {
  17044. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  17045. atRule.params
  17046. );
  17047. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  17048. atRule.params
  17049. );
  17050. let globalKeyframes = globalMode;
  17051. if (globalMatch) {
  17052. if (pureMode) {
  17053. throw atRule.error(
  17054. "@keyframes :global(...) is not allowed in pure mode"
  17055. );
  17056. }
  17057. atRule.params = globalMatch[1];
  17058. globalKeyframes = true;
  17059. } else if (localMatch) {
  17060. atRule.params = localMatch[0];
  17061. globalKeyframes = false;
  17062. } else if (
  17063. atRule.params &&
  17064. !globalMode &&
  17065. !localAliasMap.has(atRule.params)
  17066. ) {
  17067. atRule.params = ":local(" + atRule.params + ")";
  17068. }
  17069. atRule.walkDecls((declaration) => {
  17070. localizeDeclaration(declaration, {
  17071. localAliasMap,
  17072. options: options,
  17073. global: globalKeyframes,
  17074. });
  17075. });
  17076. } else if (/scope$/i.test(atRule.name)) {
  17077. if (atRule.params) {
  17078. atRule.params = atRule.params
  17079. .split("to")
  17080. .map((item) => {
  17081. const selector = item.trim().slice(1, -1).trim();
  17082. const context = localizeNode(
  17083. selector,
  17084. options.mode,
  17085. localAliasMap
  17086. );
  17087. context.options = options;
  17088. context.localAliasMap = localAliasMap;
  17089. if (pureMode && context.hasPureGlobals) {
  17090. throw atRule.error(
  17091. 'Selector in at-rule"' +
  17092. selector +
  17093. '" is not pure ' +
  17094. "(pure selectors must contain at least one local class or id)"
  17095. );
  17096. }
  17097. return `(${context.selector})`;
  17098. })
  17099. .join(" to ");
  17100. }
  17101. atRule.nodes.forEach((declaration) => {
  17102. if (declaration.type === "decl") {
  17103. localizeDeclaration(declaration, {
  17104. localAliasMap,
  17105. options: options,
  17106. global: globalMode,
  17107. });
  17108. }
  17109. });
  17110. } else if (atRule.nodes) {
  17111. atRule.nodes.forEach((declaration) => {
  17112. if (declaration.type === "decl") {
  17113. localizeDeclaration(declaration, {
  17114. localAliasMap,
  17115. options: options,
  17116. global: globalMode,
  17117. });
  17118. }
  17119. });
  17120. }
  17121. });
  17122. root.walkRules((rule) => {
  17123. if (
  17124. rule.parent &&
  17125. rule.parent.type === "atrule" &&
  17126. /keyframes$/i.test(rule.parent.name)
  17127. ) {
  17128. // ignore keyframe rules
  17129. return;
  17130. }
  17131. const context = localizeNode(rule, options.mode, localAliasMap);
  17132. context.options = options;
  17133. context.localAliasMap = localAliasMap;
  17134. if (pureMode && context.hasPureGlobals) {
  17135. throw rule.error(
  17136. 'Selector "' +
  17137. rule.selector +
  17138. '" is not pure ' +
  17139. "(pure selectors must contain at least one local class or id)"
  17140. );
  17141. }
  17142. rule.selector = context.selector;
  17143. // Less-syntax mixins parse as rules with no nodes
  17144. if (rule.nodes) {
  17145. rule.nodes.forEach((declaration) =>
  17146. localizeDeclaration(declaration, context)
  17147. );
  17148. }
  17149. });
  17150. },
  17151. };
  17152. },
  17153. };
  17154. };
  17155. src$2.exports.postcss = true;
  17156. return src$2.exports;
  17157. }
  17158. var src$1;
  17159. var hasRequiredSrc$1;
  17160. function requireSrc$1 () {
  17161. if (hasRequiredSrc$1) return src$1;
  17162. hasRequiredSrc$1 = 1;
  17163. const selectorParser = /*@__PURE__*/ requireDist();
  17164. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17165. function isNestedRule(rule) {
  17166. if (!rule.parent || rule.parent.type === "root") {
  17167. return false;
  17168. }
  17169. if (rule.parent.type === "rule") {
  17170. return true;
  17171. }
  17172. return isNestedRule(rule.parent);
  17173. }
  17174. function getSingleLocalNamesForComposes(root, rule) {
  17175. if (isNestedRule(rule)) {
  17176. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17177. }
  17178. return root.nodes.map((node) => {
  17179. if (node.type !== "selector" || node.nodes.length !== 1) {
  17180. throw new Error(
  17181. `composition is only allowed when selector is single :local class name not in "${root}"`
  17182. );
  17183. }
  17184. node = node.nodes[0];
  17185. if (
  17186. node.type !== "pseudo" ||
  17187. node.value !== ":local" ||
  17188. node.nodes.length !== 1
  17189. ) {
  17190. throw new Error(
  17191. 'composition is only allowed when selector is single :local class name not in "' +
  17192. root +
  17193. '", "' +
  17194. node +
  17195. '" is weird'
  17196. );
  17197. }
  17198. node = node.first;
  17199. if (node.type !== "selector" || node.length !== 1) {
  17200. throw new Error(
  17201. 'composition is only allowed when selector is single :local class name not in "' +
  17202. root +
  17203. '", "' +
  17204. node +
  17205. '" is weird'
  17206. );
  17207. }
  17208. node = node.first;
  17209. if (node.type !== "class") {
  17210. // 'id' is not possible, because you can't compose ids
  17211. throw new Error(
  17212. 'composition is only allowed when selector is single :local class name not in "' +
  17213. root +
  17214. '", "' +
  17215. node +
  17216. '" is weird'
  17217. );
  17218. }
  17219. return node.value;
  17220. });
  17221. }
  17222. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17223. const unescapeRegExp = new RegExp(
  17224. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17225. "ig"
  17226. );
  17227. function unescape(str) {
  17228. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17229. const high = "0x" + escaped - 0x10000;
  17230. // NaN means non-codepoint
  17231. // Workaround erroneous numeric interpretation of +"0x"
  17232. return high !== high || escapedWhitespace
  17233. ? escaped
  17234. : high < 0
  17235. ? // BMP codepoint
  17236. String.fromCharCode(high + 0x10000)
  17237. : // Supplemental Plane codepoint (surrogate pair)
  17238. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17239. });
  17240. }
  17241. const plugin = (options = {}) => {
  17242. const generateScopedName =
  17243. (options && options.generateScopedName) || plugin.generateScopedName;
  17244. const generateExportEntry =
  17245. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17246. const exportGlobals = options && options.exportGlobals;
  17247. return {
  17248. postcssPlugin: "postcss-modules-scope",
  17249. Once(root, { rule }) {
  17250. const exports = Object.create(null);
  17251. function exportScopedName(name, rawName, node) {
  17252. const scopedName = generateScopedName(
  17253. rawName ? rawName : name,
  17254. root.source.input.from,
  17255. root.source.input.css,
  17256. node
  17257. );
  17258. const exportEntry = generateExportEntry(
  17259. rawName ? rawName : name,
  17260. scopedName,
  17261. root.source.input.from,
  17262. root.source.input.css,
  17263. node
  17264. );
  17265. const { key, value } = exportEntry;
  17266. exports[key] = exports[key] || [];
  17267. if (exports[key].indexOf(value) < 0) {
  17268. exports[key].push(value);
  17269. }
  17270. return scopedName;
  17271. }
  17272. function localizeNode(node) {
  17273. switch (node.type) {
  17274. case "selector":
  17275. node.nodes = node.map((item) => localizeNode(item));
  17276. return node;
  17277. case "class":
  17278. return selectorParser.className({
  17279. value: exportScopedName(
  17280. node.value,
  17281. node.raws && node.raws.value ? node.raws.value : null,
  17282. node
  17283. ),
  17284. });
  17285. case "id": {
  17286. return selectorParser.id({
  17287. value: exportScopedName(
  17288. node.value,
  17289. node.raws && node.raws.value ? node.raws.value : null,
  17290. node
  17291. ),
  17292. });
  17293. }
  17294. case "attribute": {
  17295. if (node.attribute === "class" && node.operator === "=") {
  17296. return selectorParser.attribute({
  17297. attribute: node.attribute,
  17298. operator: node.operator,
  17299. quoteMark: "'",
  17300. value: exportScopedName(node.value, null, null),
  17301. });
  17302. }
  17303. }
  17304. }
  17305. throw new Error(
  17306. `${node.type} ("${node}") is not allowed in a :local block`
  17307. );
  17308. }
  17309. function traverseNode(node) {
  17310. switch (node.type) {
  17311. case "pseudo":
  17312. if (node.value === ":local") {
  17313. if (node.nodes.length !== 1) {
  17314. throw new Error('Unexpected comma (",") in :local block');
  17315. }
  17316. const selector = localizeNode(node.first);
  17317. // move the spaces that were around the pseudo selector to the first
  17318. // non-container node
  17319. selector.first.spaces = node.spaces;
  17320. const nextNode = node.next();
  17321. if (
  17322. nextNode &&
  17323. nextNode.type === "combinator" &&
  17324. nextNode.value === " " &&
  17325. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17326. ) {
  17327. selector.last.spaces.after = " ";
  17328. }
  17329. node.replaceWith(selector);
  17330. return;
  17331. }
  17332. /* falls through */
  17333. case "root":
  17334. case "selector": {
  17335. node.each((item) => traverseNode(item));
  17336. break;
  17337. }
  17338. case "id":
  17339. case "class":
  17340. if (exportGlobals) {
  17341. exports[node.value] = [node.value];
  17342. }
  17343. break;
  17344. }
  17345. return node;
  17346. }
  17347. // Find any :import and remember imported names
  17348. const importedNames = {};
  17349. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17350. rule.walkDecls((decl) => {
  17351. importedNames[decl.prop] = true;
  17352. });
  17353. });
  17354. // Find any :local selectors
  17355. root.walkRules((rule) => {
  17356. let parsedSelector = selectorParser().astSync(rule);
  17357. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17358. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17359. const localNames = getSingleLocalNamesForComposes(
  17360. parsedSelector,
  17361. decl.parent
  17362. );
  17363. const multiple = decl.value.split(",");
  17364. multiple.forEach((value) => {
  17365. const classes = value.trim().split(/\s+/);
  17366. classes.forEach((className) => {
  17367. const global = /^global\(([^)]+)\)$/.exec(className);
  17368. if (global) {
  17369. localNames.forEach((exportedName) => {
  17370. exports[exportedName].push(global[1]);
  17371. });
  17372. } else if (hasOwnProperty.call(importedNames, className)) {
  17373. localNames.forEach((exportedName) => {
  17374. exports[exportedName].push(className);
  17375. });
  17376. } else if (hasOwnProperty.call(exports, className)) {
  17377. localNames.forEach((exportedName) => {
  17378. exports[className].forEach((item) => {
  17379. exports[exportedName].push(item);
  17380. });
  17381. });
  17382. } else {
  17383. throw decl.error(
  17384. `referenced class name "${className}" in ${decl.prop} not found`
  17385. );
  17386. }
  17387. });
  17388. });
  17389. decl.remove();
  17390. });
  17391. // Find any :local values
  17392. rule.walkDecls((decl) => {
  17393. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17394. return;
  17395. }
  17396. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17397. tokens = tokens.map((token, idx) => {
  17398. if (idx === 0 || tokens[idx - 1] === ",") {
  17399. let result = token;
  17400. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17401. if (localMatch) {
  17402. const input = localMatch.input;
  17403. const matchPattern = localMatch[0];
  17404. const matchVal = localMatch[1];
  17405. const newVal = exportScopedName(matchVal);
  17406. result = input.replace(matchPattern, newVal);
  17407. } else {
  17408. return token;
  17409. }
  17410. return result;
  17411. } else {
  17412. return token;
  17413. }
  17414. });
  17415. decl.value = tokens.join("");
  17416. });
  17417. });
  17418. // Find any :local keyframes
  17419. root.walkAtRules(/keyframes$/i, (atRule) => {
  17420. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17421. if (!localMatch) {
  17422. return;
  17423. }
  17424. atRule.params = exportScopedName(localMatch[1]);
  17425. });
  17426. root.walkAtRules(/scope$/i, (atRule) => {
  17427. if (atRule.params) {
  17428. atRule.params = atRule.params
  17429. .split("to")
  17430. .map((item) => {
  17431. const selector = item.trim().slice(1, -1).trim();
  17432. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17433. if (!localMatch) {
  17434. return `(${selector})`;
  17435. }
  17436. let parsedSelector = selectorParser().astSync(selector);
  17437. return `(${traverseNode(parsedSelector).toString()})`;
  17438. })
  17439. .join(" to ");
  17440. }
  17441. });
  17442. // If we found any :locals, insert an :export rule
  17443. const exportedNames = Object.keys(exports);
  17444. if (exportedNames.length > 0) {
  17445. const exportRule = rule({ selector: ":export" });
  17446. exportedNames.forEach((exportedName) =>
  17447. exportRule.append({
  17448. prop: exportedName,
  17449. value: exports[exportedName].join(" "),
  17450. raws: { before: "\n " },
  17451. })
  17452. );
  17453. root.append(exportRule);
  17454. }
  17455. },
  17456. };
  17457. };
  17458. plugin.postcss = true;
  17459. plugin.generateScopedName = function (name, path) {
  17460. const sanitisedPath = path
  17461. .replace(/\.[^./\\]+$/, "")
  17462. .replace(/[\W_]+/g, "_")
  17463. .replace(/^_|_$/g, "");
  17464. return `_${sanitisedPath}__${name}`.trim();
  17465. };
  17466. plugin.generateExportEntry = function (name, scopedName) {
  17467. return {
  17468. key: unescape(name),
  17469. value: unescape(scopedName),
  17470. };
  17471. };
  17472. src$1 = plugin;
  17473. return src$1;
  17474. }
  17475. var stringHash;
  17476. var hasRequiredStringHash;
  17477. function requireStringHash () {
  17478. if (hasRequiredStringHash) return stringHash;
  17479. hasRequiredStringHash = 1;
  17480. function hash(str) {
  17481. var hash = 5381,
  17482. i = str.length;
  17483. while(i) {
  17484. hash = (hash * 33) ^ str.charCodeAt(--i);
  17485. }
  17486. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17487. * integers. Since we want the results to be always positive, convert the
  17488. * signed int to an unsigned by doing an unsigned bitshift. */
  17489. return hash >>> 0;
  17490. }
  17491. stringHash = hash;
  17492. return stringHash;
  17493. }
  17494. var src = {exports: {}};
  17495. var hasRequiredSrc;
  17496. function requireSrc () {
  17497. if (hasRequiredSrc) return src.exports;
  17498. hasRequiredSrc = 1;
  17499. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17500. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17501. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17502. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17503. src.exports = (options) => {
  17504. let importIndex = 0;
  17505. const createImportedName =
  17506. (options && options.createImportedName) ||
  17507. ((importName /*, path*/) =>
  17508. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17509. return {
  17510. postcssPlugin: "postcss-modules-values",
  17511. prepare(result) {
  17512. const importAliases = [];
  17513. const definitions = {};
  17514. return {
  17515. Once(root, postcss) {
  17516. root.walkAtRules(/value/i, (atRule) => {
  17517. const matches = atRule.params.match(matchImports);
  17518. if (matches) {
  17519. let [, /*match*/ aliases, path] = matches;
  17520. // We can use constants for path names
  17521. if (definitions[path]) {
  17522. path = definitions[path];
  17523. }
  17524. const imports = aliases
  17525. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17526. .split(/\s*,\s*/)
  17527. .map((alias) => {
  17528. const tokens = matchImport.exec(alias);
  17529. if (tokens) {
  17530. const [, /*match*/ theirName, myName = theirName] = tokens;
  17531. const importedName = createImportedName(myName);
  17532. definitions[myName] = importedName;
  17533. return { theirName, importedName };
  17534. } else {
  17535. throw new Error(`@import statement "${alias}" is invalid!`);
  17536. }
  17537. });
  17538. importAliases.push({ path, imports });
  17539. atRule.remove();
  17540. return;
  17541. }
  17542. if (atRule.params.indexOf("@value") !== -1) {
  17543. result.warn("Invalid value definition: " + atRule.params);
  17544. }
  17545. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17546. matchValueDefinition
  17547. );
  17548. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17549. if (normalizedValue.length === 0) {
  17550. result.warn("Invalid value definition: " + atRule.params);
  17551. atRule.remove();
  17552. return;
  17553. }
  17554. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17555. if (!isOnlySpace) {
  17556. value = value.trim();
  17557. }
  17558. // Add to the definitions, knowing that values can refer to each other
  17559. definitions[key] = ICSSUtils.replaceValueSymbols(
  17560. value,
  17561. definitions
  17562. );
  17563. atRule.remove();
  17564. });
  17565. /* If we have no definitions, don't continue */
  17566. if (!Object.keys(definitions).length) {
  17567. return;
  17568. }
  17569. /* Perform replacements */
  17570. ICSSUtils.replaceSymbols(root, definitions);
  17571. /* 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 */
  17572. const exportDeclarations = Object.keys(definitions).map((key) =>
  17573. postcss.decl({
  17574. value: definitions[key],
  17575. prop: key,
  17576. raws: { before: "\n " },
  17577. })
  17578. );
  17579. /* Add export rules if any */
  17580. if (exportDeclarations.length > 0) {
  17581. const exportRule = postcss.rule({
  17582. selector: ":export",
  17583. raws: { after: "\n" },
  17584. });
  17585. exportRule.append(exportDeclarations);
  17586. root.prepend(exportRule);
  17587. }
  17588. /* Add import rules */
  17589. importAliases.reverse().forEach(({ path, imports }) => {
  17590. const importRule = postcss.rule({
  17591. selector: `:import(${path})`,
  17592. raws: { after: "\n" },
  17593. });
  17594. imports.forEach(({ theirName, importedName }) => {
  17595. importRule.append({
  17596. value: theirName,
  17597. prop: importedName,
  17598. raws: { before: "\n " },
  17599. });
  17600. });
  17601. root.prepend(importRule);
  17602. });
  17603. },
  17604. };
  17605. },
  17606. };
  17607. };
  17608. src.exports.postcss = true;
  17609. return src.exports;
  17610. }
  17611. var hasRequiredScoping;
  17612. function requireScoping () {
  17613. if (hasRequiredScoping) return scoping;
  17614. hasRequiredScoping = 1;
  17615. Object.defineProperty(scoping, "__esModule", {
  17616. value: true
  17617. });
  17618. scoping.behaviours = void 0;
  17619. scoping.getDefaultPlugins = getDefaultPlugins;
  17620. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  17621. scoping.getScopedNameGenerator = getScopedNameGenerator;
  17622. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  17623. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  17624. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  17625. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  17626. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  17627. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  17628. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17629. const behaviours = {
  17630. LOCAL: "local",
  17631. GLOBAL: "global"
  17632. };
  17633. scoping.behaviours = behaviours;
  17634. function getDefaultPlugins({
  17635. behaviour,
  17636. generateScopedName,
  17637. exportGlobals
  17638. }) {
  17639. const scope = (0, _postcssModulesScope.default)({
  17640. generateScopedName,
  17641. exportGlobals
  17642. });
  17643. const plugins = {
  17644. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17645. mode: "local"
  17646. }), _postcssModulesExtractImports.default, scope],
  17647. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17648. mode: "global"
  17649. }), _postcssModulesExtractImports.default, scope]
  17650. };
  17651. return plugins[behaviour];
  17652. }
  17653. function isValidBehaviour(behaviour) {
  17654. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  17655. }
  17656. function getDefaultScopeBehaviour(scopeBehaviour) {
  17657. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  17658. }
  17659. function generateScopedNameDefault(name, filename, css) {
  17660. const i = css.indexOf(`.${name}`);
  17661. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  17662. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  17663. return `_${name}_${hash}_${lineNumber}`;
  17664. }
  17665. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  17666. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  17667. if (typeof scopedNameGenerator === "function") {
  17668. return scopedNameGenerator;
  17669. }
  17670. return (0, _genericNames.default)(scopedNameGenerator, {
  17671. context: process.cwd(),
  17672. hashPrefix: hashPrefix
  17673. });
  17674. }
  17675. return scoping;
  17676. }
  17677. var hasRequiredPluginFactory;
  17678. function requirePluginFactory () {
  17679. if (hasRequiredPluginFactory) return pluginFactory;
  17680. hasRequiredPluginFactory = 1;
  17681. Object.defineProperty(pluginFactory, "__esModule", {
  17682. value: true
  17683. });
  17684. pluginFactory.makePlugin = makePlugin;
  17685. var _postcss = _interopRequireDefault(require$$0$1);
  17686. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  17687. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  17688. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  17689. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  17690. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  17691. var _scoping = /*@__PURE__*/ requireScoping();
  17692. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17693. const PLUGIN_NAME = "postcss-modules";
  17694. function isGlobalModule(globalModules, inputFile) {
  17695. return globalModules.some(regex => inputFile.match(regex));
  17696. }
  17697. function getDefaultPluginsList(opts, inputFile) {
  17698. const globalModulesList = opts.globalModulePaths || null;
  17699. const exportGlobals = opts.exportGlobals || false;
  17700. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  17701. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  17702. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  17703. return (0, _scoping.getDefaultPlugins)({
  17704. behaviour: _scoping.behaviours.GLOBAL,
  17705. generateScopedName,
  17706. exportGlobals
  17707. });
  17708. }
  17709. return (0, _scoping.getDefaultPlugins)({
  17710. behaviour: defaultBehaviour,
  17711. generateScopedName,
  17712. exportGlobals
  17713. });
  17714. }
  17715. function getLoader(opts, plugins) {
  17716. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  17717. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  17718. }
  17719. function isOurPlugin(plugin) {
  17720. return plugin.postcssPlugin === PLUGIN_NAME;
  17721. }
  17722. function makePlugin(opts) {
  17723. return {
  17724. postcssPlugin: PLUGIN_NAME,
  17725. async OnceExit(css, {
  17726. result
  17727. }) {
  17728. const getJSON = opts.getJSON || _saveJSON.default;
  17729. const inputFile = css.source.input.file;
  17730. const pluginList = getDefaultPluginsList(opts, inputFile);
  17731. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  17732. if (resultPluginIndex === -1) {
  17733. throw new Error("Plugin missing from options.");
  17734. }
  17735. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  17736. const loaderPlugins = [...earlierPlugins, ...pluginList];
  17737. const loader = getLoader(opts, loaderPlugins);
  17738. const fetcher = async (file, relativeTo, depTrace) => {
  17739. const unquoteFile = (0, _unquote.default)(file);
  17740. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  17741. };
  17742. const parser = new _Parser.default(fetcher);
  17743. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  17744. from: inputFile
  17745. });
  17746. const out = loader.finalSource;
  17747. if (out) css.prepend(out);
  17748. if (opts.localsConvention) {
  17749. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  17750. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  17751. }
  17752. result.messages.push({
  17753. type: "export",
  17754. plugin: "postcss-modules",
  17755. exportTokens: parser.exportTokens
  17756. }); // getJSON may return a promise
  17757. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  17758. }
  17759. };
  17760. }
  17761. return pluginFactory;
  17762. }
  17763. var hasRequiredBuild;
  17764. function requireBuild () {
  17765. if (hasRequiredBuild) return build.exports;
  17766. hasRequiredBuild = 1;
  17767. var _fs = require$$0;
  17768. var _fs2 = /*@__PURE__*/ requireFs();
  17769. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  17770. (0, _fs2.setFileSystem)({
  17771. readFile: _fs.readFile,
  17772. writeFile: _fs.writeFile
  17773. });
  17774. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  17775. build.exports.postcss = true;
  17776. return build.exports;
  17777. }
  17778. var buildExports = /*@__PURE__*/ requireBuild();
  17779. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  17780. function compileStyle(options) {
  17781. return doCompileStyle({
  17782. ...options,
  17783. isAsync: false
  17784. });
  17785. }
  17786. function compileStyleAsync(options) {
  17787. return doCompileStyle({
  17788. ...options,
  17789. isAsync: true
  17790. });
  17791. }
  17792. function doCompileStyle(options) {
  17793. const {
  17794. filename,
  17795. id,
  17796. scoped = false,
  17797. trim = true,
  17798. isProd = false,
  17799. modules = false,
  17800. modulesOptions = {},
  17801. preprocessLang,
  17802. postcssOptions,
  17803. postcssPlugins
  17804. } = options;
  17805. const preprocessor = preprocessLang && processors[preprocessLang];
  17806. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  17807. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  17808. const source = preProcessedSource ? preProcessedSource.code : options.source;
  17809. const shortId = id.replace(/^data-v-/, "");
  17810. const longId = `data-v-${shortId}`;
  17811. const plugins = (postcssPlugins || []).slice();
  17812. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  17813. if (trim) {
  17814. plugins.push(trimPlugin());
  17815. }
  17816. if (scoped) {
  17817. plugins.push(scopedPlugin(longId));
  17818. }
  17819. let cssModules;
  17820. if (modules) {
  17821. if (!options.isAsync) {
  17822. throw new Error(
  17823. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  17824. );
  17825. }
  17826. plugins.push(
  17827. postcssModules({
  17828. ...modulesOptions,
  17829. getJSON: (_cssFileName, json) => {
  17830. cssModules = json;
  17831. }
  17832. })
  17833. );
  17834. }
  17835. const postCSSOptions = {
  17836. ...postcssOptions,
  17837. to: filename,
  17838. from: filename
  17839. };
  17840. if (map) {
  17841. postCSSOptions.map = {
  17842. inline: false,
  17843. annotation: false,
  17844. prev: map
  17845. };
  17846. }
  17847. let result;
  17848. let code;
  17849. let outMap;
  17850. const dependencies = new Set(
  17851. preProcessedSource ? preProcessedSource.dependencies : []
  17852. );
  17853. dependencies.delete(filename);
  17854. const errors = [];
  17855. if (preProcessedSource && preProcessedSource.errors.length) {
  17856. errors.push(...preProcessedSource.errors);
  17857. }
  17858. const recordPlainCssDependencies = (messages) => {
  17859. messages.forEach((msg) => {
  17860. if (msg.type === "dependency") {
  17861. dependencies.add(msg.file);
  17862. }
  17863. });
  17864. return dependencies;
  17865. };
  17866. try {
  17867. result = require$$0$1(plugins).process(source, postCSSOptions);
  17868. if (options.isAsync) {
  17869. return result.then((result2) => ({
  17870. code: result2.css || "",
  17871. map: result2.map && result2.map.toJSON(),
  17872. errors,
  17873. modules: cssModules,
  17874. rawResult: result2,
  17875. dependencies: recordPlainCssDependencies(result2.messages)
  17876. })).catch((error) => ({
  17877. code: "",
  17878. map: void 0,
  17879. errors: [...errors, error],
  17880. rawResult: void 0,
  17881. dependencies
  17882. }));
  17883. }
  17884. recordPlainCssDependencies(result.messages);
  17885. code = result.css;
  17886. outMap = result.map;
  17887. } catch (e) {
  17888. errors.push(e);
  17889. }
  17890. return {
  17891. code: code || ``,
  17892. map: outMap && outMap.toJSON(),
  17893. errors,
  17894. rawResult: result,
  17895. dependencies
  17896. };
  17897. }
  17898. function preprocess(options, preprocessor) {
  17899. return preprocessor(
  17900. options.source,
  17901. options.inMap || options.map,
  17902. {
  17903. filename: options.filename,
  17904. ...options.preprocessOptions
  17905. },
  17906. options.preprocessCustomRequire
  17907. );
  17908. }
  17909. const UNKNOWN_TYPE = "Unknown";
  17910. function resolveObjectKey(node, computed) {
  17911. switch (node.type) {
  17912. case "StringLiteral":
  17913. case "NumericLiteral":
  17914. return String(node.value);
  17915. case "Identifier":
  17916. if (!computed) return node.name;
  17917. }
  17918. return void 0;
  17919. }
  17920. function concatStrings(strs) {
  17921. return strs.filter((s) => !!s).join(", ");
  17922. }
  17923. function isLiteralNode(node) {
  17924. return node.type.endsWith("Literal");
  17925. }
  17926. function isCallOf(node, test) {
  17927. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  17928. }
  17929. function toRuntimeTypeString(types) {
  17930. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  17931. }
  17932. function getImportedName(specifier) {
  17933. if (specifier.type === "ImportSpecifier")
  17934. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  17935. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  17936. return "default";
  17937. }
  17938. function getId(node) {
  17939. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  17940. }
  17941. function getStringLiteralKey(node) {
  17942. return node.computed ? node.key.type === "TemplateLiteral" && !node.key.expressions.length ? node.key.quasis.map((q) => q.value.cooked).join("") : null : node.key.type === "Identifier" ? node.key.name : node.key.type === "StringLiteral" ? node.key.value : node.key.type === "NumericLiteral" ? String(node.key.value) : null;
  17943. }
  17944. const identity = (str) => str;
  17945. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  17946. const toLowerCase = (str) => str.toLowerCase();
  17947. function toFileNameLowerCase(x) {
  17948. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  17949. }
  17950. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  17951. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  17952. }
  17953. const normalize = (path$1.posix || path$1).normalize;
  17954. const windowsSlashRE = /\\/g;
  17955. function normalizePath(p) {
  17956. return normalize(p.replace(windowsSlashRE, "/"));
  17957. }
  17958. const joinPaths = (path$1.posix || path$1).join;
  17959. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  17960. function getEscapedPropName(key) {
  17961. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  17962. }
  17963. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  17964. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  17965. function analyzeScriptBindings(ast) {
  17966. for (const node of ast) {
  17967. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  17968. return analyzeBindingsFromOptions(node.declaration);
  17969. }
  17970. }
  17971. return {};
  17972. }
  17973. function analyzeBindingsFromOptions(node) {
  17974. const bindings = {};
  17975. Object.defineProperty(bindings, "__isScriptSetup", {
  17976. enumerable: false,
  17977. value: false
  17978. });
  17979. for (const property of node.properties) {
  17980. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  17981. if (property.key.name === "props") {
  17982. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17983. bindings[key] = "props";
  17984. }
  17985. } else if (property.key.name === "inject") {
  17986. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17987. bindings[key] = "options";
  17988. }
  17989. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  17990. for (const key of getObjectExpressionKeys(property.value)) {
  17991. bindings[key] = "options";
  17992. }
  17993. }
  17994. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  17995. for (const bodyItem of property.body.body) {
  17996. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  17997. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  17998. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  17999. }
  18000. }
  18001. }
  18002. }
  18003. }
  18004. return bindings;
  18005. }
  18006. function getObjectExpressionKeys(node) {
  18007. const keys = [];
  18008. for (const prop of node.properties) {
  18009. if (prop.type === "SpreadElement") continue;
  18010. const key = resolveObjectKey(prop.key, prop.computed);
  18011. if (key) keys.push(String(key));
  18012. }
  18013. return keys;
  18014. }
  18015. function getArrayExpressionKeys(node) {
  18016. const keys = [];
  18017. for (const element of node.elements) {
  18018. if (element && element.type === "StringLiteral") {
  18019. keys.push(element.value);
  18020. }
  18021. }
  18022. return keys;
  18023. }
  18024. function getObjectOrArrayExpressionKeys(value) {
  18025. if (value.type === "ArrayExpression") {
  18026. return getArrayExpressionKeys(value);
  18027. }
  18028. if (value.type === "ObjectExpression") {
  18029. return getObjectExpressionKeys(value);
  18030. }
  18031. return [];
  18032. }
  18033. var _a$1, _b;
  18034. class ScriptCompileContext {
  18035. constructor(descriptor, options) {
  18036. this.descriptor = descriptor;
  18037. this.options = options;
  18038. this.isCE = false;
  18039. this.source = this.descriptor.source;
  18040. this.filename = this.descriptor.filename;
  18041. this.s = new MagicString(this.source);
  18042. this.startOffset = (_a$1 = this.descriptor.scriptSetup) == null ? void 0 : _a$1.loc.start.offset;
  18043. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  18044. this.userImports = /* @__PURE__ */ Object.create(null);
  18045. // macros presence check
  18046. this.hasDefinePropsCall = false;
  18047. this.hasDefineEmitCall = false;
  18048. this.hasDefineExposeCall = false;
  18049. this.hasDefaultExportName = false;
  18050. this.hasDefaultExportRender = false;
  18051. this.hasDefineOptionsCall = false;
  18052. this.hasDefineSlotsCall = false;
  18053. this.hasDefineModelCall = false;
  18054. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  18055. // defineModel
  18056. this.modelDecls = /* @__PURE__ */ Object.create(null);
  18057. // codegen
  18058. this.bindingMetadata = {};
  18059. this.helperImports = /* @__PURE__ */ new Set();
  18060. const { script, scriptSetup } = descriptor;
  18061. const scriptLang = script && script.lang;
  18062. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  18063. this.isJS = isJS(scriptLang, scriptSetupLang);
  18064. this.isTS = isTS(scriptLang, scriptSetupLang);
  18065. const customElement = options.customElement;
  18066. const filename = this.descriptor.filename;
  18067. if (customElement) {
  18068. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  18069. }
  18070. const plugins = resolveParserPlugins(
  18071. scriptLang || scriptSetupLang,
  18072. options.babelParserPlugins
  18073. );
  18074. function parse(input, offset) {
  18075. try {
  18076. return parser$2.parse(input, {
  18077. plugins,
  18078. sourceType: "module"
  18079. }).program;
  18080. } catch (e) {
  18081. e.message = `[vue/compiler-sfc] ${e.message}
  18082. ${descriptor.filename}
  18083. ${shared.generateCodeFrame(
  18084. descriptor.source,
  18085. e.pos + offset,
  18086. e.pos + offset + 1
  18087. )}`;
  18088. throw e;
  18089. }
  18090. }
  18091. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  18092. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  18093. }
  18094. helper(key) {
  18095. this.helperImports.add(key);
  18096. return `_${key}`;
  18097. }
  18098. getString(node, scriptSetup = true) {
  18099. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  18100. return block.content.slice(node.start, node.end);
  18101. }
  18102. warn(msg, node, scope) {
  18103. warn(generateError(msg, node, this, scope));
  18104. }
  18105. error(msg, node, scope) {
  18106. throw new Error(
  18107. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  18108. );
  18109. }
  18110. }
  18111. function generateError(msg, node, ctx, scope) {
  18112. const offset = scope ? scope.offset : ctx.startOffset;
  18113. return `${msg}
  18114. ${(scope || ctx.descriptor).filename}
  18115. ${shared.generateCodeFrame(
  18116. (scope || ctx.descriptor).source,
  18117. node.start + offset,
  18118. node.end + offset
  18119. )}`;
  18120. }
  18121. function resolveParserPlugins(lang, userPlugins, dts = false) {
  18122. const plugins = [];
  18123. if (!userPlugins || !userPlugins.some(
  18124. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  18125. )) {
  18126. plugins.push("importAttributes");
  18127. }
  18128. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  18129. plugins.push("jsx");
  18130. } else if (userPlugins) {
  18131. userPlugins = userPlugins.filter((p) => p !== "jsx");
  18132. }
  18133. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "cts" || lang === "mtsx") {
  18134. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  18135. if (!userPlugins || !userPlugins.includes("decorators")) {
  18136. plugins.push("decorators-legacy");
  18137. }
  18138. }
  18139. if (userPlugins) {
  18140. plugins.push(...userPlugins);
  18141. }
  18142. return plugins;
  18143. }
  18144. function rewriteDefault(input, as, parserPlugins) {
  18145. const ast = parser$2.parse(input, {
  18146. sourceType: "module",
  18147. plugins: resolveParserPlugins("js", parserPlugins)
  18148. }).program.body;
  18149. const s = new MagicString(input);
  18150. rewriteDefaultAST(ast, s, as);
  18151. return s.toString();
  18152. }
  18153. function rewriteDefaultAST(ast, s, as) {
  18154. if (!hasDefaultExport(ast)) {
  18155. s.append(`
  18156. const ${as} = {}`);
  18157. return;
  18158. }
  18159. ast.forEach((node) => {
  18160. if (node.type === "ExportDefaultDeclaration") {
  18161. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  18162. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  18163. s.overwrite(start, node.declaration.id.start, ` class `);
  18164. s.append(`
  18165. const ${as} = ${node.declaration.id.name}`);
  18166. } else {
  18167. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18168. }
  18169. } else if (node.type === "ExportNamedDeclaration") {
  18170. for (const specifier of node.specifiers) {
  18171. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18172. if (node.source) {
  18173. if (specifier.local.name === "default") {
  18174. s.prepend(
  18175. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18176. `
  18177. );
  18178. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18179. s.remove(specifier.start, end2);
  18180. s.append(`
  18181. const ${as} = __VUE_DEFAULT__`);
  18182. continue;
  18183. } else {
  18184. s.prepend(
  18185. `import { ${s.slice(
  18186. specifier.local.start,
  18187. specifier.local.end
  18188. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18189. `
  18190. );
  18191. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18192. s.remove(specifier.start, end2);
  18193. s.append(`
  18194. const ${as} = __VUE_DEFAULT__`);
  18195. continue;
  18196. }
  18197. }
  18198. const end = specifierEnd(s, specifier.end, node.end);
  18199. s.remove(specifier.start, end);
  18200. s.append(`
  18201. const ${as} = ${specifier.local.name}`);
  18202. }
  18203. }
  18204. }
  18205. });
  18206. }
  18207. function hasDefaultExport(ast) {
  18208. for (const stmt of ast) {
  18209. if (stmt.type === "ExportDefaultDeclaration") {
  18210. return true;
  18211. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18212. (spec) => spec.exported.name === "default"
  18213. )) {
  18214. return true;
  18215. }
  18216. }
  18217. return false;
  18218. }
  18219. function specifierEnd(s, end, nodeEnd) {
  18220. let hasCommas = false;
  18221. let oldEnd = end;
  18222. while (end < nodeEnd) {
  18223. if (/\s/.test(s.slice(end, end + 1))) {
  18224. end++;
  18225. } else if (s.slice(end, end + 1) === ",") {
  18226. end++;
  18227. hasCommas = true;
  18228. break;
  18229. } else if (s.slice(end, end + 1) === "}") {
  18230. break;
  18231. }
  18232. }
  18233. return hasCommas ? end : oldEnd;
  18234. }
  18235. const normalScriptDefaultVar = `__default__`;
  18236. function processNormalScript(ctx, scopeId) {
  18237. var _a;
  18238. const script = ctx.descriptor.script;
  18239. try {
  18240. let content = script.content;
  18241. let map = script.map;
  18242. const scriptAst = ctx.scriptAst;
  18243. const bindings = analyzeScriptBindings(scriptAst.body);
  18244. const { cssVars } = ctx.descriptor;
  18245. const { genDefaultAs, isProd } = ctx.options;
  18246. if (cssVars.length || genDefaultAs) {
  18247. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18248. const s = new MagicString(content);
  18249. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18250. content = s.toString();
  18251. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18252. content += genNormalScriptCssVarsCode(
  18253. cssVars,
  18254. bindings,
  18255. scopeId,
  18256. !!isProd,
  18257. defaultVar
  18258. );
  18259. }
  18260. if (!genDefaultAs) {
  18261. content += `
  18262. export default ${defaultVar}`;
  18263. }
  18264. }
  18265. return {
  18266. ...script,
  18267. content,
  18268. map,
  18269. bindings,
  18270. scriptAst: scriptAst.body
  18271. };
  18272. } catch (e) {
  18273. return script;
  18274. }
  18275. }
  18276. const balanced = (a, b, str) => {
  18277. const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
  18278. const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
  18279. const r = ma !== null && mb != null && range(ma, mb, str);
  18280. return (r && {
  18281. start: r[0],
  18282. end: r[1],
  18283. pre: str.slice(0, r[0]),
  18284. body: str.slice(r[0] + ma.length, r[1]),
  18285. post: str.slice(r[1] + mb.length),
  18286. });
  18287. };
  18288. const maybeMatch = (reg, str) => {
  18289. const m = str.match(reg);
  18290. return m ? m[0] : null;
  18291. };
  18292. const range = (a, b, str) => {
  18293. let begs, beg, left, right = undefined, result;
  18294. let ai = str.indexOf(a);
  18295. let bi = str.indexOf(b, ai + 1);
  18296. let i = ai;
  18297. if (ai >= 0 && bi > 0) {
  18298. if (a === b) {
  18299. return [ai, bi];
  18300. }
  18301. begs = [];
  18302. left = str.length;
  18303. while (i >= 0 && !result) {
  18304. if (i === ai) {
  18305. begs.push(i);
  18306. ai = str.indexOf(a, i + 1);
  18307. }
  18308. else if (begs.length === 1) {
  18309. const r = begs.pop();
  18310. if (r !== undefined)
  18311. result = [r, bi];
  18312. }
  18313. else {
  18314. beg = begs.pop();
  18315. if (beg !== undefined && beg < left) {
  18316. left = beg;
  18317. right = bi;
  18318. }
  18319. bi = str.indexOf(b, i + 1);
  18320. }
  18321. i = ai < bi && ai >= 0 ? ai : bi;
  18322. }
  18323. if (begs.length && right !== undefined) {
  18324. result = [left, right];
  18325. }
  18326. }
  18327. return result;
  18328. };
  18329. const escSlash = '\0SLASH' + Math.random() + '\0';
  18330. const escOpen = '\0OPEN' + Math.random() + '\0';
  18331. const escClose = '\0CLOSE' + Math.random() + '\0';
  18332. const escComma = '\0COMMA' + Math.random() + '\0';
  18333. const escPeriod = '\0PERIOD' + Math.random() + '\0';
  18334. const escSlashPattern = new RegExp(escSlash, 'g');
  18335. const escOpenPattern = new RegExp(escOpen, 'g');
  18336. const escClosePattern = new RegExp(escClose, 'g');
  18337. const escCommaPattern = new RegExp(escComma, 'g');
  18338. const escPeriodPattern = new RegExp(escPeriod, 'g');
  18339. const slashPattern = /\\\\/g;
  18340. const openPattern = /\\{/g;
  18341. const closePattern = /\\}/g;
  18342. const commaPattern = /\\,/g;
  18343. const periodPattern = /\\\./g;
  18344. const EXPANSION_MAX = 100_000;
  18345. function numeric(str) {
  18346. return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
  18347. }
  18348. function escapeBraces(str) {
  18349. return str
  18350. .replace(slashPattern, escSlash)
  18351. .replace(openPattern, escOpen)
  18352. .replace(closePattern, escClose)
  18353. .replace(commaPattern, escComma)
  18354. .replace(periodPattern, escPeriod);
  18355. }
  18356. function unescapeBraces(str) {
  18357. return str
  18358. .replace(escSlashPattern, '\\')
  18359. .replace(escOpenPattern, '{')
  18360. .replace(escClosePattern, '}')
  18361. .replace(escCommaPattern, ',')
  18362. .replace(escPeriodPattern, '.');
  18363. }
  18364. /**
  18365. * Basically just str.split(","), but handling cases
  18366. * where we have nested braced sections, which should be
  18367. * treated as individual members, like {a,{b,c},d}
  18368. */
  18369. function parseCommaParts(str) {
  18370. if (!str) {
  18371. return [''];
  18372. }
  18373. const parts = [];
  18374. const m = balanced('{', '}', str);
  18375. if (!m) {
  18376. return str.split(',');
  18377. }
  18378. const { pre, body, post } = m;
  18379. const p = pre.split(',');
  18380. p[p.length - 1] += '{' + body + '}';
  18381. const postParts = parseCommaParts(post);
  18382. if (post.length) {
  18383. p[p.length - 1] += postParts.shift();
  18384. p.push.apply(p, postParts);
  18385. }
  18386. parts.push.apply(parts, p);
  18387. return parts;
  18388. }
  18389. function expand(str, options = {}) {
  18390. if (!str) {
  18391. return [];
  18392. }
  18393. const { max = EXPANSION_MAX } = options;
  18394. // I don't know why Bash 4.3 does this, but it does.
  18395. // Anything starting with {} will have the first two bytes preserved
  18396. // but *only* at the top level, so {},a}b will not expand to anything,
  18397. // but a{},b}c will be expanded to [a}c,abc].
  18398. // One could argue that this is a bug in Bash, but since the goal of
  18399. // this module is to match Bash's rules, we escape a leading {}
  18400. if (str.slice(0, 2) === '{}') {
  18401. str = '\\{\\}' + str.slice(2);
  18402. }
  18403. return expand_(escapeBraces(str), max, true).map(unescapeBraces);
  18404. }
  18405. function embrace(str) {
  18406. return '{' + str + '}';
  18407. }
  18408. function isPadded(el) {
  18409. return /^-?0\d/.test(el);
  18410. }
  18411. function lte(i, y) {
  18412. return i <= y;
  18413. }
  18414. function gte(i, y) {
  18415. return i >= y;
  18416. }
  18417. function expand_(str, max, isTop) {
  18418. /** @type {string[]} */
  18419. const expansions = [];
  18420. const m = balanced('{', '}', str);
  18421. if (!m)
  18422. return [str];
  18423. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18424. const pre = m.pre;
  18425. const post = m.post.length ? expand_(m.post, max, false) : [''];
  18426. if (/\$$/.test(m.pre)) {
  18427. for (let k = 0; k < post.length && k < max; k++) {
  18428. const expansion = pre + '{' + m.body + '}' + post[k];
  18429. expansions.push(expansion);
  18430. }
  18431. }
  18432. else {
  18433. const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18434. const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18435. const isSequence = isNumericSequence || isAlphaSequence;
  18436. const isOptions = m.body.indexOf(',') >= 0;
  18437. if (!isSequence && !isOptions) {
  18438. // {a},b}
  18439. if (m.post.match(/,(?!,).*\}/)) {
  18440. str = m.pre + '{' + m.body + escClose + m.post;
  18441. return expand_(str, max, true);
  18442. }
  18443. return [str];
  18444. }
  18445. let n;
  18446. if (isSequence) {
  18447. n = m.body.split(/\.\./);
  18448. }
  18449. else {
  18450. n = parseCommaParts(m.body);
  18451. if (n.length === 1 && n[0] !== undefined) {
  18452. // x{{a,b}}y ==> x{a}y x{b}y
  18453. n = expand_(n[0], max, false).map(embrace);
  18454. //XXX is this necessary? Can't seem to hit it in tests.
  18455. /* c8 ignore start */
  18456. if (n.length === 1) {
  18457. return post.map(p => m.pre + n[0] + p);
  18458. }
  18459. /* c8 ignore stop */
  18460. }
  18461. }
  18462. // at this point, n is the parts, and we know it's not a comma set
  18463. // with a single entry.
  18464. let N;
  18465. if (isSequence && n[0] !== undefined && n[1] !== undefined) {
  18466. const x = numeric(n[0]);
  18467. const y = numeric(n[1]);
  18468. const width = Math.max(n[0].length, n[1].length);
  18469. let incr = n.length === 3 && n[2] !== undefined ?
  18470. Math.max(Math.abs(numeric(n[2])), 1)
  18471. : 1;
  18472. let test = lte;
  18473. const reverse = y < x;
  18474. if (reverse) {
  18475. incr *= -1;
  18476. test = gte;
  18477. }
  18478. const pad = n.some(isPadded);
  18479. N = [];
  18480. for (let i = x; test(i, y); i += incr) {
  18481. let c;
  18482. if (isAlphaSequence) {
  18483. c = String.fromCharCode(i);
  18484. if (c === '\\') {
  18485. c = '';
  18486. }
  18487. }
  18488. else {
  18489. c = String(i);
  18490. if (pad) {
  18491. const need = width - c.length;
  18492. if (need > 0) {
  18493. const z = new Array(need + 1).join('0');
  18494. if (i < 0) {
  18495. c = '-' + z + c.slice(1);
  18496. }
  18497. else {
  18498. c = z + c;
  18499. }
  18500. }
  18501. }
  18502. }
  18503. N.push(c);
  18504. }
  18505. }
  18506. else {
  18507. N = [];
  18508. for (let j = 0; j < n.length; j++) {
  18509. N.push.apply(N, expand_(n[j], max, false));
  18510. }
  18511. }
  18512. for (let j = 0; j < N.length; j++) {
  18513. for (let k = 0; k < post.length && expansions.length < max; k++) {
  18514. const expansion = pre + N[j] + post[k];
  18515. if (!isTop || isSequence || expansion) {
  18516. expansions.push(expansion);
  18517. }
  18518. }
  18519. }
  18520. }
  18521. return expansions;
  18522. }
  18523. const MAX_PATTERN_LENGTH = 1024 * 64;
  18524. const assertValidPattern = (pattern) => {
  18525. if (typeof pattern !== 'string') {
  18526. throw new TypeError('invalid pattern');
  18527. }
  18528. if (pattern.length > MAX_PATTERN_LENGTH) {
  18529. throw new TypeError('pattern is too long');
  18530. }
  18531. };
  18532. // translate the various posix character classes into unicode properties
  18533. // this works across all unicode locales
  18534. // { <posix class>: [<translation>, /u flag required, negated]
  18535. const posixClasses = {
  18536. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  18537. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  18538. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  18539. '[:blank:]': ['\\p{Zs}\\t', true],
  18540. '[:cntrl:]': ['\\p{Cc}', true],
  18541. '[:digit:]': ['\\p{Nd}', true],
  18542. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  18543. '[:lower:]': ['\\p{Ll}', true],
  18544. '[:print:]': ['\\p{C}', true],
  18545. '[:punct:]': ['\\p{P}', true],
  18546. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  18547. '[:upper:]': ['\\p{Lu}', true],
  18548. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  18549. '[:xdigit:]': ['A-Fa-f0-9', false],
  18550. };
  18551. // only need to escape a few things inside of brace expressions
  18552. // escapes: [ \ ] -
  18553. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  18554. // escape all regexp magic characters
  18555. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18556. // everything has already been escaped, we just have to join
  18557. const rangesToString = (ranges) => ranges.join('');
  18558. // takes a glob string at a posix brace expression, and returns
  18559. // an equivalent regular expression source, and boolean indicating
  18560. // whether the /u flag needs to be applied, and the number of chars
  18561. // consumed to parse the character class.
  18562. // This also removes out of order ranges, and returns ($.) if the
  18563. // entire class just no good.
  18564. const parseClass = (glob, position) => {
  18565. const pos = position;
  18566. /* c8 ignore start */
  18567. if (glob.charAt(pos) !== '[') {
  18568. throw new Error('not in a brace expression');
  18569. }
  18570. /* c8 ignore stop */
  18571. const ranges = [];
  18572. const negs = [];
  18573. let i = pos + 1;
  18574. let sawStart = false;
  18575. let uflag = false;
  18576. let escaping = false;
  18577. let negate = false;
  18578. let endPos = pos;
  18579. let rangeStart = '';
  18580. WHILE: while (i < glob.length) {
  18581. const c = glob.charAt(i);
  18582. if ((c === '!' || c === '^') && i === pos + 1) {
  18583. negate = true;
  18584. i++;
  18585. continue;
  18586. }
  18587. if (c === ']' && sawStart && !escaping) {
  18588. endPos = i + 1;
  18589. break;
  18590. }
  18591. sawStart = true;
  18592. if (c === '\\') {
  18593. if (!escaping) {
  18594. escaping = true;
  18595. i++;
  18596. continue;
  18597. }
  18598. // escaped \ char, fall through and treat like normal char
  18599. }
  18600. if (c === '[' && !escaping) {
  18601. // either a posix class, a collation equivalent, or just a [
  18602. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  18603. if (glob.startsWith(cls, i)) {
  18604. // invalid, [a-[] is fine, but not [a-[:alpha]]
  18605. if (rangeStart) {
  18606. return ['$.', false, glob.length - pos, true];
  18607. }
  18608. i += cls.length;
  18609. if (neg)
  18610. negs.push(unip);
  18611. else
  18612. ranges.push(unip);
  18613. uflag = uflag || u;
  18614. continue WHILE;
  18615. }
  18616. }
  18617. }
  18618. // now it's just a normal character, effectively
  18619. escaping = false;
  18620. if (rangeStart) {
  18621. // throw this range away if it's not valid, but others
  18622. // can still match.
  18623. if (c > rangeStart) {
  18624. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  18625. }
  18626. else if (c === rangeStart) {
  18627. ranges.push(braceEscape(c));
  18628. }
  18629. rangeStart = '';
  18630. i++;
  18631. continue;
  18632. }
  18633. // now might be the start of a range.
  18634. // can be either c-d or c-] or c<more...>] or c] at this point
  18635. if (glob.startsWith('-]', i + 1)) {
  18636. ranges.push(braceEscape(c + '-'));
  18637. i += 2;
  18638. continue;
  18639. }
  18640. if (glob.startsWith('-', i + 1)) {
  18641. rangeStart = c;
  18642. i += 2;
  18643. continue;
  18644. }
  18645. // not the start of a range, just a single character
  18646. ranges.push(braceEscape(c));
  18647. i++;
  18648. }
  18649. if (endPos < i) {
  18650. // didn't see the end of the class, not a valid class,
  18651. // but might still be valid as a literal match.
  18652. return ['', false, 0, false];
  18653. }
  18654. // if we got no ranges and no negates, then we have a range that
  18655. // cannot possibly match anything, and that poisons the whole glob
  18656. if (!ranges.length && !negs.length) {
  18657. return ['$.', false, glob.length - pos, true];
  18658. }
  18659. // if we got one positive range, and it's a single character, then that's
  18660. // not actually a magic pattern, it's just that one literal character.
  18661. // we should not treat that as "magic", we should just return the literal
  18662. // character. [_] is a perfectly valid way to escape glob magic chars.
  18663. if (negs.length === 0 &&
  18664. ranges.length === 1 &&
  18665. /^\\?.$/.test(ranges[0]) &&
  18666. !negate) {
  18667. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  18668. return [regexpEscape(r), false, endPos - pos, false];
  18669. }
  18670. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  18671. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  18672. const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
  18673. : ranges.length ? sranges
  18674. : snegs;
  18675. return [comb, uflag, endPos - pos, true];
  18676. };
  18677. /**
  18678. * Un-escape a string that has been escaped with {@link escape}.
  18679. *
  18680. * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
  18681. * square-bracket escapes are removed, but not backslash escapes.
  18682. *
  18683. * For example, it will turn the string `'[*]'` into `*`, but it will not
  18684. * turn `'\\*'` into `'*'`, because `\` is a path separator in
  18685. * `windowsPathsNoEscape` mode.
  18686. *
  18687. * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
  18688. * backslash escapes are removed.
  18689. *
  18690. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  18691. * or unescaped.
  18692. *
  18693. * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
  18694. * unescaped.
  18695. */
  18696. const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
  18697. if (magicalBraces) {
  18698. return windowsPathsNoEscape ?
  18699. s.replace(/\[([^/\\])\]/g, '$1')
  18700. : s
  18701. .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
  18702. .replace(/\\([^/])/g, '$1');
  18703. }
  18704. return windowsPathsNoEscape ?
  18705. s.replace(/\[([^/\\{}])\]/g, '$1')
  18706. : s
  18707. .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
  18708. .replace(/\\([^/{}])/g, '$1');
  18709. };
  18710. // parse a single path portion
  18711. var _a;
  18712. const types = new Set(['!', '?', '+', '*', '@']);
  18713. const isExtglobType = (c) => types.has(c);
  18714. const isExtglobAST = (c) => isExtglobType(c.type);
  18715. // Map of which extglob types can adopt the children of a nested extglob
  18716. //
  18717. // anything but ! can adopt a matching type:
  18718. // +(a|+(b|c)|d) => +(a|b|c|d)
  18719. // *(a|*(b|c)|d) => *(a|b|c|d)
  18720. // @(a|@(b|c)|d) => @(a|b|c|d)
  18721. // ?(a|?(b|c)|d) => ?(a|b|c|d)
  18722. //
  18723. // * can adopt anything, because 0 or repetition is allowed
  18724. // *(a|?(b|c)|d) => *(a|b|c|d)
  18725. // *(a|+(b|c)|d) => *(a|b|c|d)
  18726. // *(a|@(b|c)|d) => *(a|b|c|d)
  18727. //
  18728. // + can adopt @, because 1 or repetition is allowed
  18729. // +(a|@(b|c)|d) => +(a|b|c|d)
  18730. //
  18731. // + and @ CANNOT adopt *, because 0 would be allowed
  18732. // +(a|*(b|c)|d) => would match "", on *(b|c)
  18733. // @(a|*(b|c)|d) => would match "", on *(b|c)
  18734. //
  18735. // + and @ CANNOT adopt ?, because 0 would be allowed
  18736. // +(a|?(b|c)|d) => would match "", on ?(b|c)
  18737. // @(a|?(b|c)|d) => would match "", on ?(b|c)
  18738. //
  18739. // ? can adopt @, because 0 or 1 is allowed
  18740. // ?(a|@(b|c)|d) => ?(a|b|c|d)
  18741. //
  18742. // ? and @ CANNOT adopt * or +, because >1 would be allowed
  18743. // ?(a|*(b|c)|d) => would match bbb on *(b|c)
  18744. // @(a|*(b|c)|d) => would match bbb on *(b|c)
  18745. // ?(a|+(b|c)|d) => would match bbb on +(b|c)
  18746. // @(a|+(b|c)|d) => would match bbb on +(b|c)
  18747. //
  18748. // ! CANNOT adopt ! (nothing else can either)
  18749. // !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
  18750. //
  18751. // ! can adopt @
  18752. // !(a|@(b|c)|d) => !(a|b|c|d)
  18753. //
  18754. // ! CANNOT adopt *
  18755. // !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  18756. //
  18757. // ! CANNOT adopt +
  18758. // !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  18759. //
  18760. // ! CANNOT adopt ?
  18761. // x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
  18762. const adoptionMap = new Map([
  18763. ['!', ['@']],
  18764. ['?', ['?', '@']],
  18765. ['@', ['@']],
  18766. ['*', ['*', '+', '?', '@']],
  18767. ['+', ['+', '@']],
  18768. ]);
  18769. // nested extglobs that can be adopted in, but with the addition of
  18770. // a blank '' element.
  18771. const adoptionWithSpaceMap = new Map([
  18772. ['!', ['?']],
  18773. ['@', ['?']],
  18774. ['+', ['?', '*']],
  18775. ]);
  18776. // union of the previous two maps
  18777. const adoptionAnyMap = new Map([
  18778. ['!', ['?', '@']],
  18779. ['?', ['?', '@']],
  18780. ['@', ['?', '@']],
  18781. ['*', ['*', '+', '?', '@']],
  18782. ['+', ['+', '@', '?', '*']],
  18783. ]);
  18784. // Extglobs that can take over their parent if they are the only child
  18785. // the key is parent, value maps child to resulting extglob parent type
  18786. // '@' is omitted because it's a special case. An `@` extglob with a single
  18787. // member can always be usurped by that subpattern.
  18788. const usurpMap = new Map([
  18789. ['!', new Map([['!', '@']])],
  18790. [
  18791. '?',
  18792. new Map([
  18793. ['*', '*'],
  18794. ['+', '*'],
  18795. ]),
  18796. ],
  18797. [
  18798. '@',
  18799. new Map([
  18800. ['!', '!'],
  18801. ['?', '?'],
  18802. ['@', '@'],
  18803. ['*', '*'],
  18804. ['+', '+'],
  18805. ]),
  18806. ],
  18807. [
  18808. '+',
  18809. new Map([
  18810. ['?', '*'],
  18811. ['*', '*'],
  18812. ]),
  18813. ],
  18814. ]);
  18815. // Patterns that get prepended to bind to the start of either the
  18816. // entire string, or just a single path portion, to prevent dots
  18817. // and/or traversal patterns, when needed.
  18818. // Exts don't need the ^ or / bit, because the root binds that already.
  18819. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  18820. const startNoDot = '(?!\\.)';
  18821. // characters that indicate a start of pattern needs the "no dots" bit,
  18822. // because a dot *might* be matched. ( is not in the list, because in
  18823. // the case of a child extglob, it will handle the prevention itself.
  18824. const addPatternStart = new Set(['[', '.']);
  18825. // cases where traversal is A-OK, no dot prevention needed
  18826. const justDots = new Set(['..', '.']);
  18827. const reSpecials = new Set('().*{}+?[]^$\\!');
  18828. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18829. // any single thing other than /
  18830. const qmark$1 = '[^/]';
  18831. // * => any number of characters
  18832. const star$1 = qmark$1 + '*?';
  18833. // use + when we need to ensure that *something* matches, because the * is
  18834. // the only thing in the path portion.
  18835. const starNoEmpty = qmark$1 + '+?';
  18836. // remove the \ chars that we added if we end up doing a nonmagic compare
  18837. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  18838. let ID = 0;
  18839. class AST {
  18840. type;
  18841. #root;
  18842. #hasMagic;
  18843. #uflag = false;
  18844. #parts = [];
  18845. #parent;
  18846. #parentIndex;
  18847. #negs;
  18848. #filledNegs = false;
  18849. #options;
  18850. #toString;
  18851. // set to true if it's an extglob with no children
  18852. // (which really means one child of '')
  18853. #emptyExt = false;
  18854. id = ++ID;
  18855. get depth() {
  18856. return (this.#parent?.depth ?? -1) + 1;
  18857. }
  18858. [Symbol.for('nodejs.util.inspect.custom')]() {
  18859. return {
  18860. '@@type': 'AST',
  18861. id: this.id,
  18862. type: this.type,
  18863. root: this.#root.id,
  18864. parent: this.#parent?.id,
  18865. depth: this.depth,
  18866. partsLength: this.#parts.length,
  18867. parts: this.#parts,
  18868. };
  18869. }
  18870. constructor(type, parent, options = {}) {
  18871. this.type = type;
  18872. // extglobs are inherently magical
  18873. if (type)
  18874. this.#hasMagic = true;
  18875. this.#parent = parent;
  18876. this.#root = this.#parent ? this.#parent.#root : this;
  18877. this.#options = this.#root === this ? options : this.#root.#options;
  18878. this.#negs = this.#root === this ? [] : this.#root.#negs;
  18879. if (type === '!' && !this.#root.#filledNegs)
  18880. this.#negs.push(this);
  18881. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  18882. }
  18883. get hasMagic() {
  18884. /* c8 ignore start */
  18885. if (this.#hasMagic !== undefined)
  18886. return this.#hasMagic;
  18887. /* c8 ignore stop */
  18888. for (const p of this.#parts) {
  18889. if (typeof p === 'string')
  18890. continue;
  18891. if (p.type || p.hasMagic)
  18892. return (this.#hasMagic = true);
  18893. }
  18894. // note: will be undefined until we generate the regexp src and find out
  18895. return this.#hasMagic;
  18896. }
  18897. // reconstructs the pattern
  18898. toString() {
  18899. return (this.#toString !== undefined ? this.#toString
  18900. : !this.type ?
  18901. (this.#toString = this.#parts.map(p => String(p)).join(''))
  18902. : (this.#toString =
  18903. this.type +
  18904. '(' +
  18905. this.#parts.map(p => String(p)).join('|') +
  18906. ')'));
  18907. }
  18908. #fillNegs() {
  18909. /* c8 ignore start */
  18910. if (this !== this.#root)
  18911. throw new Error('should only call on root');
  18912. if (this.#filledNegs)
  18913. return this;
  18914. /* c8 ignore stop */
  18915. // call toString() once to fill this out
  18916. this.toString();
  18917. this.#filledNegs = true;
  18918. let n;
  18919. while ((n = this.#negs.pop())) {
  18920. if (n.type !== '!')
  18921. continue;
  18922. // walk up the tree, appending everthing that comes AFTER parentIndex
  18923. let p = n;
  18924. let pp = p.#parent;
  18925. while (pp) {
  18926. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  18927. for (const part of n.#parts) {
  18928. /* c8 ignore start */
  18929. if (typeof part === 'string') {
  18930. throw new Error('string part in extglob AST??');
  18931. }
  18932. /* c8 ignore stop */
  18933. part.copyIn(pp.#parts[i]);
  18934. }
  18935. }
  18936. p = pp;
  18937. pp = p.#parent;
  18938. }
  18939. }
  18940. return this;
  18941. }
  18942. push(...parts) {
  18943. for (const p of parts) {
  18944. if (p === '')
  18945. continue;
  18946. /* c8 ignore start */
  18947. if (typeof p !== 'string' &&
  18948. !(p instanceof _a && p.#parent === this)) {
  18949. throw new Error('invalid part: ' + p);
  18950. }
  18951. /* c8 ignore stop */
  18952. this.#parts.push(p);
  18953. }
  18954. }
  18955. toJSON() {
  18956. const ret = this.type === null ?
  18957. this.#parts
  18958. .slice()
  18959. .map(p => (typeof p === 'string' ? p : p.toJSON()))
  18960. : [this.type, ...this.#parts.map(p => p.toJSON())];
  18961. if (this.isStart() && !this.type)
  18962. ret.unshift([]);
  18963. if (this.isEnd() &&
  18964. (this === this.#root ||
  18965. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  18966. ret.push({});
  18967. }
  18968. return ret;
  18969. }
  18970. isStart() {
  18971. if (this.#root === this)
  18972. return true;
  18973. // if (this.type) return !!this.#parent?.isStart()
  18974. if (!this.#parent?.isStart())
  18975. return false;
  18976. if (this.#parentIndex === 0)
  18977. return true;
  18978. // if everything AHEAD of this is a negation, then it's still the "start"
  18979. const p = this.#parent;
  18980. for (let i = 0; i < this.#parentIndex; i++) {
  18981. const pp = p.#parts[i];
  18982. if (!(pp instanceof _a && pp.type === '!')) {
  18983. return false;
  18984. }
  18985. }
  18986. return true;
  18987. }
  18988. isEnd() {
  18989. if (this.#root === this)
  18990. return true;
  18991. if (this.#parent?.type === '!')
  18992. return true;
  18993. if (!this.#parent?.isEnd())
  18994. return false;
  18995. if (!this.type)
  18996. return this.#parent?.isEnd();
  18997. // if not root, it'll always have a parent
  18998. /* c8 ignore start */
  18999. const pl = this.#parent ? this.#parent.#parts.length : 0;
  19000. /* c8 ignore stop */
  19001. return this.#parentIndex === pl - 1;
  19002. }
  19003. copyIn(part) {
  19004. if (typeof part === 'string')
  19005. this.push(part);
  19006. else
  19007. this.push(part.clone(this));
  19008. }
  19009. clone(parent) {
  19010. const c = new _a(this.type, parent);
  19011. for (const p of this.#parts) {
  19012. c.copyIn(p);
  19013. }
  19014. return c;
  19015. }
  19016. static #parseAST(str, ast, pos, opt, extDepth) {
  19017. const maxDepth = opt.maxExtglobRecursion ?? 2;
  19018. let escaping = false;
  19019. let inBrace = false;
  19020. let braceStart = -1;
  19021. let braceNeg = false;
  19022. if (ast.type === null) {
  19023. // outside of a extglob, append until we find a start
  19024. let i = pos;
  19025. let acc = '';
  19026. while (i < str.length) {
  19027. const c = str.charAt(i++);
  19028. // still accumulate escapes at this point, but we do ignore
  19029. // starts that are escaped
  19030. if (escaping || c === '\\') {
  19031. escaping = !escaping;
  19032. acc += c;
  19033. continue;
  19034. }
  19035. if (inBrace) {
  19036. if (i === braceStart + 1) {
  19037. if (c === '^' || c === '!') {
  19038. braceNeg = true;
  19039. }
  19040. }
  19041. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19042. inBrace = false;
  19043. }
  19044. acc += c;
  19045. continue;
  19046. }
  19047. else if (c === '[') {
  19048. inBrace = true;
  19049. braceStart = i;
  19050. braceNeg = false;
  19051. acc += c;
  19052. continue;
  19053. }
  19054. // we don't have to check for adoption here, because that's
  19055. // done at the other recursion point.
  19056. const doRecurse = !opt.noext &&
  19057. isExtglobType(c) &&
  19058. str.charAt(i) === '(' &&
  19059. extDepth <= maxDepth;
  19060. if (doRecurse) {
  19061. ast.push(acc);
  19062. acc = '';
  19063. const ext = new _a(c, ast);
  19064. i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
  19065. ast.push(ext);
  19066. continue;
  19067. }
  19068. acc += c;
  19069. }
  19070. ast.push(acc);
  19071. return i;
  19072. }
  19073. // some kind of extglob, pos is at the (
  19074. // find the next | or )
  19075. let i = pos + 1;
  19076. let part = new _a(null, ast);
  19077. const parts = [];
  19078. let acc = '';
  19079. while (i < str.length) {
  19080. const c = str.charAt(i++);
  19081. // still accumulate escapes at this point, but we do ignore
  19082. // starts that are escaped
  19083. if (escaping || c === '\\') {
  19084. escaping = !escaping;
  19085. acc += c;
  19086. continue;
  19087. }
  19088. if (inBrace) {
  19089. if (i === braceStart + 1) {
  19090. if (c === '^' || c === '!') {
  19091. braceNeg = true;
  19092. }
  19093. }
  19094. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19095. inBrace = false;
  19096. }
  19097. acc += c;
  19098. continue;
  19099. }
  19100. else if (c === '[') {
  19101. inBrace = true;
  19102. braceStart = i;
  19103. braceNeg = false;
  19104. acc += c;
  19105. continue;
  19106. }
  19107. const doRecurse = !opt.noext &&
  19108. isExtglobType(c) &&
  19109. str.charAt(i) === '(' &&
  19110. /* c8 ignore start - the maxDepth is sufficient here */
  19111. (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
  19112. /* c8 ignore stop */
  19113. if (doRecurse) {
  19114. const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
  19115. part.push(acc);
  19116. acc = '';
  19117. const ext = new _a(c, part);
  19118. part.push(ext);
  19119. i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
  19120. continue;
  19121. }
  19122. if (c === '|') {
  19123. part.push(acc);
  19124. acc = '';
  19125. parts.push(part);
  19126. part = new _a(null, ast);
  19127. continue;
  19128. }
  19129. if (c === ')') {
  19130. if (acc === '' && ast.#parts.length === 0) {
  19131. ast.#emptyExt = true;
  19132. }
  19133. part.push(acc);
  19134. acc = '';
  19135. ast.push(...parts, part);
  19136. return i;
  19137. }
  19138. acc += c;
  19139. }
  19140. // unfinished extglob
  19141. // if we got here, it was a malformed extglob! not an extglob, but
  19142. // maybe something else in there.
  19143. ast.type = null;
  19144. ast.#hasMagic = undefined;
  19145. ast.#parts = [str.substring(pos - 1)];
  19146. return i;
  19147. }
  19148. #canAdoptWithSpace(child) {
  19149. return this.#canAdopt(child, adoptionWithSpaceMap);
  19150. }
  19151. #canAdopt(child, map = adoptionMap) {
  19152. if (!child ||
  19153. typeof child !== 'object' ||
  19154. child.type !== null ||
  19155. child.#parts.length !== 1 ||
  19156. this.type === null) {
  19157. return false;
  19158. }
  19159. const gc = child.#parts[0];
  19160. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19161. return false;
  19162. }
  19163. return this.#canAdoptType(gc.type, map);
  19164. }
  19165. #canAdoptType(c, map = adoptionAnyMap) {
  19166. return !!map.get(this.type)?.includes(c);
  19167. }
  19168. #adoptWithSpace(child, index) {
  19169. const gc = child.#parts[0];
  19170. const blank = new _a(null, gc, this.options);
  19171. blank.#parts.push('');
  19172. gc.push(blank);
  19173. this.#adopt(child, index);
  19174. }
  19175. #adopt(child, index) {
  19176. const gc = child.#parts[0];
  19177. this.#parts.splice(index, 1, ...gc.#parts);
  19178. for (const p of gc.#parts) {
  19179. if (typeof p === 'object')
  19180. p.#parent = this;
  19181. }
  19182. this.#toString = undefined;
  19183. }
  19184. #canUsurpType(c) {
  19185. const m = usurpMap.get(this.type);
  19186. return !!m?.has(c);
  19187. }
  19188. #canUsurp(child) {
  19189. if (!child ||
  19190. typeof child !== 'object' ||
  19191. child.type !== null ||
  19192. child.#parts.length !== 1 ||
  19193. this.type === null ||
  19194. this.#parts.length !== 1) {
  19195. return false;
  19196. }
  19197. const gc = child.#parts[0];
  19198. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19199. return false;
  19200. }
  19201. return this.#canUsurpType(gc.type);
  19202. }
  19203. #usurp(child) {
  19204. const m = usurpMap.get(this.type);
  19205. const gc = child.#parts[0];
  19206. const nt = m?.get(gc.type);
  19207. /* c8 ignore start - impossible */
  19208. if (!nt)
  19209. return false;
  19210. /* c8 ignore stop */
  19211. this.#parts = gc.#parts;
  19212. for (const p of this.#parts) {
  19213. if (typeof p === 'object') {
  19214. p.#parent = this;
  19215. }
  19216. }
  19217. this.type = nt;
  19218. this.#toString = undefined;
  19219. this.#emptyExt = false;
  19220. }
  19221. static fromGlob(pattern, options = {}) {
  19222. const ast = new _a(null, undefined, options);
  19223. _a.#parseAST(pattern, ast, 0, options, 0);
  19224. return ast;
  19225. }
  19226. // returns the regular expression if there's magic, or the unescaped
  19227. // string if not.
  19228. toMMPattern() {
  19229. // should only be called on root
  19230. /* c8 ignore start */
  19231. if (this !== this.#root)
  19232. return this.#root.toMMPattern();
  19233. /* c8 ignore stop */
  19234. const glob = this.toString();
  19235. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  19236. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  19237. // still need a regular expression if we have to case-insensitively
  19238. // match capital/lowercase characters.
  19239. const anyMagic = hasMagic ||
  19240. this.#hasMagic ||
  19241. (this.#options.nocase &&
  19242. !this.#options.nocaseMagicOnly &&
  19243. glob.toUpperCase() !== glob.toLowerCase());
  19244. if (!anyMagic) {
  19245. return body;
  19246. }
  19247. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  19248. return Object.assign(new RegExp(`^${re}$`, flags), {
  19249. _src: re,
  19250. _glob: glob,
  19251. });
  19252. }
  19253. get options() {
  19254. return this.#options;
  19255. }
  19256. // returns the string match, the regexp source, whether there's magic
  19257. // in the regexp (so a regular expression is required) and whether or
  19258. // not the uflag is needed for the regular expression (for posix classes)
  19259. // TODO: instead of injecting the start/end at this point, just return
  19260. // the BODY of the regexp, along with the start/end portions suitable
  19261. // for binding the start/end in either a joined full-path makeRe context
  19262. // (where we bind to (^|/), or a standalone matchPart context (where
  19263. // we bind to ^, and not /). Otherwise slashes get duped!
  19264. //
  19265. // In part-matching mode, the start is:
  19266. // - if not isStart: nothing
  19267. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  19268. // - if dots allowed or not possible: ^
  19269. // - if dots possible and not allowed: ^(?!\.)
  19270. // end is:
  19271. // - if not isEnd(): nothing
  19272. // - else: $
  19273. //
  19274. // In full-path matching mode, we put the slash at the START of the
  19275. // pattern, so start is:
  19276. // - if first pattern: same as part-matching mode
  19277. // - if not isStart(): nothing
  19278. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  19279. // - if dots allowed or not possible: /
  19280. // - if dots possible and not allowed: /(?!\.)
  19281. // end is:
  19282. // - if last pattern, same as part-matching mode
  19283. // - else nothing
  19284. //
  19285. // Always put the (?:$|/) on negated tails, though, because that has to be
  19286. // there to bind the end of the negated pattern portion, and it's easier to
  19287. // just stick it in now rather than try to inject it later in the middle of
  19288. // the pattern.
  19289. //
  19290. // We can just always return the same end, and leave it up to the caller
  19291. // to know whether it's going to be used joined or in parts.
  19292. // And, if the start is adjusted slightly, can do the same there:
  19293. // - if not isStart: nothing
  19294. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  19295. // - if dots allowed or not possible: (?:/|^)
  19296. // - if dots possible and not allowed: (?:/|^)(?!\.)
  19297. //
  19298. // But it's better to have a simpler binding without a conditional, for
  19299. // performance, so probably better to return both start options.
  19300. //
  19301. // Then the caller just ignores the end if it's not the first pattern,
  19302. // and the start always gets applied.
  19303. //
  19304. // But that's always going to be $ if it's the ending pattern, or nothing,
  19305. // so the caller can just attach $ at the end of the pattern when building.
  19306. //
  19307. // So the todo is:
  19308. // - better detect what kind of start is needed
  19309. // - return both flavors of starting pattern
  19310. // - attach $ at the end of the pattern when creating the actual RegExp
  19311. //
  19312. // Ah, but wait, no, that all only applies to the root when the first pattern
  19313. // is not an extglob. If the first pattern IS an extglob, then we need all
  19314. // that dot prevention biz to live in the extglob portions, because eg
  19315. // +(*|.x*) can match .xy but not .yx.
  19316. //
  19317. // So, return the two flavors if it's #root and the first child is not an
  19318. // AST, otherwise leave it to the child AST to handle it, and there,
  19319. // use the (?:^|/) style of start binding.
  19320. //
  19321. // Even simplified further:
  19322. // - Since the start for a join is eg /(?!\.) and the start for a part
  19323. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  19324. // or start or whatever) and prepend ^ or / at the Regexp construction.
  19325. toRegExpSource(allowDot) {
  19326. const dot = allowDot ?? !!this.#options.dot;
  19327. if (this.#root === this) {
  19328. this.#flatten();
  19329. this.#fillNegs();
  19330. }
  19331. if (!isExtglobAST(this)) {
  19332. const noEmpty = this.isStart() &&
  19333. this.isEnd() &&
  19334. !this.#parts.some(s => typeof s !== 'string');
  19335. const src = this.#parts
  19336. .map(p => {
  19337. const [re, _, hasMagic, uflag] = typeof p === 'string' ?
  19338. _a.#parseGlob(p, this.#hasMagic, noEmpty)
  19339. : p.toRegExpSource(allowDot);
  19340. this.#hasMagic = this.#hasMagic || hasMagic;
  19341. this.#uflag = this.#uflag || uflag;
  19342. return re;
  19343. })
  19344. .join('');
  19345. let start = '';
  19346. if (this.isStart()) {
  19347. if (typeof this.#parts[0] === 'string') {
  19348. // this is the string that will match the start of the pattern,
  19349. // so we need to protect against dots and such.
  19350. // '.' and '..' cannot match unless the pattern is that exactly,
  19351. // even if it starts with . or dot:true is set.
  19352. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  19353. if (!dotTravAllowed) {
  19354. const aps = addPatternStart;
  19355. // check if we have a possibility of matching . or ..,
  19356. // and prevent that.
  19357. const needNoTrav =
  19358. // dots are allowed, and the pattern starts with [ or .
  19359. (dot && aps.has(src.charAt(0))) ||
  19360. // the pattern starts with \., and then [ or .
  19361. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  19362. // the pattern starts with \.\., and then [ or .
  19363. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  19364. // no need to prevent dots if it can't match a dot, or if a
  19365. // sub-pattern will be preventing it anyway.
  19366. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  19367. start =
  19368. needNoTrav ? startNoTraversal
  19369. : needNoDot ? startNoDot
  19370. : '';
  19371. }
  19372. }
  19373. }
  19374. // append the "end of path portion" pattern to negation tails
  19375. let end = '';
  19376. if (this.isEnd() &&
  19377. this.#root.#filledNegs &&
  19378. this.#parent?.type === '!') {
  19379. end = '(?:$|\\/)';
  19380. }
  19381. const final = start + src + end;
  19382. return [
  19383. final,
  19384. unescape(src),
  19385. (this.#hasMagic = !!this.#hasMagic),
  19386. this.#uflag,
  19387. ];
  19388. }
  19389. // We need to calculate the body *twice* if it's a repeat pattern
  19390. // at the start, once in nodot mode, then again in dot mode, so a
  19391. // pattern like *(?) can match 'x.y'
  19392. const repeated = this.type === '*' || this.type === '+';
  19393. // some kind of extglob
  19394. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  19395. let body = this.#partsToRegExp(dot);
  19396. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19397. // invalid extglob, has to at least be *something* present, if it's
  19398. // the entire path portion.
  19399. const s = this.toString();
  19400. const me = this;
  19401. me.#parts = [s];
  19402. me.type = null;
  19403. me.#hasMagic = undefined;
  19404. return [s, unescape(this.toString()), false, false];
  19405. }
  19406. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
  19407. ''
  19408. : this.#partsToRegExp(true);
  19409. if (bodyDotAllowed === body) {
  19410. bodyDotAllowed = '';
  19411. }
  19412. if (bodyDotAllowed) {
  19413. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19414. }
  19415. // an empty !() is exactly equivalent to a starNoEmpty
  19416. let final = '';
  19417. if (this.type === '!' && this.#emptyExt) {
  19418. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19419. }
  19420. else {
  19421. const close = this.type === '!' ?
  19422. // !() must match something,but !(x) can match ''
  19423. '))' +
  19424. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19425. star$1 +
  19426. ')'
  19427. : this.type === '@' ? ')'
  19428. : this.type === '?' ? ')?'
  19429. : this.type === '+' && bodyDotAllowed ? ')'
  19430. : this.type === '*' && bodyDotAllowed ? `)?`
  19431. : `)${this.type}`;
  19432. final = start + body + close;
  19433. }
  19434. return [
  19435. final,
  19436. unescape(body),
  19437. (this.#hasMagic = !!this.#hasMagic),
  19438. this.#uflag,
  19439. ];
  19440. }
  19441. #flatten() {
  19442. if (!isExtglobAST(this)) {
  19443. for (const p of this.#parts) {
  19444. if (typeof p === 'object') {
  19445. p.#flatten();
  19446. }
  19447. }
  19448. }
  19449. else {
  19450. // do up to 10 passes to flatten as much as possible
  19451. let iterations = 0;
  19452. let done = false;
  19453. do {
  19454. done = true;
  19455. for (let i = 0; i < this.#parts.length; i++) {
  19456. const c = this.#parts[i];
  19457. if (typeof c === 'object') {
  19458. c.#flatten();
  19459. if (this.#canAdopt(c)) {
  19460. done = false;
  19461. this.#adopt(c, i);
  19462. }
  19463. else if (this.#canAdoptWithSpace(c)) {
  19464. done = false;
  19465. this.#adoptWithSpace(c, i);
  19466. }
  19467. else if (this.#canUsurp(c)) {
  19468. done = false;
  19469. this.#usurp(c);
  19470. }
  19471. }
  19472. }
  19473. } while (!done && ++iterations < 10);
  19474. }
  19475. this.#toString = undefined;
  19476. }
  19477. #partsToRegExp(dot) {
  19478. return this.#parts
  19479. .map(p => {
  19480. // extglob ASTs should only contain parent ASTs
  19481. /* c8 ignore start */
  19482. if (typeof p === 'string') {
  19483. throw new Error('string type in extglob ast??');
  19484. }
  19485. /* c8 ignore stop */
  19486. // can ignore hasMagic, because extglobs are already always magic
  19487. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19488. this.#uflag = this.#uflag || uflag;
  19489. return re;
  19490. })
  19491. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19492. .join('|');
  19493. }
  19494. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19495. let escaping = false;
  19496. let re = '';
  19497. let uflag = false;
  19498. // multiple stars that aren't globstars coalesce into one *
  19499. let inStar = false;
  19500. for (let i = 0; i < glob.length; i++) {
  19501. const c = glob.charAt(i);
  19502. if (escaping) {
  19503. escaping = false;
  19504. re += (reSpecials.has(c) ? '\\' : '') + c;
  19505. continue;
  19506. }
  19507. if (c === '*') {
  19508. if (inStar)
  19509. continue;
  19510. inStar = true;
  19511. re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star$1;
  19512. hasMagic = true;
  19513. continue;
  19514. }
  19515. else {
  19516. inStar = false;
  19517. }
  19518. if (c === '\\') {
  19519. if (i === glob.length - 1) {
  19520. re += '\\\\';
  19521. }
  19522. else {
  19523. escaping = true;
  19524. }
  19525. continue;
  19526. }
  19527. if (c === '[') {
  19528. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  19529. if (consumed) {
  19530. re += src;
  19531. uflag = uflag || needUflag;
  19532. i += consumed - 1;
  19533. hasMagic = hasMagic || magic;
  19534. continue;
  19535. }
  19536. }
  19537. if (c === '?') {
  19538. re += qmark$1;
  19539. hasMagic = true;
  19540. continue;
  19541. }
  19542. re += regExpEscape$1(c);
  19543. }
  19544. return [re, unescape(glob), !!hasMagic, uflag];
  19545. }
  19546. }
  19547. _a = AST;
  19548. /**
  19549. * Escape all magic characters in a glob pattern.
  19550. *
  19551. * If the {@link MinimatchOptions.windowsPathsNoEscape}
  19552. * option is used, then characters are escaped by wrapping in `[]`, because
  19553. * a magic character wrapped in a character class can only be satisfied by
  19554. * that exact character. In this mode, `\` is _not_ escaped, because it is
  19555. * not interpreted as a magic character, but instead as a path separator.
  19556. *
  19557. * If the {@link MinimatchOptions.magicalBraces} option is used,
  19558. * then braces (`{` and `}`) will be escaped.
  19559. */
  19560. const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
  19561. // don't need to escape +@! because we escape the parens
  19562. // that make those magic, and escaping ! as [!] isn't valid,
  19563. // because [!]] is a valid glob class meaning not ']'.
  19564. if (magicalBraces) {
  19565. return windowsPathsNoEscape ?
  19566. s.replace(/[?*()[\]{}]/g, '[$&]')
  19567. : s.replace(/[?*()[\]\\{}]/g, '\\$&');
  19568. }
  19569. return windowsPathsNoEscape ?
  19570. s.replace(/[?*()[\]]/g, '[$&]')
  19571. : s.replace(/[?*()[\]\\]/g, '\\$&');
  19572. };
  19573. const minimatch = (p, pattern, options = {}) => {
  19574. assertValidPattern(pattern);
  19575. // shortcut: comments match nothing.
  19576. if (!options.nocomment && pattern.charAt(0) === '#') {
  19577. return false;
  19578. }
  19579. return new Minimatch(pattern, options).match(p);
  19580. };
  19581. // Optimized checking for the most common glob patterns.
  19582. const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
  19583. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  19584. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  19585. const starDotExtTestNocase = (ext) => {
  19586. ext = ext.toLowerCase();
  19587. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  19588. };
  19589. const starDotExtTestNocaseDot = (ext) => {
  19590. ext = ext.toLowerCase();
  19591. return (f) => f.toLowerCase().endsWith(ext);
  19592. };
  19593. const starDotStarRE = /^\*+\.\*+$/;
  19594. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  19595. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  19596. const dotStarRE = /^\.\*+$/;
  19597. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  19598. const starRE = /^\*+$/;
  19599. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  19600. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  19601. const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
  19602. const qmarksTestNocase = ([$0, ext = '']) => {
  19603. const noext = qmarksTestNoExt([$0]);
  19604. if (!ext)
  19605. return noext;
  19606. ext = ext.toLowerCase();
  19607. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19608. };
  19609. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  19610. const noext = qmarksTestNoExtDot([$0]);
  19611. if (!ext)
  19612. return noext;
  19613. ext = ext.toLowerCase();
  19614. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19615. };
  19616. const qmarksTestDot = ([$0, ext = '']) => {
  19617. const noext = qmarksTestNoExtDot([$0]);
  19618. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19619. };
  19620. const qmarksTest = ([$0, ext = '']) => {
  19621. const noext = qmarksTestNoExt([$0]);
  19622. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19623. };
  19624. const qmarksTestNoExt = ([$0]) => {
  19625. const len = $0.length;
  19626. return (f) => f.length === len && !f.startsWith('.');
  19627. };
  19628. const qmarksTestNoExtDot = ([$0]) => {
  19629. const len = $0.length;
  19630. return (f) => f.length === len && f !== '.' && f !== '..';
  19631. };
  19632. /* c8 ignore start */
  19633. const defaultPlatform = (typeof process === 'object' && process ?
  19634. (typeof process.env === 'object' &&
  19635. process.env &&
  19636. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  19637. process.platform
  19638. : 'posix');
  19639. const path = {
  19640. win32: { sep: '\\' },
  19641. posix: { sep: '/' },
  19642. };
  19643. /* c8 ignore stop */
  19644. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  19645. minimatch.sep = sep;
  19646. const GLOBSTAR = Symbol('globstar **');
  19647. minimatch.GLOBSTAR = GLOBSTAR;
  19648. // any single thing other than /
  19649. // don't need to escape / when using new RegExp()
  19650. const qmark = '[^/]';
  19651. // * => any number of characters
  19652. const star = qmark + '*?';
  19653. // ** when dots are allowed. Anything goes, except .. and .
  19654. // not (^ or / followed by one or two dots followed by $ or /),
  19655. // followed by anything, any number of times.
  19656. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  19657. // not a ^ or / followed by a dot,
  19658. // followed by anything, any number of times.
  19659. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  19660. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  19661. minimatch.filter = filter;
  19662. const ext = (a, b = {}) => Object.assign({}, a, b);
  19663. const defaults = (def) => {
  19664. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  19665. return minimatch;
  19666. }
  19667. const orig = minimatch;
  19668. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  19669. return Object.assign(m, {
  19670. Minimatch: class Minimatch extends orig.Minimatch {
  19671. constructor(pattern, options = {}) {
  19672. super(pattern, ext(def, options));
  19673. }
  19674. static defaults(options) {
  19675. return orig.defaults(ext(def, options)).Minimatch;
  19676. }
  19677. },
  19678. AST: class AST extends orig.AST {
  19679. /* c8 ignore start */
  19680. constructor(type, parent, options = {}) {
  19681. super(type, parent, ext(def, options));
  19682. }
  19683. /* c8 ignore stop */
  19684. static fromGlob(pattern, options = {}) {
  19685. return orig.AST.fromGlob(pattern, ext(def, options));
  19686. }
  19687. },
  19688. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  19689. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  19690. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  19691. defaults: (options) => orig.defaults(ext(def, options)),
  19692. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  19693. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  19694. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  19695. sep: orig.sep,
  19696. GLOBSTAR: GLOBSTAR,
  19697. });
  19698. };
  19699. minimatch.defaults = defaults;
  19700. // Brace expansion:
  19701. // a{b,c}d -> abd acd
  19702. // a{b,}c -> abc ac
  19703. // a{0..3}d -> a0d a1d a2d a3d
  19704. // a{b,c{d,e}f}g -> abg acdfg acefg
  19705. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19706. //
  19707. // Invalid sets are not expanded.
  19708. // a{2..}b -> a{2..}b
  19709. // a{b}c -> a{b}c
  19710. const braceExpand = (pattern, options = {}) => {
  19711. assertValidPattern(pattern);
  19712. // Thanks to Yeting Li <https://github.com/yetingli> for
  19713. // improving this regexp to avoid a ReDOS vulnerability.
  19714. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  19715. // shortcut. no need to expand.
  19716. return [pattern];
  19717. }
  19718. return expand(pattern, { max: options.braceExpandMax });
  19719. };
  19720. minimatch.braceExpand = braceExpand;
  19721. // parse a component of the expanded set.
  19722. // At this point, no pattern may contain "/" in it
  19723. // so we're going to return a 2d array, where each entry is the full
  19724. // pattern, split on '/', and then turned into a regular expression.
  19725. // A regexp is made at the end which joins each array with an
  19726. // escaped /, and another full one which joins each regexp with |.
  19727. //
  19728. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19729. // when it is the *only* thing in a path portion. Otherwise, any series
  19730. // of * is equivalent to a single *. Globstar behavior is enabled by
  19731. // default, and can be disabled by setting options.noglobstar.
  19732. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  19733. minimatch.makeRe = makeRe;
  19734. const match = (list, pattern, options = {}) => {
  19735. const mm = new Minimatch(pattern, options);
  19736. list = list.filter(f => mm.match(f));
  19737. if (mm.options.nonull && !list.length) {
  19738. list.push(pattern);
  19739. }
  19740. return list;
  19741. };
  19742. minimatch.match = match;
  19743. // replace stuff like \* with *
  19744. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  19745. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19746. class Minimatch {
  19747. options;
  19748. set;
  19749. pattern;
  19750. windowsPathsNoEscape;
  19751. nonegate;
  19752. negate;
  19753. comment;
  19754. empty;
  19755. preserveMultipleSlashes;
  19756. partial;
  19757. globSet;
  19758. globParts;
  19759. nocase;
  19760. isWindows;
  19761. platform;
  19762. windowsNoMagicRoot;
  19763. maxGlobstarRecursion;
  19764. regexp;
  19765. constructor(pattern, options = {}) {
  19766. assertValidPattern(pattern);
  19767. options = options || {};
  19768. this.options = options;
  19769. this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
  19770. this.pattern = pattern;
  19771. this.platform = options.platform || defaultPlatform;
  19772. this.isWindows = this.platform === 'win32';
  19773. // avoid the annoying deprecation flag lol
  19774. const awe = ('allowWindow' + 'sEscape');
  19775. this.windowsPathsNoEscape =
  19776. !!options.windowsPathsNoEscape || options[awe] === false;
  19777. if (this.windowsPathsNoEscape) {
  19778. this.pattern = this.pattern.replace(/\\/g, '/');
  19779. }
  19780. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  19781. this.regexp = null;
  19782. this.negate = false;
  19783. this.nonegate = !!options.nonegate;
  19784. this.comment = false;
  19785. this.empty = false;
  19786. this.partial = !!options.partial;
  19787. this.nocase = !!this.options.nocase;
  19788. this.windowsNoMagicRoot =
  19789. options.windowsNoMagicRoot !== undefined ?
  19790. options.windowsNoMagicRoot
  19791. : !!(this.isWindows && this.nocase);
  19792. this.globSet = [];
  19793. this.globParts = [];
  19794. this.set = [];
  19795. // make the set of regexps etc.
  19796. this.make();
  19797. }
  19798. hasMagic() {
  19799. if (this.options.magicalBraces && this.set.length > 1) {
  19800. return true;
  19801. }
  19802. for (const pattern of this.set) {
  19803. for (const part of pattern) {
  19804. if (typeof part !== 'string')
  19805. return true;
  19806. }
  19807. }
  19808. return false;
  19809. }
  19810. debug(..._) { }
  19811. make() {
  19812. const pattern = this.pattern;
  19813. const options = this.options;
  19814. // empty patterns and comments match nothing.
  19815. if (!options.nocomment && pattern.charAt(0) === '#') {
  19816. this.comment = true;
  19817. return;
  19818. }
  19819. if (!pattern) {
  19820. this.empty = true;
  19821. return;
  19822. }
  19823. // step 1: figure out negation, etc.
  19824. this.parseNegate();
  19825. // step 2: expand braces
  19826. this.globSet = [...new Set(this.braceExpand())];
  19827. if (options.debug) {
  19828. //oxlint-disable-next-line no-console
  19829. this.debug = (...args) => console.error(...args);
  19830. }
  19831. this.debug(this.pattern, this.globSet);
  19832. // step 3: now we have a set, so turn each one into a series of
  19833. // path-portion matching patterns.
  19834. // These will be regexps, except in the case of "**", which is
  19835. // set to the GLOBSTAR object for globstar behavior,
  19836. // and will not contain any / characters
  19837. //
  19838. // First, we preprocess to make the glob pattern sets a bit simpler
  19839. // and deduped. There are some perf-killing patterns that can cause
  19840. // problems with a glob walk, but we can simplify them down a bit.
  19841. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  19842. this.globParts = this.preprocess(rawGlobParts);
  19843. this.debug(this.pattern, this.globParts);
  19844. // glob --> regexps
  19845. let set = this.globParts.map((s, _, __) => {
  19846. if (this.isWindows && this.windowsNoMagicRoot) {
  19847. // check if it's a drive or unc path.
  19848. const isUNC = s[0] === '' &&
  19849. s[1] === '' &&
  19850. (s[2] === '?' || !globMagic.test(s[2])) &&
  19851. !globMagic.test(s[3]);
  19852. const isDrive = /^[a-z]:/i.test(s[0]);
  19853. if (isUNC) {
  19854. return [
  19855. ...s.slice(0, 4),
  19856. ...s.slice(4).map(ss => this.parse(ss)),
  19857. ];
  19858. }
  19859. else if (isDrive) {
  19860. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  19861. }
  19862. }
  19863. return s.map(ss => this.parse(ss));
  19864. });
  19865. this.debug(this.pattern, set);
  19866. // filter out everything that didn't compile properly.
  19867. this.set = set.filter(s => s.indexOf(false) === -1);
  19868. // do not treat the ? in UNC paths as magic
  19869. if (this.isWindows) {
  19870. for (let i = 0; i < this.set.length; i++) {
  19871. const p = this.set[i];
  19872. if (p[0] === '' &&
  19873. p[1] === '' &&
  19874. this.globParts[i][2] === '?' &&
  19875. typeof p[3] === 'string' &&
  19876. /^[a-z]:$/i.test(p[3])) {
  19877. p[2] = '?';
  19878. }
  19879. }
  19880. }
  19881. this.debug(this.pattern, this.set);
  19882. }
  19883. // various transforms to equivalent pattern sets that are
  19884. // faster to process in a filesystem walk. The goal is to
  19885. // eliminate what we can, and push all ** patterns as far
  19886. // to the right as possible, even if it increases the number
  19887. // of patterns that we have to process.
  19888. preprocess(globParts) {
  19889. // if we're not in globstar mode, then turn ** into *
  19890. if (this.options.noglobstar) {
  19891. for (const partset of globParts) {
  19892. for (let j = 0; j < partset.length; j++) {
  19893. if (partset[j] === '**') {
  19894. partset[j] = '*';
  19895. }
  19896. }
  19897. }
  19898. }
  19899. const { optimizationLevel = 1 } = this.options;
  19900. if (optimizationLevel >= 2) {
  19901. // aggressive optimization for the purpose of fs walking
  19902. globParts = this.firstPhasePreProcess(globParts);
  19903. globParts = this.secondPhasePreProcess(globParts);
  19904. }
  19905. else if (optimizationLevel >= 1) {
  19906. // just basic optimizations to remove some .. parts
  19907. globParts = this.levelOneOptimize(globParts);
  19908. }
  19909. else {
  19910. // just collapse multiple ** portions into one
  19911. globParts = this.adjascentGlobstarOptimize(globParts);
  19912. }
  19913. return globParts;
  19914. }
  19915. // just get rid of adjascent ** portions
  19916. adjascentGlobstarOptimize(globParts) {
  19917. return globParts.map(parts => {
  19918. let gs = -1;
  19919. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19920. let i = gs;
  19921. while (parts[i + 1] === '**') {
  19922. i++;
  19923. }
  19924. if (i !== gs) {
  19925. parts.splice(gs, i - gs);
  19926. }
  19927. }
  19928. return parts;
  19929. });
  19930. }
  19931. // get rid of adjascent ** and resolve .. portions
  19932. levelOneOptimize(globParts) {
  19933. return globParts.map(parts => {
  19934. parts = parts.reduce((set, part) => {
  19935. const prev = set[set.length - 1];
  19936. if (part === '**' && prev === '**') {
  19937. return set;
  19938. }
  19939. if (part === '..') {
  19940. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  19941. set.pop();
  19942. return set;
  19943. }
  19944. }
  19945. set.push(part);
  19946. return set;
  19947. }, []);
  19948. return parts.length === 0 ? [''] : parts;
  19949. });
  19950. }
  19951. levelTwoFileOptimize(parts) {
  19952. if (!Array.isArray(parts)) {
  19953. parts = this.slashSplit(parts);
  19954. }
  19955. let didSomething = false;
  19956. do {
  19957. didSomething = false;
  19958. // <pre>/<e>/<rest> -> <pre>/<rest>
  19959. if (!this.preserveMultipleSlashes) {
  19960. for (let i = 1; i < parts.length - 1; i++) {
  19961. const p = parts[i];
  19962. // don't squeeze out UNC patterns
  19963. if (i === 1 && p === '' && parts[0] === '')
  19964. continue;
  19965. if (p === '.' || p === '') {
  19966. didSomething = true;
  19967. parts.splice(i, 1);
  19968. i--;
  19969. }
  19970. }
  19971. if (parts[0] === '.' &&
  19972. parts.length === 2 &&
  19973. (parts[1] === '.' || parts[1] === '')) {
  19974. didSomething = true;
  19975. parts.pop();
  19976. }
  19977. }
  19978. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19979. let dd = 0;
  19980. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19981. const p = parts[dd - 1];
  19982. if (p &&
  19983. p !== '.' &&
  19984. p !== '..' &&
  19985. p !== '**' &&
  19986. !(this.isWindows && /^[a-z]:$/i.test(p))) {
  19987. didSomething = true;
  19988. parts.splice(dd - 1, 2);
  19989. dd -= 2;
  19990. }
  19991. }
  19992. } while (didSomething);
  19993. return parts.length === 0 ? [''] : parts;
  19994. }
  19995. // First phase: single-pattern processing
  19996. // <pre> is 1 or more portions
  19997. // <rest> is 1 or more portions
  19998. // <p> is any portion other than ., .., '', or **
  19999. // <e> is . or ''
  20000. //
  20001. // **/.. is *brutal* for filesystem walking performance, because
  20002. // it effectively resets the recursive walk each time it occurs,
  20003. // and ** cannot be reduced out by a .. pattern part like a regexp
  20004. // or most strings (other than .., ., and '') can be.
  20005. //
  20006. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  20007. // <pre>/<e>/<rest> -> <pre>/<rest>
  20008. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20009. // **/**/<rest> -> **/<rest>
  20010. //
  20011. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  20012. // this WOULD be allowed if ** did follow symlinks, or * didn't
  20013. firstPhasePreProcess(globParts) {
  20014. let didSomething = false;
  20015. do {
  20016. didSomething = false;
  20017. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  20018. for (let parts of globParts) {
  20019. let gs = -1;
  20020. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  20021. let gss = gs;
  20022. while (parts[gss + 1] === '**') {
  20023. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  20024. gss++;
  20025. }
  20026. // eg, if gs is 2 and gss is 4, that means we have 3 **
  20027. // parts, and can remove 2 of them.
  20028. if (gss > gs) {
  20029. parts.splice(gs + 1, gss - gs);
  20030. }
  20031. let next = parts[gs + 1];
  20032. const p = parts[gs + 2];
  20033. const p2 = parts[gs + 3];
  20034. if (next !== '..')
  20035. continue;
  20036. if (!p ||
  20037. p === '.' ||
  20038. p === '..' ||
  20039. !p2 ||
  20040. p2 === '.' ||
  20041. p2 === '..') {
  20042. continue;
  20043. }
  20044. didSomething = true;
  20045. // edit parts in place, and push the new one
  20046. parts.splice(gs, 1);
  20047. const other = parts.slice(0);
  20048. other[gs] = '**';
  20049. globParts.push(other);
  20050. gs--;
  20051. }
  20052. // <pre>/<e>/<rest> -> <pre>/<rest>
  20053. if (!this.preserveMultipleSlashes) {
  20054. for (let i = 1; i < parts.length - 1; i++) {
  20055. const p = parts[i];
  20056. // don't squeeze out UNC patterns
  20057. if (i === 1 && p === '' && parts[0] === '')
  20058. continue;
  20059. if (p === '.' || p === '') {
  20060. didSomething = true;
  20061. parts.splice(i, 1);
  20062. i--;
  20063. }
  20064. }
  20065. if (parts[0] === '.' &&
  20066. parts.length === 2 &&
  20067. (parts[1] === '.' || parts[1] === '')) {
  20068. didSomething = true;
  20069. parts.pop();
  20070. }
  20071. }
  20072. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20073. let dd = 0;
  20074. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  20075. const p = parts[dd - 1];
  20076. if (p && p !== '.' && p !== '..' && p !== '**') {
  20077. didSomething = true;
  20078. const needDot = dd === 1 && parts[dd + 1] === '**';
  20079. const splin = needDot ? ['.'] : [];
  20080. parts.splice(dd - 1, 2, ...splin);
  20081. if (parts.length === 0)
  20082. parts.push('');
  20083. dd -= 2;
  20084. }
  20085. }
  20086. }
  20087. } while (didSomething);
  20088. return globParts;
  20089. }
  20090. // second phase: multi-pattern dedupes
  20091. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  20092. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  20093. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  20094. //
  20095. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  20096. // ^-- not valid because ** doens't follow symlinks
  20097. secondPhasePreProcess(globParts) {
  20098. for (let i = 0; i < globParts.length - 1; i++) {
  20099. for (let j = i + 1; j < globParts.length; j++) {
  20100. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  20101. if (matched) {
  20102. globParts[i] = [];
  20103. globParts[j] = matched;
  20104. break;
  20105. }
  20106. }
  20107. }
  20108. return globParts.filter(gs => gs.length);
  20109. }
  20110. partsMatch(a, b, emptyGSMatch = false) {
  20111. let ai = 0;
  20112. let bi = 0;
  20113. let result = [];
  20114. let which = '';
  20115. while (ai < a.length && bi < b.length) {
  20116. if (a[ai] === b[bi]) {
  20117. result.push(which === 'b' ? b[bi] : a[ai]);
  20118. ai++;
  20119. bi++;
  20120. }
  20121. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  20122. result.push(a[ai]);
  20123. ai++;
  20124. }
  20125. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  20126. result.push(b[bi]);
  20127. bi++;
  20128. }
  20129. else if (a[ai] === '*' &&
  20130. b[bi] &&
  20131. (this.options.dot || !b[bi].startsWith('.')) &&
  20132. b[bi] !== '**') {
  20133. if (which === 'b')
  20134. return false;
  20135. which = 'a';
  20136. result.push(a[ai]);
  20137. ai++;
  20138. bi++;
  20139. }
  20140. else if (b[bi] === '*' &&
  20141. a[ai] &&
  20142. (this.options.dot || !a[ai].startsWith('.')) &&
  20143. a[ai] !== '**') {
  20144. if (which === 'a')
  20145. return false;
  20146. which = 'b';
  20147. result.push(b[bi]);
  20148. ai++;
  20149. bi++;
  20150. }
  20151. else {
  20152. return false;
  20153. }
  20154. }
  20155. // if we fall out of the loop, it means they two are identical
  20156. // as long as their lengths match
  20157. return a.length === b.length && result;
  20158. }
  20159. parseNegate() {
  20160. if (this.nonegate)
  20161. return;
  20162. const pattern = this.pattern;
  20163. let negate = false;
  20164. let negateOffset = 0;
  20165. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  20166. negate = !negate;
  20167. negateOffset++;
  20168. }
  20169. if (negateOffset)
  20170. this.pattern = pattern.slice(negateOffset);
  20171. this.negate = negate;
  20172. }
  20173. // set partial to true to test if, for example,
  20174. // "/a/b" matches the start of "/*/b/*/d"
  20175. // Partial means, if you run out of file before you run
  20176. // out of pattern, then that's fine, as long as all
  20177. // the parts match.
  20178. matchOne(file, pattern, partial = false) {
  20179. let fileStartIndex = 0;
  20180. let patternStartIndex = 0;
  20181. // UNC paths like //?/X:/... can match X:/... and vice versa
  20182. // Drive letters in absolute drive or unc paths are always compared
  20183. // case-insensitively.
  20184. if (this.isWindows) {
  20185. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  20186. const fileUNC = !fileDrive &&
  20187. file[0] === '' &&
  20188. file[1] === '' &&
  20189. file[2] === '?' &&
  20190. /^[a-z]:$/i.test(file[3]);
  20191. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  20192. const patternUNC = !patternDrive &&
  20193. pattern[0] === '' &&
  20194. pattern[1] === '' &&
  20195. pattern[2] === '?' &&
  20196. typeof pattern[3] === 'string' &&
  20197. /^[a-z]:$/i.test(pattern[3]);
  20198. const fdi = fileUNC ? 3
  20199. : fileDrive ? 0
  20200. : undefined;
  20201. const pdi = patternUNC ? 3
  20202. : patternDrive ? 0
  20203. : undefined;
  20204. if (typeof fdi === 'number' && typeof pdi === 'number') {
  20205. const [fd, pd] = [
  20206. file[fdi],
  20207. pattern[pdi],
  20208. ];
  20209. // start matching at the drive letter index of each
  20210. if (fd.toLowerCase() === pd.toLowerCase()) {
  20211. pattern[pdi] = fd;
  20212. patternStartIndex = pdi;
  20213. fileStartIndex = fdi;
  20214. }
  20215. }
  20216. }
  20217. // resolve and reduce . and .. portions in the file as well.
  20218. // don't need to do the second phase, because it's only one string[]
  20219. const { optimizationLevel = 1 } = this.options;
  20220. if (optimizationLevel >= 2) {
  20221. file = this.levelTwoFileOptimize(file);
  20222. }
  20223. if (pattern.includes(GLOBSTAR)) {
  20224. return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
  20225. }
  20226. return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
  20227. }
  20228. #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
  20229. // split the pattern into head, tail, and middle of ** delimited parts
  20230. const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
  20231. const lastgs = pattern.lastIndexOf(GLOBSTAR);
  20232. // split the pattern up into globstar-delimited sections
  20233. // the tail has to be at the end, and the others just have
  20234. // to be found in order from the head.
  20235. const [head, body, tail] = partial ?
  20236. [
  20237. pattern.slice(patternIndex, firstgs),
  20238. pattern.slice(firstgs + 1),
  20239. [],
  20240. ]
  20241. : [
  20242. pattern.slice(patternIndex, firstgs),
  20243. pattern.slice(firstgs + 1, lastgs),
  20244. pattern.slice(lastgs + 1),
  20245. ];
  20246. // check the head, from the current file/pattern index.
  20247. if (head.length) {
  20248. const fileHead = file.slice(fileIndex, fileIndex + head.length);
  20249. if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
  20250. return false;
  20251. }
  20252. fileIndex += head.length;
  20253. patternIndex += head.length;
  20254. }
  20255. // now we know the head matches!
  20256. // if the last portion is not empty, it MUST match the end
  20257. // check the tail
  20258. let fileTailMatch = 0;
  20259. if (tail.length) {
  20260. // if head + tail > file, then we cannot possibly match
  20261. if (tail.length + fileIndex > file.length)
  20262. return false;
  20263. // try to match the tail
  20264. let tailStart = file.length - tail.length;
  20265. if (this.#matchOne(file, tail, partial, tailStart, 0)) {
  20266. fileTailMatch = tail.length;
  20267. }
  20268. else {
  20269. // affordance for stuff like a/**/* matching a/b/
  20270. // if the last file portion is '', and there's more to the pattern
  20271. // then try without the '' bit.
  20272. if (file[file.length - 1] !== '' ||
  20273. fileIndex + tail.length === file.length) {
  20274. return false;
  20275. }
  20276. tailStart--;
  20277. if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
  20278. return false;
  20279. }
  20280. fileTailMatch = tail.length + 1;
  20281. }
  20282. }
  20283. // now we know the tail matches!
  20284. // the middle is zero or more portions wrapped in **, possibly
  20285. // containing more ** sections.
  20286. // so a/**/b/**/c/**/d has become **/b/**/c/**
  20287. // if it's empty, it means a/**/b, just verify we have no bad dots
  20288. // if there's no tail, so it ends on /**, then we must have *something*
  20289. // after the head, or it's not a matc
  20290. if (!body.length) {
  20291. let sawSome = !!fileTailMatch;
  20292. for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
  20293. const f = String(file[i]);
  20294. sawSome = true;
  20295. if (f === '.' ||
  20296. f === '..' ||
  20297. (!this.options.dot && f.startsWith('.'))) {
  20298. return false;
  20299. }
  20300. }
  20301. // in partial mode, we just need to get past all file parts
  20302. return partial || sawSome;
  20303. }
  20304. // now we know that there's one or more body sections, which can
  20305. // be matched anywhere from the 0 index (because the head was pruned)
  20306. // through to the length-fileTailMatch index.
  20307. // split the body up into sections, and note the minimum index it can
  20308. // be found at (start with the length of all previous segments)
  20309. // [section, before, after]
  20310. const bodySegments = [[[], 0]];
  20311. let currentBody = bodySegments[0];
  20312. let nonGsParts = 0;
  20313. const nonGsPartsSums = [0];
  20314. for (const b of body) {
  20315. if (b === GLOBSTAR) {
  20316. nonGsPartsSums.push(nonGsParts);
  20317. currentBody = [[], 0];
  20318. bodySegments.push(currentBody);
  20319. }
  20320. else {
  20321. currentBody[0].push(b);
  20322. nonGsParts++;
  20323. }
  20324. }
  20325. let i = bodySegments.length - 1;
  20326. const fileLength = file.length - fileTailMatch;
  20327. for (const b of bodySegments) {
  20328. b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
  20329. }
  20330. return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
  20331. }
  20332. // return false for "nope, not matching"
  20333. // return null for "not matching, cannot keep trying"
  20334. #matchGlobStarBodySections(file,
  20335. // pattern section, last possible position for it
  20336. bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
  20337. // take the first body segment, and walk from fileIndex to its "after"
  20338. // value at the end
  20339. // If it doesn't match at that position, we increment, until we hit
  20340. // that final possible position, and give up.
  20341. // If it does match, then advance and try to rest.
  20342. // If any of them fail we keep walking forward.
  20343. // this is still a bit recursively painful, but it's more constrained
  20344. // than previous implementations, because we never test something that
  20345. // can't possibly be a valid matching condition.
  20346. const bs = bodySegments[bodyIndex];
  20347. if (!bs) {
  20348. // just make sure that there's no bad dots
  20349. for (let i = fileIndex; i < file.length; i++) {
  20350. sawTail = true;
  20351. const f = file[i];
  20352. if (f === '.' ||
  20353. f === '..' ||
  20354. (!this.options.dot && f.startsWith('.'))) {
  20355. return false;
  20356. }
  20357. }
  20358. return sawTail;
  20359. }
  20360. // have a non-globstar body section to test
  20361. const [body, after] = bs;
  20362. while (fileIndex <= after) {
  20363. const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
  20364. // if limit exceeded, no match. intentional false negative,
  20365. // acceptable break in correctness for security.
  20366. if (m && globStarDepth < this.maxGlobstarRecursion) {
  20367. // match! see if the rest match. if so, we're done!
  20368. const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
  20369. if (sub !== false) {
  20370. return sub;
  20371. }
  20372. }
  20373. const f = file[fileIndex];
  20374. if (f === '.' ||
  20375. f === '..' ||
  20376. (!this.options.dot && f.startsWith('.'))) {
  20377. return false;
  20378. }
  20379. fileIndex++;
  20380. }
  20381. // walked off. no point continuing
  20382. return partial || null;
  20383. }
  20384. #matchOne(file, pattern, partial, fileIndex, patternIndex) {
  20385. let fi;
  20386. let pi;
  20387. let pl;
  20388. let fl;
  20389. for (fi = fileIndex,
  20390. pi = patternIndex,
  20391. fl = file.length,
  20392. pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  20393. this.debug('matchOne loop');
  20394. let p = pattern[pi];
  20395. let f = file[fi];
  20396. this.debug(pattern, p, f);
  20397. // should be impossible.
  20398. // some invalid regexp stuff in the set.
  20399. /* c8 ignore start */
  20400. if (p === false || p === GLOBSTAR) {
  20401. return false;
  20402. }
  20403. /* c8 ignore stop */
  20404. // something other than **
  20405. // non-magic patterns just have to match exactly
  20406. // patterns with magic have been turned into regexps.
  20407. let hit;
  20408. if (typeof p === 'string') {
  20409. hit = f === p;
  20410. this.debug('string match', p, f, hit);
  20411. }
  20412. else {
  20413. hit = p.test(f);
  20414. this.debug('pattern match', p, f, hit);
  20415. }
  20416. if (!hit)
  20417. return false;
  20418. }
  20419. // Note: ending in / means that we'll get a final ""
  20420. // at the end of the pattern. This can only match a
  20421. // corresponding "" at the end of the file.
  20422. // If the file ends in /, then it can only match a
  20423. // a pattern that ends in /, unless the pattern just
  20424. // doesn't have any more for it. But, a/b/ should *not*
  20425. // match "a/b/*", even though "" matches against the
  20426. // [^/]*? pattern, except in partial mode, where it might
  20427. // simply not be reached yet.
  20428. // However, a/b/ should still satisfy a/*
  20429. // now either we fell off the end of the pattern, or we're done.
  20430. if (fi === fl && pi === pl) {
  20431. // ran out of pattern and filename at the same time.
  20432. // an exact hit!
  20433. return true;
  20434. }
  20435. else if (fi === fl) {
  20436. // ran out of file, but still had pattern left.
  20437. // this is ok if we're doing the match as part of
  20438. // a glob fs traversal.
  20439. return partial;
  20440. }
  20441. else if (pi === pl) {
  20442. // ran out of pattern, still have file left.
  20443. // this is only acceptable if we're on the very last
  20444. // empty segment of a file with a trailing slash.
  20445. // a/* should match a/b/
  20446. return fi === fl - 1 && file[fi] === '';
  20447. /* c8 ignore start */
  20448. }
  20449. else {
  20450. // should be unreachable.
  20451. throw new Error('wtf?');
  20452. }
  20453. /* c8 ignore stop */
  20454. }
  20455. braceExpand() {
  20456. return braceExpand(this.pattern, this.options);
  20457. }
  20458. parse(pattern) {
  20459. assertValidPattern(pattern);
  20460. const options = this.options;
  20461. // shortcuts
  20462. if (pattern === '**')
  20463. return GLOBSTAR;
  20464. if (pattern === '')
  20465. return '';
  20466. // far and away, the most common glob pattern parts are
  20467. // *, *.*, and *.<ext> Add a fast check method for those.
  20468. let m;
  20469. let fastTest = null;
  20470. if ((m = pattern.match(starRE))) {
  20471. fastTest = options.dot ? starTestDot : starTest;
  20472. }
  20473. else if ((m = pattern.match(starDotExtRE))) {
  20474. fastTest = (options.nocase ?
  20475. options.dot ?
  20476. starDotExtTestNocaseDot
  20477. : starDotExtTestNocase
  20478. : options.dot ? starDotExtTestDot
  20479. : starDotExtTest)(m[1]);
  20480. }
  20481. else if ((m = pattern.match(qmarksRE))) {
  20482. fastTest = (options.nocase ?
  20483. options.dot ?
  20484. qmarksTestNocaseDot
  20485. : qmarksTestNocase
  20486. : options.dot ? qmarksTestDot
  20487. : qmarksTest)(m);
  20488. }
  20489. else if ((m = pattern.match(starDotStarRE))) {
  20490. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  20491. }
  20492. else if ((m = pattern.match(dotStarRE))) {
  20493. fastTest = dotStarTest;
  20494. }
  20495. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  20496. if (fastTest && typeof re === 'object') {
  20497. // Avoids overriding in frozen environments
  20498. Reflect.defineProperty(re, 'test', { value: fastTest });
  20499. }
  20500. return re;
  20501. }
  20502. makeRe() {
  20503. if (this.regexp || this.regexp === false)
  20504. return this.regexp;
  20505. // at this point, this.set is a 2d array of partial
  20506. // pattern strings, or "**".
  20507. //
  20508. // It's better to use .match(). This function shouldn't
  20509. // be used, really, but it's pretty convenient sometimes,
  20510. // when you just want to work with a regex.
  20511. const set = this.set;
  20512. if (!set.length) {
  20513. this.regexp = false;
  20514. return this.regexp;
  20515. }
  20516. const options = this.options;
  20517. const twoStar = options.noglobstar ? star
  20518. : options.dot ? twoStarDot
  20519. : twoStarNoDot;
  20520. const flags = new Set(options.nocase ? ['i'] : []);
  20521. // regexpify non-globstar patterns
  20522. // if ** is only item, then we just do one twoStar
  20523. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  20524. // if ** is last, append (\/twoStar|) to previous
  20525. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  20526. // then filter out GLOBSTAR symbols
  20527. let re = set
  20528. .map(pattern => {
  20529. const pp = pattern.map(p => {
  20530. if (p instanceof RegExp) {
  20531. for (const f of p.flags.split(''))
  20532. flags.add(f);
  20533. }
  20534. return (typeof p === 'string' ? regExpEscape(p)
  20535. : p === GLOBSTAR ? GLOBSTAR
  20536. : p._src);
  20537. });
  20538. pp.forEach((p, i) => {
  20539. const next = pp[i + 1];
  20540. const prev = pp[i - 1];
  20541. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  20542. return;
  20543. }
  20544. if (prev === undefined) {
  20545. if (next !== undefined && next !== GLOBSTAR) {
  20546. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  20547. }
  20548. else {
  20549. pp[i] = twoStar;
  20550. }
  20551. }
  20552. else if (next === undefined) {
  20553. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
  20554. }
  20555. else if (next !== GLOBSTAR) {
  20556. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  20557. pp[i + 1] = GLOBSTAR;
  20558. }
  20559. });
  20560. const filtered = pp.filter(p => p !== GLOBSTAR);
  20561. // For partial matches, we need to make the pattern match
  20562. // any prefix of the full path. We do this by generating
  20563. // alternative patterns that match progressively longer prefixes.
  20564. if (this.partial && filtered.length >= 1) {
  20565. const prefixes = [];
  20566. for (let i = 1; i <= filtered.length; i++) {
  20567. prefixes.push(filtered.slice(0, i).join('/'));
  20568. }
  20569. return '(?:' + prefixes.join('|') + ')';
  20570. }
  20571. return filtered.join('/');
  20572. })
  20573. .join('|');
  20574. // need to wrap in parens if we had more than one thing with |,
  20575. // otherwise only the first will be anchored to ^ and the last to $
  20576. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  20577. // must match entire pattern
  20578. // ending in a * or ** will make it less strict.
  20579. re = '^' + open + re + close + '$';
  20580. // In partial mode, '/' should always match as it's a valid prefix for any pattern
  20581. if (this.partial) {
  20582. re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
  20583. }
  20584. // can match anything, as long as it's not this.
  20585. if (this.negate)
  20586. re = '^(?!' + re + ').+$';
  20587. try {
  20588. this.regexp = new RegExp(re, [...flags].join(''));
  20589. /* c8 ignore start */
  20590. }
  20591. catch {
  20592. // should be impossible
  20593. this.regexp = false;
  20594. }
  20595. /* c8 ignore stop */
  20596. return this.regexp;
  20597. }
  20598. slashSplit(p) {
  20599. // if p starts with // on windows, we preserve that
  20600. // so that UNC paths aren't broken. Otherwise, any number of
  20601. // / characters are coalesced into one, unless
  20602. // preserveMultipleSlashes is set to true.
  20603. if (this.preserveMultipleSlashes) {
  20604. return p.split('/');
  20605. }
  20606. else if (this.isWindows && /^\/\/[^/]+/.test(p)) {
  20607. // add an extra '' for the one we lose
  20608. return ['', ...p.split(/\/+/)];
  20609. }
  20610. else {
  20611. return p.split(/\/+/);
  20612. }
  20613. }
  20614. match(f, partial = this.partial) {
  20615. this.debug('match', f, this.pattern);
  20616. // short-circuit in the case of busted things.
  20617. // comments, etc.
  20618. if (this.comment) {
  20619. return false;
  20620. }
  20621. if (this.empty) {
  20622. return f === '';
  20623. }
  20624. if (f === '/' && partial) {
  20625. return true;
  20626. }
  20627. const options = this.options;
  20628. // windows: need to use /, not \
  20629. if (this.isWindows) {
  20630. f = f.split('\\').join('/');
  20631. }
  20632. // treat the test path as a set of pathparts.
  20633. const ff = this.slashSplit(f);
  20634. this.debug(this.pattern, 'split', ff);
  20635. // just ONE of the pattern sets in this.set needs to match
  20636. // in order for it to be valid. If negating, then just one
  20637. // match means that we have failed.
  20638. // Either way, return on the first hit.
  20639. const set = this.set;
  20640. this.debug(this.pattern, 'set', set);
  20641. // Find the basename of the path by looking for the last non-empty segment
  20642. let filename = ff[ff.length - 1];
  20643. if (!filename) {
  20644. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  20645. filename = ff[i];
  20646. }
  20647. }
  20648. for (const pattern of set) {
  20649. let file = ff;
  20650. if (options.matchBase && pattern.length === 1) {
  20651. file = [filename];
  20652. }
  20653. const hit = this.matchOne(file, pattern, partial);
  20654. if (hit) {
  20655. if (options.flipNegate) {
  20656. return true;
  20657. }
  20658. return !this.negate;
  20659. }
  20660. }
  20661. // didn't get any hits. this is success if it's a negative
  20662. // pattern, failure otherwise.
  20663. if (options.flipNegate) {
  20664. return false;
  20665. }
  20666. return this.negate;
  20667. }
  20668. static defaults(def) {
  20669. return minimatch.defaults(def).Minimatch;
  20670. }
  20671. }
  20672. /* c8 ignore stop */
  20673. minimatch.AST = AST;
  20674. minimatch.Minimatch = Minimatch;
  20675. minimatch.escape = escape;
  20676. minimatch.unescape = unescape;
  20677. class TypeScope {
  20678. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  20679. this.filename = filename;
  20680. this.source = source;
  20681. this.offset = offset;
  20682. this.imports = imports;
  20683. this.types = types;
  20684. this.declares = declares;
  20685. this.isGenericScope = false;
  20686. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  20687. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  20688. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  20689. }
  20690. }
  20691. function recordScopeDep(ctx, scope) {
  20692. if (scope && scope.filename !== ctx.filename) {
  20693. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(scope.filename);
  20694. }
  20695. }
  20696. function recordResolvedElementDeps(ctx, { props }) {
  20697. for (const key in props) {
  20698. recordScopeDep(ctx, props[key]._ownerScope);
  20699. }
  20700. }
  20701. function resolveTypeElements(ctx, node, scope, typeParameters) {
  20702. const canCache = !typeParameters;
  20703. if (canCache && node._resolvedElements) {
  20704. recordResolvedElementDeps(ctx, node._resolvedElements);
  20705. return node._resolvedElements;
  20706. }
  20707. const resolved = innerResolveTypeElements(
  20708. ctx,
  20709. node,
  20710. node._ownerScope || scope || ctxToScope(ctx),
  20711. typeParameters
  20712. );
  20713. return canCache ? node._resolvedElements = resolved : resolved;
  20714. }
  20715. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  20716. var _a, _b;
  20717. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  20718. return { props: {} };
  20719. }
  20720. switch (node.type) {
  20721. case "TSTypeLiteral":
  20722. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  20723. case "TSInterfaceDeclaration":
  20724. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  20725. case "TSTypeAliasDeclaration":
  20726. case "TSTypeAnnotation":
  20727. case "TSParenthesizedType":
  20728. return resolveTypeElements(
  20729. ctx,
  20730. node.typeAnnotation,
  20731. scope,
  20732. typeParameters
  20733. );
  20734. case "TSFunctionType": {
  20735. return { props: {}, calls: [node] };
  20736. }
  20737. case "TSUnionType":
  20738. case "TSIntersectionType":
  20739. return mergeElements(
  20740. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  20741. node.type
  20742. );
  20743. case "TSMappedType":
  20744. return resolveMappedType(ctx, node, scope, typeParameters);
  20745. case "TSIndexedAccessType": {
  20746. const types = resolveIndexType(ctx, node, scope);
  20747. return mergeElements(
  20748. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  20749. "TSUnionType"
  20750. );
  20751. }
  20752. case "TSExpressionWithTypeArguments":
  20753. // referenced by interface extends
  20754. case "TSTypeReference": {
  20755. const typeName = getReferenceName(node);
  20756. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  20757. return resolveExtractPropTypes(
  20758. resolveTypeElements(
  20759. ctx,
  20760. node.typeParameters.params[0],
  20761. scope,
  20762. typeParameters
  20763. ),
  20764. scope
  20765. );
  20766. }
  20767. const resolved = resolveTypeReference(ctx, node, scope);
  20768. if (resolved) {
  20769. let typeParams;
  20770. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  20771. typeParams = /* @__PURE__ */ Object.create(null);
  20772. resolved.typeParameters.params.forEach((p, i) => {
  20773. let param = typeParameters && typeParameters[p.name];
  20774. if (!param) param = node.typeParameters.params[i];
  20775. typeParams[p.name] = param;
  20776. });
  20777. }
  20778. return resolveTypeElements(
  20779. ctx,
  20780. resolved,
  20781. resolved._ownerScope,
  20782. typeParams
  20783. );
  20784. } else {
  20785. if (typeof typeName === "string") {
  20786. if (typeParameters && typeParameters[typeName]) {
  20787. return resolveTypeElements(
  20788. ctx,
  20789. typeParameters[typeName],
  20790. scope,
  20791. typeParameters
  20792. );
  20793. }
  20794. if (
  20795. // @ts-expect-error
  20796. SupportedBuiltinsSet.has(typeName)
  20797. ) {
  20798. return resolveBuiltin(
  20799. ctx,
  20800. node,
  20801. typeName,
  20802. scope,
  20803. typeParameters
  20804. );
  20805. } else if (typeName === "ReturnType" && node.typeParameters) {
  20806. const ret = resolveReturnType(
  20807. ctx,
  20808. node.typeParameters.params[0],
  20809. scope
  20810. );
  20811. if (ret) {
  20812. return resolveTypeElements(ctx, ret, scope);
  20813. }
  20814. }
  20815. }
  20816. return ctx.error(
  20817. `Unresolvable type reference or unsupported built-in utility type`,
  20818. node,
  20819. scope
  20820. );
  20821. }
  20822. }
  20823. case "TSImportType": {
  20824. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  20825. return resolveExtractPropTypes(
  20826. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  20827. scope
  20828. );
  20829. }
  20830. const sourceScope = importSourceToScope(
  20831. ctx,
  20832. node.argument,
  20833. scope,
  20834. node.argument.value
  20835. );
  20836. const resolved = resolveTypeReference(ctx, node, sourceScope);
  20837. if (resolved) {
  20838. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20839. }
  20840. break;
  20841. }
  20842. case "TSTypeQuery":
  20843. {
  20844. const resolved = resolveTypeReference(ctx, node, scope);
  20845. if (resolved) {
  20846. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20847. }
  20848. }
  20849. break;
  20850. }
  20851. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  20852. }
  20853. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  20854. const res = { props: {} };
  20855. for (const e of elements) {
  20856. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  20857. if (typeParameters) {
  20858. scope = createChildScope(scope);
  20859. scope.isGenericScope = true;
  20860. Object.assign(scope.types, typeParameters);
  20861. }
  20862. e._ownerScope = scope;
  20863. const name = getStringLiteralKey(e);
  20864. if (name !== null) {
  20865. res.props[name] = e;
  20866. } else {
  20867. ctx.error(
  20868. `Unsupported computed key in type referenced by a macro`,
  20869. e.key,
  20870. scope
  20871. );
  20872. }
  20873. } else if (e.type === "TSCallSignatureDeclaration") {
  20874. (res.calls || (res.calls = [])).push(e);
  20875. }
  20876. }
  20877. return res;
  20878. }
  20879. function mergeElements(maps, type) {
  20880. if (maps.length === 1) return maps[0];
  20881. const res = { props: {} };
  20882. const { props: baseProps } = res;
  20883. for (const { props, calls } of maps) {
  20884. for (const key in props) {
  20885. if (!shared.hasOwn(baseProps, key)) {
  20886. baseProps[key] = props[key];
  20887. } else {
  20888. baseProps[key] = createProperty(
  20889. baseProps[key].key,
  20890. {
  20891. type,
  20892. // @ts-expect-error
  20893. types: [baseProps[key], props[key]]
  20894. },
  20895. baseProps[key]._ownerScope,
  20896. baseProps[key].optional || props[key].optional
  20897. );
  20898. }
  20899. }
  20900. if (calls) {
  20901. (res.calls || (res.calls = [])).push(...calls);
  20902. }
  20903. }
  20904. return res;
  20905. }
  20906. function createProperty(key, typeAnnotation, scope, optional) {
  20907. return {
  20908. type: "TSPropertySignature",
  20909. key,
  20910. kind: "get",
  20911. optional,
  20912. typeAnnotation: {
  20913. type: "TSTypeAnnotation",
  20914. typeAnnotation
  20915. },
  20916. _ownerScope: scope
  20917. };
  20918. }
  20919. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  20920. const base = typeElementsToMap(
  20921. ctx,
  20922. node.body.body,
  20923. node._ownerScope,
  20924. typeParameters
  20925. );
  20926. if (node.extends) {
  20927. for (const ext of node.extends) {
  20928. try {
  20929. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  20930. for (const key in props) {
  20931. if (!shared.hasOwn(base.props, key)) {
  20932. base.props[key] = props[key];
  20933. }
  20934. }
  20935. if (calls) {
  20936. ;
  20937. (base.calls || (base.calls = [])).push(...calls);
  20938. }
  20939. } catch (e) {
  20940. if (!ctx.silentOnExtendsFailure) {
  20941. ctx.error(
  20942. `Failed to resolve extends base type.
  20943. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  20944. interface Props extends /* @vue-ignore */ Base {}
  20945. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  20946. ext,
  20947. scope
  20948. );
  20949. }
  20950. }
  20951. }
  20952. }
  20953. return base;
  20954. }
  20955. function resolveMappedType(ctx, node, scope, typeParameters) {
  20956. const res = { props: {} };
  20957. let keys;
  20958. if (node.nameType) {
  20959. const { name, constraint } = node.typeParameter;
  20960. scope = createChildScope(scope);
  20961. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  20962. keys = resolveStringType(ctx, node.nameType, scope);
  20963. } else {
  20964. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  20965. }
  20966. for (const key of keys) {
  20967. res.props[key] = createProperty(
  20968. {
  20969. type: "Identifier",
  20970. name: key
  20971. },
  20972. node.typeAnnotation,
  20973. scope,
  20974. !!node.optional
  20975. );
  20976. }
  20977. return res;
  20978. }
  20979. function resolveIndexType(ctx, node, scope) {
  20980. var _a, _b;
  20981. if (node.indexType.type === "TSNumberKeyword") {
  20982. return resolveArrayElementType(ctx, node.objectType, scope);
  20983. }
  20984. const { indexType, objectType } = node;
  20985. const types = [];
  20986. let keys;
  20987. let resolved;
  20988. if (indexType.type === "TSStringKeyword") {
  20989. resolved = resolveTypeElements(ctx, objectType, scope);
  20990. keys = Object.keys(resolved.props);
  20991. } else {
  20992. keys = resolveStringType(ctx, indexType, scope);
  20993. resolved = resolveTypeElements(ctx, objectType, scope);
  20994. }
  20995. for (const key of keys) {
  20996. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  20997. if (targetType) {
  20998. targetType._ownerScope = resolved.props[key]._ownerScope;
  20999. types.push(targetType);
  21000. }
  21001. }
  21002. return types;
  21003. }
  21004. function resolveArrayElementType(ctx, node, scope) {
  21005. if (node.type === "TSArrayType") {
  21006. return [node.elementType];
  21007. }
  21008. if (node.type === "TSTupleType") {
  21009. return node.elementTypes.map(
  21010. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  21011. );
  21012. }
  21013. if (node.type === "TSTypeReference") {
  21014. if (getReferenceName(node) === "Array" && node.typeParameters) {
  21015. return node.typeParameters.params;
  21016. } else {
  21017. const resolved = resolveTypeReference(ctx, node, scope);
  21018. if (resolved) {
  21019. return resolveArrayElementType(ctx, resolved, scope);
  21020. }
  21021. }
  21022. }
  21023. return ctx.error(
  21024. "Failed to resolve element type from target type",
  21025. node,
  21026. scope
  21027. );
  21028. }
  21029. function resolveStringType(ctx, node, scope, typeParameters) {
  21030. switch (node.type) {
  21031. case "StringLiteral":
  21032. return [node.value];
  21033. case "TSLiteralType":
  21034. return resolveStringType(ctx, node.literal, scope, typeParameters);
  21035. case "TSUnionType":
  21036. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  21037. case "TemplateLiteral": {
  21038. return resolveTemplateKeys(ctx, node, scope);
  21039. }
  21040. case "TSTypeReference": {
  21041. const resolved = resolveTypeReference(ctx, node, scope);
  21042. if (resolved) {
  21043. return resolveStringType(ctx, resolved, scope, typeParameters);
  21044. }
  21045. if (node.typeName.type === "Identifier") {
  21046. const name = node.typeName.name;
  21047. if (typeParameters && typeParameters[name]) {
  21048. return resolveStringType(
  21049. ctx,
  21050. typeParameters[name],
  21051. scope,
  21052. typeParameters
  21053. );
  21054. }
  21055. const getParam = (index = 0) => resolveStringType(
  21056. ctx,
  21057. node.typeParameters.params[index],
  21058. scope,
  21059. typeParameters
  21060. );
  21061. switch (name) {
  21062. case "Extract":
  21063. return getParam(1);
  21064. case "Exclude": {
  21065. const excluded = getParam(1);
  21066. return getParam().filter((s) => !excluded.includes(s));
  21067. }
  21068. case "Uppercase":
  21069. return getParam().map((s) => s.toUpperCase());
  21070. case "Lowercase":
  21071. return getParam().map((s) => s.toLowerCase());
  21072. case "Capitalize":
  21073. return getParam().map(shared.capitalize);
  21074. case "Uncapitalize":
  21075. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  21076. default:
  21077. ctx.error(
  21078. "Unsupported type when resolving index type",
  21079. node.typeName,
  21080. scope
  21081. );
  21082. }
  21083. }
  21084. }
  21085. }
  21086. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  21087. }
  21088. function resolveTemplateKeys(ctx, node, scope) {
  21089. if (!node.expressions.length) {
  21090. return [node.quasis[0].value.raw];
  21091. }
  21092. const res = [];
  21093. const e = node.expressions[0];
  21094. const q = node.quasis[0];
  21095. const leading = q ? q.value.raw : ``;
  21096. const resolved = resolveStringType(ctx, e, scope);
  21097. const restResolved = resolveTemplateKeys(
  21098. ctx,
  21099. {
  21100. ...node,
  21101. expressions: node.expressions.slice(1),
  21102. quasis: q ? node.quasis.slice(1) : node.quasis
  21103. },
  21104. scope
  21105. );
  21106. for (const r of resolved) {
  21107. for (const rr of restResolved) {
  21108. res.push(leading + r + rr);
  21109. }
  21110. }
  21111. return res;
  21112. }
  21113. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  21114. "Partial",
  21115. "Required",
  21116. "Readonly",
  21117. "Pick",
  21118. "Omit"
  21119. ]);
  21120. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  21121. const t = resolveTypeElements(
  21122. ctx,
  21123. node.typeParameters.params[0],
  21124. scope,
  21125. typeParameters
  21126. );
  21127. switch (name) {
  21128. case "Partial": {
  21129. const res2 = { props: {}, calls: t.calls };
  21130. Object.keys(t.props).forEach((key) => {
  21131. res2.props[key] = { ...t.props[key], optional: true };
  21132. });
  21133. return res2;
  21134. }
  21135. case "Required": {
  21136. const res2 = { props: {}, calls: t.calls };
  21137. Object.keys(t.props).forEach((key) => {
  21138. res2.props[key] = { ...t.props[key], optional: false };
  21139. });
  21140. return res2;
  21141. }
  21142. case "Readonly":
  21143. return t;
  21144. case "Pick": {
  21145. const picked = resolveStringType(
  21146. ctx,
  21147. node.typeParameters.params[1],
  21148. scope,
  21149. typeParameters
  21150. );
  21151. const res2 = { props: {}, calls: t.calls };
  21152. for (const key of picked) {
  21153. res2.props[key] = t.props[key];
  21154. }
  21155. return res2;
  21156. }
  21157. case "Omit":
  21158. const omitted = resolveStringType(
  21159. ctx,
  21160. node.typeParameters.params[1],
  21161. scope,
  21162. typeParameters
  21163. );
  21164. const res = { props: {}, calls: t.calls };
  21165. for (const key in t.props) {
  21166. if (!omitted.includes(key)) {
  21167. res.props[key] = t.props[key];
  21168. }
  21169. }
  21170. return res;
  21171. }
  21172. }
  21173. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  21174. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  21175. if (canCache && node._resolvedReference) {
  21176. recordScopeDep(ctx, node._resolvedReference._ownerScope);
  21177. return node._resolvedReference;
  21178. }
  21179. const resolved = innerResolveTypeReference(
  21180. ctx,
  21181. scope || ctxToScope(ctx),
  21182. name || getReferenceName(node),
  21183. node,
  21184. onlyExported
  21185. );
  21186. return canCache ? node._resolvedReference = resolved : resolved;
  21187. }
  21188. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  21189. if (typeof name === "string") {
  21190. if (scope.imports[name]) {
  21191. return resolveTypeFromImport(ctx, node, name, scope);
  21192. } else {
  21193. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  21194. if (lookupSource[name]) {
  21195. return lookupSource[name];
  21196. } else {
  21197. const globalScopes = resolveGlobalScope(ctx);
  21198. if (globalScopes) {
  21199. for (const s of globalScopes) {
  21200. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  21201. if (src[name]) {
  21202. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  21203. const resolved = src[name];
  21204. if (resolved._ownerScope && resolved._ownerScope !== s) {
  21205. ctx.deps.add(resolved._ownerScope.filename);
  21206. }
  21207. return resolved;
  21208. }
  21209. }
  21210. }
  21211. }
  21212. }
  21213. } else {
  21214. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  21215. if (ns) {
  21216. if (ns.type !== "TSModuleDeclaration") {
  21217. ns = ns._ns;
  21218. }
  21219. if (ns) {
  21220. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  21221. return innerResolveTypeReference(
  21222. ctx,
  21223. childScope,
  21224. name.length > 2 ? name.slice(1) : name[name.length - 1],
  21225. node,
  21226. !ns.declare
  21227. );
  21228. }
  21229. }
  21230. }
  21231. }
  21232. function getReferenceName(node) {
  21233. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  21234. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  21235. return ref.name;
  21236. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  21237. return qualifiedNameToPath(ref);
  21238. } else {
  21239. return "default";
  21240. }
  21241. }
  21242. function qualifiedNameToPath(node) {
  21243. if (node.type === "Identifier") {
  21244. return [node.name];
  21245. } else {
  21246. return [...qualifiedNameToPath(node.left), node.right.name];
  21247. }
  21248. }
  21249. function resolveGlobalScope(ctx) {
  21250. if (ctx.options.globalTypeFiles) {
  21251. const fs = resolveFS(ctx);
  21252. if (!fs) {
  21253. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  21254. }
  21255. return ctx.options.globalTypeFiles.map(
  21256. (file) => fileToScope(ctx, normalizePath(file), true)
  21257. );
  21258. }
  21259. }
  21260. let ts;
  21261. let loadTS;
  21262. function registerTS(_loadTS) {
  21263. loadTS = () => {
  21264. try {
  21265. return _loadTS();
  21266. } catch (err) {
  21267. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  21268. throw new Error(
  21269. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  21270. );
  21271. } else {
  21272. throw new Error(
  21273. "Failed to load TypeScript for resolving imported types."
  21274. );
  21275. }
  21276. }
  21277. };
  21278. }
  21279. function resolveFS(ctx) {
  21280. if (ctx.fs) {
  21281. return ctx.fs;
  21282. }
  21283. if (!ts && loadTS) {
  21284. ts = loadTS();
  21285. }
  21286. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  21287. if (!fs) {
  21288. return;
  21289. }
  21290. return ctx.fs = {
  21291. fileExists(file) {
  21292. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21293. file = file.replace(/\.ts$/, "");
  21294. }
  21295. return fs.fileExists(file);
  21296. },
  21297. readFile(file) {
  21298. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21299. file = file.replace(/\.ts$/, "");
  21300. }
  21301. return fs.readFile(file);
  21302. },
  21303. realpath: fs.realpath
  21304. };
  21305. }
  21306. function resolveTypeFromImport(ctx, node, name, scope) {
  21307. const { source, imported } = scope.imports[name];
  21308. const sourceScope = importSourceToScope(ctx, node, scope, source);
  21309. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  21310. }
  21311. function importSourceToScope(ctx, node, scope, source, trackDep = true) {
  21312. let fs;
  21313. try {
  21314. fs = resolveFS(ctx);
  21315. } catch (err) {
  21316. return ctx.error(err.message, node, scope);
  21317. }
  21318. if (!fs) {
  21319. return ctx.error(
  21320. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  21321. node,
  21322. scope
  21323. );
  21324. }
  21325. let resolved = scope.resolvedImportSources[source];
  21326. if (!resolved) {
  21327. if (source.startsWith("..")) {
  21328. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  21329. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  21330. resolved = resolveExt(filename, fs);
  21331. } else if (source[0] === ".") {
  21332. const filename = joinPaths(path$1.dirname(scope.filename), source);
  21333. resolved = resolveExt(filename, fs);
  21334. } else {
  21335. if (!ts) {
  21336. if (loadTS) ts = loadTS();
  21337. if (!ts) {
  21338. return ctx.error(
  21339. `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.`,
  21340. node,
  21341. scope
  21342. );
  21343. }
  21344. }
  21345. resolved = resolveWithTS(scope.filename, source, ts, fs);
  21346. }
  21347. if (!resolved && source[0] === "." && true) {
  21348. if (!ts) {
  21349. if (loadTS) ts = loadTS();
  21350. }
  21351. if (ts) {
  21352. resolved = resolveWithTS(scope.filename, source, ts, fs);
  21353. }
  21354. }
  21355. if (resolved) {
  21356. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  21357. }
  21358. }
  21359. if (resolved) {
  21360. if (trackDep) {
  21361. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  21362. }
  21363. return fileToScope(ctx, resolved);
  21364. } else {
  21365. return ctx.error(
  21366. `Failed to resolve import source ${JSON.stringify(source)}.`,
  21367. node,
  21368. scope
  21369. );
  21370. }
  21371. }
  21372. function resolveExt(filename, fs) {
  21373. let moduleType = "u";
  21374. if (filename.endsWith(".mjs")) {
  21375. moduleType = "m";
  21376. } else if (filename.endsWith(".cjs")) {
  21377. moduleType = "c";
  21378. }
  21379. filename = filename.replace(/\.[cm]?jsx?$/, "");
  21380. const tryResolve = (filename2) => {
  21381. if (fs.fileExists(filename2)) return filename2;
  21382. };
  21383. const resolveTs = () => tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`);
  21384. const resolveMts = () => tryResolve(filename + `.mts`) || tryResolve(filename + `.d.mts`);
  21385. const resolveCts = () => tryResolve(filename + `.cts`) || tryResolve(filename + `.d.cts`);
  21386. return tryResolve(filename) || // For explicit .mjs/.cjs imports, prefer .mts/.cts declarations first.
  21387. (moduleType === "m" ? resolveMts() || resolveTs() : moduleType === "c" ? resolveCts() || resolveTs() : resolveTs() || resolveMts() || resolveCts()) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  21388. }
  21389. const tsConfigCache = createCache();
  21390. const tsConfigRefMap = /* @__PURE__ */ new Map();
  21391. function resolveWithTS(containingFile, source, ts2, fs) {
  21392. var _a, _b;
  21393. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  21394. let tsCompilerOptions;
  21395. let tsResolveCache;
  21396. if (configPath) {
  21397. let configs;
  21398. const normalizedConfigPath = normalizePath(configPath);
  21399. const cached = tsConfigCache.get(normalizedConfigPath);
  21400. if (!cached) {
  21401. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  21402. tsConfigCache.set(normalizedConfigPath, configs);
  21403. } else {
  21404. configs = cached;
  21405. }
  21406. let matchedConfig;
  21407. if (configs.length === 1) {
  21408. matchedConfig = configs[0];
  21409. } else {
  21410. const [major, minor] = ts2.versionMajorMinor.split(".").map(Number);
  21411. const getPattern = (base, p) => {
  21412. const supportsConfigDir = major > 5 || major === 5 && minor >= 5;
  21413. return p.startsWith("${configDir}") && supportsConfigDir ? normalizePath(p.replace("${configDir}", path$1.dirname(configPath))) : joinPaths(base, p);
  21414. };
  21415. for (const c of configs) {
  21416. const base = normalizePath(
  21417. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  21418. );
  21419. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  21420. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  21421. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, getPattern(base, p))))) {
  21422. if (excluded && excluded.some((p) => minimatch(containingFile, getPattern(base, p)))) {
  21423. continue;
  21424. }
  21425. matchedConfig = c;
  21426. break;
  21427. }
  21428. }
  21429. if (!matchedConfig) {
  21430. matchedConfig = configs[configs.length - 1];
  21431. }
  21432. }
  21433. tsCompilerOptions = matchedConfig.config.options;
  21434. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  21435. process__namespace.cwd(),
  21436. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  21437. tsCompilerOptions
  21438. ));
  21439. } else {
  21440. tsCompilerOptions = {};
  21441. }
  21442. const res = ts2.resolveModuleName(
  21443. source,
  21444. containingFile,
  21445. tsCompilerOptions,
  21446. fs,
  21447. tsResolveCache
  21448. );
  21449. if (res.resolvedModule) {
  21450. let filename = res.resolvedModule.resolvedFileName;
  21451. if (filename.endsWith(".vue.ts") && !filename.endsWith(".d.vue.ts")) {
  21452. filename = filename.replace(/\.ts$/, "");
  21453. }
  21454. return fs.realpath ? fs.realpath(filename) : filename;
  21455. }
  21456. }
  21457. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  21458. const parseConfigHost = ts2.sys;
  21459. const config = ts2.parseJsonConfigFileContent(
  21460. ts2.readConfigFile(configPath, fs.readFile).config,
  21461. parseConfigHost,
  21462. path$1.dirname(configPath),
  21463. void 0,
  21464. configPath
  21465. );
  21466. const res = [config];
  21467. visited.add(configPath);
  21468. if (config.projectReferences) {
  21469. for (const ref of config.projectReferences) {
  21470. const refPath = ts2.resolveProjectReferencePath(ref);
  21471. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  21472. continue;
  21473. }
  21474. tsConfigRefMap.set(refPath, configPath);
  21475. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  21476. }
  21477. }
  21478. return res;
  21479. }
  21480. const fileToScopeCache = createCache();
  21481. const fileToGlobalScopeCache = createCache();
  21482. function invalidateTypeCache(filename) {
  21483. filename = normalizePath(filename);
  21484. fileToScopeCache.delete(filename);
  21485. fileToGlobalScopeCache.delete(filename);
  21486. tsConfigCache.delete(filename);
  21487. const affectedConfig = tsConfigRefMap.get(filename);
  21488. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  21489. }
  21490. function fileToScope(ctx, filename, asGlobal = false) {
  21491. const cache = asGlobal ? fileToGlobalScopeCache : fileToScopeCache;
  21492. const cached = cache.get(filename);
  21493. if (cached) {
  21494. return cached;
  21495. }
  21496. const fs = resolveFS(ctx);
  21497. const source = fs.readFile(filename) || "";
  21498. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  21499. const scope = new TypeScope(filename, source, 0, recordImports(body));
  21500. recordTypes(ctx, body, scope, asGlobal);
  21501. cache.set(filename, scope);
  21502. return scope;
  21503. }
  21504. function parseFile(filename, content, fs, parserPlugins) {
  21505. const ext = path$1.extname(filename);
  21506. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".cts" || ext === ".mtsx") {
  21507. return parser$2.parse(content, {
  21508. plugins: resolveParserPlugins(
  21509. ext.slice(1),
  21510. parserPlugins,
  21511. /\.d\.[cm]?ts$/.test(filename)
  21512. ),
  21513. sourceType: "module"
  21514. }).program.body;
  21515. }
  21516. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  21517. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  21518. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  21519. if (hasArbitraryTypeDeclaration) {
  21520. return parser$2.parse(fs.readFile(arbitraryTypeSource), {
  21521. plugins: resolveParserPlugins("ts", parserPlugins, true),
  21522. sourceType: "module"
  21523. }).program.body;
  21524. }
  21525. if (ext === ".vue") {
  21526. const {
  21527. descriptor: { script, scriptSetup }
  21528. } = parse$1(content);
  21529. if (!script && !scriptSetup) {
  21530. return [];
  21531. }
  21532. const scriptOffset = script ? script.loc.start.offset : Infinity;
  21533. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  21534. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  21535. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  21536. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  21537. if (secondBlock) {
  21538. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  21539. }
  21540. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  21541. return parser$2.parse(scriptContent, {
  21542. plugins: resolveParserPlugins(lang, parserPlugins),
  21543. sourceType: "module"
  21544. }).program.body;
  21545. }
  21546. return [];
  21547. }
  21548. function ctxToScope(ctx) {
  21549. if (ctx.scope) {
  21550. return ctx.scope;
  21551. }
  21552. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  21553. const scope = new TypeScope(
  21554. ctx.filename,
  21555. ctx.source,
  21556. "startOffset" in ctx ? ctx.startOffset : 0,
  21557. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  21558. );
  21559. recordTypes(ctx, body, scope);
  21560. return ctx.scope = scope;
  21561. }
  21562. function moduleDeclToScope(ctx, node, parentScope) {
  21563. if (node._resolvedChildScope) {
  21564. return node._resolvedChildScope;
  21565. }
  21566. const scope = createChildScope(parentScope);
  21567. if (node.body.type === "TSModuleDeclaration") {
  21568. const decl = node.body;
  21569. decl._ownerScope = scope;
  21570. const id = getId(decl.id);
  21571. scope.types[id] = scope.exportedTypes[id] = decl;
  21572. } else {
  21573. recordTypes(ctx, node.body.body, scope);
  21574. }
  21575. return node._resolvedChildScope = scope;
  21576. }
  21577. function createChildScope(parentScope) {
  21578. return new TypeScope(
  21579. parentScope.filename,
  21580. parentScope.source,
  21581. parentScope.offset,
  21582. Object.create(parentScope.imports),
  21583. Object.create(parentScope.types),
  21584. Object.create(parentScope.declares)
  21585. );
  21586. }
  21587. const importExportRE = /^Import|^Export/;
  21588. function recordTypes(ctx, body, scope, asGlobal = false) {
  21589. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  21590. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  21591. for (const stmt of body) {
  21592. if (asGlobal) {
  21593. if (isAmbient) {
  21594. if (stmt.declare) {
  21595. recordType(stmt, types, declares);
  21596. }
  21597. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  21598. for (const s of stmt.body.body) {
  21599. if (s.type === "ExportNamedDeclaration") {
  21600. if (s.declaration) {
  21601. recordType(s.declaration, types, declares);
  21602. } else if (s.source) {
  21603. const sourceScope = importSourceToScope(
  21604. ctx,
  21605. s.source,
  21606. scope,
  21607. s.source.value,
  21608. false
  21609. );
  21610. for (const spec of s.specifiers) {
  21611. if (spec.type === "ExportSpecifier") {
  21612. const exported = getId(spec.exported);
  21613. const local = spec.local.name;
  21614. if (sourceScope.exportedTypes[local]) {
  21615. types[exported] = sourceScope.exportedTypes[local];
  21616. }
  21617. if (sourceScope.exportedDeclares[local]) {
  21618. declares[exported] = sourceScope.exportedDeclares[local];
  21619. }
  21620. }
  21621. }
  21622. }
  21623. } else if (s.type === "ExportAllDeclaration" && s.source) {
  21624. const sourceScope = importSourceToScope(
  21625. ctx,
  21626. s.source,
  21627. scope,
  21628. s.source.value,
  21629. false
  21630. );
  21631. Object.assign(types, sourceScope.exportedTypes);
  21632. Object.assign(declares, sourceScope.exportedDeclares);
  21633. } else {
  21634. recordType(s, types, declares);
  21635. }
  21636. }
  21637. }
  21638. } else {
  21639. recordType(stmt, types, declares);
  21640. }
  21641. }
  21642. if (!asGlobal) {
  21643. for (const stmt of body) {
  21644. if (stmt.type === "ExportNamedDeclaration") {
  21645. if (stmt.declaration) {
  21646. recordType(stmt.declaration, types, declares);
  21647. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  21648. } else {
  21649. for (const spec of stmt.specifiers) {
  21650. if (spec.type === "ExportSpecifier") {
  21651. const local = spec.local.name;
  21652. const exported = getId(spec.exported);
  21653. if (stmt.source) {
  21654. imports[exported] = {
  21655. source: stmt.source.value,
  21656. imported: local
  21657. };
  21658. exportedTypes[exported] = {
  21659. type: "TSTypeReference",
  21660. typeName: {
  21661. type: "Identifier",
  21662. name: local
  21663. },
  21664. _ownerScope: scope
  21665. };
  21666. } else if (types[local]) {
  21667. exportedTypes[exported] = types[local];
  21668. }
  21669. }
  21670. }
  21671. }
  21672. } else if (stmt.type === "ExportAllDeclaration") {
  21673. const sourceScope = importSourceToScope(
  21674. ctx,
  21675. stmt.source,
  21676. scope,
  21677. stmt.source.value
  21678. );
  21679. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  21680. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  21681. if (stmt.declaration.type !== "Identifier") {
  21682. recordType(stmt.declaration, types, declares, "default");
  21683. recordType(
  21684. stmt.declaration,
  21685. exportedTypes,
  21686. exportedDeclares,
  21687. "default"
  21688. );
  21689. } else if (types[stmt.declaration.name]) {
  21690. exportedTypes["default"] = types[stmt.declaration.name];
  21691. }
  21692. }
  21693. }
  21694. }
  21695. for (const key of Object.keys(types)) {
  21696. const node = types[key];
  21697. if (!node._ownerScope) node._ownerScope = scope;
  21698. if (node._ns && !node._ns._ownerScope) node._ns._ownerScope = scope;
  21699. }
  21700. for (const key of Object.keys(declares)) {
  21701. if (!declares[key]._ownerScope) declares[key]._ownerScope = scope;
  21702. }
  21703. }
  21704. function recordType(node, types, declares, overwriteId) {
  21705. switch (node.type) {
  21706. case "TSInterfaceDeclaration":
  21707. case "TSEnumDeclaration":
  21708. case "TSModuleDeclaration": {
  21709. if (node.type === "TSModuleDeclaration" && node.global) {
  21710. const body = node.body;
  21711. for (const s of body.body) {
  21712. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  21713. recordType(s.declaration, types, declares);
  21714. } else {
  21715. recordType(s, types, declares);
  21716. }
  21717. }
  21718. break;
  21719. }
  21720. const id = overwriteId || getId(node.id);
  21721. let existing = types[id];
  21722. if (existing) {
  21723. if (node.type === "TSModuleDeclaration") {
  21724. if (existing.type === "TSModuleDeclaration") {
  21725. mergeNamespaces(existing, node);
  21726. } else {
  21727. attachNamespace(existing, node);
  21728. }
  21729. break;
  21730. }
  21731. if (existing.type === "TSModuleDeclaration") {
  21732. types[id] = node;
  21733. attachNamespace(node, existing);
  21734. break;
  21735. }
  21736. if (existing.type !== node.type) {
  21737. break;
  21738. }
  21739. if (node.type === "TSInterfaceDeclaration") {
  21740. existing.body.body.push(...node.body.body);
  21741. } else {
  21742. existing.members.push(...node.members);
  21743. }
  21744. } else {
  21745. types[id] = node;
  21746. }
  21747. break;
  21748. }
  21749. case "ClassDeclaration":
  21750. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  21751. break;
  21752. case "TSTypeAliasDeclaration":
  21753. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  21754. break;
  21755. case "TSDeclareFunction":
  21756. if (node.id) declares[node.id.name] = node;
  21757. break;
  21758. case "VariableDeclaration": {
  21759. if (node.declare) {
  21760. for (const decl of node.declarations) {
  21761. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  21762. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  21763. }
  21764. }
  21765. }
  21766. break;
  21767. }
  21768. }
  21769. }
  21770. function mergeNamespaces(to, from) {
  21771. const toBody = to.body;
  21772. const fromBody = from.body;
  21773. if (toBody.type === "TSModuleDeclaration") {
  21774. if (fromBody.type === "TSModuleDeclaration") {
  21775. mergeNamespaces(toBody, fromBody);
  21776. } else {
  21777. fromBody.body.push({
  21778. type: "ExportNamedDeclaration",
  21779. declaration: toBody,
  21780. exportKind: "type",
  21781. specifiers: []
  21782. });
  21783. }
  21784. } else if (fromBody.type === "TSModuleDeclaration") {
  21785. toBody.body.push({
  21786. type: "ExportNamedDeclaration",
  21787. declaration: fromBody,
  21788. exportKind: "type",
  21789. specifiers: []
  21790. });
  21791. } else {
  21792. toBody.body.push(...fromBody.body);
  21793. }
  21794. }
  21795. function attachNamespace(to, ns) {
  21796. if (!to._ns) {
  21797. to._ns = ns;
  21798. } else {
  21799. mergeNamespaces(to._ns, ns);
  21800. }
  21801. }
  21802. function recordImports(body) {
  21803. const imports = /* @__PURE__ */ Object.create(null);
  21804. for (const s of body) {
  21805. recordImport(s, imports);
  21806. }
  21807. return imports;
  21808. }
  21809. function recordImport(node, imports) {
  21810. if (node.type !== "ImportDeclaration") {
  21811. return;
  21812. }
  21813. for (const s of node.specifiers) {
  21814. imports[s.local.name] = {
  21815. imported: getImportedName(s),
  21816. source: node.source.value
  21817. };
  21818. }
  21819. }
  21820. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  21821. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  21822. return [UNKNOWN_TYPE];
  21823. }
  21824. const prevSilent = ctx.silentOnExtendsFailure;
  21825. ctx.silentOnExtendsFailure = true;
  21826. try {
  21827. switch (node.type) {
  21828. case "TSStringKeyword":
  21829. return ["String"];
  21830. case "TSNumberKeyword":
  21831. return ["Number"];
  21832. case "TSBooleanKeyword":
  21833. return ["Boolean"];
  21834. case "TSObjectKeyword":
  21835. return ["Object"];
  21836. case "TSNullKeyword":
  21837. return ["null"];
  21838. case "TSTypeLiteral":
  21839. case "TSInterfaceDeclaration": {
  21840. const types = /* @__PURE__ */ new Set();
  21841. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  21842. for (const m of members) {
  21843. if (isKeyOf) {
  21844. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  21845. types.add("Number");
  21846. } else if (m.type === "TSIndexSignature") {
  21847. const annotation = m.parameters[0].typeAnnotation;
  21848. if (annotation && annotation.type !== "Noop") {
  21849. const type = inferRuntimeType(
  21850. ctx,
  21851. annotation.typeAnnotation,
  21852. scope
  21853. )[0];
  21854. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  21855. types.add(type);
  21856. }
  21857. } else {
  21858. types.add("String");
  21859. }
  21860. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  21861. types.add("Function");
  21862. } else {
  21863. types.add("Object");
  21864. }
  21865. }
  21866. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  21867. }
  21868. case "TSPropertySignature":
  21869. if (node.typeAnnotation) {
  21870. return inferRuntimeType(
  21871. ctx,
  21872. node.typeAnnotation.typeAnnotation,
  21873. scope
  21874. );
  21875. }
  21876. break;
  21877. case "TSMethodSignature":
  21878. case "TSFunctionType":
  21879. return ["Function"];
  21880. case "TSArrayType":
  21881. case "TSTupleType":
  21882. return ["Array"];
  21883. case "TSLiteralType":
  21884. switch (node.literal.type) {
  21885. case "StringLiteral":
  21886. return ["String"];
  21887. case "BooleanLiteral":
  21888. return ["Boolean"];
  21889. case "NumericLiteral":
  21890. case "BigIntLiteral":
  21891. return ["Number"];
  21892. default:
  21893. return [UNKNOWN_TYPE];
  21894. }
  21895. case "TSTypeReference": {
  21896. let resolved;
  21897. try {
  21898. resolved = resolveTypeReference(ctx, node, scope);
  21899. } catch {
  21900. }
  21901. if (resolved) {
  21902. if (resolved.type === "TSTypeAliasDeclaration") {
  21903. if (resolved.typeAnnotation.type === "TSFunctionType") {
  21904. return ["Function"];
  21905. }
  21906. if (node.typeParameters) {
  21907. const typeParams = /* @__PURE__ */ Object.create(null);
  21908. if (resolved.typeParameters) {
  21909. resolved.typeParameters.params.forEach((p, i) => {
  21910. typeParams[p.name] = node.typeParameters.params[i];
  21911. });
  21912. }
  21913. return inferRuntimeType(
  21914. ctx,
  21915. resolved.typeAnnotation,
  21916. resolved._ownerScope,
  21917. isKeyOf,
  21918. typeParams
  21919. );
  21920. }
  21921. }
  21922. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  21923. }
  21924. if (node.typeName.type === "Identifier") {
  21925. if (typeParameters && typeParameters[node.typeName.name]) {
  21926. return inferRuntimeType(
  21927. ctx,
  21928. typeParameters[node.typeName.name],
  21929. scope,
  21930. isKeyOf,
  21931. typeParameters
  21932. );
  21933. }
  21934. if (isKeyOf) {
  21935. switch (node.typeName.name) {
  21936. case "String":
  21937. case "Array":
  21938. case "ArrayLike":
  21939. case "Parameters":
  21940. case "ConstructorParameters":
  21941. case "ReadonlyArray":
  21942. return ["String", "Number"];
  21943. // TS built-in utility types
  21944. case "Record":
  21945. case "Partial":
  21946. case "Required":
  21947. case "Readonly":
  21948. if (node.typeParameters && node.typeParameters.params[0]) {
  21949. return inferRuntimeType(
  21950. ctx,
  21951. node.typeParameters.params[0],
  21952. scope,
  21953. true
  21954. );
  21955. }
  21956. break;
  21957. case "Pick":
  21958. case "Extract":
  21959. if (node.typeParameters && node.typeParameters.params[1]) {
  21960. return inferRuntimeType(
  21961. ctx,
  21962. node.typeParameters.params[1],
  21963. scope
  21964. );
  21965. }
  21966. break;
  21967. case "Function":
  21968. case "Object":
  21969. case "Set":
  21970. case "Map":
  21971. case "WeakSet":
  21972. case "WeakMap":
  21973. case "Date":
  21974. case "Promise":
  21975. case "Error":
  21976. case "Uppercase":
  21977. case "Lowercase":
  21978. case "Capitalize":
  21979. case "Uncapitalize":
  21980. case "ReadonlyMap":
  21981. case "ReadonlySet":
  21982. return ["String"];
  21983. }
  21984. } else {
  21985. switch (node.typeName.name) {
  21986. case "Array":
  21987. case "Function":
  21988. case "Object":
  21989. case "Set":
  21990. case "Map":
  21991. case "WeakSet":
  21992. case "WeakMap":
  21993. case "Date":
  21994. case "Promise":
  21995. case "Error":
  21996. return [node.typeName.name];
  21997. // TS built-in utility types
  21998. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  21999. case "Partial":
  22000. case "Required":
  22001. case "Readonly":
  22002. case "Record":
  22003. case "Pick":
  22004. case "Omit":
  22005. case "InstanceType":
  22006. return ["Object"];
  22007. case "Uppercase":
  22008. case "Lowercase":
  22009. case "Capitalize":
  22010. case "Uncapitalize":
  22011. return ["String"];
  22012. case "Parameters":
  22013. case "ConstructorParameters":
  22014. case "ReadonlyArray":
  22015. return ["Array"];
  22016. case "ReadonlyMap":
  22017. return ["Map"];
  22018. case "ReadonlySet":
  22019. return ["Set"];
  22020. // Vue ref wrapper types — handled here so that runtime type
  22021. // inference still works when `vue` types cannot be resolved
  22022. // (e.g. consumed as built artifacts in another package). #14729
  22023. case "Ref":
  22024. case "ShallowRef":
  22025. case "ComputedRef":
  22026. case "WritableComputedRef":
  22027. return ["Object"];
  22028. case "MaybeRef":
  22029. case "MaybeRefOrGetter": {
  22030. const types = /* @__PURE__ */ new Set(["Object"]);
  22031. if (node.typeName.name === "MaybeRefOrGetter") {
  22032. types.add("Function");
  22033. }
  22034. if (node.typeParameters && node.typeParameters.params[0]) {
  22035. for (const t of inferRuntimeType(
  22036. ctx,
  22037. node.typeParameters.params[0],
  22038. scope,
  22039. false,
  22040. typeParameters
  22041. )) {
  22042. types.add(t);
  22043. }
  22044. }
  22045. return Array.from(types);
  22046. }
  22047. case "NonNullable":
  22048. if (node.typeParameters && node.typeParameters.params[0]) {
  22049. return inferRuntimeType(
  22050. ctx,
  22051. node.typeParameters.params[0],
  22052. scope
  22053. ).filter((t) => t !== "null");
  22054. }
  22055. break;
  22056. case "Extract":
  22057. if (node.typeParameters && node.typeParameters.params[1]) {
  22058. return inferRuntimeType(
  22059. ctx,
  22060. node.typeParameters.params[1],
  22061. scope
  22062. );
  22063. }
  22064. break;
  22065. case "Exclude":
  22066. case "OmitThisParameter":
  22067. if (node.typeParameters && node.typeParameters.params[0]) {
  22068. return inferRuntimeType(
  22069. ctx,
  22070. node.typeParameters.params[0],
  22071. scope
  22072. );
  22073. }
  22074. break;
  22075. }
  22076. }
  22077. }
  22078. break;
  22079. }
  22080. case "TSParenthesizedType":
  22081. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  22082. case "TSUnionType":
  22083. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  22084. case "TSIntersectionType": {
  22085. return flattenTypes(
  22086. ctx,
  22087. node.types,
  22088. scope,
  22089. isKeyOf,
  22090. typeParameters
  22091. ).filter((t) => t !== UNKNOWN_TYPE);
  22092. }
  22093. case "TSMappedType": {
  22094. const { typeAnnotation, typeParameter } = node;
  22095. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  22096. const constraint = typeParameter.constraint;
  22097. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  22098. const typeName = constraint.typeAnnotation.typeName.name;
  22099. const index = typeAnnotation.indexType;
  22100. const obj = typeAnnotation.objectType;
  22101. if (obj && obj.type === "TSTypeReference" && obj.typeName.type === "Identifier" && obj.typeName.name === typeName && index && index.type === "TSTypeReference" && index.typeName.type === "Identifier" && index.typeName.name === typeParameter.name) {
  22102. const targetType = typeParameters[typeName];
  22103. if (targetType) {
  22104. return inferRuntimeType(ctx, targetType, scope);
  22105. }
  22106. }
  22107. }
  22108. }
  22109. return [UNKNOWN_TYPE];
  22110. }
  22111. case "TSEnumDeclaration":
  22112. return inferEnumType(node);
  22113. case "TSSymbolKeyword":
  22114. return ["Symbol"];
  22115. case "TSIndexedAccessType": {
  22116. const types = resolveIndexType(ctx, node, scope);
  22117. return flattenTypes(ctx, types, scope, isKeyOf);
  22118. }
  22119. case "ClassDeclaration":
  22120. return ["Object"];
  22121. case "TSImportType": {
  22122. const sourceScope = importSourceToScope(
  22123. ctx,
  22124. node.argument,
  22125. scope,
  22126. node.argument.value
  22127. );
  22128. const resolved = resolveTypeReference(ctx, node, sourceScope);
  22129. if (resolved) {
  22130. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  22131. }
  22132. break;
  22133. }
  22134. case "TSTypeQuery": {
  22135. const id = node.exprName;
  22136. if (id.type === "Identifier") {
  22137. const matched = scope.declares[id.name];
  22138. if (matched) {
  22139. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  22140. }
  22141. }
  22142. break;
  22143. }
  22144. // e.g. readonly
  22145. case "TSTypeOperator": {
  22146. return inferRuntimeType(
  22147. ctx,
  22148. node.typeAnnotation,
  22149. scope,
  22150. node.operator === "keyof"
  22151. );
  22152. }
  22153. case "TSAnyKeyword": {
  22154. if (isKeyOf) {
  22155. return ["String", "Number", "Symbol"];
  22156. }
  22157. break;
  22158. }
  22159. }
  22160. } catch (e) {
  22161. } finally {
  22162. ctx.silentOnExtendsFailure = prevSilent;
  22163. }
  22164. return [UNKNOWN_TYPE];
  22165. }
  22166. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  22167. if (types.length === 1) {
  22168. return inferRuntimeType(
  22169. ctx,
  22170. types[0],
  22171. types[0]._ownerScope || scope,
  22172. isKeyOf,
  22173. typeParameters
  22174. );
  22175. }
  22176. return [
  22177. ...new Set(
  22178. [].concat(
  22179. ...types.map(
  22180. (t) => inferRuntimeType(
  22181. ctx,
  22182. t,
  22183. t._ownerScope || scope,
  22184. isKeyOf,
  22185. typeParameters
  22186. )
  22187. )
  22188. )
  22189. )
  22190. ];
  22191. }
  22192. function inferEnumType(node) {
  22193. const types = /* @__PURE__ */ new Set();
  22194. for (const m of node.members) {
  22195. if (m.initializer) {
  22196. switch (m.initializer.type) {
  22197. case "StringLiteral":
  22198. types.add("String");
  22199. break;
  22200. case "NumericLiteral":
  22201. types.add("Number");
  22202. break;
  22203. }
  22204. }
  22205. }
  22206. return types.size ? [...types] : ["Number"];
  22207. }
  22208. function resolveExtractPropTypes({ props }, scope) {
  22209. const res = { props: {} };
  22210. for (const key in props) {
  22211. const raw = props[key];
  22212. res.props[key] = reverseInferType(
  22213. raw.key,
  22214. raw.typeAnnotation.typeAnnotation,
  22215. scope
  22216. );
  22217. }
  22218. return res;
  22219. }
  22220. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  22221. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  22222. const typeType = findStaticPropertyType(node, "type");
  22223. if (typeType) {
  22224. const requiredType = findStaticPropertyType(node, "required");
  22225. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  22226. return reverseInferType(key, typeType, scope, optional2, false);
  22227. }
  22228. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  22229. if (node.typeName.name.endsWith("Constructor")) {
  22230. return createProperty(
  22231. key,
  22232. ctorToType(node.typeName.name),
  22233. scope,
  22234. optional
  22235. );
  22236. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  22237. return createProperty(key, node.typeParameters.params[0], scope, optional);
  22238. }
  22239. }
  22240. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  22241. for (const t of node.typeParameters.params) {
  22242. const inferred = reverseInferType(key, t, scope, optional);
  22243. if (inferred) return inferred;
  22244. }
  22245. }
  22246. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  22247. }
  22248. function ctorToType(ctorType) {
  22249. const ctor = ctorType.slice(0, -11);
  22250. switch (ctor) {
  22251. case "String":
  22252. case "Number":
  22253. case "Boolean":
  22254. return { type: `TS${ctor}Keyword` };
  22255. case "Array":
  22256. case "Function":
  22257. case "Object":
  22258. case "Set":
  22259. case "Map":
  22260. case "WeakSet":
  22261. case "WeakMap":
  22262. case "Date":
  22263. case "Promise":
  22264. return {
  22265. type: "TSTypeReference",
  22266. typeName: { type: "Identifier", name: ctor }
  22267. };
  22268. }
  22269. return { type: `TSNullKeyword` };
  22270. }
  22271. function findStaticPropertyType(node, key) {
  22272. const prop = node.members.find(
  22273. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  22274. );
  22275. return prop && prop.typeAnnotation.typeAnnotation;
  22276. }
  22277. function resolveReturnType(ctx, arg, scope) {
  22278. var _a;
  22279. let resolved = arg;
  22280. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  22281. resolved = resolveTypeReference(ctx, arg, scope);
  22282. }
  22283. if (!resolved) return;
  22284. if (resolved.type === "TSFunctionType") {
  22285. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  22286. }
  22287. if (resolved.type === "TSDeclareFunction") {
  22288. return resolved.returnType;
  22289. }
  22290. }
  22291. function resolveUnionType(ctx, node, scope) {
  22292. if (node.type === "TSTypeReference") {
  22293. const resolved = resolveTypeReference(ctx, node, scope);
  22294. if (resolved) node = resolved;
  22295. }
  22296. let types;
  22297. if (node.type === "TSUnionType") {
  22298. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  22299. } else {
  22300. types = [node];
  22301. }
  22302. return types;
  22303. }
  22304. const DEFINE_MODEL = "defineModel";
  22305. function processDefineModel(ctx, node, declId) {
  22306. if (!isCallOf(node, DEFINE_MODEL)) {
  22307. return false;
  22308. }
  22309. ctx.hasDefineModelCall = true;
  22310. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  22311. let modelName;
  22312. let options;
  22313. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  22314. const hasName = arg0 && (arg0.type === "StringLiteral" || arg0.type === "TemplateLiteral" && arg0.expressions.length === 0);
  22315. if (hasName) {
  22316. modelName = arg0.type === "StringLiteral" ? arg0.value : arg0.quasis[0].value.cooked;
  22317. options = node.arguments[1];
  22318. } else {
  22319. modelName = "modelValue";
  22320. options = arg0;
  22321. }
  22322. if (ctx.modelDecls[modelName]) {
  22323. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  22324. }
  22325. let optionsString = options && ctx.getString(options);
  22326. let optionsRemoved = !options;
  22327. const runtimeOptionNodes = [];
  22328. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  22329. let removed = 0;
  22330. for (let i = options.properties.length - 1; i >= 0; i--) {
  22331. const p = options.properties[i];
  22332. const next = options.properties[i + 1];
  22333. const start = p.start;
  22334. const end = next ? next.start : options.end - 1;
  22335. 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"))) {
  22336. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  22337. } else {
  22338. removed++;
  22339. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  22340. runtimeOptionNodes.push(p);
  22341. }
  22342. }
  22343. if (removed === options.properties.length) {
  22344. optionsRemoved = true;
  22345. ctx.s.remove(
  22346. ctx.startOffset + (hasName ? arg0.end : options.start),
  22347. ctx.startOffset + options.end
  22348. );
  22349. }
  22350. }
  22351. ctx.modelDecls[modelName] = {
  22352. type,
  22353. options: optionsString,
  22354. runtimeOptionNodes,
  22355. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  22356. };
  22357. ctx.bindingMetadata[modelName] = "props";
  22358. ctx.s.overwrite(
  22359. ctx.startOffset + node.callee.start,
  22360. ctx.startOffset + node.callee.end,
  22361. ctx.helper("useModel")
  22362. );
  22363. ctx.s.appendLeft(
  22364. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  22365. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  22366. );
  22367. return true;
  22368. }
  22369. function genModelProps(ctx) {
  22370. if (!ctx.hasDefineModelCall) return;
  22371. const isProd = !!ctx.options.isProd;
  22372. let modelPropsDecl = "";
  22373. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  22374. ctx.modelDecls
  22375. )) {
  22376. let skipCheck = false;
  22377. let codegenOptions = ``;
  22378. let runtimeTypes = type && inferRuntimeType(ctx, type);
  22379. if (runtimeTypes) {
  22380. const hasBoolean = runtimeTypes.includes("Boolean");
  22381. const hasFunction = runtimeTypes.includes("Function");
  22382. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  22383. if (hasUnknownType) {
  22384. if (hasBoolean || hasFunction) {
  22385. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  22386. skipCheck = true;
  22387. } else {
  22388. runtimeTypes = ["null"];
  22389. }
  22390. }
  22391. if (!isProd) {
  22392. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  22393. } else if (hasBoolean || runtimeOptions && hasFunction) {
  22394. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  22395. } else ;
  22396. }
  22397. let decl;
  22398. if (codegenOptions && runtimeOptions) {
  22399. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  22400. } else if (codegenOptions) {
  22401. decl = `{ ${codegenOptions} }`;
  22402. } else if (runtimeOptions) {
  22403. decl = runtimeOptions;
  22404. } else {
  22405. decl = `{}`;
  22406. }
  22407. modelPropsDecl += `
  22408. ${JSON.stringify(name)}: ${decl},`;
  22409. const modifierPropName = JSON.stringify(
  22410. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  22411. );
  22412. modelPropsDecl += `
  22413. ${modifierPropName}: {},`;
  22414. }
  22415. return `{${modelPropsDecl}
  22416. }`;
  22417. }
  22418. const DEFINE_PROPS = "defineProps";
  22419. const WITH_DEFAULTS = "withDefaults";
  22420. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  22421. if (!isCallOf(node, DEFINE_PROPS)) {
  22422. return processWithDefaults(ctx, node, declId);
  22423. }
  22424. if (ctx.hasDefinePropsCall) {
  22425. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  22426. }
  22427. ctx.hasDefinePropsCall = true;
  22428. ctx.propsRuntimeDecl = node.arguments[0];
  22429. if (ctx.propsRuntimeDecl) {
  22430. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  22431. if (!(key in ctx.bindingMetadata)) {
  22432. ctx.bindingMetadata[key] = "props";
  22433. }
  22434. }
  22435. }
  22436. if (node.typeParameters) {
  22437. if (ctx.propsRuntimeDecl) {
  22438. ctx.error(
  22439. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22440. node
  22441. );
  22442. }
  22443. ctx.propsTypeDecl = node.typeParameters.params[0];
  22444. }
  22445. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  22446. processPropsDestructure(ctx, declId);
  22447. }
  22448. ctx.propsCall = node;
  22449. ctx.propsDecl = declId;
  22450. return true;
  22451. }
  22452. function processWithDefaults(ctx, node, declId) {
  22453. if (!isCallOf(node, WITH_DEFAULTS)) {
  22454. return false;
  22455. }
  22456. if (!processDefineProps(
  22457. ctx,
  22458. node.arguments[0],
  22459. declId,
  22460. true
  22461. )) {
  22462. ctx.error(
  22463. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  22464. node.arguments[0] || node
  22465. );
  22466. }
  22467. if (ctx.propsRuntimeDecl) {
  22468. ctx.error(
  22469. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  22470. node
  22471. );
  22472. }
  22473. if (declId && declId.type === "ObjectPattern") {
  22474. ctx.warn(
  22475. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  22476. Reactive destructure will be disabled when using withDefaults().
  22477. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  22478. node.callee
  22479. );
  22480. }
  22481. ctx.propsRuntimeDefaults = node.arguments[1];
  22482. if (!ctx.propsRuntimeDefaults) {
  22483. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  22484. }
  22485. ctx.propsCall = node;
  22486. return true;
  22487. }
  22488. function genRuntimeProps(ctx) {
  22489. let propsDecls;
  22490. if (ctx.propsRuntimeDecl) {
  22491. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  22492. if (ctx.propsDestructureDecl) {
  22493. const defaults = [];
  22494. for (const key in ctx.propsDestructuredBindings) {
  22495. const d = genDestructuredDefaultValue(ctx, key);
  22496. const finalKey = getEscapedPropName(key);
  22497. if (d)
  22498. defaults.push(
  22499. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  22500. );
  22501. }
  22502. if (defaults.length) {
  22503. propsDecls = `/*@__PURE__*/${ctx.helper(
  22504. `mergeDefaults`
  22505. )}(${propsDecls}, {
  22506. ${defaults.join(",\n ")}
  22507. })`;
  22508. }
  22509. }
  22510. } else if (ctx.propsTypeDecl) {
  22511. propsDecls = extractRuntimeProps(ctx);
  22512. }
  22513. const modelsDecls = genModelProps(ctx);
  22514. if (propsDecls && modelsDecls) {
  22515. return `/*@__PURE__*/${ctx.helper(
  22516. "mergeModels"
  22517. )}(${propsDecls}, ${modelsDecls})`;
  22518. } else {
  22519. return modelsDecls || propsDecls;
  22520. }
  22521. }
  22522. function extractRuntimeProps(ctx) {
  22523. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  22524. if (!props.length) {
  22525. return;
  22526. }
  22527. const propStrings = [];
  22528. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  22529. for (const prop of props) {
  22530. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  22531. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  22532. ctx.bindingMetadata[prop.key] = "props";
  22533. }
  22534. }
  22535. let propsDecls = `{
  22536. ${propStrings.join(",\n ")}
  22537. }`;
  22538. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  22539. propsDecls = `/*@__PURE__*/${ctx.helper(
  22540. "mergeDefaults"
  22541. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  22542. }
  22543. return propsDecls;
  22544. }
  22545. function resolveRuntimePropsFromType(ctx, node) {
  22546. const props = [];
  22547. const elements = resolveTypeElements(ctx, node);
  22548. for (const key in elements.props) {
  22549. const e = elements.props[key];
  22550. let type = inferRuntimeType(ctx, e);
  22551. let skipCheck = false;
  22552. if (type.includes(UNKNOWN_TYPE)) {
  22553. if (type.includes("Boolean") || type.includes("Function")) {
  22554. type = type.filter((t) => t !== UNKNOWN_TYPE);
  22555. skipCheck = true;
  22556. } else {
  22557. type = ["null"];
  22558. }
  22559. }
  22560. props.push({
  22561. key,
  22562. required: !e.optional,
  22563. type: type || [`null`],
  22564. skipCheck
  22565. });
  22566. }
  22567. return props;
  22568. }
  22569. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  22570. let defaultString;
  22571. const destructured = genDestructuredDefaultValue(ctx, key, type);
  22572. if (destructured) {
  22573. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  22574. } else if (hasStaticDefaults) {
  22575. const prop = ctx.propsRuntimeDefaults.properties.find(
  22576. (node) => {
  22577. if (node.type === "SpreadElement") return false;
  22578. return resolveObjectKey(node.key, node.computed) === key;
  22579. }
  22580. );
  22581. if (prop) {
  22582. if (prop.type === "ObjectProperty") {
  22583. defaultString = `default: ${ctx.getString(prop.value)}`;
  22584. } else {
  22585. let paramsString = "";
  22586. if (prop.params.length) {
  22587. const start = prop.params[0].start;
  22588. const end = prop.params[prop.params.length - 1].end;
  22589. paramsString = ctx.getString({ start, end });
  22590. }
  22591. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default(${paramsString}) ${ctx.getString(prop.body)}`;
  22592. }
  22593. }
  22594. }
  22595. const finalKey = getEscapedPropName(key);
  22596. if (!ctx.options.isProd) {
  22597. return `${finalKey}: { ${concatStrings([
  22598. `type: ${toRuntimeTypeString(type)}`,
  22599. `required: ${required}`,
  22600. skipCheck && "skipCheck: true",
  22601. defaultString
  22602. ])} }`;
  22603. } else if (type.some(
  22604. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  22605. )) {
  22606. return `${finalKey}: { ${concatStrings([
  22607. `type: ${toRuntimeTypeString(type)}`,
  22608. defaultString
  22609. ])} }`;
  22610. } else {
  22611. if (ctx.isCE) {
  22612. if (defaultString) {
  22613. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  22614. type
  22615. )} }`}`;
  22616. } else {
  22617. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  22618. }
  22619. }
  22620. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  22621. }
  22622. }
  22623. function hasStaticWithDefaults(ctx) {
  22624. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  22625. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  22626. ));
  22627. }
  22628. function genDestructuredDefaultValue(ctx, key, inferredType) {
  22629. const destructured = ctx.propsDestructuredBindings[key];
  22630. const defaultVal = destructured && destructured.default;
  22631. if (defaultVal) {
  22632. const value = ctx.getString(defaultVal);
  22633. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  22634. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  22635. const valueType = inferValueType(unwrapped);
  22636. if (valueType && !inferredType.includes(valueType)) {
  22637. ctx.error(
  22638. `Default value of prop "${key}" does not match declared type.`,
  22639. unwrapped
  22640. );
  22641. }
  22642. }
  22643. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  22644. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  22645. return {
  22646. valueString: needFactoryWrap ? `() => (${value})` : value,
  22647. needSkipFactory
  22648. };
  22649. }
  22650. }
  22651. function inferValueType(node) {
  22652. switch (node.type) {
  22653. case "StringLiteral":
  22654. return "String";
  22655. case "NumericLiteral":
  22656. return "Number";
  22657. case "BooleanLiteral":
  22658. return "Boolean";
  22659. case "ObjectExpression":
  22660. return "Object";
  22661. case "ArrayExpression":
  22662. return "Array";
  22663. case "FunctionExpression":
  22664. case "ArrowFunctionExpression":
  22665. return "Function";
  22666. }
  22667. }
  22668. function processPropsDestructure(ctx, declId) {
  22669. if (ctx.options.propsDestructure === "error") {
  22670. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  22671. } else if (ctx.options.propsDestructure === false) {
  22672. return;
  22673. }
  22674. ctx.propsDestructureDecl = declId;
  22675. const registerBinding = (key, local, defaultValue) => {
  22676. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  22677. if (local !== key) {
  22678. ctx.bindingMetadata[local] = "props-aliased";
  22679. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  22680. }
  22681. };
  22682. for (const prop of declId.properties) {
  22683. if (prop.type === "ObjectProperty") {
  22684. const propKey = resolveObjectKey(prop.key, prop.computed);
  22685. if (!propKey) {
  22686. ctx.error(
  22687. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  22688. prop.key
  22689. );
  22690. }
  22691. if (prop.value.type === "AssignmentPattern") {
  22692. const { left, right } = prop.value;
  22693. if (left.type !== "Identifier") {
  22694. ctx.error(
  22695. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22696. left
  22697. );
  22698. }
  22699. registerBinding(propKey, left.name, right);
  22700. } else if (prop.value.type === "Identifier") {
  22701. registerBinding(propKey, prop.value.name);
  22702. } else {
  22703. ctx.error(
  22704. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22705. prop.value
  22706. );
  22707. }
  22708. } else {
  22709. ctx.propsDestructureRestId = prop.argument.name;
  22710. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  22711. }
  22712. }
  22713. }
  22714. function transformDestructuredProps(ctx, vueImportAliases) {
  22715. if (ctx.options.propsDestructure === false) {
  22716. return;
  22717. }
  22718. const rootScope = /* @__PURE__ */ Object.create(null);
  22719. const scopeStack = [rootScope];
  22720. let currentScope = rootScope;
  22721. const excludedIds = /* @__PURE__ */ new WeakSet();
  22722. const parentStack = [];
  22723. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  22724. for (const key in ctx.propsDestructuredBindings) {
  22725. const { local } = ctx.propsDestructuredBindings[key];
  22726. rootScope[local] = true;
  22727. propsLocalToPublicMap[local] = key;
  22728. }
  22729. function pushScope() {
  22730. scopeStack.push(currentScope = Object.create(currentScope));
  22731. }
  22732. function popScope() {
  22733. scopeStack.pop();
  22734. currentScope = scopeStack[scopeStack.length - 1] || null;
  22735. }
  22736. function registerLocalBinding(id) {
  22737. excludedIds.add(id);
  22738. if (currentScope) {
  22739. currentScope[id.name] = false;
  22740. } else {
  22741. ctx.error(
  22742. "registerBinding called without active scope, something is wrong.",
  22743. id
  22744. );
  22745. }
  22746. }
  22747. function walkScope(node, isRoot = false) {
  22748. for (const stmt of node.body) {
  22749. if (stmt.type === "VariableDeclaration") {
  22750. walkVariableDeclaration(stmt, isRoot);
  22751. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  22752. if (stmt.declare || !stmt.id) continue;
  22753. registerLocalBinding(stmt.id);
  22754. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  22755. walkVariableDeclaration(stmt.declaration, isRoot);
  22756. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  22757. walkVariableDeclaration(stmt.body, isRoot);
  22758. }
  22759. }
  22760. }
  22761. function walkVariableDeclaration(stmt, isRoot = false) {
  22762. if (stmt.declare) {
  22763. return;
  22764. }
  22765. for (const decl of stmt.declarations) {
  22766. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  22767. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  22768. if (isDefineProps) {
  22769. excludedIds.add(id);
  22770. } else {
  22771. registerLocalBinding(id);
  22772. }
  22773. }
  22774. }
  22775. }
  22776. function rewriteId(id, parent, parentStack2) {
  22777. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  22778. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  22779. }
  22780. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  22781. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  22782. ctx.s.appendLeft(
  22783. id.end + ctx.startOffset,
  22784. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  22785. );
  22786. }
  22787. } else {
  22788. ctx.s.overwrite(
  22789. id.start + ctx.startOffset,
  22790. id.end + ctx.startOffset,
  22791. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  22792. );
  22793. }
  22794. }
  22795. function checkUsage(node, method, alias = method) {
  22796. if (isCallOf(node, alias)) {
  22797. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22798. if (arg.type === "Identifier" && currentScope[arg.name]) {
  22799. ctx.error(
  22800. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  22801. arg
  22802. );
  22803. }
  22804. }
  22805. }
  22806. const ast = ctx.scriptSetupAst;
  22807. walkScope(ast, true);
  22808. estreeWalker.walk(ast, {
  22809. enter(node, parent) {
  22810. parent && parentStack.push(parent);
  22811. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22812. return this.skip();
  22813. }
  22814. checkUsage(node, "watch", vueImportAliases.watch);
  22815. checkUsage(node, "toRef", vueImportAliases.toRef);
  22816. if (CompilerDOM.isFunctionType(node)) {
  22817. pushScope();
  22818. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  22819. if (node.body.type === "BlockStatement") {
  22820. walkScope(node.body);
  22821. }
  22822. return;
  22823. }
  22824. if (node.type === "CatchClause") {
  22825. pushScope();
  22826. if (node.param && node.param.type === "Identifier") {
  22827. registerLocalBinding(node.param);
  22828. }
  22829. walkScope(node.body);
  22830. return;
  22831. }
  22832. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22833. pushScope();
  22834. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  22835. if (varDecl && varDecl.type === "VariableDeclaration") {
  22836. walkVariableDeclaration(varDecl);
  22837. }
  22838. if (node.body.type === "BlockStatement") {
  22839. walkScope(node.body);
  22840. }
  22841. return;
  22842. }
  22843. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22844. pushScope();
  22845. walkScope(node);
  22846. return;
  22847. }
  22848. if (node.type === "Identifier") {
  22849. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  22850. if (currentScope[node.name]) {
  22851. rewriteId(node, parent, parentStack);
  22852. }
  22853. }
  22854. }
  22855. },
  22856. leave(node, parent) {
  22857. parent && parentStack.pop();
  22858. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node) || node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22859. popScope();
  22860. }
  22861. }
  22862. });
  22863. }
  22864. const DEFINE_EMITS = "defineEmits";
  22865. function processDefineEmits(ctx, node, declId) {
  22866. if (!isCallOf(node, DEFINE_EMITS)) {
  22867. return false;
  22868. }
  22869. if (ctx.hasDefineEmitCall) {
  22870. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  22871. }
  22872. ctx.hasDefineEmitCall = true;
  22873. ctx.emitsRuntimeDecl = node.arguments[0];
  22874. if (node.typeParameters) {
  22875. if (ctx.emitsRuntimeDecl) {
  22876. ctx.error(
  22877. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22878. node
  22879. );
  22880. }
  22881. ctx.emitsTypeDecl = node.typeParameters.params[0];
  22882. }
  22883. ctx.emitDecl = declId;
  22884. return true;
  22885. }
  22886. function genRuntimeEmits(ctx) {
  22887. let emitsDecl = "";
  22888. if (ctx.emitsRuntimeDecl) {
  22889. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  22890. } else if (ctx.emitsTypeDecl) {
  22891. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  22892. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  22893. }
  22894. if (ctx.hasDefineModelCall) {
  22895. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  22896. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  22897. "mergeModels"
  22898. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  22899. }
  22900. return emitsDecl;
  22901. }
  22902. function extractRuntimeEmits(ctx) {
  22903. const emits = /* @__PURE__ */ new Set();
  22904. const node = ctx.emitsTypeDecl;
  22905. if (node.type === "TSFunctionType") {
  22906. extractEventNames(ctx, node.parameters[0], emits);
  22907. return emits;
  22908. }
  22909. const { props, calls } = resolveTypeElements(ctx, node);
  22910. let hasProperty = false;
  22911. for (const key in props) {
  22912. emits.add(key);
  22913. hasProperty = true;
  22914. }
  22915. if (calls) {
  22916. if (hasProperty) {
  22917. ctx.error(
  22918. `defineEmits() type cannot mixed call signature and property syntax.`,
  22919. node
  22920. );
  22921. }
  22922. for (const call of calls) {
  22923. extractEventNames(ctx, call.parameters[0], emits);
  22924. }
  22925. }
  22926. return emits;
  22927. }
  22928. function extractEventNames(ctx, eventName, emits) {
  22929. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  22930. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  22931. for (const type of types) {
  22932. if (type.type === "TSLiteralType") {
  22933. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  22934. emits.add(String(type.literal.value));
  22935. }
  22936. }
  22937. }
  22938. }
  22939. }
  22940. const DEFINE_EXPOSE = "defineExpose";
  22941. function processDefineExpose(ctx, node) {
  22942. if (isCallOf(node, DEFINE_EXPOSE)) {
  22943. if (ctx.hasDefineExposeCall) {
  22944. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  22945. }
  22946. ctx.hasDefineExposeCall = true;
  22947. return true;
  22948. }
  22949. return false;
  22950. }
  22951. const DEFINE_SLOTS = "defineSlots";
  22952. function processDefineSlots(ctx, node, declId) {
  22953. if (!isCallOf(node, DEFINE_SLOTS)) {
  22954. return false;
  22955. }
  22956. if (ctx.hasDefineSlotsCall) {
  22957. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  22958. }
  22959. ctx.hasDefineSlotsCall = true;
  22960. if (node.arguments.length > 0) {
  22961. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  22962. }
  22963. if (declId) {
  22964. ctx.s.overwrite(
  22965. ctx.startOffset + node.start,
  22966. ctx.startOffset + node.end,
  22967. `${ctx.helper("useSlots")}()`
  22968. );
  22969. }
  22970. return true;
  22971. }
  22972. const DEFINE_OPTIONS = "defineOptions";
  22973. function processDefineOptions(ctx, node) {
  22974. if (!isCallOf(node, DEFINE_OPTIONS)) {
  22975. return false;
  22976. }
  22977. if (ctx.hasDefineOptionsCall) {
  22978. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  22979. }
  22980. if (node.typeParameters) {
  22981. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  22982. }
  22983. if (!node.arguments[0]) return true;
  22984. ctx.hasDefineOptionsCall = true;
  22985. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22986. let propsOption = void 0;
  22987. let emitsOption = void 0;
  22988. let exposeOption = void 0;
  22989. let slotsOption = void 0;
  22990. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  22991. for (const prop of ctx.optionsRuntimeDecl.properties) {
  22992. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  22993. switch (prop.key.name) {
  22994. case "props":
  22995. propsOption = prop;
  22996. break;
  22997. case "emits":
  22998. emitsOption = prop;
  22999. break;
  23000. case "expose":
  23001. exposeOption = prop;
  23002. break;
  23003. case "slots":
  23004. slotsOption = prop;
  23005. break;
  23006. }
  23007. }
  23008. }
  23009. }
  23010. if (propsOption) {
  23011. ctx.error(
  23012. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  23013. propsOption
  23014. );
  23015. }
  23016. if (emitsOption) {
  23017. ctx.error(
  23018. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  23019. emitsOption
  23020. );
  23021. }
  23022. if (exposeOption) {
  23023. ctx.error(
  23024. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  23025. exposeOption
  23026. );
  23027. }
  23028. if (slotsOption) {
  23029. ctx.error(
  23030. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  23031. slotsOption
  23032. );
  23033. }
  23034. return true;
  23035. }
  23036. function processAwait(ctx, node, needSemi, isStatement) {
  23037. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  23038. const startOffset = ctx.startOffset;
  23039. const argumentStr = ctx.descriptor.source.slice(
  23040. argumentStart + startOffset,
  23041. node.argument.end + startOffset
  23042. );
  23043. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  23044. ctx.s.overwrite(
  23045. node.start + startOffset,
  23046. argumentStart + startOffset,
  23047. `${needSemi ? `;` : ``}(
  23048. ([__temp,__restore] = ${ctx.helper(
  23049. `withAsyncContext`
  23050. )}(${containsNestedAwait ? `async ` : ``}() => `
  23051. );
  23052. ctx.s.appendLeft(
  23053. node.end + startOffset,
  23054. `)),
  23055. ${isStatement ? `` : `__temp = `}await __temp,
  23056. __restore()${isStatement ? `` : `,
  23057. __temp`}
  23058. )`
  23059. );
  23060. }
  23061. const MACROS = [
  23062. DEFINE_PROPS,
  23063. DEFINE_EMITS,
  23064. DEFINE_EXPOSE,
  23065. DEFINE_OPTIONS,
  23066. DEFINE_SLOTS,
  23067. DEFINE_MODEL,
  23068. WITH_DEFAULTS
  23069. ];
  23070. function compileScript(sfc, options) {
  23071. var _a, _b, _c;
  23072. if (!options.id) {
  23073. warnOnce(
  23074. `compileScript now requires passing the \`id\` option.
  23075. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  23076. );
  23077. }
  23078. const { script, scriptSetup, source, filename } = sfc;
  23079. const hoistStatic = options.hoistStatic !== false && !script;
  23080. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  23081. const scriptLang = script && script.lang;
  23082. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  23083. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  23084. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  23085. throw new Error(
  23086. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  23087. );
  23088. }
  23089. if (!scriptSetup) {
  23090. if (!script) {
  23091. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  23092. }
  23093. if (script.lang && !isJSOrTS) {
  23094. return script;
  23095. }
  23096. const ctx2 = new ScriptCompileContext(sfc, options);
  23097. return processNormalScript(ctx2, scopeId);
  23098. }
  23099. if (scriptSetupLang && !isJSOrTS) {
  23100. return scriptSetup;
  23101. }
  23102. const ctx = new ScriptCompileContext(sfc, options);
  23103. const scriptBindings = /* @__PURE__ */ Object.create(null);
  23104. const setupBindings = /* @__PURE__ */ Object.create(null);
  23105. let defaultExport;
  23106. let hasAwait = false;
  23107. let hasInlinedSsrRenderFn = false;
  23108. const startOffset = ctx.startOffset;
  23109. const endOffset = ctx.endOffset;
  23110. const scriptStartOffset = script && script.loc.start.offset;
  23111. const scriptEndOffset = script && script.loc.end.offset;
  23112. function hoistNode(node) {
  23113. const start = node.start + startOffset;
  23114. let end = node.end + startOffset;
  23115. if (node.trailingComments && node.trailingComments.length > 0) {
  23116. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  23117. end = lastCommentNode.end + startOffset;
  23118. }
  23119. while (end <= source.length) {
  23120. if (!/\s/.test(source.charAt(end))) {
  23121. break;
  23122. }
  23123. end++;
  23124. }
  23125. ctx.s.move(start, end, 0);
  23126. }
  23127. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  23128. let isUsedInTemplate = needTemplateUsageCheck;
  23129. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  23130. isUsedInTemplate = isImportUsed(local, sfc);
  23131. }
  23132. ctx.userImports[local] = {
  23133. isType,
  23134. imported,
  23135. local,
  23136. source: source2,
  23137. isFromSetup,
  23138. isUsedInTemplate
  23139. };
  23140. }
  23141. function checkInvalidScopeReference(node, method) {
  23142. if (!node) return;
  23143. CompilerDOM.walkIdentifiers(node, (id) => {
  23144. const binding = setupBindings[id.name];
  23145. if (binding && binding !== "literal-const") {
  23146. ctx.error(
  23147. `\`${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.`,
  23148. id
  23149. );
  23150. }
  23151. });
  23152. }
  23153. const scriptAst = ctx.scriptAst;
  23154. const scriptSetupAst = ctx.scriptSetupAst;
  23155. if (scriptAst) {
  23156. for (const node of scriptAst.body) {
  23157. if (node.type === "ImportDeclaration") {
  23158. for (const specifier of node.specifiers) {
  23159. const imported = getImportedName(specifier);
  23160. registerUserImport(
  23161. node.source.value,
  23162. specifier.local.name,
  23163. imported,
  23164. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23165. false,
  23166. !options.inlineTemplate
  23167. );
  23168. }
  23169. }
  23170. }
  23171. }
  23172. for (const node of scriptSetupAst.body) {
  23173. if (node.type === "ImportDeclaration") {
  23174. hoistNode(node);
  23175. let removed = 0;
  23176. const removeSpecifier = (i) => {
  23177. const removeLeft = i > removed;
  23178. removed++;
  23179. const current = node.specifiers[i];
  23180. const next = node.specifiers[i + 1];
  23181. ctx.s.remove(
  23182. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  23183. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  23184. );
  23185. };
  23186. for (let i = 0; i < node.specifiers.length; i++) {
  23187. const specifier = node.specifiers[i];
  23188. const local = specifier.local.name;
  23189. const imported = getImportedName(specifier);
  23190. const source2 = node.source.value;
  23191. const existing = ctx.userImports[local];
  23192. if (source2 === "vue" && MACROS.includes(imported)) {
  23193. if (local === imported) {
  23194. warnOnce(
  23195. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  23196. );
  23197. } else {
  23198. ctx.error(
  23199. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  23200. specifier
  23201. );
  23202. }
  23203. removeSpecifier(i);
  23204. } else if (existing) {
  23205. if (existing.source === source2 && existing.imported === imported) {
  23206. removeSpecifier(i);
  23207. } else {
  23208. ctx.error(
  23209. `different imports aliased to same local name.`,
  23210. specifier
  23211. );
  23212. }
  23213. } else {
  23214. registerUserImport(
  23215. source2,
  23216. local,
  23217. imported,
  23218. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23219. true,
  23220. !options.inlineTemplate
  23221. );
  23222. }
  23223. }
  23224. if (node.specifiers.length && removed === node.specifiers.length) {
  23225. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23226. }
  23227. }
  23228. }
  23229. const vueImportAliases = {};
  23230. for (const key in ctx.userImports) {
  23231. const { source: source2, imported, local } = ctx.userImports[key];
  23232. if (source2 === "vue") vueImportAliases[imported] = local;
  23233. }
  23234. if (script && scriptAst) {
  23235. for (const node of scriptAst.body) {
  23236. if (node.type === "ExportDefaultDeclaration") {
  23237. defaultExport = node;
  23238. let optionProperties;
  23239. if (defaultExport.declaration.type === "ObjectExpression") {
  23240. optionProperties = defaultExport.declaration.properties;
  23241. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  23242. optionProperties = defaultExport.declaration.arguments[0].properties;
  23243. }
  23244. if (optionProperties) {
  23245. for (const p of optionProperties) {
  23246. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  23247. ctx.hasDefaultExportName = true;
  23248. }
  23249. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  23250. ctx.hasDefaultExportRender = true;
  23251. }
  23252. }
  23253. }
  23254. const start = node.start + scriptStartOffset;
  23255. const end = node.declaration.start + scriptStartOffset;
  23256. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  23257. } else if (node.type === "ExportNamedDeclaration") {
  23258. const defaultSpecifier = node.specifiers.find(
  23259. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  23260. );
  23261. if (defaultSpecifier) {
  23262. defaultExport = node;
  23263. if (node.specifiers.length > 1) {
  23264. ctx.s.remove(
  23265. defaultSpecifier.start + scriptStartOffset,
  23266. defaultSpecifier.end + scriptStartOffset
  23267. );
  23268. } else {
  23269. ctx.s.remove(
  23270. node.start + scriptStartOffset,
  23271. node.end + scriptStartOffset
  23272. );
  23273. }
  23274. if (node.source) {
  23275. ctx.s.prepend(
  23276. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  23277. `
  23278. );
  23279. } else {
  23280. ctx.s.appendLeft(
  23281. scriptEndOffset,
  23282. `
  23283. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  23284. `
  23285. );
  23286. }
  23287. }
  23288. if (node.declaration) {
  23289. walkDeclaration(
  23290. "script",
  23291. node.declaration,
  23292. scriptBindings,
  23293. vueImportAliases,
  23294. hoistStatic
  23295. );
  23296. }
  23297. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23298. walkDeclaration(
  23299. "script",
  23300. node,
  23301. scriptBindings,
  23302. vueImportAliases,
  23303. hoistStatic
  23304. );
  23305. }
  23306. }
  23307. if (scriptStartOffset > startOffset) {
  23308. if (!/\n$/.test(script.content.trim())) {
  23309. ctx.s.appendLeft(scriptEndOffset, `
  23310. `);
  23311. }
  23312. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  23313. }
  23314. }
  23315. for (const node of scriptSetupAst.body) {
  23316. if (node.type === "ExpressionStatement") {
  23317. const expr = CompilerDOM.unwrapTSNode(node.expression);
  23318. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  23319. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23320. } else if (processDefineExpose(ctx, expr)) {
  23321. const callee = expr.callee;
  23322. ctx.s.overwrite(
  23323. callee.start + startOffset,
  23324. callee.end + startOffset,
  23325. "__expose"
  23326. );
  23327. } else {
  23328. processDefineModel(ctx, expr);
  23329. }
  23330. }
  23331. if (node.type === "VariableDeclaration" && !node.declare) {
  23332. const total = node.declarations.length;
  23333. let left = total;
  23334. let lastNonRemoved;
  23335. for (let i = 0; i < total; i++) {
  23336. const decl = node.declarations[i];
  23337. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  23338. if (init) {
  23339. if (processDefineOptions(ctx, init)) {
  23340. ctx.error(
  23341. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  23342. node
  23343. );
  23344. }
  23345. const isDefineProps = processDefineProps(ctx, init, decl.id);
  23346. if (ctx.propsDestructureRestId) {
  23347. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  23348. }
  23349. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  23350. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  23351. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  23352. if (left === 1) {
  23353. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23354. } else {
  23355. let start = decl.start + startOffset;
  23356. let end = decl.end + startOffset;
  23357. if (i === total - 1) {
  23358. start = node.declarations[lastNonRemoved].end + startOffset;
  23359. } else {
  23360. end = node.declarations[i + 1].start + startOffset;
  23361. }
  23362. ctx.s.remove(start, end);
  23363. left--;
  23364. }
  23365. } else if (isDefineEmits) {
  23366. ctx.s.overwrite(
  23367. startOffset + init.start,
  23368. startOffset + init.end,
  23369. "__emit"
  23370. );
  23371. } else {
  23372. lastNonRemoved = i;
  23373. }
  23374. }
  23375. }
  23376. }
  23377. let isAllLiteral = false;
  23378. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23379. isAllLiteral = walkDeclaration(
  23380. "scriptSetup",
  23381. node,
  23382. setupBindings,
  23383. vueImportAliases,
  23384. hoistStatic,
  23385. !!ctx.propsDestructureDecl
  23386. );
  23387. }
  23388. if (hoistStatic && isAllLiteral) {
  23389. hoistNode(node);
  23390. }
  23391. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  23392. const scope = [scriptSetupAst.body];
  23393. estreeWalker.walk(node, {
  23394. enter(child, parent) {
  23395. if (CompilerDOM.isFunctionType(child)) {
  23396. this.skip();
  23397. }
  23398. if (child.type === "BlockStatement") {
  23399. scope.push(child.body);
  23400. }
  23401. if (child.type === "AwaitExpression") {
  23402. hasAwait = true;
  23403. const currentScope = scope[scope.length - 1];
  23404. const needsSemi = currentScope.some((n, i) => {
  23405. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  23406. });
  23407. processAwait(
  23408. ctx,
  23409. child,
  23410. needsSemi,
  23411. parent.type === "ExpressionStatement"
  23412. );
  23413. }
  23414. },
  23415. exit(node2) {
  23416. if (node2.type === "BlockStatement") scope.pop();
  23417. }
  23418. });
  23419. }
  23420. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  23421. ctx.error(
  23422. `<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.`,
  23423. node
  23424. );
  23425. }
  23426. if (ctx.isTS) {
  23427. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  23428. if (node.type !== "TSEnumDeclaration") {
  23429. hoistNode(node);
  23430. }
  23431. }
  23432. }
  23433. }
  23434. if (ctx.propsDestructureDecl) {
  23435. transformDestructuredProps(ctx, vueImportAliases);
  23436. }
  23437. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  23438. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  23439. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  23440. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  23441. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  23442. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  23443. for (const node of runtimeOptionNodes) {
  23444. checkInvalidScopeReference(node, DEFINE_MODEL);
  23445. }
  23446. }
  23447. if (script) {
  23448. if (startOffset < scriptStartOffset) {
  23449. ctx.s.remove(0, startOffset);
  23450. ctx.s.remove(endOffset, scriptStartOffset);
  23451. ctx.s.remove(scriptEndOffset, source.length);
  23452. } else {
  23453. ctx.s.remove(0, scriptStartOffset);
  23454. ctx.s.remove(scriptEndOffset, startOffset);
  23455. ctx.s.remove(endOffset, source.length);
  23456. }
  23457. } else {
  23458. ctx.s.remove(0, startOffset);
  23459. ctx.s.remove(endOffset, source.length);
  23460. }
  23461. if (scriptAst) {
  23462. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  23463. }
  23464. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  23465. ctx.userImports
  23466. )) {
  23467. if (isType) continue;
  23468. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  23469. }
  23470. for (const key in scriptBindings) {
  23471. ctx.bindingMetadata[key] = scriptBindings[key];
  23472. }
  23473. for (const key in setupBindings) {
  23474. ctx.bindingMetadata[key] = setupBindings[key];
  23475. }
  23476. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  23477. const vModelIds = resolveTemplateVModelIdentifiers(sfc);
  23478. if (vModelIds.size) {
  23479. const toDemote = /* @__PURE__ */ new Set();
  23480. for (const id of vModelIds) {
  23481. if (setupBindings[id] === "setup-reactive-const") {
  23482. toDemote.add(id);
  23483. }
  23484. }
  23485. if (toDemote.size) {
  23486. for (const node of scriptSetupAst.body) {
  23487. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  23488. const demotedInDecl = [];
  23489. for (const decl of node.declarations) {
  23490. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  23491. demotedInDecl.push(decl.id.name);
  23492. }
  23493. }
  23494. if (demotedInDecl.length) {
  23495. ctx.s.overwrite(
  23496. node.start + startOffset,
  23497. node.start + startOffset + "const".length,
  23498. "let"
  23499. );
  23500. for (const id of demotedInDecl) {
  23501. setupBindings[id] = "setup-let";
  23502. ctx.bindingMetadata[id] = "setup-let";
  23503. warnOnce(
  23504. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  23505. );
  23506. }
  23507. }
  23508. }
  23509. }
  23510. }
  23511. }
  23512. }
  23513. if (sfc.cssVars.length && // no need to do this when targeting SSR
  23514. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  23515. ctx.helperImports.add(CSS_VARS_HELPER);
  23516. ctx.helperImports.add("unref");
  23517. ctx.s.prependLeft(
  23518. startOffset,
  23519. `
  23520. ${genCssVarsCode(
  23521. sfc.cssVars,
  23522. ctx.bindingMetadata,
  23523. scopeId,
  23524. !!options.isProd
  23525. )}
  23526. `
  23527. );
  23528. }
  23529. let args = `__props`;
  23530. if (ctx.propsTypeDecl) {
  23531. args += `: any`;
  23532. }
  23533. if (ctx.propsDecl) {
  23534. if (ctx.propsDestructureRestId) {
  23535. ctx.s.overwrite(
  23536. startOffset + ctx.propsCall.start,
  23537. startOffset + ctx.propsCall.end,
  23538. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  23539. Object.keys(ctx.propsDestructuredBindings)
  23540. )})`
  23541. );
  23542. ctx.s.overwrite(
  23543. startOffset + ctx.propsDestructureDecl.start,
  23544. startOffset + ctx.propsDestructureDecl.end,
  23545. ctx.propsDestructureRestId
  23546. );
  23547. } else if (!ctx.propsDestructureDecl) {
  23548. ctx.s.overwrite(
  23549. startOffset + ctx.propsCall.start,
  23550. startOffset + ctx.propsCall.end,
  23551. "__props"
  23552. );
  23553. }
  23554. }
  23555. if (hasAwait) {
  23556. const any = ctx.isTS ? `: any` : ``;
  23557. ctx.s.prependLeft(startOffset, `
  23558. let __temp${any}, __restore${any}
  23559. `);
  23560. }
  23561. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  23562. if (ctx.emitDecl) {
  23563. destructureElements.push(`emit: __emit`);
  23564. }
  23565. if (destructureElements.length) {
  23566. args += `, { ${destructureElements.join(", ")} }`;
  23567. }
  23568. let templateMap;
  23569. let returned;
  23570. const propsDecl = genRuntimeProps(ctx);
  23571. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  23572. const allBindings = {
  23573. ...scriptBindings,
  23574. ...setupBindings
  23575. };
  23576. for (const key in ctx.userImports) {
  23577. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  23578. allBindings[key] = true;
  23579. }
  23580. }
  23581. returned = `{ `;
  23582. for (const key in allBindings) {
  23583. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  23584. returned += `get ${key}() { return ${key} }, `;
  23585. } else if (ctx.bindingMetadata[key] === "setup-let") {
  23586. const setArg = key === "v" ? `_v` : `v`;
  23587. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  23588. } else {
  23589. returned += `${key}, `;
  23590. }
  23591. }
  23592. returned = returned.replace(/, $/, "") + ` }`;
  23593. } else {
  23594. if (sfc.template && !sfc.template.src) {
  23595. if (options.templateOptions && options.templateOptions.ssr) {
  23596. hasInlinedSsrRenderFn = true;
  23597. }
  23598. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate({
  23599. filename,
  23600. ast: sfc.template.ast,
  23601. source: sfc.template.content,
  23602. inMap: sfc.template.map,
  23603. ...options.templateOptions,
  23604. id: scopeId,
  23605. scoped: sfc.styles.some((s) => s.scoped),
  23606. isProd: options.isProd,
  23607. ssrCssVars: sfc.cssVars,
  23608. compilerOptions: {
  23609. ...options.templateOptions && options.templateOptions.compilerOptions,
  23610. inline: true,
  23611. isTS: ctx.isTS,
  23612. bindingMetadata: ctx.bindingMetadata
  23613. }
  23614. });
  23615. templateMap = map2;
  23616. if (tips.length) {
  23617. tips.forEach(warnOnce);
  23618. }
  23619. const err = errors[0];
  23620. if (typeof err === "string") {
  23621. throw new Error(err);
  23622. } else if (err) {
  23623. if (err.loc) {
  23624. err.message += `
  23625. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  23626. source,
  23627. err.loc.start.offset,
  23628. err.loc.end.offset
  23629. ) + `
  23630. `;
  23631. }
  23632. throw err;
  23633. }
  23634. if (preamble) {
  23635. ctx.s.prepend(preamble);
  23636. }
  23637. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  23638. ctx.helperImports.delete("unref");
  23639. }
  23640. returned = code;
  23641. } else {
  23642. returned = `() => {}`;
  23643. }
  23644. }
  23645. if (!options.inlineTemplate && true) {
  23646. ctx.s.appendRight(
  23647. endOffset,
  23648. `
  23649. const __returned__ = ${returned}
  23650. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  23651. return __returned__
  23652. }
  23653. `
  23654. );
  23655. } else {
  23656. ctx.s.appendRight(endOffset, `
  23657. return ${returned}
  23658. }
  23659. `);
  23660. }
  23661. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  23662. let runtimeOptions = ``;
  23663. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  23664. const match = filename.match(/([^/\\]+)\.\w+$/);
  23665. if (match) {
  23666. runtimeOptions += `
  23667. __name: '${match[1]}',`;
  23668. }
  23669. }
  23670. if (hasInlinedSsrRenderFn) {
  23671. runtimeOptions += `
  23672. __ssrInlineRender: true,`;
  23673. }
  23674. if (propsDecl) runtimeOptions += `
  23675. props: ${propsDecl},`;
  23676. const emitsDecl = genRuntimeEmits(ctx);
  23677. if (emitsDecl) runtimeOptions += `
  23678. emits: ${emitsDecl},`;
  23679. let definedOptions = "";
  23680. if (ctx.optionsRuntimeDecl) {
  23681. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  23682. }
  23683. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  23684. `;
  23685. if (ctx.isTS) {
  23686. const def = (defaultExport ? `
  23687. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  23688. ...${definedOptions},` : "");
  23689. ctx.s.prependLeft(
  23690. startOffset,
  23691. `
  23692. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  23693. `defineComponent`
  23694. )}({${def}${runtimeOptions}
  23695. ${hasAwait ? `async ` : ``}setup(${args}) {
  23696. ${exposeCall}`
  23697. );
  23698. ctx.s.appendRight(endOffset, `})`);
  23699. } else {
  23700. if (defaultExport || definedOptions) {
  23701. ctx.s.prependLeft(
  23702. startOffset,
  23703. `
  23704. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  23705. ${hasAwait ? `async ` : ``}setup(${args}) {
  23706. ${exposeCall}`
  23707. );
  23708. ctx.s.appendRight(endOffset, `})`);
  23709. } else {
  23710. ctx.s.prependLeft(
  23711. startOffset,
  23712. `
  23713. ${genDefaultAs} {${runtimeOptions}
  23714. ${hasAwait ? `async ` : ``}setup(${args}) {
  23715. ${exposeCall}`
  23716. );
  23717. ctx.s.appendRight(endOffset, `}`);
  23718. }
  23719. }
  23720. if (ctx.helperImports.size > 0) {
  23721. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  23722. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  23723. ctx.s.prepend(
  23724. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  23725. `
  23726. );
  23727. }
  23728. const content = ctx.s.toString();
  23729. let map = options.sourceMap !== false ? ctx.s.generateMap({
  23730. source: filename,
  23731. hires: true,
  23732. includeContent: true
  23733. }) : void 0;
  23734. if (templateMap && map) {
  23735. const offset = content.indexOf(returned);
  23736. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  23737. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  23738. }
  23739. return {
  23740. ...scriptSetup,
  23741. bindings: ctx.bindingMetadata,
  23742. imports: ctx.userImports,
  23743. content,
  23744. map,
  23745. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  23746. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  23747. deps: ctx.deps ? [...ctx.deps] : void 0
  23748. };
  23749. }
  23750. function registerBinding(bindings, node, type) {
  23751. bindings[node.name] = type;
  23752. }
  23753. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  23754. let isAllLiteral = false;
  23755. if (node.type === "VariableDeclaration") {
  23756. const isConst = node.kind === "const";
  23757. isAllLiteral = isConst && node.declarations.every(
  23758. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  23759. );
  23760. for (const { id, init: _init } of node.declarations) {
  23761. const init = _init && CompilerDOM.unwrapTSNode(_init);
  23762. const isConstMacroCall = isConst && isCallOf(
  23763. init,
  23764. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  23765. );
  23766. if (id.type === "Identifier") {
  23767. let bindingType;
  23768. const userReactiveBinding = userImportAliases["reactive"];
  23769. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  23770. bindingType = "literal-const";
  23771. } else if (isCallOf(init, userReactiveBinding)) {
  23772. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  23773. } else if (
  23774. // if a declaration is a const literal, we can mark it so that
  23775. // the generated render fn code doesn't need to unref() it
  23776. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  23777. ) {
  23778. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  23779. } else if (isConst) {
  23780. if (isCallOf(
  23781. init,
  23782. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  23783. )) {
  23784. bindingType = "setup-ref";
  23785. } else {
  23786. bindingType = "setup-maybe-ref";
  23787. }
  23788. } else {
  23789. bindingType = "setup-let";
  23790. }
  23791. registerBinding(bindings, id, bindingType);
  23792. } else {
  23793. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  23794. continue;
  23795. }
  23796. if (id.type === "ObjectPattern") {
  23797. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  23798. } else if (id.type === "ArrayPattern") {
  23799. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  23800. }
  23801. }
  23802. }
  23803. } else if (node.type === "TSEnumDeclaration") {
  23804. isAllLiteral = node.members.every(
  23805. (member) => !member.initializer || isStaticNode(member.initializer)
  23806. );
  23807. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  23808. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  23809. bindings[node.id.name] = "setup-const";
  23810. }
  23811. return isAllLiteral;
  23812. }
  23813. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  23814. for (const p of node.properties) {
  23815. if (p.type === "ObjectProperty") {
  23816. if (p.key.type === "Identifier" && p.key === p.value) {
  23817. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23818. registerBinding(bindings, p.key, type);
  23819. } else {
  23820. walkPattern(p.value, bindings, isConst, isDefineCall);
  23821. }
  23822. } else {
  23823. const type = isConst ? "setup-const" : "setup-let";
  23824. registerBinding(bindings, p.argument, type);
  23825. }
  23826. }
  23827. }
  23828. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  23829. for (const e of node.elements) {
  23830. e && walkPattern(e, bindings, isConst, isDefineCall);
  23831. }
  23832. }
  23833. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  23834. if (node.type === "Identifier") {
  23835. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23836. registerBinding(bindings, node, type);
  23837. } else if (node.type === "RestElement") {
  23838. const type = isConst ? "setup-const" : "setup-let";
  23839. registerBinding(bindings, node.argument, type);
  23840. } else if (node.type === "ObjectPattern") {
  23841. walkObjectPattern(node, bindings, isConst);
  23842. } else if (node.type === "ArrayPattern") {
  23843. walkArrayPattern(node, bindings, isConst);
  23844. } else if (node.type === "AssignmentPattern") {
  23845. if (node.left.type === "Identifier") {
  23846. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23847. registerBinding(bindings, node.left, type);
  23848. } else {
  23849. walkPattern(node.left, bindings, isConst);
  23850. }
  23851. }
  23852. }
  23853. function canNeverBeRef(node, userReactiveImport) {
  23854. if (isCallOf(node, userReactiveImport)) {
  23855. return true;
  23856. }
  23857. switch (node.type) {
  23858. case "UnaryExpression":
  23859. case "BinaryExpression":
  23860. case "ArrayExpression":
  23861. case "ObjectExpression":
  23862. case "FunctionExpression":
  23863. case "ArrowFunctionExpression":
  23864. case "UpdateExpression":
  23865. case "ClassExpression":
  23866. case "TaggedTemplateExpression":
  23867. return true;
  23868. case "SequenceExpression":
  23869. return canNeverBeRef(
  23870. node.expressions[node.expressions.length - 1],
  23871. userReactiveImport
  23872. );
  23873. default:
  23874. if (isLiteralNode(node)) {
  23875. return true;
  23876. }
  23877. return false;
  23878. }
  23879. }
  23880. function isStaticNode(node) {
  23881. node = CompilerDOM.unwrapTSNode(node);
  23882. switch (node.type) {
  23883. case "UnaryExpression":
  23884. return isStaticNode(node.argument);
  23885. case "LogicalExpression":
  23886. // 1 > 2
  23887. case "BinaryExpression":
  23888. return isStaticNode(node.left) && isStaticNode(node.right);
  23889. case "ConditionalExpression": {
  23890. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  23891. }
  23892. case "SequenceExpression":
  23893. // (1, 2)
  23894. case "TemplateLiteral":
  23895. return node.expressions.every((expr) => isStaticNode(expr));
  23896. case "ParenthesizedExpression":
  23897. return isStaticNode(node.expression);
  23898. case "StringLiteral":
  23899. case "NumericLiteral":
  23900. case "BooleanLiteral":
  23901. case "NullLiteral":
  23902. case "BigIntLiteral":
  23903. return true;
  23904. }
  23905. return false;
  23906. }
  23907. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  23908. const generator = new sourceMapJs.SourceMapGenerator();
  23909. const addMapping = (map, lineOffset = 0) => {
  23910. const consumer = new sourceMapJs.SourceMapConsumer(map);
  23911. consumer.sources.forEach((sourceFile) => {
  23912. generator._sources.add(sourceFile);
  23913. const sourceContent = consumer.sourceContentFor(sourceFile);
  23914. if (sourceContent != null) {
  23915. generator.setSourceContent(sourceFile, sourceContent);
  23916. }
  23917. });
  23918. consumer.eachMapping((m) => {
  23919. if (m.originalLine == null) return;
  23920. generator.addMapping({
  23921. generated: {
  23922. line: m.generatedLine + lineOffset,
  23923. column: m.generatedColumn
  23924. },
  23925. original: {
  23926. line: m.originalLine,
  23927. column: m.originalColumn
  23928. },
  23929. source: m.source,
  23930. name: m.name
  23931. });
  23932. });
  23933. };
  23934. addMapping(scriptMap);
  23935. addMapping(templateMap, templateLineOffset);
  23936. generator._sourceRoot = scriptMap.sourceRoot;
  23937. generator._file = scriptMap.file;
  23938. return generator.toJSON();
  23939. }
  23940. const version = "3.5.35";
  23941. const parseCache = parseCache$1;
  23942. const errorMessages = {
  23943. ...CompilerDOM.errorMessages,
  23944. ...CompilerDOM.DOMErrorMessages
  23945. };
  23946. const walk = estreeWalker.walk;
  23947. const shouldTransformRef = () => false;
  23948. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  23949. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  23950. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  23951. exports.isStaticProperty = compilerCore.isStaticProperty;
  23952. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  23953. exports.MagicString = MagicString;
  23954. exports.babelParse = parser$2.parse;
  23955. exports.compileScript = compileScript;
  23956. exports.compileStyle = compileStyle;
  23957. exports.compileStyleAsync = compileStyleAsync;
  23958. exports.compileTemplate = compileTemplate;
  23959. exports.errorMessages = errorMessages;
  23960. exports.extractRuntimeEmits = extractRuntimeEmits;
  23961. exports.extractRuntimeProps = extractRuntimeProps;
  23962. exports.inferRuntimeType = inferRuntimeType;
  23963. exports.invalidateTypeCache = invalidateTypeCache;
  23964. exports.parse = parse$1;
  23965. exports.parseCache = parseCache;
  23966. exports.registerTS = registerTS;
  23967. exports.resolveTypeElements = resolveTypeElements;
  23968. exports.rewriteDefault = rewriteDefault;
  23969. exports.rewriteDefaultAST = rewriteDefaultAST;
  23970. exports.shouldTransformRef = shouldTransformRef;
  23971. exports.version = version;
  23972. exports.walk = walk;