compiler-sfc.cjs.js 828 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217
  1. /**
  2. * @vue/compiler-sfc v3.5.27
  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 === "@";
  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 parseUrl(url) {
  2071. const firstChar = url.charAt(0);
  2072. if (firstChar === "~") {
  2073. const secondChar = url.charAt(1);
  2074. url = url.slice(secondChar === "/" ? 2 : 1);
  2075. }
  2076. return parseUriParts(url);
  2077. }
  2078. function parseUriParts(urlString) {
  2079. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2080. }
  2081. const defaultAssetUrlOptions = {
  2082. base: null,
  2083. includeAbsolute: false,
  2084. tags: {
  2085. video: ["src", "poster"],
  2086. source: ["src"],
  2087. img: ["src"],
  2088. image: ["xlink:href", "href"],
  2089. use: ["xlink:href", "href"]
  2090. }
  2091. };
  2092. const normalizeOptions = (options) => {
  2093. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2094. return {
  2095. ...defaultAssetUrlOptions,
  2096. tags: options
  2097. };
  2098. }
  2099. return {
  2100. ...defaultAssetUrlOptions,
  2101. ...options
  2102. };
  2103. };
  2104. const createAssetUrlTransformWithOptions = (options) => {
  2105. return (node, context) => transformAssetUrl(node, context, options);
  2106. };
  2107. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2108. if (node.type === 1) {
  2109. if (!node.props.length) {
  2110. return;
  2111. }
  2112. const tags = options.tags || defaultAssetUrlOptions.tags;
  2113. const attrs = tags[node.tag];
  2114. const wildCardAttrs = tags["*"];
  2115. if (!attrs && !wildCardAttrs) {
  2116. return;
  2117. }
  2118. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2119. node.props.forEach((attr, index) => {
  2120. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value || isExternalUrl(attr.value.content) || isDataUrl(attr.value.content) || attr.value.content[0] === "#" || !options.includeAbsolute && !isRelativeUrl(attr.value.content)) {
  2121. return;
  2122. }
  2123. const url = parseUrl(attr.value.content);
  2124. if (options.base && attr.value.content[0] === ".") {
  2125. const base = parseUrl(options.base);
  2126. const protocol = base.protocol || "";
  2127. const host = base.host ? protocol + "//" + base.host : "";
  2128. const basePath = base.path || "/";
  2129. attr.value.content = host + (path$1.posix || path$1).join(basePath, url.path + (url.hash || ""));
  2130. return;
  2131. }
  2132. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2133. node.props[index] = {
  2134. type: 7,
  2135. name: "bind",
  2136. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2137. exp,
  2138. modifiers: [],
  2139. loc: attr.loc
  2140. };
  2141. });
  2142. }
  2143. };
  2144. function getImportsExpressionExp(path2, hash, loc, context) {
  2145. if (path2) {
  2146. let name;
  2147. let exp;
  2148. const existingIndex = context.imports.findIndex((i) => i.path === path2);
  2149. if (existingIndex > -1) {
  2150. name = `_imports_${existingIndex}`;
  2151. exp = context.imports[existingIndex].exp;
  2152. } else {
  2153. name = `_imports_${context.imports.length}`;
  2154. exp = compilerCore.createSimpleExpression(
  2155. name,
  2156. false,
  2157. loc,
  2158. 3
  2159. );
  2160. context.imports.push({
  2161. exp,
  2162. path: decodeURIComponent(path2)
  2163. });
  2164. }
  2165. if (!hash) {
  2166. return exp;
  2167. }
  2168. const hashExp = `${name} + '${hash}'`;
  2169. const finalExp = compilerCore.createSimpleExpression(
  2170. hashExp,
  2171. false,
  2172. loc,
  2173. 3
  2174. );
  2175. if (!context.hoistStatic) {
  2176. return finalExp;
  2177. }
  2178. const existingHoistIndex = context.hoists.findIndex((h) => {
  2179. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2180. });
  2181. if (existingHoistIndex > -1) {
  2182. return compilerCore.createSimpleExpression(
  2183. `_hoisted_${existingHoistIndex + 1}`,
  2184. false,
  2185. loc,
  2186. 3
  2187. );
  2188. }
  2189. return context.hoist(finalExp);
  2190. } else {
  2191. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2192. }
  2193. }
  2194. const srcsetTags = ["img", "source"];
  2195. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2196. const createSrcsetTransformWithOptions = (options) => {
  2197. return (node, context) => transformSrcset(node, context, options);
  2198. };
  2199. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2200. if (node.type === 1) {
  2201. if (srcsetTags.includes(node.tag) && node.props.length) {
  2202. node.props.forEach((attr, index) => {
  2203. if (attr.name === "srcset" && attr.type === 6) {
  2204. if (!attr.value) return;
  2205. const value = attr.value.content;
  2206. if (!value) return;
  2207. const imageCandidates = value.split(",").map((s) => {
  2208. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2209. return { url, descriptor };
  2210. });
  2211. for (let i = 0; i < imageCandidates.length; i++) {
  2212. const { url } = imageCandidates[i];
  2213. if (isDataUrl(url)) {
  2214. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2215. imageCandidates.splice(i, 1);
  2216. }
  2217. }
  2218. const shouldProcessUrl = (url) => {
  2219. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2220. };
  2221. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2222. return;
  2223. }
  2224. if (options.base) {
  2225. const base = options.base;
  2226. const set = [];
  2227. let needImportTransform = false;
  2228. imageCandidates.forEach((candidate) => {
  2229. let { url, descriptor } = candidate;
  2230. descriptor = descriptor ? ` ${descriptor}` : ``;
  2231. if (url[0] === ".") {
  2232. candidate.url = (path$1.posix || path$1).join(base, url);
  2233. set.push(candidate.url + descriptor);
  2234. } else if (shouldProcessUrl(url)) {
  2235. needImportTransform = true;
  2236. } else {
  2237. set.push(url + descriptor);
  2238. }
  2239. });
  2240. if (!needImportTransform) {
  2241. attr.value.content = set.join(", ");
  2242. return;
  2243. }
  2244. }
  2245. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2246. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2247. if (shouldProcessUrl(url)) {
  2248. const { path: path2 } = parseUrl(url);
  2249. let exp2;
  2250. if (path2) {
  2251. const existingImportsIndex = context.imports.findIndex(
  2252. (i) => i.path === path2
  2253. );
  2254. if (existingImportsIndex > -1) {
  2255. exp2 = compilerCore.createSimpleExpression(
  2256. `_imports_${existingImportsIndex}`,
  2257. false,
  2258. attr.loc,
  2259. 3
  2260. );
  2261. } else {
  2262. exp2 = compilerCore.createSimpleExpression(
  2263. `_imports_${context.imports.length}`,
  2264. false,
  2265. attr.loc,
  2266. 3
  2267. );
  2268. context.imports.push({ exp: exp2, path: path2 });
  2269. }
  2270. compoundExpression.children.push(exp2);
  2271. }
  2272. } else {
  2273. const exp2 = compilerCore.createSimpleExpression(
  2274. `"${url}"`,
  2275. false,
  2276. attr.loc,
  2277. 3
  2278. );
  2279. compoundExpression.children.push(exp2);
  2280. }
  2281. const isNotLast = imageCandidates.length - 1 > index2;
  2282. if (descriptor && isNotLast) {
  2283. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2284. } else if (descriptor) {
  2285. compoundExpression.children.push(` + ' ${descriptor}'`);
  2286. } else if (isNotLast) {
  2287. compoundExpression.children.push(` + ', ' + `);
  2288. }
  2289. });
  2290. let exp = compoundExpression;
  2291. if (context.hoistStatic) {
  2292. exp = context.hoist(compoundExpression);
  2293. exp.constType = 3;
  2294. }
  2295. node.props[index] = {
  2296. type: 7,
  2297. name: "bind",
  2298. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2299. exp,
  2300. modifiers: [],
  2301. loc: attr.loc
  2302. };
  2303. }
  2304. });
  2305. }
  2306. }
  2307. };
  2308. function commonjsRequire(path) {
  2309. 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.');
  2310. }
  2311. var consolidate$2 = {exports: {}};
  2312. var hasRequiredConsolidate$1;
  2313. function requireConsolidate$1 () {
  2314. if (hasRequiredConsolidate$1) return consolidate$2.exports;
  2315. hasRequiredConsolidate$1 = 1;
  2316. (function (module, exports$1) {
  2317. /*
  2318. * Engines which do not support caching of their file contents
  2319. * should use the `read()` function defined in consolidate.js
  2320. * On top of this, when an engine compiles to a `Function`,
  2321. * these functions should either be cached within consolidate.js
  2322. * or the engine itself via `options.cache`. This will allow
  2323. * users and frameworks to pass `options.cache = true` for
  2324. * `NODE_ENV=production`, however edit the file(s) without
  2325. * re-loading the application in development.
  2326. */
  2327. /**
  2328. * Module dependencies.
  2329. */
  2330. var fs = require$$0;
  2331. var path = path$1;
  2332. var util = require$$2;
  2333. var join = path.join;
  2334. var resolve = path.resolve;
  2335. var extname = path.extname;
  2336. var dirname = path.dirname;
  2337. var isAbsolute = path.isAbsolute;
  2338. var readCache = {};
  2339. /**
  2340. * Require cache.
  2341. */
  2342. var cacheStore = {};
  2343. /**
  2344. * Require cache.
  2345. */
  2346. var requires = {};
  2347. /**
  2348. * Clear the cache.
  2349. *
  2350. * @api public
  2351. */
  2352. exports$1.clearCache = function() {
  2353. readCache = {};
  2354. cacheStore = {};
  2355. };
  2356. /**
  2357. * Conditionally cache `compiled` template based
  2358. * on the `options` filename and `.cache` boolean.
  2359. *
  2360. * @param {Object} options
  2361. * @param {Function} compiled
  2362. * @return {Function}
  2363. * @api private
  2364. */
  2365. function cache(options, compiled) {
  2366. // cachable
  2367. if (compiled && options.filename && options.cache) {
  2368. delete readCache[options.filename];
  2369. cacheStore[options.filename] = compiled;
  2370. return compiled;
  2371. }
  2372. // check cache
  2373. if (options.filename && options.cache) {
  2374. return cacheStore[options.filename];
  2375. }
  2376. return compiled;
  2377. }
  2378. /**
  2379. * Read `path` with `options` with
  2380. * callback `(err, str)`. When `options.cache`
  2381. * is true the template string will be cached.
  2382. *
  2383. * @param {String} options
  2384. * @param {Function} cb
  2385. * @api private
  2386. */
  2387. function read(path, options, cb) {
  2388. var str = readCache[path];
  2389. var cached = options.cache && str && typeof str === 'string';
  2390. // cached (only if cached is a string and not a compiled template function)
  2391. if (cached) return cb(null, str);
  2392. // read
  2393. fs.readFile(path, 'utf8', function(err, str) {
  2394. if (err) return cb(err);
  2395. // remove extraneous utf8 BOM marker
  2396. str = str.replace(/^\uFEFF/, '');
  2397. if (options.cache) readCache[path] = str;
  2398. cb(null, str);
  2399. });
  2400. }
  2401. /**
  2402. * Read `path` with `options` with
  2403. * callback `(err, str)`. When `options.cache`
  2404. * is true the partial string will be cached.
  2405. *
  2406. * @param {String} options
  2407. * @param {Function} fn
  2408. * @api private
  2409. */
  2410. function readPartials(path, options, cb) {
  2411. if (!options.partials) return cb();
  2412. var keys = Object.keys(options.partials);
  2413. var partials = {};
  2414. function next(index) {
  2415. if (index === keys.length) return cb(null, partials);
  2416. var key = keys[index];
  2417. var partialPath = options.partials[key];
  2418. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2419. return next(++index);
  2420. }
  2421. var file;
  2422. if (isAbsolute(partialPath)) {
  2423. if (extname(partialPath) !== '') {
  2424. file = partialPath;
  2425. } else {
  2426. file = join(partialPath + extname(path));
  2427. }
  2428. } else {
  2429. file = join(dirname(path), partialPath + extname(path));
  2430. }
  2431. read(file, options, function(err, str) {
  2432. if (err) return cb(err);
  2433. partials[key] = str;
  2434. next(++index);
  2435. });
  2436. }
  2437. next(0);
  2438. }
  2439. /**
  2440. * promisify
  2441. */
  2442. function promisify(cb, fn) {
  2443. return new Promise(function(resolve, reject) {
  2444. cb = cb || function(err, html) {
  2445. if (err) {
  2446. return reject(err);
  2447. }
  2448. resolve(html);
  2449. };
  2450. fn(cb);
  2451. });
  2452. }
  2453. /**
  2454. * fromStringRenderer
  2455. */
  2456. function fromStringRenderer(name) {
  2457. return function(path, options, cb) {
  2458. options.filename = path;
  2459. return promisify(cb, function(cb) {
  2460. readPartials(path, options, function(err, partials) {
  2461. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2462. var opts = extend({}, options);
  2463. opts.partials = partials;
  2464. if (err) return cb(err);
  2465. if (cache(opts)) {
  2466. exports$1[name].render('', opts, cb);
  2467. } else {
  2468. read(path, opts, function(err, str) {
  2469. if (err) return cb(err);
  2470. exports$1[name].render(str, opts, cb);
  2471. });
  2472. }
  2473. });
  2474. });
  2475. };
  2476. }
  2477. /**
  2478. * velocity support.
  2479. */
  2480. exports$1.velocityjs = fromStringRenderer('velocityjs');
  2481. /**
  2482. * velocity string support.
  2483. */
  2484. exports$1.velocityjs.render = function(str, options, cb) {
  2485. return promisify(cb, function(cb) {
  2486. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2487. try {
  2488. options.locals = options;
  2489. cb(null, engine.render(str, options).trimLeft());
  2490. } catch (err) {
  2491. cb(err);
  2492. }
  2493. });
  2494. };
  2495. /**
  2496. * Liquid support.
  2497. */
  2498. exports$1.liquid = fromStringRenderer('liquid');
  2499. /**
  2500. * Liquid string support.
  2501. */
  2502. /**
  2503. * Note that in order to get filters and custom tags we've had to push
  2504. * all user-defined locals down into @locals. However, just to make things
  2505. * backwards-compatible, any property of `options` that is left after
  2506. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2507. * `includeDir` will also become a local.
  2508. */
  2509. function _renderTinyliquid(engine, str, options, cb) {
  2510. var context = engine.newContext();
  2511. var k;
  2512. /**
  2513. * Note that there's a bug in the library that doesn't allow us to pass
  2514. * the locals to newContext(), hence looping through the keys:
  2515. */
  2516. if (options.locals) {
  2517. for (k in options.locals) {
  2518. context.setLocals(k, options.locals[k]);
  2519. }
  2520. delete options.locals;
  2521. }
  2522. if (options.meta) {
  2523. context.setLocals('page', options.meta);
  2524. delete options.meta;
  2525. }
  2526. /**
  2527. * Add any defined filters:
  2528. */
  2529. if (options.filters) {
  2530. for (k in options.filters) {
  2531. context.setFilter(k, options.filters[k]);
  2532. }
  2533. delete options.filters;
  2534. }
  2535. /**
  2536. * Set up a callback for the include directory:
  2537. */
  2538. var includeDir = options.includeDir || process.cwd();
  2539. context.onInclude(function(name, callback) {
  2540. var extname = path.extname(name) ? '' : '.liquid';
  2541. var filename = path.resolve(includeDir, name + extname);
  2542. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2543. if (err) return callback(err);
  2544. callback(null, engine.parse(data));
  2545. });
  2546. });
  2547. delete options.includeDir;
  2548. /**
  2549. * The custom tag functions need to have their results pushed back
  2550. * through the parser, so set up a shim before calling the provided
  2551. * callback:
  2552. */
  2553. var compileOptions = {
  2554. customTags: {}
  2555. };
  2556. if (options.customTags) {
  2557. var tagFunctions = options.customTags;
  2558. for (k in options.customTags) {
  2559. /*Tell jshint there's no problem with having this function in the loop */
  2560. /*jshint -W083 */
  2561. compileOptions.customTags[k] = function(context, name, body) {
  2562. var tpl = tagFunctions[name](body.trim());
  2563. context.astStack.push(engine.parse(tpl));
  2564. };
  2565. /*jshint +W083 */
  2566. }
  2567. delete options.customTags;
  2568. }
  2569. /**
  2570. * Now anything left in `options` becomes a local:
  2571. */
  2572. for (k in options) {
  2573. context.setLocals(k, options[k]);
  2574. }
  2575. /**
  2576. * Finally, execute the template:
  2577. */
  2578. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2579. tmpl(context, cb);
  2580. }
  2581. exports$1.liquid.render = function(str, options, cb) {
  2582. return promisify(cb, function(cb) {
  2583. var engine = requires.liquid;
  2584. var Liquid;
  2585. try {
  2586. // set up tinyliquid engine
  2587. engine = requires.liquid = require('tinyliquid');
  2588. // use tinyliquid engine
  2589. _renderTinyliquid(engine, str, options, cb);
  2590. return;
  2591. } catch (err) {
  2592. // set up liquid-node engine
  2593. try {
  2594. Liquid = requires.liquid = require('liquid-node');
  2595. engine = new Liquid.Engine();
  2596. } catch (err) {
  2597. throw err;
  2598. }
  2599. }
  2600. // use liquid-node engine
  2601. try {
  2602. var locals = options.locals || {};
  2603. if (options.meta) {
  2604. locals.pages = options.meta;
  2605. delete options.meta;
  2606. }
  2607. /**
  2608. * Add any defined filters:
  2609. */
  2610. if (options.filters) {
  2611. engine.registerFilters(options.filters);
  2612. delete options.filters;
  2613. }
  2614. /**
  2615. * Set up a callback for the include directory:
  2616. */
  2617. var includeDir = options.includeDir || process.cwd();
  2618. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2619. delete options.includeDir;
  2620. /**
  2621. * The custom tag functions need to have their results pushed back
  2622. * through the parser, so set up a shim before calling the provided
  2623. * callback:
  2624. */
  2625. if (options.customTags) {
  2626. var tagFunctions = options.customTags;
  2627. for (k in options.customTags) {
  2628. engine.registerTag(k, tagFunctions[k]);
  2629. }
  2630. delete options.customTags;
  2631. }
  2632. /**
  2633. * Now anything left in `options` becomes a local:
  2634. */
  2635. for (var k in options) {
  2636. locals[k] = options[k];
  2637. }
  2638. /**
  2639. * Finally, execute the template:
  2640. */
  2641. return engine
  2642. .parseAndRender(str, locals)
  2643. .nodeify(function(err, result) {
  2644. if (err) {
  2645. throw new Error(err);
  2646. } else {
  2647. return cb(null, result);
  2648. }
  2649. });
  2650. } catch (err) {
  2651. cb(err);
  2652. }
  2653. });
  2654. };
  2655. /**
  2656. * Jade support.
  2657. */
  2658. exports$1.jade = function(path, options, cb) {
  2659. return promisify(cb, function(cb) {
  2660. var engine = requires.jade;
  2661. if (!engine) {
  2662. try {
  2663. engine = requires.jade = require('jade');
  2664. } catch (err) {
  2665. try {
  2666. engine = requires.jade = require('then-jade');
  2667. } catch (otherError) {
  2668. throw err;
  2669. }
  2670. }
  2671. }
  2672. try {
  2673. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2674. cb(null, tmpl(options));
  2675. } catch (err) {
  2676. cb(err);
  2677. }
  2678. });
  2679. };
  2680. /**
  2681. * Jade string support.
  2682. */
  2683. exports$1.jade.render = function(str, options, cb) {
  2684. return promisify(cb, function(cb) {
  2685. var engine = requires.jade;
  2686. if (!engine) {
  2687. try {
  2688. engine = requires.jade = require('jade');
  2689. } catch (err) {
  2690. try {
  2691. engine = requires.jade = require('then-jade');
  2692. } catch (otherError) {
  2693. throw err;
  2694. }
  2695. }
  2696. }
  2697. try {
  2698. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2699. cb(null, tmpl(options));
  2700. } catch (err) {
  2701. cb(err);
  2702. }
  2703. });
  2704. };
  2705. /**
  2706. * Dust support.
  2707. */
  2708. exports$1.dust = fromStringRenderer('dust');
  2709. /**
  2710. * Dust string support.
  2711. */
  2712. exports$1.dust.render = function(str, options, cb) {
  2713. return promisify(cb, function(cb) {
  2714. var engine = requires.dust;
  2715. if (!engine) {
  2716. try {
  2717. engine = requires.dust = require('dust');
  2718. } catch (err) {
  2719. try {
  2720. engine = requires.dust = require('dustjs-helpers');
  2721. } catch (err) {
  2722. engine = requires.dust = require('dustjs-linkedin');
  2723. }
  2724. }
  2725. }
  2726. var ext = 'dust';
  2727. var views = '.';
  2728. if (options) {
  2729. if (options.ext) ext = options.ext;
  2730. if (options.views) views = options.views;
  2731. if (options.settings && options.settings.views) views = options.settings.views;
  2732. }
  2733. if (!options || (options && !options.cache)) engine.cache = {};
  2734. engine.onLoad = function(path, callback) {
  2735. if (extname(path) === '') path += '.' + ext;
  2736. if (path[0] !== '/') path = views + '/' + path;
  2737. read(path, options, callback);
  2738. };
  2739. try {
  2740. var templateName;
  2741. if (options.filename) {
  2742. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2743. }
  2744. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2745. tmpl(options, cb);
  2746. } catch (err) {
  2747. cb(err);
  2748. }
  2749. });
  2750. };
  2751. /**
  2752. * Swig support.
  2753. */
  2754. exports$1.swig = fromStringRenderer('swig');
  2755. /**
  2756. * Swig string support.
  2757. */
  2758. exports$1.swig.render = function(str, options, cb) {
  2759. return promisify(cb, function(cb) {
  2760. var engine = requires.swig;
  2761. if (!engine) {
  2762. try {
  2763. engine = requires.swig = require('swig');
  2764. } catch (err) {
  2765. try {
  2766. engine = requires.swig = require('swig-templates');
  2767. } catch (otherError) {
  2768. throw err;
  2769. }
  2770. }
  2771. }
  2772. try {
  2773. if (options.cache === true) options.cache = 'memory';
  2774. engine.setDefaults({ cache: options.cache });
  2775. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2776. cb(null, tmpl(options));
  2777. } catch (err) {
  2778. cb(err);
  2779. }
  2780. });
  2781. };
  2782. /**
  2783. * Razor support.
  2784. */
  2785. exports$1.razor = function(path, options, cb) {
  2786. return promisify(cb, function(cb) {
  2787. var engine = requires.razor;
  2788. if (!engine) {
  2789. try {
  2790. engine = requires.razor = require('razor-tmpl');
  2791. } catch (err) {
  2792. throw err;
  2793. }
  2794. }
  2795. try {
  2796. var tmpl = cache(options) || cache(options, (locals) => {
  2797. console.log('Rendering razor file', path);
  2798. return engine.renderFileSync(path, locals);
  2799. });
  2800. cb(null, tmpl(options));
  2801. } catch (err) {
  2802. cb(err);
  2803. }
  2804. });
  2805. };
  2806. /**
  2807. * razor string support.
  2808. */
  2809. exports$1.razor.render = function(str, options, cb) {
  2810. return promisify(cb, function(cb) {
  2811. try {
  2812. var engine = requires.razor = require('razor-tmpl');
  2813. } catch (err) {
  2814. throw err;
  2815. }
  2816. try {
  2817. var tf = engine.compile(str);
  2818. var tmpl = cache(options) || cache(options, tf);
  2819. cb(null, tmpl(options));
  2820. } catch (err) {
  2821. cb(err);
  2822. }
  2823. });
  2824. };
  2825. /**
  2826. * Atpl support.
  2827. */
  2828. exports$1.atpl = fromStringRenderer('atpl');
  2829. /**
  2830. * Atpl string support.
  2831. */
  2832. exports$1.atpl.render = function(str, options, cb) {
  2833. return promisify(cb, function(cb) {
  2834. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2835. try {
  2836. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2837. cb(null, tmpl(options));
  2838. } catch (err) {
  2839. cb(err);
  2840. }
  2841. });
  2842. };
  2843. /**
  2844. * Liquor support,
  2845. */
  2846. exports$1.liquor = fromStringRenderer('liquor');
  2847. /**
  2848. * Liquor string support.
  2849. */
  2850. exports$1.liquor.render = function(str, options, cb) {
  2851. return promisify(cb, function(cb) {
  2852. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2853. try {
  2854. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2855. cb(null, tmpl(options));
  2856. } catch (err) {
  2857. cb(err);
  2858. }
  2859. });
  2860. };
  2861. /**
  2862. * Twig support.
  2863. */
  2864. exports$1.twig = fromStringRenderer('twig');
  2865. /**
  2866. * Twig string support.
  2867. */
  2868. exports$1.twig.render = function(str, options, cb) {
  2869. return promisify(cb, function(cb) {
  2870. var engine = requires.twig || (requires.twig = require('twig').twig);
  2871. var templateData = {
  2872. data: str,
  2873. allowInlineIncludes: options.allowInlineIncludes,
  2874. namespaces: options.namespaces,
  2875. path: options.path
  2876. };
  2877. try {
  2878. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2879. cb(null, tmpl.render(options));
  2880. } catch (err) {
  2881. cb(err);
  2882. }
  2883. });
  2884. };
  2885. /**
  2886. * EJS support.
  2887. */
  2888. exports$1.ejs = fromStringRenderer('ejs');
  2889. /**
  2890. * EJS string support.
  2891. */
  2892. exports$1.ejs.render = function(str, options, cb) {
  2893. return promisify(cb, function(cb) {
  2894. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2895. try {
  2896. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2897. cb(null, tmpl(options));
  2898. } catch (err) {
  2899. cb(err);
  2900. }
  2901. });
  2902. };
  2903. /**
  2904. * Eco support.
  2905. */
  2906. exports$1.eco = fromStringRenderer('eco');
  2907. /**
  2908. * Eco string support.
  2909. */
  2910. exports$1.eco.render = function(str, options, cb) {
  2911. return promisify(cb, function(cb) {
  2912. var engine = requires.eco || (requires.eco = require('eco'));
  2913. try {
  2914. cb(null, engine.render(str, options));
  2915. } catch (err) {
  2916. cb(err);
  2917. }
  2918. });
  2919. };
  2920. /**
  2921. * Jazz support.
  2922. */
  2923. exports$1.jazz = fromStringRenderer('jazz');
  2924. /**
  2925. * Jazz string support.
  2926. */
  2927. exports$1.jazz.render = function(str, options, cb) {
  2928. return promisify(cb, function(cb) {
  2929. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2930. try {
  2931. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2932. tmpl.eval(options, function(str) {
  2933. cb(null, str);
  2934. });
  2935. } catch (err) {
  2936. cb(err);
  2937. }
  2938. });
  2939. };
  2940. /**
  2941. * JQTPL support.
  2942. */
  2943. exports$1.jqtpl = fromStringRenderer('jqtpl');
  2944. /**
  2945. * JQTPL string support.
  2946. */
  2947. exports$1.jqtpl.render = function(str, options, cb) {
  2948. return promisify(cb, function(cb) {
  2949. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2950. try {
  2951. engine.template(str, str);
  2952. cb(null, engine.tmpl(str, options));
  2953. } catch (err) {
  2954. cb(err);
  2955. }
  2956. });
  2957. };
  2958. /**
  2959. * Haml support.
  2960. */
  2961. exports$1.haml = fromStringRenderer('haml');
  2962. /**
  2963. * Haml string support.
  2964. */
  2965. exports$1.haml.render = function(str, options, cb) {
  2966. return promisify(cb, function(cb) {
  2967. var engine = requires.haml || (requires.haml = require('hamljs'));
  2968. try {
  2969. options.locals = options;
  2970. cb(null, engine.render(str, options).trimLeft());
  2971. } catch (err) {
  2972. cb(err);
  2973. }
  2974. });
  2975. };
  2976. /**
  2977. * Hamlet support.
  2978. */
  2979. exports$1.hamlet = fromStringRenderer('hamlet');
  2980. /**
  2981. * Hamlet string support.
  2982. */
  2983. exports$1.hamlet.render = function(str, options, cb) {
  2984. return promisify(cb, function(cb) {
  2985. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  2986. try {
  2987. options.locals = options;
  2988. cb(null, engine.render(str, options).trimLeft());
  2989. } catch (err) {
  2990. cb(err);
  2991. }
  2992. });
  2993. };
  2994. /**
  2995. * Whiskers support.
  2996. */
  2997. exports$1.whiskers = function(path, options, cb) {
  2998. return promisify(cb, function(cb) {
  2999. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3000. engine.__express(path, options, cb);
  3001. });
  3002. };
  3003. /**
  3004. * Whiskers string support.
  3005. */
  3006. exports$1.whiskers.render = function(str, options, cb) {
  3007. return promisify(cb, function(cb) {
  3008. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3009. try {
  3010. cb(null, engine.render(str, options));
  3011. } catch (err) {
  3012. cb(err);
  3013. }
  3014. });
  3015. };
  3016. /**
  3017. * Coffee-HAML support.
  3018. */
  3019. exports$1['haml-coffee'] = fromStringRenderer('haml-coffee');
  3020. /**
  3021. * Coffee-HAML string support.
  3022. */
  3023. exports$1['haml-coffee'].render = function(str, options, cb) {
  3024. return promisify(cb, function(cb) {
  3025. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3026. try {
  3027. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3028. cb(null, tmpl(options));
  3029. } catch (err) {
  3030. cb(err);
  3031. }
  3032. });
  3033. };
  3034. /**
  3035. * Hogan support.
  3036. */
  3037. exports$1.hogan = fromStringRenderer('hogan');
  3038. /**
  3039. * Hogan string support.
  3040. */
  3041. exports$1.hogan.render = function(str, options, cb) {
  3042. return promisify(cb, function(cb) {
  3043. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3044. try {
  3045. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3046. cb(null, tmpl.render(options, options.partials));
  3047. } catch (err) {
  3048. cb(err);
  3049. }
  3050. });
  3051. };
  3052. /**
  3053. * templayed.js support.
  3054. */
  3055. exports$1.templayed = fromStringRenderer('templayed');
  3056. /**
  3057. * templayed.js string support.
  3058. */
  3059. exports$1.templayed.render = function(str, options, cb) {
  3060. return promisify(cb, function(cb) {
  3061. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3062. try {
  3063. var tmpl = cache(options) || cache(options, engine(str));
  3064. cb(null, tmpl(options));
  3065. } catch (err) {
  3066. cb(err);
  3067. }
  3068. });
  3069. };
  3070. /**
  3071. * Handlebars support.
  3072. */
  3073. exports$1.handlebars = fromStringRenderer('handlebars');
  3074. /**
  3075. * Handlebars string support.
  3076. */
  3077. exports$1.handlebars.render = function(str, options, cb) {
  3078. return promisify(cb, function(cb) {
  3079. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3080. try {
  3081. for (var partial in options.partials) {
  3082. engine.registerPartial(partial, options.partials[partial]);
  3083. }
  3084. for (var helper in options.helpers) {
  3085. engine.registerHelper(helper, options.helpers[helper]);
  3086. }
  3087. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3088. cb(null, tmpl(options));
  3089. } catch (err) {
  3090. cb(err);
  3091. }
  3092. });
  3093. };
  3094. /**
  3095. * Underscore support.
  3096. */
  3097. exports$1.underscore = fromStringRenderer('underscore');
  3098. /**
  3099. * Underscore string support.
  3100. */
  3101. exports$1.underscore.render = function(str, options, cb) {
  3102. return promisify(cb, function(cb) {
  3103. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3104. try {
  3105. const partials = {};
  3106. for (var partial in options.partials) {
  3107. partials[partial] = engine.template(options.partials[partial]);
  3108. }
  3109. options.partials = partials;
  3110. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3111. cb(null, tmpl(options).replace(/\n$/, ''));
  3112. } catch (err) {
  3113. cb(err);
  3114. }
  3115. });
  3116. };
  3117. /**
  3118. * Lodash support.
  3119. */
  3120. exports$1.lodash = fromStringRenderer('lodash');
  3121. /**
  3122. * Lodash string support.
  3123. */
  3124. exports$1.lodash.render = function(str, options, cb) {
  3125. return promisify(cb, function(cb) {
  3126. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3127. try {
  3128. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3129. cb(null, tmpl(options).replace(/\n$/, ''));
  3130. } catch (err) {
  3131. cb(err);
  3132. }
  3133. });
  3134. };
  3135. /**
  3136. * Pug support. (formerly Jade)
  3137. */
  3138. exports$1.pug = function(path, options, cb) {
  3139. return promisify(cb, function(cb) {
  3140. var engine = requires.pug;
  3141. if (!engine) {
  3142. try {
  3143. engine = requires.pug = require('pug');
  3144. } catch (err) {
  3145. try {
  3146. engine = requires.pug = require('then-pug');
  3147. } catch (otherError) {
  3148. throw err;
  3149. }
  3150. }
  3151. }
  3152. try {
  3153. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3154. cb(null, tmpl(options));
  3155. } catch (err) {
  3156. cb(err);
  3157. }
  3158. });
  3159. };
  3160. /**
  3161. * Pug string support.
  3162. */
  3163. exports$1.pug.render = function(str, options, cb) {
  3164. return promisify(cb, function(cb) {
  3165. var engine = requires.pug;
  3166. if (!engine) {
  3167. try {
  3168. engine = requires.pug = require('pug');
  3169. } catch (err) {
  3170. try {
  3171. engine = requires.pug = require('then-pug');
  3172. } catch (otherError) {
  3173. throw err;
  3174. }
  3175. }
  3176. }
  3177. try {
  3178. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3179. cb(null, tmpl(options));
  3180. } catch (err) {
  3181. cb(err);
  3182. }
  3183. });
  3184. };
  3185. /**
  3186. * QEJS support.
  3187. */
  3188. exports$1.qejs = fromStringRenderer('qejs');
  3189. /**
  3190. * QEJS string support.
  3191. */
  3192. exports$1.qejs.render = function(str, options, cb) {
  3193. return promisify(cb, function(cb) {
  3194. try {
  3195. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3196. engine.render(str, options).then(function(result) {
  3197. cb(null, result);
  3198. }, function(err) {
  3199. cb(err);
  3200. }).done();
  3201. } catch (err) {
  3202. cb(err);
  3203. }
  3204. });
  3205. };
  3206. /**
  3207. * Walrus support.
  3208. */
  3209. exports$1.walrus = fromStringRenderer('walrus');
  3210. /**
  3211. * Walrus string support.
  3212. */
  3213. exports$1.walrus.render = function(str, options, cb) {
  3214. return promisify(cb, function(cb) {
  3215. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3216. try {
  3217. var tmpl = cache(options) || cache(options, engine.parse(str));
  3218. cb(null, tmpl.compile(options));
  3219. } catch (err) {
  3220. cb(err);
  3221. }
  3222. });
  3223. };
  3224. /**
  3225. * Mustache support.
  3226. */
  3227. exports$1.mustache = fromStringRenderer('mustache');
  3228. /**
  3229. * Mustache string support.
  3230. */
  3231. exports$1.mustache.render = function(str, options, cb) {
  3232. return promisify(cb, function(cb) {
  3233. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3234. try {
  3235. cb(null, engine.render(str, options, options.partials));
  3236. } catch (err) {
  3237. cb(err);
  3238. }
  3239. });
  3240. };
  3241. /**
  3242. * Just support.
  3243. */
  3244. exports$1.just = function(path, options, cb) {
  3245. return promisify(cb, function(cb) {
  3246. var engine = requires.just;
  3247. if (!engine) {
  3248. var JUST = require('just');
  3249. engine = requires.just = new JUST();
  3250. }
  3251. engine.configure({ useCache: options.cache });
  3252. engine.render(path, options, cb);
  3253. });
  3254. };
  3255. /**
  3256. * Just string support.
  3257. */
  3258. exports$1.just.render = function(str, options, cb) {
  3259. return promisify(cb, function(cb) {
  3260. var JUST = require('just');
  3261. var engine = new JUST({ root: { page: str }});
  3262. engine.render('page', options, cb);
  3263. });
  3264. };
  3265. /**
  3266. * ECT support.
  3267. */
  3268. exports$1.ect = function(path, options, cb) {
  3269. return promisify(cb, function(cb) {
  3270. var engine = requires.ect;
  3271. if (!engine) {
  3272. var ECT = require('ect');
  3273. engine = requires.ect = new ECT(options);
  3274. }
  3275. engine.configure({ cache: options.cache });
  3276. engine.render(path, options, cb);
  3277. });
  3278. };
  3279. /**
  3280. * ECT string support.
  3281. */
  3282. exports$1.ect.render = function(str, options, cb) {
  3283. return promisify(cb, function(cb) {
  3284. var ECT = require('ect');
  3285. var engine = new ECT({ root: { page: str }});
  3286. engine.render('page', options, cb);
  3287. });
  3288. };
  3289. /**
  3290. * mote support.
  3291. */
  3292. exports$1.mote = fromStringRenderer('mote');
  3293. /**
  3294. * mote string support.
  3295. */
  3296. exports$1.mote.render = function(str, options, cb) {
  3297. return promisify(cb, function(cb) {
  3298. var engine = requires.mote || (requires.mote = require('mote'));
  3299. try {
  3300. var tmpl = cache(options) || cache(options, engine.compile(str));
  3301. cb(null, tmpl(options));
  3302. } catch (err) {
  3303. cb(err);
  3304. }
  3305. });
  3306. };
  3307. /**
  3308. * Toffee support.
  3309. */
  3310. exports$1.toffee = function(path, options, cb) {
  3311. return promisify(cb, function(cb) {
  3312. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3313. toffee.__consolidate_engine_render(path, options, cb);
  3314. });
  3315. };
  3316. /**
  3317. * Toffee string support.
  3318. */
  3319. exports$1.toffee.render = function(str, options, cb) {
  3320. return promisify(cb, function(cb) {
  3321. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3322. try {
  3323. engine.str_render(str, options, cb);
  3324. } catch (err) {
  3325. cb(err);
  3326. }
  3327. });
  3328. };
  3329. /**
  3330. * doT support.
  3331. */
  3332. exports$1.dot = fromStringRenderer('dot');
  3333. /**
  3334. * doT string support.
  3335. */
  3336. exports$1.dot.render = function(str, options, cb) {
  3337. return promisify(cb, function(cb) {
  3338. var engine = requires.dot || (requires.dot = require('dot'));
  3339. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3340. try {
  3341. var settings = {};
  3342. settings = extend(settings, engine.templateSettings);
  3343. settings = extend(settings, options ? options.dot : {});
  3344. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3345. cb(null, tmpl(options));
  3346. } catch (err) {
  3347. cb(err);
  3348. }
  3349. });
  3350. };
  3351. /**
  3352. * bracket support.
  3353. */
  3354. exports$1.bracket = fromStringRenderer('bracket');
  3355. /**
  3356. * bracket string support.
  3357. */
  3358. exports$1.bracket.render = function(str, options, cb) {
  3359. return promisify(cb, function(cb) {
  3360. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3361. try {
  3362. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3363. cb(null, tmpl(options));
  3364. } catch (err) {
  3365. cb(err);
  3366. }
  3367. });
  3368. };
  3369. /**
  3370. * Ractive support.
  3371. */
  3372. exports$1.ractive = fromStringRenderer('ractive');
  3373. /**
  3374. * Ractive string support.
  3375. */
  3376. exports$1.ractive.render = function(str, options, cb) {
  3377. return promisify(cb, function(cb) {
  3378. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3379. var template = cache(options) || cache(options, Engine.parse(str));
  3380. options.template = template;
  3381. if (options.data === null || options.data === undefined) {
  3382. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3383. // Shallow clone the options object
  3384. options.data = extend({}, options);
  3385. // Remove consolidate-specific properties from the clone
  3386. var i;
  3387. var length;
  3388. var properties = ['template', 'filename', 'cache', 'partials'];
  3389. for (i = 0, length = properties.length; i < length; i++) {
  3390. var property = properties[i];
  3391. delete options.data[property];
  3392. }
  3393. }
  3394. try {
  3395. cb(null, new Engine(options).toHTML());
  3396. } catch (err) {
  3397. cb(err);
  3398. }
  3399. });
  3400. };
  3401. /**
  3402. * Nunjucks support.
  3403. */
  3404. exports$1.nunjucks = fromStringRenderer('nunjucks');
  3405. /**
  3406. * Nunjucks string support.
  3407. */
  3408. exports$1.nunjucks.render = function(str, options, cb) {
  3409. return promisify(cb, function(cb) {
  3410. try {
  3411. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3412. var env = engine;
  3413. // deprecated fallback support for express
  3414. // <https://github.com/tj/consolidate.js/pull/152>
  3415. // <https://github.com/tj/consolidate.js/pull/224>
  3416. if (options.settings && options.settings.views) {
  3417. env = engine.configure(options.settings.views);
  3418. } else if (options.nunjucks && options.nunjucks.configure) {
  3419. env = engine.configure.apply(engine, options.nunjucks.configure);
  3420. }
  3421. //
  3422. // because `renderString` does not initiate loaders
  3423. // we must manually create a loader for it based off
  3424. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3425. //
  3426. // <https://github.com/mozilla/nunjucks/issues/730>
  3427. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3428. //
  3429. // so instead we simply check if we passed a custom loader
  3430. // otherwise we create a simple file based loader
  3431. if (options.loader) {
  3432. env = new engine.Environment(options.loader);
  3433. } else if (options.settings && options.settings.views) {
  3434. env = new engine.Environment(
  3435. new engine.FileSystemLoader(options.settings.views)
  3436. );
  3437. } else if (options.nunjucks && options.nunjucks.loader) {
  3438. if (typeof options.nunjucks.loader === 'string') {
  3439. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3440. } else {
  3441. env = new engine.Environment(
  3442. new engine.FileSystemLoader(
  3443. options.nunjucks.loader[0],
  3444. options.nunjucks.loader[1]
  3445. )
  3446. );
  3447. }
  3448. }
  3449. env.renderString(str, options, cb);
  3450. } catch (err) {
  3451. throw cb(err);
  3452. }
  3453. });
  3454. };
  3455. /**
  3456. * HTMLing support.
  3457. */
  3458. exports$1.htmling = fromStringRenderer('htmling');
  3459. /**
  3460. * HTMLing string support.
  3461. */
  3462. exports$1.htmling.render = function(str, options, cb) {
  3463. return promisify(cb, function(cb) {
  3464. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3465. try {
  3466. var tmpl = cache(options) || cache(options, engine.string(str));
  3467. cb(null, tmpl.render(options));
  3468. } catch (err) {
  3469. cb(err);
  3470. }
  3471. });
  3472. };
  3473. /**
  3474. * Rendering function
  3475. */
  3476. function requireReact(module, filename) {
  3477. var babel = requires.babel || (requires.babel = require('babel-core'));
  3478. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3479. return module._compile(compiled, filename);
  3480. }
  3481. exports$1.requireReact = requireReact;
  3482. /**
  3483. * Converting a string into a node module.
  3484. */
  3485. function requireReactString(src, filename) {
  3486. var babel = requires.babel || (requires.babel = require('babel-core'));
  3487. if (!filename) filename = '';
  3488. var m = new module.constructor();
  3489. filename = filename || '';
  3490. // Compile Using React
  3491. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3492. // Compile as a module
  3493. m.paths = module.paths;
  3494. m._compile(compiled, filename);
  3495. return m.exports;
  3496. }
  3497. /**
  3498. * A naive helper to replace {{tags}} with options.tags content
  3499. */
  3500. function reactBaseTmpl(data, options) {
  3501. var exp;
  3502. var regex;
  3503. // Iterates through the keys in file object
  3504. // and interpolate / replace {{key}} with it's value
  3505. for (var k in options) {
  3506. if (options.hasOwnProperty(k)) {
  3507. exp = '{{' + k + '}}';
  3508. regex = new RegExp(exp, 'g');
  3509. if (data.match(regex)) {
  3510. data = data.replace(regex, options[k]);
  3511. }
  3512. }
  3513. }
  3514. return data;
  3515. }
  3516. /**
  3517. * Plates Support.
  3518. */
  3519. exports$1.plates = fromStringRenderer('plates');
  3520. /**
  3521. * Plates string support.
  3522. */
  3523. exports$1.plates.render = function(str, options, cb) {
  3524. return promisify(cb, function(cb) {
  3525. var engine = requires.plates || (requires.plates = require('plates'));
  3526. var map = options.map || undefined;
  3527. try {
  3528. var tmpl = engine.bind(str, options, map);
  3529. cb(null, tmpl);
  3530. } catch (err) {
  3531. cb(err);
  3532. }
  3533. });
  3534. };
  3535. /**
  3536. * The main render parser for React bsaed templates
  3537. */
  3538. function reactRenderer(type) {
  3539. if (commonjsRequire.extensions) {
  3540. // Ensure JSX is transformed on require
  3541. if (!commonjsRequire.extensions['.jsx']) {
  3542. commonjsRequire.extensions['.jsx'] = requireReact;
  3543. }
  3544. // Supporting .react extension as well as test cases
  3545. // Using .react extension is not recommended.
  3546. if (!commonjsRequire.extensions['.react']) {
  3547. commonjsRequire.extensions['.react'] = requireReact;
  3548. }
  3549. }
  3550. // Return rendering fx
  3551. return function(str, options, cb) {
  3552. return promisify(cb, function(cb) {
  3553. // React Import
  3554. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3555. var react = requires.react || (requires.react = require('react'));
  3556. // Assign HTML Base
  3557. var base = options.base;
  3558. delete options.base;
  3559. var enableCache = options.cache;
  3560. delete options.cache;
  3561. var isNonStatic = options.isNonStatic;
  3562. delete options.isNonStatic;
  3563. // Start Conversion
  3564. try {
  3565. var Code;
  3566. var Factory;
  3567. var baseStr;
  3568. var content;
  3569. var parsed;
  3570. if (!cache(options)) {
  3571. // Parsing
  3572. if (type === 'path') {
  3573. var path = resolve(str);
  3574. delete require.cache[path];
  3575. Code = commonjsRequire(path);
  3576. } else {
  3577. Code = requireReactString(str);
  3578. }
  3579. Factory = cache(options, react.createFactory(Code));
  3580. } else {
  3581. Factory = cache(options);
  3582. }
  3583. parsed = new Factory(options);
  3584. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3585. if (base) {
  3586. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3587. if (enableCache) {
  3588. readCache[str] = baseStr;
  3589. }
  3590. options.content = content;
  3591. content = reactBaseTmpl(baseStr, options);
  3592. }
  3593. cb(null, content);
  3594. } catch (err) {
  3595. cb(err);
  3596. }
  3597. });
  3598. };
  3599. }
  3600. /**
  3601. * React JS Support
  3602. */
  3603. exports$1.react = reactRenderer('path');
  3604. /**
  3605. * React JS string support.
  3606. */
  3607. exports$1.react.render = reactRenderer('string');
  3608. /**
  3609. * ARC-templates support.
  3610. */
  3611. exports$1['arc-templates'] = fromStringRenderer('arc-templates');
  3612. /**
  3613. * ARC-templates string support.
  3614. */
  3615. exports$1['arc-templates'].render = function(str, options, cb) {
  3616. var readFileWithOptions = util.promisify(read);
  3617. var consolidateFileSystem = {};
  3618. consolidateFileSystem.readFile = function(path) {
  3619. return readFileWithOptions(path, options);
  3620. };
  3621. return promisify(cb, function(cb) {
  3622. try {
  3623. var engine = requires['arc-templates'];
  3624. if (!engine) {
  3625. var Engine = require('arc-templates/dist/es5');
  3626. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3627. }
  3628. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3629. compiler.then(function(func) { return func(options); })
  3630. .then(function(result) { cb(null, result.content); })
  3631. .catch(cb);
  3632. } catch (err) {
  3633. cb(err);
  3634. }
  3635. });
  3636. };
  3637. /**
  3638. * Vash support
  3639. */
  3640. exports$1.vash = fromStringRenderer('vash');
  3641. /**
  3642. * Vash string support
  3643. */
  3644. exports$1.vash.render = function(str, options, cb) {
  3645. return promisify(cb, function(cb) {
  3646. var engine = requires.vash || (requires.vash = require('vash'));
  3647. try {
  3648. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3649. if (options.helpers) {
  3650. for (var key in options.helpers) {
  3651. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3652. continue;
  3653. }
  3654. engine.helpers[key] = options.helpers[key];
  3655. }
  3656. }
  3657. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3658. tmpl(options, function sealLayout(err, ctx) {
  3659. if (err) cb(err);
  3660. ctx.finishLayout();
  3661. cb(null, ctx.toString().replace(/\n$/, ''));
  3662. });
  3663. } catch (err) {
  3664. cb(err);
  3665. }
  3666. });
  3667. };
  3668. /**
  3669. * Slm support.
  3670. */
  3671. exports$1.slm = fromStringRenderer('slm');
  3672. /**
  3673. * Slm string support.
  3674. */
  3675. exports$1.slm.render = function(str, options, cb) {
  3676. return promisify(cb, function(cb) {
  3677. var engine = requires.slm || (requires.slm = require('slm'));
  3678. try {
  3679. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3680. cb(null, tmpl(options));
  3681. } catch (err) {
  3682. cb(err);
  3683. }
  3684. });
  3685. };
  3686. /**
  3687. * Marko support.
  3688. */
  3689. exports$1.marko = function(path, options, cb) {
  3690. return promisify(cb, function(cb) {
  3691. var engine = requires.marko || (requires.marko = require('marko'));
  3692. options.writeToDisk = !!options.cache;
  3693. try {
  3694. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3695. tmpl.renderToString(options, cb);
  3696. } catch (err) {
  3697. cb(err);
  3698. }
  3699. });
  3700. };
  3701. /**
  3702. * Marko string support.
  3703. */
  3704. exports$1.marko.render = function(str, options, cb) {
  3705. return promisify(cb, function(cb) {
  3706. var engine = requires.marko || (requires.marko = require('marko'));
  3707. options.writeToDisk = !!options.cache;
  3708. options.filename = options.filename || 'string.marko';
  3709. try {
  3710. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3711. tmpl.renderToString(options, cb);
  3712. } catch (err) {
  3713. cb(err);
  3714. }
  3715. });
  3716. };
  3717. /**
  3718. * Teacup support.
  3719. */
  3720. exports$1.teacup = function(path, options, cb) {
  3721. return promisify(cb, function(cb) {
  3722. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3723. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3724. if (path[0] !== '/') {
  3725. path = join(process.cwd(), path);
  3726. }
  3727. if (!options.cache) {
  3728. var callback = cb;
  3729. cb = function() {
  3730. delete require.cache[path];
  3731. callback.apply(this, arguments);
  3732. };
  3733. }
  3734. engine.renderFile(path, options, cb);
  3735. });
  3736. };
  3737. /**
  3738. * Teacup string support.
  3739. */
  3740. exports$1.teacup.render = function(str, options, cb) {
  3741. var coffee = require('coffee-script');
  3742. var vm = require('vm');
  3743. var sandbox = {
  3744. module: {exports: {}},
  3745. require: commonjsRequire
  3746. };
  3747. return promisify(cb, function(cb) {
  3748. vm.runInNewContext(coffee.compile(str), sandbox);
  3749. var tmpl = sandbox.module.exports;
  3750. cb(null, tmpl(options));
  3751. });
  3752. };
  3753. /**
  3754. * Squirrelly support.
  3755. */
  3756. exports$1.squirrelly = fromStringRenderer('squirrelly');
  3757. /**
  3758. * Squirrelly string support.
  3759. */
  3760. exports$1.squirrelly.render = function(str, options, cb) {
  3761. return promisify(cb, function(cb) {
  3762. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3763. try {
  3764. for (var partial in options.partials) {
  3765. engine.definePartial(partial, options.partials[partial]);
  3766. }
  3767. for (var helper in options.helpers) {
  3768. engine.defineHelper(helper, options.helpers[helper]);
  3769. }
  3770. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3771. cb(null, tmpl(options, engine));
  3772. } catch (err) {
  3773. cb(err);
  3774. }
  3775. });
  3776. };
  3777. /**
  3778. * Twing support.
  3779. */
  3780. exports$1.twing = fromStringRenderer('twing');
  3781. /**
  3782. * Twing string support.
  3783. */
  3784. exports$1.twing.render = function(str, options, cb) {
  3785. return promisify(cb, function(cb) {
  3786. var engine = requires.twing || (requires.twing = require('twing'));
  3787. try {
  3788. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3789. twingTemplate.render(options).then((rendTmpl) => {
  3790. var tmpl = cache(options) || cache(options, rendTmpl);
  3791. cb(null, tmpl);
  3792. });
  3793. });
  3794. } catch (err) {
  3795. cb(err);
  3796. }
  3797. });
  3798. };
  3799. /**
  3800. * expose the instance of the engine
  3801. */
  3802. exports$1.requires = requires;
  3803. } (consolidate$2, consolidate$2.exports));
  3804. return consolidate$2.exports;
  3805. }
  3806. var consolidate$1;
  3807. var hasRequiredConsolidate;
  3808. function requireConsolidate () {
  3809. if (hasRequiredConsolidate) return consolidate$1;
  3810. hasRequiredConsolidate = 1;
  3811. consolidate$1 = /*@__PURE__*/ requireConsolidate$1();
  3812. return consolidate$1;
  3813. }
  3814. var consolidateExports = /*@__PURE__*/ requireConsolidate();
  3815. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports);
  3816. const hasWarned = {};
  3817. function warnOnce(msg) {
  3818. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3819. if (!isNodeProd && true && !hasWarned[msg]) {
  3820. hasWarned[msg] = true;
  3821. warn(msg);
  3822. }
  3823. }
  3824. function warn(msg) {
  3825. console.warn(
  3826. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3827. `
  3828. );
  3829. }
  3830. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3831. let res = "";
  3832. let err = null;
  3833. preprocessor.render(
  3834. source,
  3835. { filename, ...preprocessOptions },
  3836. (_err, _res) => {
  3837. if (_err) err = _err;
  3838. res = _res;
  3839. }
  3840. );
  3841. if (err) throw err;
  3842. return res;
  3843. }
  3844. function compileTemplate(options) {
  3845. const { preprocessLang, preprocessCustomRequire } = options;
  3846. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3847. if (preprocessor) {
  3848. try {
  3849. return doCompileTemplate({
  3850. ...options,
  3851. source: preprocess$1(options, preprocessor),
  3852. ast: void 0
  3853. // invalidate AST if template goes through preprocessor
  3854. });
  3855. } catch (e) {
  3856. return {
  3857. code: `export default function render() {}`,
  3858. source: options.source,
  3859. tips: [],
  3860. errors: [e]
  3861. };
  3862. }
  3863. } else if (preprocessLang) {
  3864. return {
  3865. code: `export default function render() {}`,
  3866. source: options.source,
  3867. tips: [
  3868. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3869. ],
  3870. errors: [
  3871. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3872. ]
  3873. };
  3874. } else {
  3875. return doCompileTemplate(options);
  3876. }
  3877. }
  3878. function doCompileTemplate({
  3879. filename,
  3880. id,
  3881. scoped,
  3882. slotted,
  3883. inMap,
  3884. source,
  3885. ast: inAST,
  3886. ssr = false,
  3887. ssrCssVars,
  3888. isProd = false,
  3889. compiler,
  3890. compilerOptions = {},
  3891. transformAssetUrls
  3892. }) {
  3893. const errors = [];
  3894. const warnings = [];
  3895. let nodeTransforms = [];
  3896. if (shared.isObject(transformAssetUrls)) {
  3897. const assetOptions = normalizeOptions(transformAssetUrls);
  3898. nodeTransforms = [
  3899. createAssetUrlTransformWithOptions(assetOptions),
  3900. createSrcsetTransformWithOptions(assetOptions)
  3901. ];
  3902. } else if (transformAssetUrls !== false) {
  3903. nodeTransforms = [transformAssetUrl, transformSrcset];
  3904. }
  3905. if (ssr && !ssrCssVars) {
  3906. warnOnce(
  3907. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3908. );
  3909. }
  3910. if (!id) {
  3911. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3912. id = "";
  3913. }
  3914. const shortId = id.replace(/^data-v-/, "");
  3915. const longId = `data-v-${shortId}`;
  3916. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3917. compiler = compiler || defaultCompiler;
  3918. if (compiler !== defaultCompiler) {
  3919. inAST = void 0;
  3920. }
  3921. if (inAST == null ? void 0 : inAST.transformed) {
  3922. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3923. prefixIdentifiers: true,
  3924. ...compilerOptions,
  3925. parseMode: "sfc",
  3926. onError: (e) => errors.push(e)
  3927. });
  3928. const template = newAST.children.find(
  3929. (node) => node.type === 1 && node.tag === "template"
  3930. );
  3931. inAST = compilerCore.createRoot(template.children, inAST.source);
  3932. }
  3933. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3934. mode: "module",
  3935. prefixIdentifiers: true,
  3936. hoistStatic: true,
  3937. cacheHandlers: true,
  3938. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3939. scopeId: scoped ? longId : void 0,
  3940. slotted,
  3941. sourceMap: true,
  3942. ...compilerOptions,
  3943. hmr: !isProd,
  3944. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3945. filename,
  3946. onError: (e) => errors.push(e),
  3947. onWarn: (w) => warnings.push(w)
  3948. });
  3949. if (inMap && !inAST) {
  3950. if (map) {
  3951. map = mapLines(inMap, map);
  3952. }
  3953. if (errors.length) {
  3954. patchErrors(errors, source, inMap);
  3955. }
  3956. }
  3957. const tips = warnings.map((w) => {
  3958. let msg = w.message;
  3959. if (w.loc) {
  3960. msg += `
  3961. ${shared.generateCodeFrame(
  3962. (inAST == null ? void 0 : inAST.source) || source,
  3963. w.loc.start.offset,
  3964. w.loc.end.offset
  3965. )}`;
  3966. }
  3967. return msg;
  3968. });
  3969. return { code, ast, preamble, source, errors, tips, map };
  3970. }
  3971. function mapLines(oldMap, newMap) {
  3972. if (!oldMap) return newMap;
  3973. if (!newMap) return oldMap;
  3974. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  3975. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  3976. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  3977. newMapConsumer.eachMapping((m) => {
  3978. if (m.originalLine == null) {
  3979. return;
  3980. }
  3981. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  3982. line: m.originalLine,
  3983. column: m.originalColumn
  3984. });
  3985. if (origPosInOldMap.source == null) {
  3986. return;
  3987. }
  3988. mergedMapGenerator.addMapping({
  3989. generated: {
  3990. line: m.generatedLine,
  3991. column: m.generatedColumn
  3992. },
  3993. original: {
  3994. line: origPosInOldMap.line,
  3995. // map line
  3996. // use current column, since the oldMap produced by @vue/compiler-sfc
  3997. // does not
  3998. column: m.originalColumn
  3999. },
  4000. source: origPosInOldMap.source,
  4001. name: origPosInOldMap.name
  4002. });
  4003. });
  4004. const generator = mergedMapGenerator;
  4005. oldMapConsumer.sources.forEach((sourceFile) => {
  4006. generator._sources.add(sourceFile);
  4007. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  4008. if (sourceContent != null) {
  4009. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  4010. }
  4011. });
  4012. generator._sourceRoot = oldMap.sourceRoot;
  4013. generator._file = oldMap.file;
  4014. return generator.toJSON();
  4015. }
  4016. function patchErrors(errors, source, inMap) {
  4017. const originalSource = inMap.sourcesContent[0];
  4018. const offset = originalSource.indexOf(source);
  4019. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  4020. errors.forEach((err) => {
  4021. if (err.loc) {
  4022. err.loc.start.line += lineOffset;
  4023. err.loc.start.offset += offset;
  4024. if (err.loc.end !== err.loc.start) {
  4025. err.loc.end.line += lineOffset;
  4026. err.loc.end.offset += offset;
  4027. }
  4028. }
  4029. });
  4030. }
  4031. const trimPlugin = () => {
  4032. return {
  4033. postcssPlugin: "vue-sfc-trim",
  4034. Once(root) {
  4035. root.walk(({ type, raws }) => {
  4036. if (type === "rule" || type === "atrule") {
  4037. if (raws.before) raws.before = "\n";
  4038. if ("after" in raws && raws.after) raws.after = "\n";
  4039. }
  4040. });
  4041. }
  4042. };
  4043. };
  4044. trimPlugin.postcss = true;
  4045. var dist$1 = {exports: {}};
  4046. var processor$1 = {exports: {}};
  4047. var parser$1 = {exports: {}};
  4048. var root$1 = {exports: {}};
  4049. var container$1 = {exports: {}};
  4050. var node$2 = {exports: {}};
  4051. var util$2 = {};
  4052. var unesc$1 = {exports: {}};
  4053. var hasRequiredUnesc$1;
  4054. function requireUnesc$1 () {
  4055. if (hasRequiredUnesc$1) return unesc$1.exports;
  4056. hasRequiredUnesc$1 = 1;
  4057. (function (module, exports$1) {
  4058. exports$1.__esModule = true;
  4059. exports$1["default"] = unesc;
  4060. // Many thanks for this post which made this migration much easier.
  4061. // https://mathiasbynens.be/notes/css-escapes
  4062. /**
  4063. *
  4064. * @param {string} str
  4065. * @returns {[string, number]|undefined}
  4066. */
  4067. function gobbleHex(str) {
  4068. var lower = str.toLowerCase();
  4069. var hex = '';
  4070. var spaceTerminated = false;
  4071. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4072. var code = lower.charCodeAt(i);
  4073. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4074. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4075. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4076. spaceTerminated = code === 32;
  4077. if (!valid) {
  4078. break;
  4079. }
  4080. hex += lower[i];
  4081. }
  4082. if (hex.length === 0) {
  4083. return undefined;
  4084. }
  4085. var codePoint = parseInt(hex, 16);
  4086. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4087. // Add special case for
  4088. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4089. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4090. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4091. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4092. }
  4093. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4094. }
  4095. var CONTAINS_ESCAPE = /\\/;
  4096. function unesc(str) {
  4097. var needToProcess = CONTAINS_ESCAPE.test(str);
  4098. if (!needToProcess) {
  4099. return str;
  4100. }
  4101. var ret = "";
  4102. for (var i = 0; i < str.length; i++) {
  4103. if (str[i] === "\\") {
  4104. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4105. if (gobbled !== undefined) {
  4106. ret += gobbled[0];
  4107. i += gobbled[1];
  4108. continue;
  4109. }
  4110. // Retain a pair of \\ if double escaped `\\\\`
  4111. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4112. if (str[i + 1] === "\\") {
  4113. ret += "\\";
  4114. i++;
  4115. continue;
  4116. }
  4117. // if \\ is at the end of the string retain it
  4118. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4119. if (str.length === i + 1) {
  4120. ret += str[i];
  4121. }
  4122. continue;
  4123. }
  4124. ret += str[i];
  4125. }
  4126. return ret;
  4127. }
  4128. module.exports = exports$1.default;
  4129. } (unesc$1, unesc$1.exports));
  4130. return unesc$1.exports;
  4131. }
  4132. var getProp$1 = {exports: {}};
  4133. var hasRequiredGetProp$1;
  4134. function requireGetProp$1 () {
  4135. if (hasRequiredGetProp$1) return getProp$1.exports;
  4136. hasRequiredGetProp$1 = 1;
  4137. (function (module, exports$1) {
  4138. exports$1.__esModule = true;
  4139. exports$1["default"] = getProp;
  4140. function getProp(obj) {
  4141. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4142. props[_key - 1] = arguments[_key];
  4143. }
  4144. while (props.length > 0) {
  4145. var prop = props.shift();
  4146. if (!obj[prop]) {
  4147. return undefined;
  4148. }
  4149. obj = obj[prop];
  4150. }
  4151. return obj;
  4152. }
  4153. module.exports = exports$1.default;
  4154. } (getProp$1, getProp$1.exports));
  4155. return getProp$1.exports;
  4156. }
  4157. var ensureObject$1 = {exports: {}};
  4158. var hasRequiredEnsureObject$1;
  4159. function requireEnsureObject$1 () {
  4160. if (hasRequiredEnsureObject$1) return ensureObject$1.exports;
  4161. hasRequiredEnsureObject$1 = 1;
  4162. (function (module, exports$1) {
  4163. exports$1.__esModule = true;
  4164. exports$1["default"] = ensureObject;
  4165. function ensureObject(obj) {
  4166. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4167. props[_key - 1] = arguments[_key];
  4168. }
  4169. while (props.length > 0) {
  4170. var prop = props.shift();
  4171. if (!obj[prop]) {
  4172. obj[prop] = {};
  4173. }
  4174. obj = obj[prop];
  4175. }
  4176. }
  4177. module.exports = exports$1.default;
  4178. } (ensureObject$1, ensureObject$1.exports));
  4179. return ensureObject$1.exports;
  4180. }
  4181. var stripComments$1 = {exports: {}};
  4182. var hasRequiredStripComments$1;
  4183. function requireStripComments$1 () {
  4184. if (hasRequiredStripComments$1) return stripComments$1.exports;
  4185. hasRequiredStripComments$1 = 1;
  4186. (function (module, exports$1) {
  4187. exports$1.__esModule = true;
  4188. exports$1["default"] = stripComments;
  4189. function stripComments(str) {
  4190. var s = "";
  4191. var commentStart = str.indexOf("/*");
  4192. var lastEnd = 0;
  4193. while (commentStart >= 0) {
  4194. s = s + str.slice(lastEnd, commentStart);
  4195. var commentEnd = str.indexOf("*/", commentStart + 2);
  4196. if (commentEnd < 0) {
  4197. return s;
  4198. }
  4199. lastEnd = commentEnd + 2;
  4200. commentStart = str.indexOf("/*", lastEnd);
  4201. }
  4202. s = s + str.slice(lastEnd);
  4203. return s;
  4204. }
  4205. module.exports = exports$1.default;
  4206. } (stripComments$1, stripComments$1.exports));
  4207. return stripComments$1.exports;
  4208. }
  4209. var hasRequiredUtil$2;
  4210. function requireUtil$2 () {
  4211. if (hasRequiredUtil$2) return util$2;
  4212. hasRequiredUtil$2 = 1;
  4213. util$2.__esModule = true;
  4214. util$2.unesc = util$2.stripComments = util$2.getProp = util$2.ensureObject = void 0;
  4215. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  4216. util$2.unesc = _unesc["default"];
  4217. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp$1());
  4218. util$2.getProp = _getProp["default"];
  4219. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject$1());
  4220. util$2.ensureObject = _ensureObject["default"];
  4221. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments$1());
  4222. util$2.stripComments = _stripComments["default"];
  4223. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4224. return util$2;
  4225. }
  4226. var hasRequiredNode$2;
  4227. function requireNode$2 () {
  4228. if (hasRequiredNode$2) return node$2.exports;
  4229. hasRequiredNode$2 = 1;
  4230. (function (module, exports$1) {
  4231. exports$1.__esModule = true;
  4232. exports$1["default"] = void 0;
  4233. var _util = /*@__PURE__*/ requireUtil$2();
  4234. 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); } }
  4235. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4236. var cloneNode = function cloneNode(obj, parent) {
  4237. if (typeof obj !== 'object' || obj === null) {
  4238. return obj;
  4239. }
  4240. var cloned = new obj.constructor();
  4241. for (var i in obj) {
  4242. if (!obj.hasOwnProperty(i)) {
  4243. continue;
  4244. }
  4245. var value = obj[i];
  4246. var type = typeof value;
  4247. if (i === 'parent' && type === 'object') {
  4248. if (parent) {
  4249. cloned[i] = parent;
  4250. }
  4251. } else if (value instanceof Array) {
  4252. cloned[i] = value.map(function (j) {
  4253. return cloneNode(j, cloned);
  4254. });
  4255. } else {
  4256. cloned[i] = cloneNode(value, cloned);
  4257. }
  4258. }
  4259. return cloned;
  4260. };
  4261. var Node = /*#__PURE__*/function () {
  4262. function Node(opts) {
  4263. if (opts === void 0) {
  4264. opts = {};
  4265. }
  4266. Object.assign(this, opts);
  4267. this.spaces = this.spaces || {};
  4268. this.spaces.before = this.spaces.before || '';
  4269. this.spaces.after = this.spaces.after || '';
  4270. }
  4271. var _proto = Node.prototype;
  4272. _proto.remove = function remove() {
  4273. if (this.parent) {
  4274. this.parent.removeChild(this);
  4275. }
  4276. this.parent = undefined;
  4277. return this;
  4278. };
  4279. _proto.replaceWith = function replaceWith() {
  4280. if (this.parent) {
  4281. for (var index in arguments) {
  4282. this.parent.insertBefore(this, arguments[index]);
  4283. }
  4284. this.remove();
  4285. }
  4286. return this;
  4287. };
  4288. _proto.next = function next() {
  4289. return this.parent.at(this.parent.index(this) + 1);
  4290. };
  4291. _proto.prev = function prev() {
  4292. return this.parent.at(this.parent.index(this) - 1);
  4293. };
  4294. _proto.clone = function clone(overrides) {
  4295. if (overrides === void 0) {
  4296. overrides = {};
  4297. }
  4298. var cloned = cloneNode(this);
  4299. for (var name in overrides) {
  4300. cloned[name] = overrides[name];
  4301. }
  4302. return cloned;
  4303. }
  4304. /**
  4305. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4306. * This allows non standard syntax to be appended to an existing property
  4307. * by specifying the escaped value. By specifying the escaped value,
  4308. * illegal characters are allowed to be directly inserted into css output.
  4309. * @param {string} name the property to set
  4310. * @param {any} value the unescaped value of the property
  4311. * @param {string} valueEscaped optional. the escaped value of the property.
  4312. */;
  4313. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4314. if (!this.raws) {
  4315. this.raws = {};
  4316. }
  4317. var originalValue = this[name];
  4318. var originalEscaped = this.raws[name];
  4319. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4320. if (originalEscaped || valueEscaped !== value) {
  4321. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4322. } else {
  4323. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4324. }
  4325. }
  4326. /**
  4327. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4328. * This allows the escaped value to be specified directly, allowing illegal
  4329. * characters to be directly inserted into css output.
  4330. * @param {string} name the property to set
  4331. * @param {any} value the unescaped value of the property
  4332. * @param {string} valueEscaped the escaped value of the property.
  4333. */;
  4334. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4335. if (!this.raws) {
  4336. this.raws = {};
  4337. }
  4338. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4339. this.raws[name] = valueEscaped;
  4340. }
  4341. /**
  4342. * When you want a value to passed through to CSS directly. This method
  4343. * deletes the corresponding raw value causing the stringifier to fallback
  4344. * to the unescaped value.
  4345. * @param {string} name the property to set.
  4346. * @param {any} value The value that is both escaped and unescaped.
  4347. */;
  4348. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4349. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4350. if (this.raws) {
  4351. delete this.raws[name];
  4352. }
  4353. }
  4354. /**
  4355. *
  4356. * @param {number} line The number (starting with 1)
  4357. * @param {number} column The column number (starting with 1)
  4358. */;
  4359. _proto.isAtPosition = function isAtPosition(line, column) {
  4360. if (this.source && this.source.start && this.source.end) {
  4361. if (this.source.start.line > line) {
  4362. return false;
  4363. }
  4364. if (this.source.end.line < line) {
  4365. return false;
  4366. }
  4367. if (this.source.start.line === line && this.source.start.column > column) {
  4368. return false;
  4369. }
  4370. if (this.source.end.line === line && this.source.end.column < column) {
  4371. return false;
  4372. }
  4373. return true;
  4374. }
  4375. return undefined;
  4376. };
  4377. _proto.stringifyProperty = function stringifyProperty(name) {
  4378. return this.raws && this.raws[name] || this[name];
  4379. };
  4380. _proto.valueToString = function valueToString() {
  4381. return String(this.stringifyProperty("value"));
  4382. };
  4383. _proto.toString = function toString() {
  4384. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4385. };
  4386. _createClass(Node, [{
  4387. key: "rawSpaceBefore",
  4388. get: function get() {
  4389. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4390. if (rawSpace === undefined) {
  4391. rawSpace = this.spaces && this.spaces.before;
  4392. }
  4393. return rawSpace || "";
  4394. },
  4395. set: function set(raw) {
  4396. (0, _util.ensureObject)(this, "raws", "spaces");
  4397. this.raws.spaces.before = raw;
  4398. }
  4399. }, {
  4400. key: "rawSpaceAfter",
  4401. get: function get() {
  4402. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4403. if (rawSpace === undefined) {
  4404. rawSpace = this.spaces.after;
  4405. }
  4406. return rawSpace || "";
  4407. },
  4408. set: function set(raw) {
  4409. (0, _util.ensureObject)(this, "raws", "spaces");
  4410. this.raws.spaces.after = raw;
  4411. }
  4412. }]);
  4413. return Node;
  4414. }();
  4415. exports$1["default"] = Node;
  4416. module.exports = exports$1.default;
  4417. } (node$2, node$2.exports));
  4418. return node$2.exports;
  4419. }
  4420. var types$2 = {};
  4421. var hasRequiredTypes$1;
  4422. function requireTypes$1 () {
  4423. if (hasRequiredTypes$1) return types$2;
  4424. hasRequiredTypes$1 = 1;
  4425. types$2.__esModule = true;
  4426. 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;
  4427. var TAG = 'tag';
  4428. types$2.TAG = TAG;
  4429. var STRING = 'string';
  4430. types$2.STRING = STRING;
  4431. var SELECTOR = 'selector';
  4432. types$2.SELECTOR = SELECTOR;
  4433. var ROOT = 'root';
  4434. types$2.ROOT = ROOT;
  4435. var PSEUDO = 'pseudo';
  4436. types$2.PSEUDO = PSEUDO;
  4437. var NESTING = 'nesting';
  4438. types$2.NESTING = NESTING;
  4439. var ID = 'id';
  4440. types$2.ID = ID;
  4441. var COMMENT = 'comment';
  4442. types$2.COMMENT = COMMENT;
  4443. var COMBINATOR = 'combinator';
  4444. types$2.COMBINATOR = COMBINATOR;
  4445. var CLASS = 'class';
  4446. types$2.CLASS = CLASS;
  4447. var ATTRIBUTE = 'attribute';
  4448. types$2.ATTRIBUTE = ATTRIBUTE;
  4449. var UNIVERSAL = 'universal';
  4450. types$2.UNIVERSAL = UNIVERSAL;
  4451. return types$2;
  4452. }
  4453. var hasRequiredContainer$1;
  4454. function requireContainer$1 () {
  4455. if (hasRequiredContainer$1) return container$1.exports;
  4456. hasRequiredContainer$1 = 1;
  4457. (function (module, exports$1) {
  4458. exports$1.__esModule = true;
  4459. exports$1["default"] = void 0;
  4460. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4461. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  4462. 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); }
  4463. 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; }
  4464. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4465. 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."); }
  4466. 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); }
  4467. 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; }
  4468. 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); } }
  4469. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4470. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4471. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4472. var Container = /*#__PURE__*/function (_Node) {
  4473. _inheritsLoose(Container, _Node);
  4474. function Container(opts) {
  4475. var _this;
  4476. _this = _Node.call(this, opts) || this;
  4477. if (!_this.nodes) {
  4478. _this.nodes = [];
  4479. }
  4480. return _this;
  4481. }
  4482. var _proto = Container.prototype;
  4483. _proto.append = function append(selector) {
  4484. selector.parent = this;
  4485. this.nodes.push(selector);
  4486. return this;
  4487. };
  4488. _proto.prepend = function prepend(selector) {
  4489. selector.parent = this;
  4490. this.nodes.unshift(selector);
  4491. for (var id in this.indexes) {
  4492. this.indexes[id]++;
  4493. }
  4494. return this;
  4495. };
  4496. _proto.at = function at(index) {
  4497. return this.nodes[index];
  4498. };
  4499. _proto.index = function index(child) {
  4500. if (typeof child === 'number') {
  4501. return child;
  4502. }
  4503. return this.nodes.indexOf(child);
  4504. };
  4505. _proto.removeChild = function removeChild(child) {
  4506. child = this.index(child);
  4507. this.at(child).parent = undefined;
  4508. this.nodes.splice(child, 1);
  4509. var index;
  4510. for (var id in this.indexes) {
  4511. index = this.indexes[id];
  4512. if (index >= child) {
  4513. this.indexes[id] = index - 1;
  4514. }
  4515. }
  4516. return this;
  4517. };
  4518. _proto.removeAll = function removeAll() {
  4519. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4520. var node = _step.value;
  4521. node.parent = undefined;
  4522. }
  4523. this.nodes = [];
  4524. return this;
  4525. };
  4526. _proto.empty = function empty() {
  4527. return this.removeAll();
  4528. };
  4529. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4530. var _this$nodes;
  4531. newNode.parent = this;
  4532. var oldIndex = this.index(oldNode);
  4533. var resetNode = [];
  4534. for (var i = 2; i < arguments.length; i++) {
  4535. resetNode.push(arguments[i]);
  4536. }
  4537. (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
  4538. newNode.parent = this;
  4539. var index;
  4540. for (var id in this.indexes) {
  4541. index = this.indexes[id];
  4542. if (oldIndex < index) {
  4543. this.indexes[id] = index + arguments.length - 1;
  4544. }
  4545. }
  4546. return this;
  4547. };
  4548. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4549. var _this$nodes2;
  4550. newNode.parent = this;
  4551. var oldIndex = this.index(oldNode);
  4552. var resetNode = [];
  4553. for (var i = 2; i < arguments.length; i++) {
  4554. resetNode.push(arguments[i]);
  4555. }
  4556. (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
  4557. newNode.parent = this;
  4558. var index;
  4559. for (var id in this.indexes) {
  4560. index = this.indexes[id];
  4561. if (index >= oldIndex) {
  4562. this.indexes[id] = index + arguments.length - 1;
  4563. }
  4564. }
  4565. return this;
  4566. };
  4567. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4568. var found = undefined;
  4569. this.each(function (node) {
  4570. if (node.atPosition) {
  4571. var foundChild = node.atPosition(line, col);
  4572. if (foundChild) {
  4573. found = foundChild;
  4574. return false;
  4575. }
  4576. } else if (node.isAtPosition(line, col)) {
  4577. found = node;
  4578. return false;
  4579. }
  4580. });
  4581. return found;
  4582. }
  4583. /**
  4584. * Return the most specific node at the line and column number given.
  4585. * The source location is based on the original parsed location, locations aren't
  4586. * updated as selector nodes are mutated.
  4587. *
  4588. * Note that this location is relative to the location of the first character
  4589. * of the selector, and not the location of the selector in the overall document
  4590. * when used in conjunction with postcss.
  4591. *
  4592. * If not found, returns undefined.
  4593. * @param {number} line The line number of the node to find. (1-based index)
  4594. * @param {number} col The column number of the node to find. (1-based index)
  4595. */;
  4596. _proto.atPosition = function atPosition(line, col) {
  4597. if (this.isAtPosition(line, col)) {
  4598. return this._findChildAtPosition(line, col) || this;
  4599. } else {
  4600. return undefined;
  4601. }
  4602. };
  4603. _proto._inferEndPosition = function _inferEndPosition() {
  4604. if (this.last && this.last.source && this.last.source.end) {
  4605. this.source = this.source || {};
  4606. this.source.end = this.source.end || {};
  4607. Object.assign(this.source.end, this.last.source.end);
  4608. }
  4609. };
  4610. _proto.each = function each(callback) {
  4611. if (!this.lastEach) {
  4612. this.lastEach = 0;
  4613. }
  4614. if (!this.indexes) {
  4615. this.indexes = {};
  4616. }
  4617. this.lastEach++;
  4618. var id = this.lastEach;
  4619. this.indexes[id] = 0;
  4620. if (!this.length) {
  4621. return undefined;
  4622. }
  4623. var index, result;
  4624. while (this.indexes[id] < this.length) {
  4625. index = this.indexes[id];
  4626. result = callback(this.at(index), index);
  4627. if (result === false) {
  4628. break;
  4629. }
  4630. this.indexes[id] += 1;
  4631. }
  4632. delete this.indexes[id];
  4633. if (result === false) {
  4634. return false;
  4635. }
  4636. };
  4637. _proto.walk = function walk(callback) {
  4638. return this.each(function (node, i) {
  4639. var result = callback(node, i);
  4640. if (result !== false && node.length) {
  4641. result = node.walk(callback);
  4642. }
  4643. if (result === false) {
  4644. return false;
  4645. }
  4646. });
  4647. };
  4648. _proto.walkAttributes = function walkAttributes(callback) {
  4649. var _this2 = this;
  4650. return this.walk(function (selector) {
  4651. if (selector.type === types.ATTRIBUTE) {
  4652. return callback.call(_this2, selector);
  4653. }
  4654. });
  4655. };
  4656. _proto.walkClasses = function walkClasses(callback) {
  4657. var _this3 = this;
  4658. return this.walk(function (selector) {
  4659. if (selector.type === types.CLASS) {
  4660. return callback.call(_this3, selector);
  4661. }
  4662. });
  4663. };
  4664. _proto.walkCombinators = function walkCombinators(callback) {
  4665. var _this4 = this;
  4666. return this.walk(function (selector) {
  4667. if (selector.type === types.COMBINATOR) {
  4668. return callback.call(_this4, selector);
  4669. }
  4670. });
  4671. };
  4672. _proto.walkComments = function walkComments(callback) {
  4673. var _this5 = this;
  4674. return this.walk(function (selector) {
  4675. if (selector.type === types.COMMENT) {
  4676. return callback.call(_this5, selector);
  4677. }
  4678. });
  4679. };
  4680. _proto.walkIds = function walkIds(callback) {
  4681. var _this6 = this;
  4682. return this.walk(function (selector) {
  4683. if (selector.type === types.ID) {
  4684. return callback.call(_this6, selector);
  4685. }
  4686. });
  4687. };
  4688. _proto.walkNesting = function walkNesting(callback) {
  4689. var _this7 = this;
  4690. return this.walk(function (selector) {
  4691. if (selector.type === types.NESTING) {
  4692. return callback.call(_this7, selector);
  4693. }
  4694. });
  4695. };
  4696. _proto.walkPseudos = function walkPseudos(callback) {
  4697. var _this8 = this;
  4698. return this.walk(function (selector) {
  4699. if (selector.type === types.PSEUDO) {
  4700. return callback.call(_this8, selector);
  4701. }
  4702. });
  4703. };
  4704. _proto.walkTags = function walkTags(callback) {
  4705. var _this9 = this;
  4706. return this.walk(function (selector) {
  4707. if (selector.type === types.TAG) {
  4708. return callback.call(_this9, selector);
  4709. }
  4710. });
  4711. };
  4712. _proto.walkUniversals = function walkUniversals(callback) {
  4713. var _this10 = this;
  4714. return this.walk(function (selector) {
  4715. if (selector.type === types.UNIVERSAL) {
  4716. return callback.call(_this10, selector);
  4717. }
  4718. });
  4719. };
  4720. _proto.split = function split(callback) {
  4721. var _this11 = this;
  4722. var current = [];
  4723. return this.reduce(function (memo, node, index) {
  4724. var split = callback.call(_this11, node);
  4725. current.push(node);
  4726. if (split) {
  4727. memo.push(current);
  4728. current = [];
  4729. } else if (index === _this11.length - 1) {
  4730. memo.push(current);
  4731. }
  4732. return memo;
  4733. }, []);
  4734. };
  4735. _proto.map = function map(callback) {
  4736. return this.nodes.map(callback);
  4737. };
  4738. _proto.reduce = function reduce(callback, memo) {
  4739. return this.nodes.reduce(callback, memo);
  4740. };
  4741. _proto.every = function every(callback) {
  4742. return this.nodes.every(callback);
  4743. };
  4744. _proto.some = function some(callback) {
  4745. return this.nodes.some(callback);
  4746. };
  4747. _proto.filter = function filter(callback) {
  4748. return this.nodes.filter(callback);
  4749. };
  4750. _proto.sort = function sort(callback) {
  4751. return this.nodes.sort(callback);
  4752. };
  4753. _proto.toString = function toString() {
  4754. return this.map(String).join('');
  4755. };
  4756. _createClass(Container, [{
  4757. key: "first",
  4758. get: function get() {
  4759. return this.at(0);
  4760. }
  4761. }, {
  4762. key: "last",
  4763. get: function get() {
  4764. return this.at(this.length - 1);
  4765. }
  4766. }, {
  4767. key: "length",
  4768. get: function get() {
  4769. return this.nodes.length;
  4770. }
  4771. }]);
  4772. return Container;
  4773. }(_node["default"]);
  4774. exports$1["default"] = Container;
  4775. module.exports = exports$1.default;
  4776. } (container$1, container$1.exports));
  4777. return container$1.exports;
  4778. }
  4779. var hasRequiredRoot$1;
  4780. function requireRoot$1 () {
  4781. if (hasRequiredRoot$1) return root$1.exports;
  4782. hasRequiredRoot$1 = 1;
  4783. (function (module, exports$1) {
  4784. exports$1.__esModule = true;
  4785. exports$1["default"] = void 0;
  4786. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4787. var _types = /*@__PURE__*/ requireTypes$1();
  4788. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4789. 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); } }
  4790. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4791. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4792. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4793. var Root = /*#__PURE__*/function (_Container) {
  4794. _inheritsLoose(Root, _Container);
  4795. function Root(opts) {
  4796. var _this;
  4797. _this = _Container.call(this, opts) || this;
  4798. _this.type = _types.ROOT;
  4799. return _this;
  4800. }
  4801. var _proto = Root.prototype;
  4802. _proto.toString = function toString() {
  4803. var str = this.reduce(function (memo, selector) {
  4804. memo.push(String(selector));
  4805. return memo;
  4806. }, []).join(',');
  4807. return this.trailingComma ? str + ',' : str;
  4808. };
  4809. _proto.error = function error(message, options) {
  4810. if (this._error) {
  4811. return this._error(message, options);
  4812. } else {
  4813. return new Error(message);
  4814. }
  4815. };
  4816. _createClass(Root, [{
  4817. key: "errorGenerator",
  4818. set: function set(handler) {
  4819. this._error = handler;
  4820. }
  4821. }]);
  4822. return Root;
  4823. }(_container["default"]);
  4824. exports$1["default"] = Root;
  4825. module.exports = exports$1.default;
  4826. } (root$1, root$1.exports));
  4827. return root$1.exports;
  4828. }
  4829. var selector$1 = {exports: {}};
  4830. var hasRequiredSelector$1;
  4831. function requireSelector$1 () {
  4832. if (hasRequiredSelector$1) return selector$1.exports;
  4833. hasRequiredSelector$1 = 1;
  4834. (function (module, exports$1) {
  4835. exports$1.__esModule = true;
  4836. exports$1["default"] = void 0;
  4837. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4838. var _types = /*@__PURE__*/ requireTypes$1();
  4839. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4840. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4841. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4842. var Selector = /*#__PURE__*/function (_Container) {
  4843. _inheritsLoose(Selector, _Container);
  4844. function Selector(opts) {
  4845. var _this;
  4846. _this = _Container.call(this, opts) || this;
  4847. _this.type = _types.SELECTOR;
  4848. return _this;
  4849. }
  4850. return Selector;
  4851. }(_container["default"]);
  4852. exports$1["default"] = Selector;
  4853. module.exports = exports$1.default;
  4854. } (selector$1, selector$1.exports));
  4855. return selector$1.exports;
  4856. }
  4857. var className$1 = {exports: {}};
  4858. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4859. var cssesc_1;
  4860. var hasRequiredCssesc;
  4861. function requireCssesc () {
  4862. if (hasRequiredCssesc) return cssesc_1;
  4863. hasRequiredCssesc = 1;
  4864. var object = {};
  4865. var hasOwnProperty = object.hasOwnProperty;
  4866. var merge = function merge(options, defaults) {
  4867. if (!options) {
  4868. return defaults;
  4869. }
  4870. var result = {};
  4871. for (var key in defaults) {
  4872. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4873. // only recognized option names are used.
  4874. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  4875. }
  4876. return result;
  4877. };
  4878. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4879. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4880. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4881. // https://mathiasbynens.be/notes/css-escapes#css
  4882. var cssesc = function cssesc(string, options) {
  4883. options = merge(options, cssesc.options);
  4884. if (options.quotes != 'single' && options.quotes != 'double') {
  4885. options.quotes = 'single';
  4886. }
  4887. var quote = options.quotes == 'double' ? '"' : '\'';
  4888. var isIdentifier = options.isIdentifier;
  4889. var firstChar = string.charAt(0);
  4890. var output = '';
  4891. var counter = 0;
  4892. var length = string.length;
  4893. while (counter < length) {
  4894. var character = string.charAt(counter++);
  4895. var codePoint = character.charCodeAt();
  4896. var value = void 0;
  4897. // If it’s not a printable ASCII character…
  4898. if (codePoint < 0x20 || codePoint > 0x7E) {
  4899. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4900. // It’s a high surrogate, and there is a next character.
  4901. var extra = string.charCodeAt(counter++);
  4902. if ((extra & 0xFC00) == 0xDC00) {
  4903. // next character is low surrogate
  4904. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4905. } else {
  4906. // It’s an unmatched surrogate; only append this code unit, in case
  4907. // the next code unit is the high surrogate of a surrogate pair.
  4908. counter--;
  4909. }
  4910. }
  4911. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4912. } else {
  4913. if (options.escapeEverything) {
  4914. if (regexAnySingleEscape.test(character)) {
  4915. value = '\\' + character;
  4916. } else {
  4917. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4918. }
  4919. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4920. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4921. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4922. value = '\\' + character;
  4923. } else {
  4924. value = character;
  4925. }
  4926. }
  4927. output += value;
  4928. }
  4929. if (isIdentifier) {
  4930. if (/^-[-\d]/.test(output)) {
  4931. output = '\\-' + output.slice(1);
  4932. } else if (/\d/.test(firstChar)) {
  4933. output = '\\3' + firstChar + ' ' + output.slice(1);
  4934. }
  4935. }
  4936. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4937. // since they’re redundant. Note that this is only possible if the escape
  4938. // sequence isn’t preceded by an odd number of backslashes.
  4939. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4940. if ($1 && $1.length % 2) {
  4941. // It’s not safe to remove the space, so don’t.
  4942. return $0;
  4943. }
  4944. // Strip the space.
  4945. return ($1 || '') + $2;
  4946. });
  4947. if (!isIdentifier && options.wrap) {
  4948. return quote + output + quote;
  4949. }
  4950. return output;
  4951. };
  4952. // Expose default options (so they can be overridden globally).
  4953. cssesc.options = {
  4954. 'escapeEverything': false,
  4955. 'isIdentifier': false,
  4956. 'quotes': 'single',
  4957. 'wrap': false
  4958. };
  4959. cssesc.version = '3.0.0';
  4960. cssesc_1 = cssesc;
  4961. return cssesc_1;
  4962. }
  4963. var hasRequiredClassName$1;
  4964. function requireClassName$1 () {
  4965. if (hasRequiredClassName$1) return className$1.exports;
  4966. hasRequiredClassName$1 = 1;
  4967. (function (module, exports$1) {
  4968. exports$1.__esModule = true;
  4969. exports$1["default"] = void 0;
  4970. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  4971. var _util = /*@__PURE__*/ requireUtil$2();
  4972. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4973. var _types = /*@__PURE__*/ requireTypes$1();
  4974. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4975. 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); } }
  4976. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4977. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4978. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4979. var ClassName = /*#__PURE__*/function (_Node) {
  4980. _inheritsLoose(ClassName, _Node);
  4981. function ClassName(opts) {
  4982. var _this;
  4983. _this = _Node.call(this, opts) || this;
  4984. _this.type = _types.CLASS;
  4985. _this._constructed = true;
  4986. return _this;
  4987. }
  4988. var _proto = ClassName.prototype;
  4989. _proto.valueToString = function valueToString() {
  4990. return '.' + _Node.prototype.valueToString.call(this);
  4991. };
  4992. _createClass(ClassName, [{
  4993. key: "value",
  4994. get: function get() {
  4995. return this._value;
  4996. },
  4997. set: function set(v) {
  4998. if (this._constructed) {
  4999. var escaped = (0, _cssesc["default"])(v, {
  5000. isIdentifier: true
  5001. });
  5002. if (escaped !== v) {
  5003. (0, _util.ensureObject)(this, "raws");
  5004. this.raws.value = escaped;
  5005. } else if (this.raws) {
  5006. delete this.raws.value;
  5007. }
  5008. }
  5009. this._value = v;
  5010. }
  5011. }]);
  5012. return ClassName;
  5013. }(_node["default"]);
  5014. exports$1["default"] = ClassName;
  5015. module.exports = exports$1.default;
  5016. } (className$1, className$1.exports));
  5017. return className$1.exports;
  5018. }
  5019. var comment$1 = {exports: {}};
  5020. var hasRequiredComment$1;
  5021. function requireComment$1 () {
  5022. if (hasRequiredComment$1) return comment$1.exports;
  5023. hasRequiredComment$1 = 1;
  5024. (function (module, exports$1) {
  5025. exports$1.__esModule = true;
  5026. exports$1["default"] = void 0;
  5027. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5028. var _types = /*@__PURE__*/ requireTypes$1();
  5029. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5030. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5031. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5032. var Comment = /*#__PURE__*/function (_Node) {
  5033. _inheritsLoose(Comment, _Node);
  5034. function Comment(opts) {
  5035. var _this;
  5036. _this = _Node.call(this, opts) || this;
  5037. _this.type = _types.COMMENT;
  5038. return _this;
  5039. }
  5040. return Comment;
  5041. }(_node["default"]);
  5042. exports$1["default"] = Comment;
  5043. module.exports = exports$1.default;
  5044. } (comment$1, comment$1.exports));
  5045. return comment$1.exports;
  5046. }
  5047. var id$1 = {exports: {}};
  5048. var hasRequiredId$1;
  5049. function requireId$1 () {
  5050. if (hasRequiredId$1) return id$1.exports;
  5051. hasRequiredId$1 = 1;
  5052. (function (module, exports$1) {
  5053. exports$1.__esModule = true;
  5054. exports$1["default"] = void 0;
  5055. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5056. var _types = /*@__PURE__*/ requireTypes$1();
  5057. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5058. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5059. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5060. var ID = /*#__PURE__*/function (_Node) {
  5061. _inheritsLoose(ID, _Node);
  5062. function ID(opts) {
  5063. var _this;
  5064. _this = _Node.call(this, opts) || this;
  5065. _this.type = _types.ID;
  5066. return _this;
  5067. }
  5068. var _proto = ID.prototype;
  5069. _proto.valueToString = function valueToString() {
  5070. return '#' + _Node.prototype.valueToString.call(this);
  5071. };
  5072. return ID;
  5073. }(_node["default"]);
  5074. exports$1["default"] = ID;
  5075. module.exports = exports$1.default;
  5076. } (id$1, id$1.exports));
  5077. return id$1.exports;
  5078. }
  5079. var tag$1 = {exports: {}};
  5080. var namespace$1 = {exports: {}};
  5081. var hasRequiredNamespace$1;
  5082. function requireNamespace$1 () {
  5083. if (hasRequiredNamespace$1) return namespace$1.exports;
  5084. hasRequiredNamespace$1 = 1;
  5085. (function (module, exports$1) {
  5086. exports$1.__esModule = true;
  5087. exports$1["default"] = void 0;
  5088. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5089. var _util = /*@__PURE__*/ requireUtil$2();
  5090. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5091. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5092. 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); } }
  5093. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5094. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5095. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5096. var Namespace = /*#__PURE__*/function (_Node) {
  5097. _inheritsLoose(Namespace, _Node);
  5098. function Namespace() {
  5099. return _Node.apply(this, arguments) || this;
  5100. }
  5101. var _proto = Namespace.prototype;
  5102. _proto.qualifiedName = function qualifiedName(value) {
  5103. if (this.namespace) {
  5104. return this.namespaceString + "|" + value;
  5105. } else {
  5106. return value;
  5107. }
  5108. };
  5109. _proto.valueToString = function valueToString() {
  5110. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5111. };
  5112. _createClass(Namespace, [{
  5113. key: "namespace",
  5114. get: function get() {
  5115. return this._namespace;
  5116. },
  5117. set: function set(namespace) {
  5118. if (namespace === true || namespace === "*" || namespace === "&") {
  5119. this._namespace = namespace;
  5120. if (this.raws) {
  5121. delete this.raws.namespace;
  5122. }
  5123. return;
  5124. }
  5125. var escaped = (0, _cssesc["default"])(namespace, {
  5126. isIdentifier: true
  5127. });
  5128. this._namespace = namespace;
  5129. if (escaped !== namespace) {
  5130. (0, _util.ensureObject)(this, "raws");
  5131. this.raws.namespace = escaped;
  5132. } else if (this.raws) {
  5133. delete this.raws.namespace;
  5134. }
  5135. }
  5136. }, {
  5137. key: "ns",
  5138. get: function get() {
  5139. return this._namespace;
  5140. },
  5141. set: function set(namespace) {
  5142. this.namespace = namespace;
  5143. }
  5144. }, {
  5145. key: "namespaceString",
  5146. get: function get() {
  5147. if (this.namespace) {
  5148. var ns = this.stringifyProperty("namespace");
  5149. if (ns === true) {
  5150. return '';
  5151. } else {
  5152. return ns;
  5153. }
  5154. } else {
  5155. return '';
  5156. }
  5157. }
  5158. }]);
  5159. return Namespace;
  5160. }(_node["default"]);
  5161. exports$1["default"] = Namespace;
  5162. module.exports = exports$1.default;
  5163. } (namespace$1, namespace$1.exports));
  5164. return namespace$1.exports;
  5165. }
  5166. var hasRequiredTag$1;
  5167. function requireTag$1 () {
  5168. if (hasRequiredTag$1) return tag$1.exports;
  5169. hasRequiredTag$1 = 1;
  5170. (function (module, exports$1) {
  5171. exports$1.__esModule = true;
  5172. exports$1["default"] = void 0;
  5173. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5174. var _types = /*@__PURE__*/ requireTypes$1();
  5175. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5176. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5177. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5178. var Tag = /*#__PURE__*/function (_Namespace) {
  5179. _inheritsLoose(Tag, _Namespace);
  5180. function Tag(opts) {
  5181. var _this;
  5182. _this = _Namespace.call(this, opts) || this;
  5183. _this.type = _types.TAG;
  5184. return _this;
  5185. }
  5186. return Tag;
  5187. }(_namespace["default"]);
  5188. exports$1["default"] = Tag;
  5189. module.exports = exports$1.default;
  5190. } (tag$1, tag$1.exports));
  5191. return tag$1.exports;
  5192. }
  5193. var string$1 = {exports: {}};
  5194. var hasRequiredString$1;
  5195. function requireString$1 () {
  5196. if (hasRequiredString$1) return string$1.exports;
  5197. hasRequiredString$1 = 1;
  5198. (function (module, exports$1) {
  5199. exports$1.__esModule = true;
  5200. exports$1["default"] = void 0;
  5201. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5202. var _types = /*@__PURE__*/ requireTypes$1();
  5203. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5204. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5205. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5206. var String = /*#__PURE__*/function (_Node) {
  5207. _inheritsLoose(String, _Node);
  5208. function String(opts) {
  5209. var _this;
  5210. _this = _Node.call(this, opts) || this;
  5211. _this.type = _types.STRING;
  5212. return _this;
  5213. }
  5214. return String;
  5215. }(_node["default"]);
  5216. exports$1["default"] = String;
  5217. module.exports = exports$1.default;
  5218. } (string$1, string$1.exports));
  5219. return string$1.exports;
  5220. }
  5221. var pseudo$1 = {exports: {}};
  5222. var hasRequiredPseudo$1;
  5223. function requirePseudo$1 () {
  5224. if (hasRequiredPseudo$1) return pseudo$1.exports;
  5225. hasRequiredPseudo$1 = 1;
  5226. (function (module, exports$1) {
  5227. exports$1.__esModule = true;
  5228. exports$1["default"] = void 0;
  5229. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  5230. var _types = /*@__PURE__*/ requireTypes$1();
  5231. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5232. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5233. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5234. var Pseudo = /*#__PURE__*/function (_Container) {
  5235. _inheritsLoose(Pseudo, _Container);
  5236. function Pseudo(opts) {
  5237. var _this;
  5238. _this = _Container.call(this, opts) || this;
  5239. _this.type = _types.PSEUDO;
  5240. return _this;
  5241. }
  5242. var _proto = Pseudo.prototype;
  5243. _proto.toString = function toString() {
  5244. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5245. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5246. };
  5247. return Pseudo;
  5248. }(_container["default"]);
  5249. exports$1["default"] = Pseudo;
  5250. module.exports = exports$1.default;
  5251. } (pseudo$1, pseudo$1.exports));
  5252. return pseudo$1.exports;
  5253. }
  5254. var attribute$1 = {};
  5255. var node$1;
  5256. var hasRequiredNode$1;
  5257. function requireNode$1 () {
  5258. if (hasRequiredNode$1) return node$1;
  5259. hasRequiredNode$1 = 1;
  5260. /**
  5261. * For Node.js, simply re-export the core `util.deprecate` function.
  5262. */
  5263. node$1 = require$$2.deprecate;
  5264. return node$1;
  5265. }
  5266. var hasRequiredAttribute$1;
  5267. function requireAttribute$1 () {
  5268. if (hasRequiredAttribute$1) return attribute$1;
  5269. hasRequiredAttribute$1 = 1;
  5270. (function (exports$1) {
  5271. exports$1.__esModule = true;
  5272. exports$1["default"] = void 0;
  5273. exports$1.unescapeValue = unescapeValue;
  5274. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5275. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  5276. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5277. var _types = /*@__PURE__*/ requireTypes$1();
  5278. var _CSSESC_QUOTE_OPTIONS;
  5279. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5280. 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); } }
  5281. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5282. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5283. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5284. var deprecate = /*@__PURE__*/ requireNode$1();
  5285. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5286. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5287. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5288. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5289. function unescapeValue(value) {
  5290. var deprecatedUsage = false;
  5291. var quoteMark = null;
  5292. var unescaped = value;
  5293. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5294. if (m) {
  5295. quoteMark = m[1];
  5296. unescaped = m[2];
  5297. }
  5298. unescaped = (0, _unesc["default"])(unescaped);
  5299. if (unescaped !== value) {
  5300. deprecatedUsage = true;
  5301. }
  5302. return {
  5303. deprecatedUsage: deprecatedUsage,
  5304. unescaped: unescaped,
  5305. quoteMark: quoteMark
  5306. };
  5307. }
  5308. function handleDeprecatedContructorOpts(opts) {
  5309. if (opts.quoteMark !== undefined) {
  5310. return opts;
  5311. }
  5312. if (opts.value === undefined) {
  5313. return opts;
  5314. }
  5315. warnOfDeprecatedConstructor();
  5316. var _unescapeValue = unescapeValue(opts.value),
  5317. quoteMark = _unescapeValue.quoteMark,
  5318. unescaped = _unescapeValue.unescaped;
  5319. if (!opts.raws) {
  5320. opts.raws = {};
  5321. }
  5322. if (opts.raws.value === undefined) {
  5323. opts.raws.value = opts.value;
  5324. }
  5325. opts.value = unescaped;
  5326. opts.quoteMark = quoteMark;
  5327. return opts;
  5328. }
  5329. var Attribute = /*#__PURE__*/function (_Namespace) {
  5330. _inheritsLoose(Attribute, _Namespace);
  5331. function Attribute(opts) {
  5332. var _this;
  5333. if (opts === void 0) {
  5334. opts = {};
  5335. }
  5336. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5337. _this.type = _types.ATTRIBUTE;
  5338. _this.raws = _this.raws || {};
  5339. Object.defineProperty(_this.raws, 'unquoted', {
  5340. get: deprecate(function () {
  5341. return _this.value;
  5342. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5343. set: deprecate(function () {
  5344. return _this.value;
  5345. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5346. });
  5347. _this._constructed = true;
  5348. return _this;
  5349. }
  5350. /**
  5351. * Returns the Attribute's value quoted such that it would be legal to use
  5352. * in the value of a css file. The original value's quotation setting
  5353. * used for stringification is left unchanged. See `setValue(value, options)`
  5354. * if you want to control the quote settings of a new value for the attribute.
  5355. *
  5356. * You can also change the quotation used for the current value by setting quoteMark.
  5357. *
  5358. * Options:
  5359. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5360. * option is not set, the original value for quoteMark will be used. If
  5361. * indeterminate, a double quote is used. The legal values are:
  5362. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5363. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5364. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5365. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5366. * over the quoteMark option value.
  5367. * * smart {boolean} - if true, will select a quote mark based on the value
  5368. * and the other options specified here. See the `smartQuoteMark()`
  5369. * method.
  5370. **/
  5371. var _proto = Attribute.prototype;
  5372. _proto.getQuotedValue = function getQuotedValue(options) {
  5373. if (options === void 0) {
  5374. options = {};
  5375. }
  5376. var quoteMark = this._determineQuoteMark(options);
  5377. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5378. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5379. return escaped;
  5380. };
  5381. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5382. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5383. }
  5384. /**
  5385. * Set the unescaped value with the specified quotation options. The value
  5386. * provided must not include any wrapping quote marks -- those quotes will
  5387. * be interpreted as part of the value and escaped accordingly.
  5388. */;
  5389. _proto.setValue = function setValue(value, options) {
  5390. if (options === void 0) {
  5391. options = {};
  5392. }
  5393. this._value = value;
  5394. this._quoteMark = this._determineQuoteMark(options);
  5395. this._syncRawValue();
  5396. }
  5397. /**
  5398. * Intelligently select a quoteMark value based on the value's contents. If
  5399. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5400. * mark will be picked that minimizes the number of escapes.
  5401. *
  5402. * If there's no clear winner, the quote mark from these options is used,
  5403. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5404. * true). If the quoteMark is unspecified, a double quote is used.
  5405. *
  5406. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5407. * from the quoteValue method.
  5408. */;
  5409. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5410. var v = this.value;
  5411. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5412. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5413. if (numSingleQuotes + numDoubleQuotes === 0) {
  5414. var escaped = (0, _cssesc["default"])(v, {
  5415. isIdentifier: true
  5416. });
  5417. if (escaped === v) {
  5418. return Attribute.NO_QUOTE;
  5419. } else {
  5420. var pref = this.preferredQuoteMark(options);
  5421. if (pref === Attribute.NO_QUOTE) {
  5422. // pick a quote mark that isn't none and see if it's smaller
  5423. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5424. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5425. var quoteValue = (0, _cssesc["default"])(v, opts);
  5426. if (quoteValue.length < escaped.length) {
  5427. return quote;
  5428. }
  5429. }
  5430. return pref;
  5431. }
  5432. } else if (numDoubleQuotes === numSingleQuotes) {
  5433. return this.preferredQuoteMark(options);
  5434. } else if (numDoubleQuotes < numSingleQuotes) {
  5435. return Attribute.DOUBLE_QUOTE;
  5436. } else {
  5437. return Attribute.SINGLE_QUOTE;
  5438. }
  5439. }
  5440. /**
  5441. * Selects the preferred quote mark based on the options and the current quote mark value.
  5442. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5443. * instead.
  5444. */;
  5445. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5446. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5447. if (quoteMark === undefined) {
  5448. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5449. }
  5450. if (quoteMark === undefined) {
  5451. quoteMark = Attribute.DOUBLE_QUOTE;
  5452. }
  5453. return quoteMark;
  5454. };
  5455. _proto._syncRawValue = function _syncRawValue() {
  5456. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5457. if (rawValue === this._value) {
  5458. if (this.raws) {
  5459. delete this.raws.value;
  5460. }
  5461. } else {
  5462. this.raws.value = rawValue;
  5463. }
  5464. };
  5465. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5466. if (this._constructed) {
  5467. var escaped = (0, _cssesc["default"])(value, {
  5468. isIdentifier: true
  5469. });
  5470. if (escaped !== value) {
  5471. this.raws[prop] = escaped;
  5472. } else {
  5473. delete this.raws[prop];
  5474. }
  5475. }
  5476. };
  5477. _proto._spacesFor = function _spacesFor(name) {
  5478. var attrSpaces = {
  5479. before: '',
  5480. after: ''
  5481. };
  5482. var spaces = this.spaces[name] || {};
  5483. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5484. return Object.assign(attrSpaces, spaces, rawSpaces);
  5485. };
  5486. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5487. if (spaceName === void 0) {
  5488. spaceName = name;
  5489. }
  5490. if (concat === void 0) {
  5491. concat = defaultAttrConcat;
  5492. }
  5493. var attrSpaces = this._spacesFor(spaceName);
  5494. return concat(this.stringifyProperty(name), attrSpaces);
  5495. }
  5496. /**
  5497. * returns the offset of the attribute part specified relative to the
  5498. * start of the node of the output string.
  5499. *
  5500. * * "ns" - alias for "namespace"
  5501. * * "namespace" - the namespace if it exists.
  5502. * * "attribute" - the attribute name
  5503. * * "attributeNS" - the start of the attribute or its namespace
  5504. * * "operator" - the match operator of the attribute
  5505. * * "value" - The value (string or identifier)
  5506. * * "insensitive" - the case insensitivity flag;
  5507. * @param part One of the possible values inside an attribute.
  5508. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5509. */;
  5510. _proto.offsetOf = function offsetOf(name) {
  5511. var count = 1;
  5512. var attributeSpaces = this._spacesFor("attribute");
  5513. count += attributeSpaces.before.length;
  5514. if (name === "namespace" || name === "ns") {
  5515. return this.namespace ? count : -1;
  5516. }
  5517. if (name === "attributeNS") {
  5518. return count;
  5519. }
  5520. count += this.namespaceString.length;
  5521. if (this.namespace) {
  5522. count += 1;
  5523. }
  5524. if (name === "attribute") {
  5525. return count;
  5526. }
  5527. count += this.stringifyProperty("attribute").length;
  5528. count += attributeSpaces.after.length;
  5529. var operatorSpaces = this._spacesFor("operator");
  5530. count += operatorSpaces.before.length;
  5531. var operator = this.stringifyProperty("operator");
  5532. if (name === "operator") {
  5533. return operator ? count : -1;
  5534. }
  5535. count += operator.length;
  5536. count += operatorSpaces.after.length;
  5537. var valueSpaces = this._spacesFor("value");
  5538. count += valueSpaces.before.length;
  5539. var value = this.stringifyProperty("value");
  5540. if (name === "value") {
  5541. return value ? count : -1;
  5542. }
  5543. count += value.length;
  5544. count += valueSpaces.after.length;
  5545. var insensitiveSpaces = this._spacesFor("insensitive");
  5546. count += insensitiveSpaces.before.length;
  5547. if (name === "insensitive") {
  5548. return this.insensitive ? count : -1;
  5549. }
  5550. return -1;
  5551. };
  5552. _proto.toString = function toString() {
  5553. var _this2 = this;
  5554. var selector = [this.rawSpaceBefore, '['];
  5555. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5556. if (this.operator && (this.value || this.value === '')) {
  5557. selector.push(this._stringFor('operator'));
  5558. selector.push(this._stringFor('value'));
  5559. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5560. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5561. attrSpaces.before = " ";
  5562. }
  5563. return defaultAttrConcat(attrValue, attrSpaces);
  5564. }));
  5565. }
  5566. selector.push(']');
  5567. selector.push(this.rawSpaceAfter);
  5568. return selector.join('');
  5569. };
  5570. _createClass(Attribute, [{
  5571. key: "quoted",
  5572. get: function get() {
  5573. var qm = this.quoteMark;
  5574. return qm === "'" || qm === '"';
  5575. },
  5576. set: function set(value) {
  5577. warnOfDeprecatedQuotedAssignment();
  5578. }
  5579. /**
  5580. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5581. * returns `null` if the value is not quoted.
  5582. * returns `undefined` if the quotation state is unknown (this can happen when
  5583. * the attribute is constructed without specifying a quote mark.)
  5584. */
  5585. }, {
  5586. key: "quoteMark",
  5587. get: function get() {
  5588. return this._quoteMark;
  5589. }
  5590. /**
  5591. * Set the quote mark to be used by this attribute's value.
  5592. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5593. * value is updated accordingly.
  5594. *
  5595. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5596. */,
  5597. set: function set(quoteMark) {
  5598. if (!this._constructed) {
  5599. this._quoteMark = quoteMark;
  5600. return;
  5601. }
  5602. if (this._quoteMark !== quoteMark) {
  5603. this._quoteMark = quoteMark;
  5604. this._syncRawValue();
  5605. }
  5606. }
  5607. }, {
  5608. key: "qualifiedAttribute",
  5609. get: function get() {
  5610. return this.qualifiedName(this.raws.attribute || this.attribute);
  5611. }
  5612. }, {
  5613. key: "insensitiveFlag",
  5614. get: function get() {
  5615. return this.insensitive ? 'i' : '';
  5616. }
  5617. }, {
  5618. key: "value",
  5619. get: function get() {
  5620. return this._value;
  5621. },
  5622. set:
  5623. /**
  5624. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5625. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5626. * is unescaped during parsing and any quote marks are removed.
  5627. *
  5628. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5629. * a deprecation warning is raised when the new value contains any characters that would
  5630. * require escaping (including if it contains wrapped quotes).
  5631. *
  5632. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5633. * how the new value is quoted.
  5634. */
  5635. function set(v) {
  5636. if (this._constructed) {
  5637. var _unescapeValue2 = unescapeValue(v),
  5638. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5639. unescaped = _unescapeValue2.unescaped,
  5640. quoteMark = _unescapeValue2.quoteMark;
  5641. if (deprecatedUsage) {
  5642. warnOfDeprecatedValueAssignment();
  5643. }
  5644. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5645. return;
  5646. }
  5647. this._value = unescaped;
  5648. this._quoteMark = quoteMark;
  5649. this._syncRawValue();
  5650. } else {
  5651. this._value = v;
  5652. }
  5653. }
  5654. }, {
  5655. key: "insensitive",
  5656. get: function get() {
  5657. return this._insensitive;
  5658. }
  5659. /**
  5660. * Set the case insensitive flag.
  5661. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5662. * of the attribute is updated accordingly.
  5663. *
  5664. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5665. */,
  5666. set: function set(insensitive) {
  5667. if (!insensitive) {
  5668. this._insensitive = false;
  5669. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5670. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5671. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5672. this.raws.insensitiveFlag = undefined;
  5673. }
  5674. }
  5675. this._insensitive = insensitive;
  5676. }
  5677. }, {
  5678. key: "attribute",
  5679. get: function get() {
  5680. return this._attribute;
  5681. },
  5682. set: function set(name) {
  5683. this._handleEscapes("attribute", name);
  5684. this._attribute = name;
  5685. }
  5686. }]);
  5687. return Attribute;
  5688. }(_namespace["default"]);
  5689. exports$1["default"] = Attribute;
  5690. Attribute.NO_QUOTE = null;
  5691. Attribute.SINGLE_QUOTE = "'";
  5692. Attribute.DOUBLE_QUOTE = '"';
  5693. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5694. "'": {
  5695. quotes: 'single',
  5696. wrap: true
  5697. },
  5698. '"': {
  5699. quotes: 'double',
  5700. wrap: true
  5701. }
  5702. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5703. isIdentifier: true
  5704. }, _CSSESC_QUOTE_OPTIONS);
  5705. function defaultAttrConcat(attrValue, attrSpaces) {
  5706. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5707. }
  5708. } (attribute$1));
  5709. return attribute$1;
  5710. }
  5711. var universal$1 = {exports: {}};
  5712. var hasRequiredUniversal$1;
  5713. function requireUniversal$1 () {
  5714. if (hasRequiredUniversal$1) return universal$1.exports;
  5715. hasRequiredUniversal$1 = 1;
  5716. (function (module, exports$1) {
  5717. exports$1.__esModule = true;
  5718. exports$1["default"] = void 0;
  5719. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5720. var _types = /*@__PURE__*/ requireTypes$1();
  5721. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5722. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5723. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5724. var Universal = /*#__PURE__*/function (_Namespace) {
  5725. _inheritsLoose(Universal, _Namespace);
  5726. function Universal(opts) {
  5727. var _this;
  5728. _this = _Namespace.call(this, opts) || this;
  5729. _this.type = _types.UNIVERSAL;
  5730. _this.value = '*';
  5731. return _this;
  5732. }
  5733. return Universal;
  5734. }(_namespace["default"]);
  5735. exports$1["default"] = Universal;
  5736. module.exports = exports$1.default;
  5737. } (universal$1, universal$1.exports));
  5738. return universal$1.exports;
  5739. }
  5740. var combinator$1 = {exports: {}};
  5741. var hasRequiredCombinator$1;
  5742. function requireCombinator$1 () {
  5743. if (hasRequiredCombinator$1) return combinator$1.exports;
  5744. hasRequiredCombinator$1 = 1;
  5745. (function (module, exports$1) {
  5746. exports$1.__esModule = true;
  5747. exports$1["default"] = void 0;
  5748. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5749. var _types = /*@__PURE__*/ requireTypes$1();
  5750. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5751. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5752. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5753. var Combinator = /*#__PURE__*/function (_Node) {
  5754. _inheritsLoose(Combinator, _Node);
  5755. function Combinator(opts) {
  5756. var _this;
  5757. _this = _Node.call(this, opts) || this;
  5758. _this.type = _types.COMBINATOR;
  5759. return _this;
  5760. }
  5761. return Combinator;
  5762. }(_node["default"]);
  5763. exports$1["default"] = Combinator;
  5764. module.exports = exports$1.default;
  5765. } (combinator$1, combinator$1.exports));
  5766. return combinator$1.exports;
  5767. }
  5768. var nesting$1 = {exports: {}};
  5769. var hasRequiredNesting$1;
  5770. function requireNesting$1 () {
  5771. if (hasRequiredNesting$1) return nesting$1.exports;
  5772. hasRequiredNesting$1 = 1;
  5773. (function (module, exports$1) {
  5774. exports$1.__esModule = true;
  5775. exports$1["default"] = void 0;
  5776. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5777. var _types = /*@__PURE__*/ requireTypes$1();
  5778. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5779. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5780. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5781. var Nesting = /*#__PURE__*/function (_Node) {
  5782. _inheritsLoose(Nesting, _Node);
  5783. function Nesting(opts) {
  5784. var _this;
  5785. _this = _Node.call(this, opts) || this;
  5786. _this.type = _types.NESTING;
  5787. _this.value = '&';
  5788. return _this;
  5789. }
  5790. return Nesting;
  5791. }(_node["default"]);
  5792. exports$1["default"] = Nesting;
  5793. module.exports = exports$1.default;
  5794. } (nesting$1, nesting$1.exports));
  5795. return nesting$1.exports;
  5796. }
  5797. var sortAscending$1 = {exports: {}};
  5798. var hasRequiredSortAscending$1;
  5799. function requireSortAscending$1 () {
  5800. if (hasRequiredSortAscending$1) return sortAscending$1.exports;
  5801. hasRequiredSortAscending$1 = 1;
  5802. (function (module, exports$1) {
  5803. exports$1.__esModule = true;
  5804. exports$1["default"] = sortAscending;
  5805. function sortAscending(list) {
  5806. return list.sort(function (a, b) {
  5807. return a - b;
  5808. });
  5809. }
  5810. module.exports = exports$1.default;
  5811. } (sortAscending$1, sortAscending$1.exports));
  5812. return sortAscending$1.exports;
  5813. }
  5814. var tokenize$1 = {};
  5815. var tokenTypes$1 = {};
  5816. var hasRequiredTokenTypes$1;
  5817. function requireTokenTypes$1 () {
  5818. if (hasRequiredTokenTypes$1) return tokenTypes$1;
  5819. hasRequiredTokenTypes$1 = 1;
  5820. tokenTypes$1.__esModule = true;
  5821. 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;
  5822. var ampersand = 38; // `&`.charCodeAt(0);
  5823. tokenTypes$1.ampersand = ampersand;
  5824. var asterisk = 42; // `*`.charCodeAt(0);
  5825. tokenTypes$1.asterisk = asterisk;
  5826. var at = 64; // `@`.charCodeAt(0);
  5827. tokenTypes$1.at = at;
  5828. var comma = 44; // `,`.charCodeAt(0);
  5829. tokenTypes$1.comma = comma;
  5830. var colon = 58; // `:`.charCodeAt(0);
  5831. tokenTypes$1.colon = colon;
  5832. var semicolon = 59; // `;`.charCodeAt(0);
  5833. tokenTypes$1.semicolon = semicolon;
  5834. var openParenthesis = 40; // `(`.charCodeAt(0);
  5835. tokenTypes$1.openParenthesis = openParenthesis;
  5836. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5837. tokenTypes$1.closeParenthesis = closeParenthesis;
  5838. var openSquare = 91; // `[`.charCodeAt(0);
  5839. tokenTypes$1.openSquare = openSquare;
  5840. var closeSquare = 93; // `]`.charCodeAt(0);
  5841. tokenTypes$1.closeSquare = closeSquare;
  5842. var dollar = 36; // `$`.charCodeAt(0);
  5843. tokenTypes$1.dollar = dollar;
  5844. var tilde = 126; // `~`.charCodeAt(0);
  5845. tokenTypes$1.tilde = tilde;
  5846. var caret = 94; // `^`.charCodeAt(0);
  5847. tokenTypes$1.caret = caret;
  5848. var plus = 43; // `+`.charCodeAt(0);
  5849. tokenTypes$1.plus = plus;
  5850. var equals = 61; // `=`.charCodeAt(0);
  5851. tokenTypes$1.equals = equals;
  5852. var pipe = 124; // `|`.charCodeAt(0);
  5853. tokenTypes$1.pipe = pipe;
  5854. var greaterThan = 62; // `>`.charCodeAt(0);
  5855. tokenTypes$1.greaterThan = greaterThan;
  5856. var space = 32; // ` `.charCodeAt(0);
  5857. tokenTypes$1.space = space;
  5858. var singleQuote = 39; // `'`.charCodeAt(0);
  5859. tokenTypes$1.singleQuote = singleQuote;
  5860. var doubleQuote = 34; // `"`.charCodeAt(0);
  5861. tokenTypes$1.doubleQuote = doubleQuote;
  5862. var slash = 47; // `/`.charCodeAt(0);
  5863. tokenTypes$1.slash = slash;
  5864. var bang = 33; // `!`.charCodeAt(0);
  5865. tokenTypes$1.bang = bang;
  5866. var backslash = 92; // '\\'.charCodeAt(0);
  5867. tokenTypes$1.backslash = backslash;
  5868. var cr = 13; // '\r'.charCodeAt(0);
  5869. tokenTypes$1.cr = cr;
  5870. var feed = 12; // '\f'.charCodeAt(0);
  5871. tokenTypes$1.feed = feed;
  5872. var newline = 10; // '\n'.charCodeAt(0);
  5873. tokenTypes$1.newline = newline;
  5874. var tab = 9; // '\t'.charCodeAt(0);
  5875. // Expose aliases primarily for readability.
  5876. tokenTypes$1.tab = tab;
  5877. var str = singleQuote;
  5878. // No good single character representation!
  5879. tokenTypes$1.str = str;
  5880. var comment = -1;
  5881. tokenTypes$1.comment = comment;
  5882. var word = -2;
  5883. tokenTypes$1.word = word;
  5884. var combinator = -3;
  5885. tokenTypes$1.combinator = combinator;
  5886. return tokenTypes$1;
  5887. }
  5888. var hasRequiredTokenize$1;
  5889. function requireTokenize$1 () {
  5890. if (hasRequiredTokenize$1) return tokenize$1;
  5891. hasRequiredTokenize$1 = 1;
  5892. (function (exports$1) {
  5893. exports$1.__esModule = true;
  5894. exports$1.FIELDS = void 0;
  5895. exports$1["default"] = tokenize;
  5896. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  5897. var _unescapable, _wordDelimiters;
  5898. 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); }
  5899. 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; }
  5900. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5901. 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);
  5902. var hex = {};
  5903. var hexChars = "0123456789abcdefABCDEF";
  5904. for (var i = 0; i < hexChars.length; i++) {
  5905. hex[hexChars.charCodeAt(i)] = true;
  5906. }
  5907. /**
  5908. * Returns the last index of the bar css word
  5909. * @param {string} css The string in which the word begins
  5910. * @param {number} start The index into the string where word's first letter occurs
  5911. */
  5912. function consumeWord(css, start) {
  5913. var next = start;
  5914. var code;
  5915. do {
  5916. code = css.charCodeAt(next);
  5917. if (wordDelimiters[code]) {
  5918. return next - 1;
  5919. } else if (code === t.backslash) {
  5920. next = consumeEscape(css, next) + 1;
  5921. } else {
  5922. // All other characters are part of the word
  5923. next++;
  5924. }
  5925. } while (next < css.length);
  5926. return next - 1;
  5927. }
  5928. /**
  5929. * Returns the last index of the escape sequence
  5930. * @param {string} css The string in which the sequence begins
  5931. * @param {number} start The index into the string where escape character (`\`) occurs.
  5932. */
  5933. function consumeEscape(css, start) {
  5934. var next = start;
  5935. var code = css.charCodeAt(next + 1);
  5936. if (unescapable[code]) ; else if (hex[code]) {
  5937. var hexDigits = 0;
  5938. // consume up to 6 hex chars
  5939. do {
  5940. next++;
  5941. hexDigits++;
  5942. code = css.charCodeAt(next + 1);
  5943. } while (hex[code] && hexDigits < 6);
  5944. // if fewer than 6 hex chars, a trailing space ends the escape
  5945. if (hexDigits < 6 && code === t.space) {
  5946. next++;
  5947. }
  5948. } else {
  5949. // the next char is part of the current word
  5950. next++;
  5951. }
  5952. return next;
  5953. }
  5954. var FIELDS = {
  5955. TYPE: 0,
  5956. START_LINE: 1,
  5957. START_COL: 2,
  5958. END_LINE: 3,
  5959. END_COL: 4,
  5960. START_POS: 5,
  5961. END_POS: 6
  5962. };
  5963. exports$1.FIELDS = FIELDS;
  5964. function tokenize(input) {
  5965. var tokens = [];
  5966. var css = input.css.valueOf();
  5967. var _css = css,
  5968. length = _css.length;
  5969. var offset = -1;
  5970. var line = 1;
  5971. var start = 0;
  5972. var end = 0;
  5973. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5974. function unclosed(what, fix) {
  5975. if (input.safe) {
  5976. // fyi: this is never set to true.
  5977. css += fix;
  5978. next = css.length - 1;
  5979. } else {
  5980. throw input.error('Unclosed ' + what, line, start - offset, start);
  5981. }
  5982. }
  5983. while (start < length) {
  5984. code = css.charCodeAt(start);
  5985. if (code === t.newline) {
  5986. offset = start;
  5987. line += 1;
  5988. }
  5989. switch (code) {
  5990. case t.space:
  5991. case t.tab:
  5992. case t.newline:
  5993. case t.cr:
  5994. case t.feed:
  5995. next = start;
  5996. do {
  5997. next += 1;
  5998. code = css.charCodeAt(next);
  5999. if (code === t.newline) {
  6000. offset = next;
  6001. line += 1;
  6002. }
  6003. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  6004. tokenType = t.space;
  6005. endLine = line;
  6006. endColumn = next - offset - 1;
  6007. end = next;
  6008. break;
  6009. case t.plus:
  6010. case t.greaterThan:
  6011. case t.tilde:
  6012. case t.pipe:
  6013. next = start;
  6014. do {
  6015. next += 1;
  6016. code = css.charCodeAt(next);
  6017. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  6018. tokenType = t.combinator;
  6019. endLine = line;
  6020. endColumn = start - offset;
  6021. end = next;
  6022. break;
  6023. // Consume these characters as single tokens.
  6024. case t.asterisk:
  6025. case t.ampersand:
  6026. case t.bang:
  6027. case t.comma:
  6028. case t.equals:
  6029. case t.dollar:
  6030. case t.caret:
  6031. case t.openSquare:
  6032. case t.closeSquare:
  6033. case t.colon:
  6034. case t.semicolon:
  6035. case t.openParenthesis:
  6036. case t.closeParenthesis:
  6037. next = start;
  6038. tokenType = code;
  6039. endLine = line;
  6040. endColumn = start - offset;
  6041. end = next + 1;
  6042. break;
  6043. case t.singleQuote:
  6044. case t.doubleQuote:
  6045. quote = code === t.singleQuote ? "'" : '"';
  6046. next = start;
  6047. do {
  6048. escaped = false;
  6049. next = css.indexOf(quote, next + 1);
  6050. if (next === -1) {
  6051. unclosed('quote', quote);
  6052. }
  6053. escapePos = next;
  6054. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6055. escapePos -= 1;
  6056. escaped = !escaped;
  6057. }
  6058. } while (escaped);
  6059. tokenType = t.str;
  6060. endLine = line;
  6061. endColumn = start - offset;
  6062. end = next + 1;
  6063. break;
  6064. default:
  6065. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6066. next = css.indexOf('*/', start + 2) + 1;
  6067. if (next === 0) {
  6068. unclosed('comment', '*/');
  6069. }
  6070. content = css.slice(start, next + 1);
  6071. lines = content.split('\n');
  6072. last = lines.length - 1;
  6073. if (last > 0) {
  6074. nextLine = line + last;
  6075. nextOffset = next - lines[last].length;
  6076. } else {
  6077. nextLine = line;
  6078. nextOffset = offset;
  6079. }
  6080. tokenType = t.comment;
  6081. line = nextLine;
  6082. endLine = nextLine;
  6083. endColumn = next - nextOffset;
  6084. } else if (code === t.slash) {
  6085. next = start;
  6086. tokenType = code;
  6087. endLine = line;
  6088. endColumn = start - offset;
  6089. end = next + 1;
  6090. } else {
  6091. next = consumeWord(css, start);
  6092. tokenType = t.word;
  6093. endLine = line;
  6094. endColumn = next - offset;
  6095. }
  6096. end = next + 1;
  6097. break;
  6098. }
  6099. // Ensure that the token structure remains consistent
  6100. tokens.push([tokenType,
  6101. // [0] Token type
  6102. line,
  6103. // [1] Starting line
  6104. start - offset,
  6105. // [2] Starting column
  6106. endLine,
  6107. // [3] Ending line
  6108. endColumn,
  6109. // [4] Ending column
  6110. start,
  6111. // [5] Start position / Source index
  6112. end // [6] End position
  6113. ]);
  6114. // Reset offset for the next token
  6115. if (nextOffset) {
  6116. offset = nextOffset;
  6117. nextOffset = null;
  6118. }
  6119. start = end;
  6120. }
  6121. return tokens;
  6122. }
  6123. } (tokenize$1));
  6124. return tokenize$1;
  6125. }
  6126. var hasRequiredParser$2;
  6127. function requireParser$2 () {
  6128. if (hasRequiredParser$2) return parser$1.exports;
  6129. hasRequiredParser$2 = 1;
  6130. (function (module, exports$1) {
  6131. exports$1.__esModule = true;
  6132. exports$1["default"] = void 0;
  6133. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  6134. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  6135. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  6136. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  6137. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  6138. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  6139. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  6140. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  6141. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute$1());
  6142. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  6143. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  6144. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  6145. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending$1());
  6146. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize$1());
  6147. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  6148. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  6149. var _util = /*@__PURE__*/ requireUtil$2();
  6150. var _WHITESPACE_TOKENS, _Object$assign;
  6151. 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); }
  6152. 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; }
  6153. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6154. 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); } }
  6155. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6156. 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);
  6157. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6158. function tokenStart(token) {
  6159. return {
  6160. line: token[_tokenize.FIELDS.START_LINE],
  6161. column: token[_tokenize.FIELDS.START_COL]
  6162. };
  6163. }
  6164. function tokenEnd(token) {
  6165. return {
  6166. line: token[_tokenize.FIELDS.END_LINE],
  6167. column: token[_tokenize.FIELDS.END_COL]
  6168. };
  6169. }
  6170. function getSource(startLine, startColumn, endLine, endColumn) {
  6171. return {
  6172. start: {
  6173. line: startLine,
  6174. column: startColumn
  6175. },
  6176. end: {
  6177. line: endLine,
  6178. column: endColumn
  6179. }
  6180. };
  6181. }
  6182. function getTokenSource(token) {
  6183. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6184. }
  6185. function getTokenSourceSpan(startToken, endToken) {
  6186. if (!startToken) {
  6187. return undefined;
  6188. }
  6189. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6190. }
  6191. function unescapeProp(node, prop) {
  6192. var value = node[prop];
  6193. if (typeof value !== "string") {
  6194. return;
  6195. }
  6196. if (value.indexOf("\\") !== -1) {
  6197. (0, _util.ensureObject)(node, 'raws');
  6198. node[prop] = (0, _util.unesc)(value);
  6199. if (node.raws[prop] === undefined) {
  6200. node.raws[prop] = value;
  6201. }
  6202. }
  6203. return node;
  6204. }
  6205. function indexesOf(array, item) {
  6206. var i = -1;
  6207. var indexes = [];
  6208. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6209. indexes.push(i);
  6210. }
  6211. return indexes;
  6212. }
  6213. function uniqs() {
  6214. var list = Array.prototype.concat.apply([], arguments);
  6215. return list.filter(function (item, i) {
  6216. return i === list.indexOf(item);
  6217. });
  6218. }
  6219. var Parser = /*#__PURE__*/function () {
  6220. function Parser(rule, options) {
  6221. if (options === void 0) {
  6222. options = {};
  6223. }
  6224. this.rule = rule;
  6225. this.options = Object.assign({
  6226. lossy: false,
  6227. safe: false
  6228. }, options);
  6229. this.position = 0;
  6230. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6231. this.tokens = (0, _tokenize["default"])({
  6232. css: this.css,
  6233. error: this._errorGenerator(),
  6234. safe: this.options.safe
  6235. });
  6236. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6237. this.root = new _root["default"]({
  6238. source: rootSource
  6239. });
  6240. this.root.errorGenerator = this._errorGenerator();
  6241. var selector = new _selector["default"]({
  6242. source: {
  6243. start: {
  6244. line: 1,
  6245. column: 1
  6246. }
  6247. },
  6248. sourceIndex: 0
  6249. });
  6250. this.root.append(selector);
  6251. this.current = selector;
  6252. this.loop();
  6253. }
  6254. var _proto = Parser.prototype;
  6255. _proto._errorGenerator = function _errorGenerator() {
  6256. var _this = this;
  6257. return function (message, errorOptions) {
  6258. if (typeof _this.rule === 'string') {
  6259. return new Error(message);
  6260. }
  6261. return _this.rule.error(message, errorOptions);
  6262. };
  6263. };
  6264. _proto.attribute = function attribute() {
  6265. var attr = [];
  6266. var startingToken = this.currToken;
  6267. this.position++;
  6268. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6269. attr.push(this.currToken);
  6270. this.position++;
  6271. }
  6272. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6273. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6274. }
  6275. var len = attr.length;
  6276. var node = {
  6277. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6278. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6279. };
  6280. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6281. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6282. }
  6283. var pos = 0;
  6284. var spaceBefore = '';
  6285. var commentBefore = '';
  6286. var lastAdded = null;
  6287. var spaceAfterMeaningfulToken = false;
  6288. while (pos < len) {
  6289. var token = attr[pos];
  6290. var content = this.content(token);
  6291. var next = attr[pos + 1];
  6292. switch (token[_tokenize.FIELDS.TYPE]) {
  6293. case tokens.space:
  6294. // if (
  6295. // len === 1 ||
  6296. // pos === 0 && this.content(next) === '|'
  6297. // ) {
  6298. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6299. // }
  6300. spaceAfterMeaningfulToken = true;
  6301. if (this.options.lossy) {
  6302. break;
  6303. }
  6304. if (lastAdded) {
  6305. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6306. var prevContent = node.spaces[lastAdded].after || '';
  6307. node.spaces[lastAdded].after = prevContent + content;
  6308. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6309. if (existingComment) {
  6310. node.raws.spaces[lastAdded].after = existingComment + content;
  6311. }
  6312. } else {
  6313. spaceBefore = spaceBefore + content;
  6314. commentBefore = commentBefore + content;
  6315. }
  6316. break;
  6317. case tokens.asterisk:
  6318. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6319. node.operator = content;
  6320. lastAdded = 'operator';
  6321. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6322. if (spaceBefore) {
  6323. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6324. node.spaces.attribute.before = spaceBefore;
  6325. spaceBefore = '';
  6326. }
  6327. if (commentBefore) {
  6328. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6329. node.raws.spaces.attribute.before = spaceBefore;
  6330. commentBefore = '';
  6331. }
  6332. node.namespace = (node.namespace || "") + content;
  6333. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6334. if (rawValue) {
  6335. node.raws.namespace += content;
  6336. }
  6337. lastAdded = 'namespace';
  6338. }
  6339. spaceAfterMeaningfulToken = false;
  6340. break;
  6341. case tokens.dollar:
  6342. if (lastAdded === "value") {
  6343. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6344. node.value += "$";
  6345. if (oldRawValue) {
  6346. node.raws.value = oldRawValue + "$";
  6347. }
  6348. break;
  6349. }
  6350. // Falls through
  6351. case tokens.caret:
  6352. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6353. node.operator = content;
  6354. lastAdded = 'operator';
  6355. }
  6356. spaceAfterMeaningfulToken = false;
  6357. break;
  6358. case tokens.combinator:
  6359. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6360. node.operator = content;
  6361. lastAdded = 'operator';
  6362. }
  6363. if (content !== '|') {
  6364. spaceAfterMeaningfulToken = false;
  6365. break;
  6366. }
  6367. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6368. node.operator = content;
  6369. lastAdded = 'operator';
  6370. } else if (!node.namespace && !node.attribute) {
  6371. node.namespace = true;
  6372. }
  6373. spaceAfterMeaningfulToken = false;
  6374. break;
  6375. case tokens.word:
  6376. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6377. // this look-ahead probably fails with comment nodes involved.
  6378. !node.operator && !node.namespace) {
  6379. node.namespace = content;
  6380. lastAdded = 'namespace';
  6381. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6382. if (spaceBefore) {
  6383. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6384. node.spaces.attribute.before = spaceBefore;
  6385. spaceBefore = '';
  6386. }
  6387. if (commentBefore) {
  6388. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6389. node.raws.spaces.attribute.before = commentBefore;
  6390. commentBefore = '';
  6391. }
  6392. node.attribute = (node.attribute || "") + content;
  6393. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6394. if (_rawValue) {
  6395. node.raws.attribute += content;
  6396. }
  6397. lastAdded = 'attribute';
  6398. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6399. var _unescaped = (0, _util.unesc)(content);
  6400. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6401. var oldValue = node.value || '';
  6402. node.value = oldValue + _unescaped;
  6403. node.quoteMark = null;
  6404. if (_unescaped !== content || _oldRawValue) {
  6405. (0, _util.ensureObject)(node, 'raws');
  6406. node.raws.value = (_oldRawValue || oldValue) + content;
  6407. }
  6408. lastAdded = 'value';
  6409. } else {
  6410. var insensitive = content === 'i' || content === "I";
  6411. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6412. node.insensitive = insensitive;
  6413. if (!insensitive || content === "I") {
  6414. (0, _util.ensureObject)(node, 'raws');
  6415. node.raws.insensitiveFlag = content;
  6416. }
  6417. lastAdded = 'insensitive';
  6418. if (spaceBefore) {
  6419. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6420. node.spaces.insensitive.before = spaceBefore;
  6421. spaceBefore = '';
  6422. }
  6423. if (commentBefore) {
  6424. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6425. node.raws.spaces.insensitive.before = commentBefore;
  6426. commentBefore = '';
  6427. }
  6428. } else if (node.value || node.value === '') {
  6429. lastAdded = 'value';
  6430. node.value += content;
  6431. if (node.raws.value) {
  6432. node.raws.value += content;
  6433. }
  6434. }
  6435. }
  6436. spaceAfterMeaningfulToken = false;
  6437. break;
  6438. case tokens.str:
  6439. if (!node.attribute || !node.operator) {
  6440. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6441. index: token[_tokenize.FIELDS.START_POS]
  6442. });
  6443. }
  6444. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6445. unescaped = _unescapeValue.unescaped,
  6446. quoteMark = _unescapeValue.quoteMark;
  6447. node.value = unescaped;
  6448. node.quoteMark = quoteMark;
  6449. lastAdded = 'value';
  6450. (0, _util.ensureObject)(node, 'raws');
  6451. node.raws.value = content;
  6452. spaceAfterMeaningfulToken = false;
  6453. break;
  6454. case tokens.equals:
  6455. if (!node.attribute) {
  6456. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6457. }
  6458. if (node.value) {
  6459. return this.error('Unexpected "=" found; an operator was already defined.', {
  6460. index: token[_tokenize.FIELDS.START_POS]
  6461. });
  6462. }
  6463. node.operator = node.operator ? node.operator + content : content;
  6464. lastAdded = 'operator';
  6465. spaceAfterMeaningfulToken = false;
  6466. break;
  6467. case tokens.comment:
  6468. if (lastAdded) {
  6469. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6470. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6471. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6472. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6473. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6474. } else {
  6475. var lastValue = node[lastAdded] || '';
  6476. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6477. (0, _util.ensureObject)(node, 'raws');
  6478. node.raws[lastAdded] = rawLastValue + content;
  6479. }
  6480. } else {
  6481. commentBefore = commentBefore + content;
  6482. }
  6483. break;
  6484. default:
  6485. return this.error("Unexpected \"" + content + "\" found.", {
  6486. index: token[_tokenize.FIELDS.START_POS]
  6487. });
  6488. }
  6489. pos++;
  6490. }
  6491. unescapeProp(node, "attribute");
  6492. unescapeProp(node, "namespace");
  6493. this.newNode(new _attribute["default"](node));
  6494. this.position++;
  6495. }
  6496. /**
  6497. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6498. * if the token position is negative, all remaining tokens are consumed.
  6499. *
  6500. * This returns an array containing a single string node if all whitespace,
  6501. * otherwise an array of comment nodes with space before and after.
  6502. *
  6503. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6504. * a previous node's space metadata.
  6505. *
  6506. * In lossy mode, this returns only comments.
  6507. */;
  6508. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6509. if (stopPosition < 0) {
  6510. stopPosition = this.tokens.length;
  6511. }
  6512. var startPosition = this.position;
  6513. var nodes = [];
  6514. var space = "";
  6515. var lastComment = undefined;
  6516. do {
  6517. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6518. if (!this.options.lossy) {
  6519. space += this.content();
  6520. }
  6521. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6522. var spaces = {};
  6523. if (space) {
  6524. spaces.before = space;
  6525. space = "";
  6526. }
  6527. lastComment = new _comment["default"]({
  6528. value: this.content(),
  6529. source: getTokenSource(this.currToken),
  6530. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6531. spaces: spaces
  6532. });
  6533. nodes.push(lastComment);
  6534. }
  6535. } while (++this.position < stopPosition);
  6536. if (space) {
  6537. if (lastComment) {
  6538. lastComment.spaces.after = space;
  6539. } else if (!this.options.lossy) {
  6540. var firstToken = this.tokens[startPosition];
  6541. var lastToken = this.tokens[this.position - 1];
  6542. nodes.push(new _string["default"]({
  6543. value: '',
  6544. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6545. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6546. spaces: {
  6547. before: space,
  6548. after: ''
  6549. }
  6550. }));
  6551. }
  6552. }
  6553. return nodes;
  6554. }
  6555. /**
  6556. *
  6557. * @param {*} nodes
  6558. */;
  6559. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6560. var _this2 = this;
  6561. if (requiredSpace === void 0) {
  6562. requiredSpace = false;
  6563. }
  6564. var space = "";
  6565. var rawSpace = "";
  6566. nodes.forEach(function (n) {
  6567. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6568. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6569. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6570. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6571. });
  6572. if (rawSpace === space) {
  6573. rawSpace = undefined;
  6574. }
  6575. var result = {
  6576. space: space,
  6577. rawSpace: rawSpace
  6578. };
  6579. return result;
  6580. };
  6581. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6582. if (position === void 0) {
  6583. position = this.position;
  6584. }
  6585. 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;
  6586. };
  6587. _proto.namedCombinator = function namedCombinator() {
  6588. if (this.isNamedCombinator()) {
  6589. var nameRaw = this.content(this.tokens[this.position + 1]);
  6590. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6591. var raws = {};
  6592. if (name !== nameRaw) {
  6593. raws.value = "/" + nameRaw + "/";
  6594. }
  6595. var node = new _combinator["default"]({
  6596. value: "/" + name + "/",
  6597. 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]),
  6598. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6599. raws: raws
  6600. });
  6601. this.position = this.position + 3;
  6602. return node;
  6603. } else {
  6604. this.unexpected();
  6605. }
  6606. };
  6607. _proto.combinator = function combinator() {
  6608. var _this3 = this;
  6609. if (this.content() === '|') {
  6610. return this.namespace();
  6611. }
  6612. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6613. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6614. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6615. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6616. if (nodes.length > 0) {
  6617. var last = this.current.last;
  6618. if (last) {
  6619. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6620. space = _this$convertWhitespa.space,
  6621. rawSpace = _this$convertWhitespa.rawSpace;
  6622. if (rawSpace !== undefined) {
  6623. last.rawSpaceAfter += rawSpace;
  6624. }
  6625. last.spaces.after += space;
  6626. } else {
  6627. nodes.forEach(function (n) {
  6628. return _this3.newNode(n);
  6629. });
  6630. }
  6631. }
  6632. return;
  6633. }
  6634. var firstToken = this.currToken;
  6635. var spaceOrDescendantSelectorNodes = undefined;
  6636. if (nextSigTokenPos > this.position) {
  6637. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6638. }
  6639. var node;
  6640. if (this.isNamedCombinator()) {
  6641. node = this.namedCombinator();
  6642. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6643. node = new _combinator["default"]({
  6644. value: this.content(),
  6645. source: getTokenSource(this.currToken),
  6646. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6647. });
  6648. this.position++;
  6649. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6650. this.unexpected();
  6651. }
  6652. if (node) {
  6653. if (spaceOrDescendantSelectorNodes) {
  6654. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6655. _space = _this$convertWhitespa2.space,
  6656. _rawSpace = _this$convertWhitespa2.rawSpace;
  6657. node.spaces.before = _space;
  6658. node.rawSpaceBefore = _rawSpace;
  6659. }
  6660. } else {
  6661. // descendant combinator
  6662. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6663. _space2 = _this$convertWhitespa3.space,
  6664. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6665. if (!_rawSpace2) {
  6666. _rawSpace2 = _space2;
  6667. }
  6668. var spaces = {};
  6669. var raws = {
  6670. spaces: {}
  6671. };
  6672. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6673. spaces.before = _space2.slice(0, _space2.length - 1);
  6674. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6675. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  6676. spaces.after = _space2.slice(1);
  6677. raws.spaces.after = _rawSpace2.slice(1);
  6678. } else {
  6679. raws.value = _rawSpace2;
  6680. }
  6681. node = new _combinator["default"]({
  6682. value: ' ',
  6683. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6684. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6685. spaces: spaces,
  6686. raws: raws
  6687. });
  6688. }
  6689. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6690. node.spaces.after = this.optionalSpace(this.content());
  6691. this.position++;
  6692. }
  6693. return this.newNode(node);
  6694. };
  6695. _proto.comma = function comma() {
  6696. if (this.position === this.tokens.length - 1) {
  6697. this.root.trailingComma = true;
  6698. this.position++;
  6699. return;
  6700. }
  6701. this.current._inferEndPosition();
  6702. var selector = new _selector["default"]({
  6703. source: {
  6704. start: tokenStart(this.tokens[this.position + 1])
  6705. },
  6706. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6707. });
  6708. this.current.parent.append(selector);
  6709. this.current = selector;
  6710. this.position++;
  6711. };
  6712. _proto.comment = function comment() {
  6713. var current = this.currToken;
  6714. this.newNode(new _comment["default"]({
  6715. value: this.content(),
  6716. source: getTokenSource(current),
  6717. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6718. }));
  6719. this.position++;
  6720. };
  6721. _proto.error = function error(message, opts) {
  6722. throw this.root.error(message, opts);
  6723. };
  6724. _proto.missingBackslash = function missingBackslash() {
  6725. return this.error('Expected a backslash preceding the semicolon.', {
  6726. index: this.currToken[_tokenize.FIELDS.START_POS]
  6727. });
  6728. };
  6729. _proto.missingParenthesis = function missingParenthesis() {
  6730. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6731. };
  6732. _proto.missingSquareBracket = function missingSquareBracket() {
  6733. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6734. };
  6735. _proto.unexpected = function unexpected() {
  6736. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6737. };
  6738. _proto.unexpectedPipe = function unexpectedPipe() {
  6739. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6740. };
  6741. _proto.namespace = function namespace() {
  6742. var before = this.prevToken && this.content(this.prevToken) || true;
  6743. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6744. this.position++;
  6745. return this.word(before);
  6746. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6747. this.position++;
  6748. return this.universal(before);
  6749. }
  6750. this.unexpectedPipe();
  6751. };
  6752. _proto.nesting = function nesting() {
  6753. if (this.nextToken) {
  6754. var nextContent = this.content(this.nextToken);
  6755. if (nextContent === "|") {
  6756. this.position++;
  6757. return;
  6758. }
  6759. }
  6760. var current = this.currToken;
  6761. this.newNode(new _nesting["default"]({
  6762. value: this.content(),
  6763. source: getTokenSource(current),
  6764. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6765. }));
  6766. this.position++;
  6767. };
  6768. _proto.parentheses = function parentheses() {
  6769. var last = this.current.last;
  6770. var unbalanced = 1;
  6771. this.position++;
  6772. if (last && last.type === types.PSEUDO) {
  6773. var selector = new _selector["default"]({
  6774. source: {
  6775. start: tokenStart(this.tokens[this.position])
  6776. },
  6777. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6778. });
  6779. var cache = this.current;
  6780. last.append(selector);
  6781. this.current = selector;
  6782. while (this.position < this.tokens.length && unbalanced) {
  6783. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6784. unbalanced++;
  6785. }
  6786. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6787. unbalanced--;
  6788. }
  6789. if (unbalanced) {
  6790. this.parse();
  6791. } else {
  6792. this.current.source.end = tokenEnd(this.currToken);
  6793. this.current.parent.source.end = tokenEnd(this.currToken);
  6794. this.position++;
  6795. }
  6796. }
  6797. this.current = cache;
  6798. } else {
  6799. // I think this case should be an error. It's used to implement a basic parse of media queries
  6800. // but I don't think it's a good idea.
  6801. var parenStart = this.currToken;
  6802. var parenValue = "(";
  6803. var parenEnd;
  6804. while (this.position < this.tokens.length && unbalanced) {
  6805. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6806. unbalanced++;
  6807. }
  6808. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6809. unbalanced--;
  6810. }
  6811. parenEnd = this.currToken;
  6812. parenValue += this.parseParenthesisToken(this.currToken);
  6813. this.position++;
  6814. }
  6815. if (last) {
  6816. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6817. } else {
  6818. this.newNode(new _string["default"]({
  6819. value: parenValue,
  6820. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6821. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6822. }));
  6823. }
  6824. }
  6825. if (unbalanced) {
  6826. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6827. }
  6828. };
  6829. _proto.pseudo = function pseudo() {
  6830. var _this4 = this;
  6831. var pseudoStr = '';
  6832. var startingToken = this.currToken;
  6833. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6834. pseudoStr += this.content();
  6835. this.position++;
  6836. }
  6837. if (!this.currToken) {
  6838. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6839. }
  6840. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6841. this.splitWord(false, function (first, length) {
  6842. pseudoStr += first;
  6843. _this4.newNode(new _pseudo["default"]({
  6844. value: pseudoStr,
  6845. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6846. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6847. }));
  6848. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6849. _this4.error('Misplaced parenthesis.', {
  6850. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6851. });
  6852. }
  6853. });
  6854. } else {
  6855. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6856. }
  6857. };
  6858. _proto.space = function space() {
  6859. var content = this.content();
  6860. // Handle space before and after the selector
  6861. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6862. return node.type === 'comment';
  6863. })) {
  6864. this.spaces = this.optionalSpace(content);
  6865. this.position++;
  6866. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6867. this.current.last.spaces.after = this.optionalSpace(content);
  6868. this.position++;
  6869. } else {
  6870. this.combinator();
  6871. }
  6872. };
  6873. _proto.string = function string() {
  6874. var current = this.currToken;
  6875. this.newNode(new _string["default"]({
  6876. value: this.content(),
  6877. source: getTokenSource(current),
  6878. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6879. }));
  6880. this.position++;
  6881. };
  6882. _proto.universal = function universal(namespace) {
  6883. var nextToken = this.nextToken;
  6884. if (nextToken && this.content(nextToken) === '|') {
  6885. this.position++;
  6886. return this.namespace();
  6887. }
  6888. var current = this.currToken;
  6889. this.newNode(new _universal["default"]({
  6890. value: this.content(),
  6891. source: getTokenSource(current),
  6892. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6893. }), namespace);
  6894. this.position++;
  6895. };
  6896. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6897. var _this5 = this;
  6898. var nextToken = this.nextToken;
  6899. var word = this.content();
  6900. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6901. this.position++;
  6902. var current = this.content();
  6903. word += current;
  6904. if (current.lastIndexOf('\\') === current.length - 1) {
  6905. var next = this.nextToken;
  6906. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6907. word += this.requiredSpace(this.content(next));
  6908. this.position++;
  6909. }
  6910. }
  6911. nextToken = this.nextToken;
  6912. }
  6913. var hasClass = indexesOf(word, '.').filter(function (i) {
  6914. // Allow escaped dot within class name
  6915. var escapedDot = word[i - 1] === '\\';
  6916. // Allow decimal numbers percent in @keyframes
  6917. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6918. return !escapedDot && !isKeyframesPercent;
  6919. });
  6920. var hasId = indexesOf(word, '#').filter(function (i) {
  6921. return word[i - 1] !== '\\';
  6922. });
  6923. // Eliminate Sass interpolations from the list of id indexes
  6924. var interpolations = indexesOf(word, '#{');
  6925. if (interpolations.length) {
  6926. hasId = hasId.filter(function (hashIndex) {
  6927. return !~interpolations.indexOf(hashIndex);
  6928. });
  6929. }
  6930. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6931. indices.forEach(function (ind, i) {
  6932. var index = indices[i + 1] || word.length;
  6933. var value = word.slice(ind, index);
  6934. if (i === 0 && firstCallback) {
  6935. return firstCallback.call(_this5, value, indices.length);
  6936. }
  6937. var node;
  6938. var current = _this5.currToken;
  6939. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6940. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6941. if (~hasClass.indexOf(ind)) {
  6942. var classNameOpts = {
  6943. value: value.slice(1),
  6944. source: source,
  6945. sourceIndex: sourceIndex
  6946. };
  6947. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6948. } else if (~hasId.indexOf(ind)) {
  6949. var idOpts = {
  6950. value: value.slice(1),
  6951. source: source,
  6952. sourceIndex: sourceIndex
  6953. };
  6954. node = new _id["default"](unescapeProp(idOpts, "value"));
  6955. } else {
  6956. var tagOpts = {
  6957. value: value,
  6958. source: source,
  6959. sourceIndex: sourceIndex
  6960. };
  6961. unescapeProp(tagOpts, "value");
  6962. node = new _tag["default"](tagOpts);
  6963. }
  6964. _this5.newNode(node, namespace);
  6965. // Ensure that the namespace is used only once
  6966. namespace = null;
  6967. });
  6968. this.position++;
  6969. };
  6970. _proto.word = function word(namespace) {
  6971. var nextToken = this.nextToken;
  6972. if (nextToken && this.content(nextToken) === '|') {
  6973. this.position++;
  6974. return this.namespace();
  6975. }
  6976. return this.splitWord(namespace);
  6977. };
  6978. _proto.loop = function loop() {
  6979. while (this.position < this.tokens.length) {
  6980. this.parse(true);
  6981. }
  6982. this.current._inferEndPosition();
  6983. return this.root;
  6984. };
  6985. _proto.parse = function parse(throwOnParenthesis) {
  6986. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6987. case tokens.space:
  6988. this.space();
  6989. break;
  6990. case tokens.comment:
  6991. this.comment();
  6992. break;
  6993. case tokens.openParenthesis:
  6994. this.parentheses();
  6995. break;
  6996. case tokens.closeParenthesis:
  6997. if (throwOnParenthesis) {
  6998. this.missingParenthesis();
  6999. }
  7000. break;
  7001. case tokens.openSquare:
  7002. this.attribute();
  7003. break;
  7004. case tokens.dollar:
  7005. case tokens.caret:
  7006. case tokens.equals:
  7007. case tokens.word:
  7008. this.word();
  7009. break;
  7010. case tokens.colon:
  7011. this.pseudo();
  7012. break;
  7013. case tokens.comma:
  7014. this.comma();
  7015. break;
  7016. case tokens.asterisk:
  7017. this.universal();
  7018. break;
  7019. case tokens.ampersand:
  7020. this.nesting();
  7021. break;
  7022. case tokens.slash:
  7023. case tokens.combinator:
  7024. this.combinator();
  7025. break;
  7026. case tokens.str:
  7027. this.string();
  7028. break;
  7029. // These cases throw; no break needed.
  7030. case tokens.closeSquare:
  7031. this.missingSquareBracket();
  7032. case tokens.semicolon:
  7033. this.missingBackslash();
  7034. default:
  7035. this.unexpected();
  7036. }
  7037. }
  7038. /**
  7039. * Helpers
  7040. */;
  7041. _proto.expected = function expected(description, index, found) {
  7042. if (Array.isArray(description)) {
  7043. var last = description.pop();
  7044. description = description.join(', ') + " or " + last;
  7045. }
  7046. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  7047. if (!found) {
  7048. return this.error("Expected " + an + " " + description + ".", {
  7049. index: index
  7050. });
  7051. }
  7052. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  7053. index: index
  7054. });
  7055. };
  7056. _proto.requiredSpace = function requiredSpace(space) {
  7057. return this.options.lossy ? ' ' : space;
  7058. };
  7059. _proto.optionalSpace = function optionalSpace(space) {
  7060. return this.options.lossy ? '' : space;
  7061. };
  7062. _proto.lossySpace = function lossySpace(space, required) {
  7063. if (this.options.lossy) {
  7064. return required ? ' ' : '';
  7065. } else {
  7066. return space;
  7067. }
  7068. };
  7069. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  7070. var content = this.content(token);
  7071. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  7072. return this.requiredSpace(content);
  7073. } else {
  7074. return content;
  7075. }
  7076. };
  7077. _proto.newNode = function newNode(node, namespace) {
  7078. if (namespace) {
  7079. if (/^ +$/.test(namespace)) {
  7080. if (!this.options.lossy) {
  7081. this.spaces = (this.spaces || '') + namespace;
  7082. }
  7083. namespace = true;
  7084. }
  7085. node.namespace = namespace;
  7086. unescapeProp(node, "namespace");
  7087. }
  7088. if (this.spaces) {
  7089. node.spaces.before = this.spaces;
  7090. this.spaces = '';
  7091. }
  7092. return this.current.append(node);
  7093. };
  7094. _proto.content = function content(token) {
  7095. if (token === void 0) {
  7096. token = this.currToken;
  7097. }
  7098. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  7099. };
  7100. /**
  7101. * returns the index of the next non-whitespace, non-comment token.
  7102. * returns -1 if no meaningful token is found.
  7103. */
  7104. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  7105. if (startPosition === void 0) {
  7106. startPosition = this.position + 1;
  7107. }
  7108. var searchPosition = startPosition;
  7109. while (searchPosition < this.tokens.length) {
  7110. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  7111. searchPosition++;
  7112. continue;
  7113. } else {
  7114. return searchPosition;
  7115. }
  7116. }
  7117. return -1;
  7118. };
  7119. _createClass(Parser, [{
  7120. key: "currToken",
  7121. get: function get() {
  7122. return this.tokens[this.position];
  7123. }
  7124. }, {
  7125. key: "nextToken",
  7126. get: function get() {
  7127. return this.tokens[this.position + 1];
  7128. }
  7129. }, {
  7130. key: "prevToken",
  7131. get: function get() {
  7132. return this.tokens[this.position - 1];
  7133. }
  7134. }]);
  7135. return Parser;
  7136. }();
  7137. exports$1["default"] = Parser;
  7138. module.exports = exports$1.default;
  7139. } (parser$1, parser$1.exports));
  7140. return parser$1.exports;
  7141. }
  7142. var hasRequiredProcessor$1;
  7143. function requireProcessor$1 () {
  7144. if (hasRequiredProcessor$1) return processor$1.exports;
  7145. hasRequiredProcessor$1 = 1;
  7146. (function (module, exports$1) {
  7147. exports$1.__esModule = true;
  7148. exports$1["default"] = void 0;
  7149. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser$2());
  7150. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7151. var Processor = /*#__PURE__*/function () {
  7152. function Processor(func, options) {
  7153. this.func = func || function noop() {};
  7154. this.funcRes = null;
  7155. this.options = options;
  7156. }
  7157. var _proto = Processor.prototype;
  7158. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7159. if (options === void 0) {
  7160. options = {};
  7161. }
  7162. var merged = Object.assign({}, this.options, options);
  7163. if (merged.updateSelector === false) {
  7164. return false;
  7165. } else {
  7166. return typeof rule !== "string";
  7167. }
  7168. };
  7169. _proto._isLossy = function _isLossy(options) {
  7170. if (options === void 0) {
  7171. options = {};
  7172. }
  7173. var merged = Object.assign({}, this.options, options);
  7174. if (merged.lossless === false) {
  7175. return true;
  7176. } else {
  7177. return false;
  7178. }
  7179. };
  7180. _proto._root = function _root(rule, options) {
  7181. if (options === void 0) {
  7182. options = {};
  7183. }
  7184. var parser = new _parser["default"](rule, this._parseOptions(options));
  7185. return parser.root;
  7186. };
  7187. _proto._parseOptions = function _parseOptions(options) {
  7188. return {
  7189. lossy: this._isLossy(options)
  7190. };
  7191. };
  7192. _proto._run = function _run(rule, options) {
  7193. var _this = this;
  7194. if (options === void 0) {
  7195. options = {};
  7196. }
  7197. return new Promise(function (resolve, reject) {
  7198. try {
  7199. var root = _this._root(rule, options);
  7200. Promise.resolve(_this.func(root)).then(function (transform) {
  7201. var string = undefined;
  7202. if (_this._shouldUpdateSelector(rule, options)) {
  7203. string = root.toString();
  7204. rule.selector = string;
  7205. }
  7206. return {
  7207. transform: transform,
  7208. root: root,
  7209. string: string
  7210. };
  7211. }).then(resolve, reject);
  7212. } catch (e) {
  7213. reject(e);
  7214. return;
  7215. }
  7216. });
  7217. };
  7218. _proto._runSync = function _runSync(rule, options) {
  7219. if (options === void 0) {
  7220. options = {};
  7221. }
  7222. var root = this._root(rule, options);
  7223. var transform = this.func(root);
  7224. if (transform && typeof transform.then === "function") {
  7225. throw new Error("Selector processor returned a promise to a synchronous call.");
  7226. }
  7227. var string = undefined;
  7228. if (options.updateSelector && typeof rule !== "string") {
  7229. string = root.toString();
  7230. rule.selector = string;
  7231. }
  7232. return {
  7233. transform: transform,
  7234. root: root,
  7235. string: string
  7236. };
  7237. }
  7238. /**
  7239. * Process rule into a selector AST.
  7240. *
  7241. * @param rule {postcss.Rule | string} The css selector to be processed
  7242. * @param options The options for processing
  7243. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7244. */;
  7245. _proto.ast = function ast(rule, options) {
  7246. return this._run(rule, options).then(function (result) {
  7247. return result.root;
  7248. });
  7249. }
  7250. /**
  7251. * Process rule into a selector AST synchronously.
  7252. *
  7253. * @param rule {postcss.Rule | string} The css selector to be processed
  7254. * @param options The options for processing
  7255. * @returns {parser.Root} The AST of the selector after processing it.
  7256. */;
  7257. _proto.astSync = function astSync(rule, options) {
  7258. return this._runSync(rule, options).root;
  7259. }
  7260. /**
  7261. * Process a selector into a transformed value asynchronously
  7262. *
  7263. * @param rule {postcss.Rule | string} The css selector to be processed
  7264. * @param options The options for processing
  7265. * @returns {Promise<any>} The value returned by the processor.
  7266. */;
  7267. _proto.transform = function transform(rule, options) {
  7268. return this._run(rule, options).then(function (result) {
  7269. return result.transform;
  7270. });
  7271. }
  7272. /**
  7273. * Process a selector into a transformed value synchronously.
  7274. *
  7275. * @param rule {postcss.Rule | string} The css selector to be processed
  7276. * @param options The options for processing
  7277. * @returns {any} The value returned by the processor.
  7278. */;
  7279. _proto.transformSync = function transformSync(rule, options) {
  7280. return this._runSync(rule, options).transform;
  7281. }
  7282. /**
  7283. * Process a selector into a new selector string asynchronously.
  7284. *
  7285. * @param rule {postcss.Rule | string} The css selector to be processed
  7286. * @param options The options for processing
  7287. * @returns {string} the selector after processing.
  7288. */;
  7289. _proto.process = function process(rule, options) {
  7290. return this._run(rule, options).then(function (result) {
  7291. return result.string || result.root.toString();
  7292. });
  7293. }
  7294. /**
  7295. * Process a selector into a new selector string synchronously.
  7296. *
  7297. * @param rule {postcss.Rule | string} The css selector to be processed
  7298. * @param options The options for processing
  7299. * @returns {string} the selector after processing.
  7300. */;
  7301. _proto.processSync = function processSync(rule, options) {
  7302. var result = this._runSync(rule, options);
  7303. return result.string || result.root.toString();
  7304. };
  7305. return Processor;
  7306. }();
  7307. exports$1["default"] = Processor;
  7308. module.exports = exports$1.default;
  7309. } (processor$1, processor$1.exports));
  7310. return processor$1.exports;
  7311. }
  7312. var selectors$1 = {};
  7313. var constructors$1 = {};
  7314. var hasRequiredConstructors$1;
  7315. function requireConstructors$1 () {
  7316. if (hasRequiredConstructors$1) return constructors$1;
  7317. hasRequiredConstructors$1 = 1;
  7318. constructors$1.__esModule = true;
  7319. 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;
  7320. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute$1());
  7321. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  7322. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  7323. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  7324. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  7325. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  7326. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  7327. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  7328. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  7329. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  7330. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  7331. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  7332. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7333. var attribute = function attribute(opts) {
  7334. return new _attribute["default"](opts);
  7335. };
  7336. constructors$1.attribute = attribute;
  7337. var className = function className(opts) {
  7338. return new _className["default"](opts);
  7339. };
  7340. constructors$1.className = className;
  7341. var combinator = function combinator(opts) {
  7342. return new _combinator["default"](opts);
  7343. };
  7344. constructors$1.combinator = combinator;
  7345. var comment = function comment(opts) {
  7346. return new _comment["default"](opts);
  7347. };
  7348. constructors$1.comment = comment;
  7349. var id = function id(opts) {
  7350. return new _id["default"](opts);
  7351. };
  7352. constructors$1.id = id;
  7353. var nesting = function nesting(opts) {
  7354. return new _nesting["default"](opts);
  7355. };
  7356. constructors$1.nesting = nesting;
  7357. var pseudo = function pseudo(opts) {
  7358. return new _pseudo["default"](opts);
  7359. };
  7360. constructors$1.pseudo = pseudo;
  7361. var root = function root(opts) {
  7362. return new _root["default"](opts);
  7363. };
  7364. constructors$1.root = root;
  7365. var selector = function selector(opts) {
  7366. return new _selector["default"](opts);
  7367. };
  7368. constructors$1.selector = selector;
  7369. var string = function string(opts) {
  7370. return new _string["default"](opts);
  7371. };
  7372. constructors$1.string = string;
  7373. var tag = function tag(opts) {
  7374. return new _tag["default"](opts);
  7375. };
  7376. constructors$1.tag = tag;
  7377. var universal = function universal(opts) {
  7378. return new _universal["default"](opts);
  7379. };
  7380. constructors$1.universal = universal;
  7381. return constructors$1;
  7382. }
  7383. var guards$1 = {};
  7384. var hasRequiredGuards$1;
  7385. function requireGuards$1 () {
  7386. if (hasRequiredGuards$1) return guards$1;
  7387. hasRequiredGuards$1 = 1;
  7388. guards$1.__esModule = true;
  7389. guards$1.isComment = guards$1.isCombinator = guards$1.isClassName = guards$1.isAttribute = void 0;
  7390. guards$1.isContainer = isContainer;
  7391. guards$1.isIdentifier = void 0;
  7392. guards$1.isNamespace = isNamespace;
  7393. guards$1.isNesting = void 0;
  7394. guards$1.isNode = isNode;
  7395. guards$1.isPseudo = void 0;
  7396. guards$1.isPseudoClass = isPseudoClass;
  7397. guards$1.isPseudoElement = isPseudoElement;
  7398. guards$1.isUniversal = guards$1.isTag = guards$1.isString = guards$1.isSelector = guards$1.isRoot = void 0;
  7399. var _types = /*@__PURE__*/ requireTypes$1();
  7400. var _IS_TYPE;
  7401. 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);
  7402. function isNode(node) {
  7403. return typeof node === "object" && IS_TYPE[node.type];
  7404. }
  7405. function isNodeType(type, node) {
  7406. return isNode(node) && node.type === type;
  7407. }
  7408. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7409. guards$1.isAttribute = isAttribute;
  7410. var isClassName = isNodeType.bind(null, _types.CLASS);
  7411. guards$1.isClassName = isClassName;
  7412. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7413. guards$1.isCombinator = isCombinator;
  7414. var isComment = isNodeType.bind(null, _types.COMMENT);
  7415. guards$1.isComment = isComment;
  7416. var isIdentifier = isNodeType.bind(null, _types.ID);
  7417. guards$1.isIdentifier = isIdentifier;
  7418. var isNesting = isNodeType.bind(null, _types.NESTING);
  7419. guards$1.isNesting = isNesting;
  7420. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7421. guards$1.isPseudo = isPseudo;
  7422. var isRoot = isNodeType.bind(null, _types.ROOT);
  7423. guards$1.isRoot = isRoot;
  7424. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7425. guards$1.isSelector = isSelector;
  7426. var isString = isNodeType.bind(null, _types.STRING);
  7427. guards$1.isString = isString;
  7428. var isTag = isNodeType.bind(null, _types.TAG);
  7429. guards$1.isTag = isTag;
  7430. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7431. guards$1.isUniversal = isUniversal;
  7432. function isPseudoElement(node) {
  7433. 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");
  7434. }
  7435. function isPseudoClass(node) {
  7436. return isPseudo(node) && !isPseudoElement(node);
  7437. }
  7438. function isContainer(node) {
  7439. return !!(isNode(node) && node.walk);
  7440. }
  7441. function isNamespace(node) {
  7442. return isAttribute(node) || isTag(node);
  7443. }
  7444. return guards$1;
  7445. }
  7446. var hasRequiredSelectors$1;
  7447. function requireSelectors$1 () {
  7448. if (hasRequiredSelectors$1) return selectors$1;
  7449. hasRequiredSelectors$1 = 1;
  7450. (function (exports$1) {
  7451. exports$1.__esModule = true;
  7452. var _types = /*@__PURE__*/ requireTypes$1();
  7453. Object.keys(_types).forEach(function (key) {
  7454. if (key === "default" || key === "__esModule") return;
  7455. if (key in exports$1 && exports$1[key] === _types[key]) return;
  7456. exports$1[key] = _types[key];
  7457. });
  7458. var _constructors = /*@__PURE__*/ requireConstructors$1();
  7459. Object.keys(_constructors).forEach(function (key) {
  7460. if (key === "default" || key === "__esModule") return;
  7461. if (key in exports$1 && exports$1[key] === _constructors[key]) return;
  7462. exports$1[key] = _constructors[key];
  7463. });
  7464. var _guards = /*@__PURE__*/ requireGuards$1();
  7465. Object.keys(_guards).forEach(function (key) {
  7466. if (key === "default" || key === "__esModule") return;
  7467. if (key in exports$1 && exports$1[key] === _guards[key]) return;
  7468. exports$1[key] = _guards[key];
  7469. });
  7470. } (selectors$1));
  7471. return selectors$1;
  7472. }
  7473. var hasRequiredDist$1;
  7474. function requireDist$1 () {
  7475. if (hasRequiredDist$1) return dist$1.exports;
  7476. hasRequiredDist$1 = 1;
  7477. (function (module, exports$1) {
  7478. exports$1.__esModule = true;
  7479. exports$1["default"] = void 0;
  7480. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor$1());
  7481. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors$1());
  7482. 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); }
  7483. 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; }
  7484. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7485. var parser = function parser(processor) {
  7486. return new _processor["default"](processor);
  7487. };
  7488. Object.assign(parser, selectors);
  7489. delete parser.__esModule;
  7490. var _default = parser;
  7491. exports$1["default"] = _default;
  7492. module.exports = exports$1.default;
  7493. } (dist$1, dist$1.exports));
  7494. return dist$1.exports;
  7495. }
  7496. var distExports = /*@__PURE__*/ requireDist$1();
  7497. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7498. const animationNameRE = /^(?:-\w+-)?animation-name$/;
  7499. const animationRE = /^(?:-\w+-)?animation$/;
  7500. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  7501. const scopedPlugin = (id = "") => {
  7502. const keyframes = /* @__PURE__ */ Object.create(null);
  7503. const shortId = id.replace(/^data-v-/, "");
  7504. return {
  7505. postcssPlugin: "vue-sfc-scoped",
  7506. Rule(rule) {
  7507. processRule(id, rule);
  7508. },
  7509. AtRule(node) {
  7510. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7511. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7512. }
  7513. },
  7514. OnceExit(root) {
  7515. if (Object.keys(keyframes).length) {
  7516. root.walkDecls((decl) => {
  7517. if (animationNameRE.test(decl.prop)) {
  7518. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7519. }
  7520. if (animationRE.test(decl.prop)) {
  7521. decl.value = decl.value.split(",").map((v) => {
  7522. const vals = v.trim().split(/\s+/);
  7523. const i = vals.findIndex((val) => keyframes[val]);
  7524. if (i !== -1) {
  7525. vals.splice(i, 1, keyframes[vals[i]]);
  7526. return vals.join(" ");
  7527. } else {
  7528. return v;
  7529. }
  7530. }).join(",");
  7531. }
  7532. });
  7533. }
  7534. }
  7535. };
  7536. };
  7537. const processedRules = /* @__PURE__ */ new WeakSet();
  7538. function processRule(id, rule) {
  7539. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  7540. return;
  7541. }
  7542. processedRules.add(rule);
  7543. let deep = false;
  7544. let parent = rule.parent;
  7545. while (parent && parent.type !== "root") {
  7546. if (parent.__deep) {
  7547. deep = true;
  7548. break;
  7549. }
  7550. parent = parent.parent;
  7551. }
  7552. rule.selector = selectorParser((selectorRoot) => {
  7553. selectorRoot.each((selector) => {
  7554. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7555. });
  7556. }).processSync(rule.selector);
  7557. }
  7558. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7559. let node = null;
  7560. let shouldInject = !deep;
  7561. selector.each((n) => {
  7562. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7563. n.value = " ";
  7564. n.spaces.before = n.spaces.after = "";
  7565. warn(
  7566. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7567. );
  7568. return false;
  7569. }
  7570. if (n.type === "pseudo") {
  7571. const { value } = n;
  7572. if (value === ":deep" || value === "::v-deep") {
  7573. rule.__deep = true;
  7574. if (n.nodes.length) {
  7575. let last = n;
  7576. n.nodes[0].each((ss) => {
  7577. selector.insertAfter(last, ss);
  7578. last = ss;
  7579. });
  7580. const prev = selector.at(selector.index(n) - 1);
  7581. if (!prev || !isSpaceCombinator(prev)) {
  7582. selector.insertAfter(
  7583. n,
  7584. selectorParser.combinator({
  7585. value: " "
  7586. })
  7587. );
  7588. }
  7589. selector.removeChild(n);
  7590. } else {
  7591. warn(
  7592. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7593. );
  7594. const prev = selector.at(selector.index(n) - 1);
  7595. if (prev && isSpaceCombinator(prev)) {
  7596. selector.removeChild(prev);
  7597. }
  7598. selector.removeChild(n);
  7599. }
  7600. return false;
  7601. }
  7602. if (value === ":slotted" || value === "::v-slotted") {
  7603. rewriteSelector(
  7604. id,
  7605. rule,
  7606. n.nodes[0],
  7607. selectorRoot,
  7608. deep,
  7609. true
  7610. );
  7611. let last = n;
  7612. n.nodes[0].each((ss) => {
  7613. selector.insertAfter(last, ss);
  7614. last = ss;
  7615. });
  7616. selector.removeChild(n);
  7617. shouldInject = false;
  7618. return false;
  7619. }
  7620. if (value === ":global" || value === "::v-global") {
  7621. selector.replaceWith(n.nodes[0]);
  7622. return false;
  7623. }
  7624. }
  7625. if (n.type === "universal") {
  7626. const prev = selector.at(selector.index(n) - 1);
  7627. const next = selector.at(selector.index(n) + 1);
  7628. if (!prev) {
  7629. if (next) {
  7630. if (next.type === "combinator" && next.value === " ") {
  7631. selector.removeChild(next);
  7632. }
  7633. selector.removeChild(n);
  7634. return;
  7635. } else {
  7636. node = selectorParser.combinator({
  7637. value: ""
  7638. });
  7639. selector.insertBefore(n, node);
  7640. selector.removeChild(n);
  7641. return false;
  7642. }
  7643. }
  7644. if (node) return;
  7645. }
  7646. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node) {
  7647. node = n;
  7648. }
  7649. });
  7650. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7651. const deep2 = rule.__deep;
  7652. if (!deep2) {
  7653. extractAndWrapNodes(rule);
  7654. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7655. for (const atnode of atruleNodes) {
  7656. extractAndWrapNodes(atnode);
  7657. }
  7658. }
  7659. shouldInject = deep2;
  7660. }
  7661. if (node) {
  7662. const { type, value } = node;
  7663. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7664. node.nodes.forEach(
  7665. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7666. );
  7667. shouldInject = false;
  7668. }
  7669. }
  7670. if (node) {
  7671. node.spaces.after = "";
  7672. } else {
  7673. selector.first.spaces.before = "";
  7674. }
  7675. if (shouldInject) {
  7676. const idToAdd = slotted ? id + "-s" : id;
  7677. selector.insertAfter(
  7678. // If node is null it means we need to inject [id] at the start
  7679. // insertAfter can handle `null` here
  7680. node,
  7681. selectorParser.attribute({
  7682. attribute: idToAdd,
  7683. value: idToAdd,
  7684. raws: {},
  7685. quoteMark: `"`
  7686. })
  7687. );
  7688. }
  7689. }
  7690. function isSpaceCombinator(node) {
  7691. return node.type === "combinator" && /^\s+$/.test(node.value);
  7692. }
  7693. function extractAndWrapNodes(parentNode) {
  7694. if (!parentNode.nodes) return;
  7695. const nodes = parentNode.nodes.filter(
  7696. (node) => node.type === "decl" || node.type === "comment"
  7697. );
  7698. if (nodes.length) {
  7699. for (const node of nodes) {
  7700. parentNode.removeChild(node);
  7701. }
  7702. const wrappedRule = new require$$0$1.Rule({
  7703. nodes,
  7704. selector: "&"
  7705. });
  7706. parentNode.prepend(wrappedRule);
  7707. }
  7708. }
  7709. scopedPlugin.postcss = true;
  7710. var sourceMap = {};
  7711. var sourceMapGenerator = {};
  7712. var base64Vlq = {};
  7713. var base64 = {};
  7714. /* -*- Mode: js; js-indent-level: 2; -*- */
  7715. var hasRequiredBase64;
  7716. function requireBase64 () {
  7717. if (hasRequiredBase64) return base64;
  7718. hasRequiredBase64 = 1;
  7719. /*
  7720. * Copyright 2011 Mozilla Foundation and contributors
  7721. * Licensed under the New BSD license. See LICENSE or:
  7722. * http://opensource.org/licenses/BSD-3-Clause
  7723. */
  7724. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7725. /**
  7726. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7727. */
  7728. base64.encode = function (number) {
  7729. if (0 <= number && number < intToCharMap.length) {
  7730. return intToCharMap[number];
  7731. }
  7732. throw new TypeError("Must be between 0 and 63: " + number);
  7733. };
  7734. /**
  7735. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7736. * failure.
  7737. */
  7738. base64.decode = function (charCode) {
  7739. var bigA = 65; // 'A'
  7740. var bigZ = 90; // 'Z'
  7741. var littleA = 97; // 'a'
  7742. var littleZ = 122; // 'z'
  7743. var zero = 48; // '0'
  7744. var nine = 57; // '9'
  7745. var plus = 43; // '+'
  7746. var slash = 47; // '/'
  7747. var littleOffset = 26;
  7748. var numberOffset = 52;
  7749. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7750. if (bigA <= charCode && charCode <= bigZ) {
  7751. return (charCode - bigA);
  7752. }
  7753. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7754. if (littleA <= charCode && charCode <= littleZ) {
  7755. return (charCode - littleA + littleOffset);
  7756. }
  7757. // 52 - 61: 0123456789
  7758. if (zero <= charCode && charCode <= nine) {
  7759. return (charCode - zero + numberOffset);
  7760. }
  7761. // 62: +
  7762. if (charCode == plus) {
  7763. return 62;
  7764. }
  7765. // 63: /
  7766. if (charCode == slash) {
  7767. return 63;
  7768. }
  7769. // Invalid base64 digit.
  7770. return -1;
  7771. };
  7772. return base64;
  7773. }
  7774. /* -*- Mode: js; js-indent-level: 2; -*- */
  7775. var hasRequiredBase64Vlq;
  7776. function requireBase64Vlq () {
  7777. if (hasRequiredBase64Vlq) return base64Vlq;
  7778. hasRequiredBase64Vlq = 1;
  7779. /*
  7780. * Copyright 2011 Mozilla Foundation and contributors
  7781. * Licensed under the New BSD license. See LICENSE or:
  7782. * http://opensource.org/licenses/BSD-3-Clause
  7783. *
  7784. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7785. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7786. *
  7787. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7788. * Redistribution and use in source and binary forms, with or without
  7789. * modification, are permitted provided that the following conditions are
  7790. * met:
  7791. *
  7792. * * Redistributions of source code must retain the above copyright
  7793. * notice, this list of conditions and the following disclaimer.
  7794. * * Redistributions in binary form must reproduce the above
  7795. * copyright notice, this list of conditions and the following
  7796. * disclaimer in the documentation and/or other materials provided
  7797. * with the distribution.
  7798. * * Neither the name of Google Inc. nor the names of its
  7799. * contributors may be used to endorse or promote products derived
  7800. * from this software without specific prior written permission.
  7801. *
  7802. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7803. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7804. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7805. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7806. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7807. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7808. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7809. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7810. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7811. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7812. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7813. */
  7814. var base64 = /*@__PURE__*/ requireBase64();
  7815. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7816. // length quantities we use in the source map spec, the first bit is the sign,
  7817. // the next four bits are the actual value, and the 6th bit is the
  7818. // continuation bit. The continuation bit tells us whether there are more
  7819. // digits in this value following this digit.
  7820. //
  7821. // Continuation
  7822. // | Sign
  7823. // | |
  7824. // V V
  7825. // 101011
  7826. var VLQ_BASE_SHIFT = 5;
  7827. // binary: 100000
  7828. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7829. // binary: 011111
  7830. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7831. // binary: 100000
  7832. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7833. /**
  7834. * Converts from a two-complement value to a value where the sign bit is
  7835. * placed in the least significant bit. For example, as decimals:
  7836. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7837. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7838. */
  7839. function toVLQSigned(aValue) {
  7840. return aValue < 0
  7841. ? ((-aValue) << 1) + 1
  7842. : (aValue << 1) + 0;
  7843. }
  7844. /**
  7845. * Converts to a two-complement value from a value where the sign bit is
  7846. * placed in the least significant bit. For example, as decimals:
  7847. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7848. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7849. */
  7850. function fromVLQSigned(aValue) {
  7851. var isNegative = (aValue & 1) === 1;
  7852. var shifted = aValue >> 1;
  7853. return isNegative
  7854. ? -shifted
  7855. : shifted;
  7856. }
  7857. /**
  7858. * Returns the base 64 VLQ encoded value.
  7859. */
  7860. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7861. var encoded = "";
  7862. var digit;
  7863. var vlq = toVLQSigned(aValue);
  7864. do {
  7865. digit = vlq & VLQ_BASE_MASK;
  7866. vlq >>>= VLQ_BASE_SHIFT;
  7867. if (vlq > 0) {
  7868. // There are still more digits in this value, so we must make sure the
  7869. // continuation bit is marked.
  7870. digit |= VLQ_CONTINUATION_BIT;
  7871. }
  7872. encoded += base64.encode(digit);
  7873. } while (vlq > 0);
  7874. return encoded;
  7875. };
  7876. /**
  7877. * Decodes the next base 64 VLQ value from the given string and returns the
  7878. * value and the rest of the string via the out parameter.
  7879. */
  7880. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7881. var strLen = aStr.length;
  7882. var result = 0;
  7883. var shift = 0;
  7884. var continuation, digit;
  7885. do {
  7886. if (aIndex >= strLen) {
  7887. throw new Error("Expected more digits in base 64 VLQ value.");
  7888. }
  7889. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7890. if (digit === -1) {
  7891. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7892. }
  7893. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7894. digit &= VLQ_BASE_MASK;
  7895. result = result + (digit << shift);
  7896. shift += VLQ_BASE_SHIFT;
  7897. } while (continuation);
  7898. aOutParam.value = fromVLQSigned(result);
  7899. aOutParam.rest = aIndex;
  7900. };
  7901. return base64Vlq;
  7902. }
  7903. var util$1 = {};
  7904. /* -*- Mode: js; js-indent-level: 2; -*- */
  7905. var hasRequiredUtil$1;
  7906. function requireUtil$1 () {
  7907. if (hasRequiredUtil$1) return util$1;
  7908. hasRequiredUtil$1 = 1;
  7909. (function (exports$1) {
  7910. /*
  7911. * Copyright 2011 Mozilla Foundation and contributors
  7912. * Licensed under the New BSD license. See LICENSE or:
  7913. * http://opensource.org/licenses/BSD-3-Clause
  7914. */
  7915. /**
  7916. * This is a helper function for getting values from parameter/options
  7917. * objects.
  7918. *
  7919. * @param args The object we are extracting values from
  7920. * @param name The name of the property we are getting.
  7921. * @param defaultValue An optional value to return if the property is missing
  7922. * from the object. If this is not specified and the property is missing, an
  7923. * error will be thrown.
  7924. */
  7925. function getArg(aArgs, aName, aDefaultValue) {
  7926. if (aName in aArgs) {
  7927. return aArgs[aName];
  7928. } else if (arguments.length === 3) {
  7929. return aDefaultValue;
  7930. } else {
  7931. throw new Error('"' + aName + '" is a required argument.');
  7932. }
  7933. }
  7934. exports$1.getArg = getArg;
  7935. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7936. var dataUrlRegexp = /^data:.+\,.+$/;
  7937. function urlParse(aUrl) {
  7938. var match = aUrl.match(urlRegexp);
  7939. if (!match) {
  7940. return null;
  7941. }
  7942. return {
  7943. scheme: match[1],
  7944. auth: match[2],
  7945. host: match[3],
  7946. port: match[4],
  7947. path: match[5]
  7948. };
  7949. }
  7950. exports$1.urlParse = urlParse;
  7951. function urlGenerate(aParsedUrl) {
  7952. var url = '';
  7953. if (aParsedUrl.scheme) {
  7954. url += aParsedUrl.scheme + ':';
  7955. }
  7956. url += '//';
  7957. if (aParsedUrl.auth) {
  7958. url += aParsedUrl.auth + '@';
  7959. }
  7960. if (aParsedUrl.host) {
  7961. url += aParsedUrl.host;
  7962. }
  7963. if (aParsedUrl.port) {
  7964. url += ":" + aParsedUrl.port;
  7965. }
  7966. if (aParsedUrl.path) {
  7967. url += aParsedUrl.path;
  7968. }
  7969. return url;
  7970. }
  7971. exports$1.urlGenerate = urlGenerate;
  7972. /**
  7973. * Normalizes a path, or the path portion of a URL:
  7974. *
  7975. * - Replaces consecutive slashes with one slash.
  7976. * - Removes unnecessary '.' parts.
  7977. * - Removes unnecessary '<dir>/..' parts.
  7978. *
  7979. * Based on code in the Node.js 'path' core module.
  7980. *
  7981. * @param aPath The path or url to normalize.
  7982. */
  7983. function normalize(aPath) {
  7984. var path = aPath;
  7985. var url = urlParse(aPath);
  7986. if (url) {
  7987. if (!url.path) {
  7988. return aPath;
  7989. }
  7990. path = url.path;
  7991. }
  7992. var isAbsolute = exports$1.isAbsolute(path);
  7993. var parts = path.split(/\/+/);
  7994. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7995. part = parts[i];
  7996. if (part === '.') {
  7997. parts.splice(i, 1);
  7998. } else if (part === '..') {
  7999. up++;
  8000. } else if (up > 0) {
  8001. if (part === '') {
  8002. // The first part is blank if the path is absolute. Trying to go
  8003. // above the root is a no-op. Therefore we can remove all '..' parts
  8004. // directly after the root.
  8005. parts.splice(i + 1, up);
  8006. up = 0;
  8007. } else {
  8008. parts.splice(i, 2);
  8009. up--;
  8010. }
  8011. }
  8012. }
  8013. path = parts.join('/');
  8014. if (path === '') {
  8015. path = isAbsolute ? '/' : '.';
  8016. }
  8017. if (url) {
  8018. url.path = path;
  8019. return urlGenerate(url);
  8020. }
  8021. return path;
  8022. }
  8023. exports$1.normalize = normalize;
  8024. /**
  8025. * Joins two paths/URLs.
  8026. *
  8027. * @param aRoot The root path or URL.
  8028. * @param aPath The path or URL to be joined with the root.
  8029. *
  8030. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  8031. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  8032. * first.
  8033. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  8034. * is updated with the result and aRoot is returned. Otherwise the result
  8035. * is returned.
  8036. * - If aPath is absolute, the result is aPath.
  8037. * - Otherwise the two paths are joined with a slash.
  8038. * - Joining for example 'http://' and 'www.example.com' is also supported.
  8039. */
  8040. function join(aRoot, aPath) {
  8041. if (aRoot === "") {
  8042. aRoot = ".";
  8043. }
  8044. if (aPath === "") {
  8045. aPath = ".";
  8046. }
  8047. var aPathUrl = urlParse(aPath);
  8048. var aRootUrl = urlParse(aRoot);
  8049. if (aRootUrl) {
  8050. aRoot = aRootUrl.path || '/';
  8051. }
  8052. // `join(foo, '//www.example.org')`
  8053. if (aPathUrl && !aPathUrl.scheme) {
  8054. if (aRootUrl) {
  8055. aPathUrl.scheme = aRootUrl.scheme;
  8056. }
  8057. return urlGenerate(aPathUrl);
  8058. }
  8059. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8060. return aPath;
  8061. }
  8062. // `join('http://', 'www.example.com')`
  8063. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8064. aRootUrl.host = aPath;
  8065. return urlGenerate(aRootUrl);
  8066. }
  8067. var joined = aPath.charAt(0) === '/'
  8068. ? aPath
  8069. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8070. if (aRootUrl) {
  8071. aRootUrl.path = joined;
  8072. return urlGenerate(aRootUrl);
  8073. }
  8074. return joined;
  8075. }
  8076. exports$1.join = join;
  8077. exports$1.isAbsolute = function (aPath) {
  8078. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8079. };
  8080. /**
  8081. * Make a path relative to a URL or another path.
  8082. *
  8083. * @param aRoot The root path or URL.
  8084. * @param aPath The path or URL to be made relative to aRoot.
  8085. */
  8086. function relative(aRoot, aPath) {
  8087. if (aRoot === "") {
  8088. aRoot = ".";
  8089. }
  8090. aRoot = aRoot.replace(/\/$/, '');
  8091. // It is possible for the path to be above the root. In this case, simply
  8092. // checking whether the root is a prefix of the path won't work. Instead, we
  8093. // need to remove components from the root one by one, until either we find
  8094. // a prefix that fits, or we run out of components to remove.
  8095. var level = 0;
  8096. while (aPath.indexOf(aRoot + '/') !== 0) {
  8097. var index = aRoot.lastIndexOf("/");
  8098. if (index < 0) {
  8099. return aPath;
  8100. }
  8101. // If the only part of the root that is left is the scheme (i.e. http://,
  8102. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8103. // have exhausted all components, so the path is not relative to the root.
  8104. aRoot = aRoot.slice(0, index);
  8105. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8106. return aPath;
  8107. }
  8108. ++level;
  8109. }
  8110. // Make sure we add a "../" for each component we removed from the root.
  8111. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8112. }
  8113. exports$1.relative = relative;
  8114. var supportsNullProto = (function () {
  8115. var obj = Object.create(null);
  8116. return !('__proto__' in obj);
  8117. }());
  8118. function identity (s) {
  8119. return s;
  8120. }
  8121. /**
  8122. * Because behavior goes wacky when you set `__proto__` on objects, we
  8123. * have to prefix all the strings in our set with an arbitrary character.
  8124. *
  8125. * See https://github.com/mozilla/source-map/pull/31 and
  8126. * https://github.com/mozilla/source-map/issues/30
  8127. *
  8128. * @param String aStr
  8129. */
  8130. function toSetString(aStr) {
  8131. if (isProtoString(aStr)) {
  8132. return '$' + aStr;
  8133. }
  8134. return aStr;
  8135. }
  8136. exports$1.toSetString = supportsNullProto ? identity : toSetString;
  8137. function fromSetString(aStr) {
  8138. if (isProtoString(aStr)) {
  8139. return aStr.slice(1);
  8140. }
  8141. return aStr;
  8142. }
  8143. exports$1.fromSetString = supportsNullProto ? identity : fromSetString;
  8144. function isProtoString(s) {
  8145. if (!s) {
  8146. return false;
  8147. }
  8148. var length = s.length;
  8149. if (length < 9 /* "__proto__".length */) {
  8150. return false;
  8151. }
  8152. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8153. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8154. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8155. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8156. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8157. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8158. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8159. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8160. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8161. return false;
  8162. }
  8163. for (var i = length - 10; i >= 0; i--) {
  8164. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8165. return false;
  8166. }
  8167. }
  8168. return true;
  8169. }
  8170. /**
  8171. * Comparator between two mappings where the original positions are compared.
  8172. *
  8173. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8174. * mappings with the same original source/line/column, but different generated
  8175. * line and column the same. Useful when searching for a mapping with a
  8176. * stubbed out mapping.
  8177. */
  8178. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8179. var cmp = strcmp(mappingA.source, mappingB.source);
  8180. if (cmp !== 0) {
  8181. return cmp;
  8182. }
  8183. cmp = mappingA.originalLine - mappingB.originalLine;
  8184. if (cmp !== 0) {
  8185. return cmp;
  8186. }
  8187. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8188. if (cmp !== 0 || onlyCompareOriginal) {
  8189. return cmp;
  8190. }
  8191. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8192. if (cmp !== 0) {
  8193. return cmp;
  8194. }
  8195. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8196. if (cmp !== 0) {
  8197. return cmp;
  8198. }
  8199. return strcmp(mappingA.name, mappingB.name);
  8200. }
  8201. exports$1.compareByOriginalPositions = compareByOriginalPositions;
  8202. /**
  8203. * Comparator between two mappings with deflated source and name indices where
  8204. * the generated positions are compared.
  8205. *
  8206. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8207. * mappings with the same generated line and column, but different
  8208. * source/name/original line and column the same. Useful when searching for a
  8209. * mapping with a stubbed out mapping.
  8210. */
  8211. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8212. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8213. if (cmp !== 0) {
  8214. return cmp;
  8215. }
  8216. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8217. if (cmp !== 0 || onlyCompareGenerated) {
  8218. return cmp;
  8219. }
  8220. cmp = strcmp(mappingA.source, mappingB.source);
  8221. if (cmp !== 0) {
  8222. return cmp;
  8223. }
  8224. cmp = mappingA.originalLine - mappingB.originalLine;
  8225. if (cmp !== 0) {
  8226. return cmp;
  8227. }
  8228. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8229. if (cmp !== 0) {
  8230. return cmp;
  8231. }
  8232. return strcmp(mappingA.name, mappingB.name);
  8233. }
  8234. exports$1.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8235. function strcmp(aStr1, aStr2) {
  8236. if (aStr1 === aStr2) {
  8237. return 0;
  8238. }
  8239. if (aStr1 === null) {
  8240. return 1; // aStr2 !== null
  8241. }
  8242. if (aStr2 === null) {
  8243. return -1; // aStr1 !== null
  8244. }
  8245. if (aStr1 > aStr2) {
  8246. return 1;
  8247. }
  8248. return -1;
  8249. }
  8250. /**
  8251. * Comparator between two mappings with inflated source and name strings where
  8252. * the generated positions are compared.
  8253. */
  8254. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8255. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8256. if (cmp !== 0) {
  8257. return cmp;
  8258. }
  8259. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8260. if (cmp !== 0) {
  8261. return cmp;
  8262. }
  8263. cmp = strcmp(mappingA.source, mappingB.source);
  8264. if (cmp !== 0) {
  8265. return cmp;
  8266. }
  8267. cmp = mappingA.originalLine - mappingB.originalLine;
  8268. if (cmp !== 0) {
  8269. return cmp;
  8270. }
  8271. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8272. if (cmp !== 0) {
  8273. return cmp;
  8274. }
  8275. return strcmp(mappingA.name, mappingB.name);
  8276. }
  8277. exports$1.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8278. /**
  8279. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8280. * in the source maps specification), and then parse the string as
  8281. * JSON.
  8282. */
  8283. function parseSourceMapInput(str) {
  8284. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8285. }
  8286. exports$1.parseSourceMapInput = parseSourceMapInput;
  8287. /**
  8288. * Compute the URL of a source given the the source root, the source's
  8289. * URL, and the source map's URL.
  8290. */
  8291. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8292. sourceURL = sourceURL || '';
  8293. if (sourceRoot) {
  8294. // This follows what Chrome does.
  8295. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8296. sourceRoot += '/';
  8297. }
  8298. // The spec says:
  8299. // Line 4: An optional source root, useful for relocating source
  8300. // files on a server or removing repeated values in the
  8301. // “sources” entry. This value is prepended to the individual
  8302. // entries in the “source” field.
  8303. sourceURL = sourceRoot + sourceURL;
  8304. }
  8305. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8306. // a parameter. This mode is still somewhat supported, which is why
  8307. // this code block is conditional. However, it's preferable to pass
  8308. // the source map URL to SourceMapConsumer, so that this function
  8309. // can implement the source URL resolution algorithm as outlined in
  8310. // the spec. This block is basically the equivalent of:
  8311. // new URL(sourceURL, sourceMapURL).toString()
  8312. // ... except it avoids using URL, which wasn't available in the
  8313. // older releases of node still supported by this library.
  8314. //
  8315. // The spec says:
  8316. // If the sources are not absolute URLs after prepending of the
  8317. // “sourceRoot”, the sources are resolved relative to the
  8318. // SourceMap (like resolving script src in a html document).
  8319. if (sourceMapURL) {
  8320. var parsed = urlParse(sourceMapURL);
  8321. if (!parsed) {
  8322. throw new Error("sourceMapURL could not be parsed");
  8323. }
  8324. if (parsed.path) {
  8325. // Strip the last path component, but keep the "/".
  8326. var index = parsed.path.lastIndexOf('/');
  8327. if (index >= 0) {
  8328. parsed.path = parsed.path.substring(0, index + 1);
  8329. }
  8330. }
  8331. sourceURL = join(urlGenerate(parsed), sourceURL);
  8332. }
  8333. return normalize(sourceURL);
  8334. }
  8335. exports$1.computeSourceURL = computeSourceURL;
  8336. } (util$1));
  8337. return util$1;
  8338. }
  8339. var arraySet = {};
  8340. /* -*- Mode: js; js-indent-level: 2; -*- */
  8341. var hasRequiredArraySet;
  8342. function requireArraySet () {
  8343. if (hasRequiredArraySet) return arraySet;
  8344. hasRequiredArraySet = 1;
  8345. /*
  8346. * Copyright 2011 Mozilla Foundation and contributors
  8347. * Licensed under the New BSD license. See LICENSE or:
  8348. * http://opensource.org/licenses/BSD-3-Clause
  8349. */
  8350. var util = /*@__PURE__*/ requireUtil$1();
  8351. var has = Object.prototype.hasOwnProperty;
  8352. var hasNativeMap = typeof Map !== "undefined";
  8353. /**
  8354. * A data structure which is a combination of an array and a set. Adding a new
  8355. * member is O(1), testing for membership is O(1), and finding the index of an
  8356. * element is O(1). Removing elements from the set is not supported. Only
  8357. * strings are supported for membership.
  8358. */
  8359. function ArraySet() {
  8360. this._array = [];
  8361. this._set = hasNativeMap ? new Map() : Object.create(null);
  8362. }
  8363. /**
  8364. * Static method for creating ArraySet instances from an existing array.
  8365. */
  8366. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8367. var set = new ArraySet();
  8368. for (var i = 0, len = aArray.length; i < len; i++) {
  8369. set.add(aArray[i], aAllowDuplicates);
  8370. }
  8371. return set;
  8372. };
  8373. /**
  8374. * Return how many unique items are in this ArraySet. If duplicates have been
  8375. * added, than those do not count towards the size.
  8376. *
  8377. * @returns Number
  8378. */
  8379. ArraySet.prototype.size = function ArraySet_size() {
  8380. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8381. };
  8382. /**
  8383. * Add the given string to this set.
  8384. *
  8385. * @param String aStr
  8386. */
  8387. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8388. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8389. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8390. var idx = this._array.length;
  8391. if (!isDuplicate || aAllowDuplicates) {
  8392. this._array.push(aStr);
  8393. }
  8394. if (!isDuplicate) {
  8395. if (hasNativeMap) {
  8396. this._set.set(aStr, idx);
  8397. } else {
  8398. this._set[sStr] = idx;
  8399. }
  8400. }
  8401. };
  8402. /**
  8403. * Is the given string a member of this set?
  8404. *
  8405. * @param String aStr
  8406. */
  8407. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8408. if (hasNativeMap) {
  8409. return this._set.has(aStr);
  8410. } else {
  8411. var sStr = util.toSetString(aStr);
  8412. return has.call(this._set, sStr);
  8413. }
  8414. };
  8415. /**
  8416. * What is the index of the given string in the array?
  8417. *
  8418. * @param String aStr
  8419. */
  8420. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8421. if (hasNativeMap) {
  8422. var idx = this._set.get(aStr);
  8423. if (idx >= 0) {
  8424. return idx;
  8425. }
  8426. } else {
  8427. var sStr = util.toSetString(aStr);
  8428. if (has.call(this._set, sStr)) {
  8429. return this._set[sStr];
  8430. }
  8431. }
  8432. throw new Error('"' + aStr + '" is not in the set.');
  8433. };
  8434. /**
  8435. * What is the element at the given index?
  8436. *
  8437. * @param Number aIdx
  8438. */
  8439. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8440. if (aIdx >= 0 && aIdx < this._array.length) {
  8441. return this._array[aIdx];
  8442. }
  8443. throw new Error('No element indexed by ' + aIdx);
  8444. };
  8445. /**
  8446. * Returns the array representation of this set (which has the proper indices
  8447. * indicated by indexOf). Note that this is a copy of the internal array used
  8448. * for storing the members so that no one can mess with internal state.
  8449. */
  8450. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8451. return this._array.slice();
  8452. };
  8453. arraySet.ArraySet = ArraySet;
  8454. return arraySet;
  8455. }
  8456. var mappingList = {};
  8457. /* -*- Mode: js; js-indent-level: 2; -*- */
  8458. var hasRequiredMappingList;
  8459. function requireMappingList () {
  8460. if (hasRequiredMappingList) return mappingList;
  8461. hasRequiredMappingList = 1;
  8462. /*
  8463. * Copyright 2014 Mozilla Foundation and contributors
  8464. * Licensed under the New BSD license. See LICENSE or:
  8465. * http://opensource.org/licenses/BSD-3-Clause
  8466. */
  8467. var util = /*@__PURE__*/ requireUtil$1();
  8468. /**
  8469. * Determine whether mappingB is after mappingA with respect to generated
  8470. * position.
  8471. */
  8472. function generatedPositionAfter(mappingA, mappingB) {
  8473. // Optimized for most common case
  8474. var lineA = mappingA.generatedLine;
  8475. var lineB = mappingB.generatedLine;
  8476. var columnA = mappingA.generatedColumn;
  8477. var columnB = mappingB.generatedColumn;
  8478. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8479. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8480. }
  8481. /**
  8482. * A data structure to provide a sorted view of accumulated mappings in a
  8483. * performance conscious manner. It trades a neglibable overhead in general
  8484. * case for a large speedup in case of mappings being added in order.
  8485. */
  8486. function MappingList() {
  8487. this._array = [];
  8488. this._sorted = true;
  8489. // Serves as infimum
  8490. this._last = {generatedLine: -1, generatedColumn: 0};
  8491. }
  8492. /**
  8493. * Iterate through internal items. This method takes the same arguments that
  8494. * `Array.prototype.forEach` takes.
  8495. *
  8496. * NOTE: The order of the mappings is NOT guaranteed.
  8497. */
  8498. MappingList.prototype.unsortedForEach =
  8499. function MappingList_forEach(aCallback, aThisArg) {
  8500. this._array.forEach(aCallback, aThisArg);
  8501. };
  8502. /**
  8503. * Add the given source mapping.
  8504. *
  8505. * @param Object aMapping
  8506. */
  8507. MappingList.prototype.add = function MappingList_add(aMapping) {
  8508. if (generatedPositionAfter(this._last, aMapping)) {
  8509. this._last = aMapping;
  8510. this._array.push(aMapping);
  8511. } else {
  8512. this._sorted = false;
  8513. this._array.push(aMapping);
  8514. }
  8515. };
  8516. /**
  8517. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8518. * generated position.
  8519. *
  8520. * WARNING: This method returns internal data without copying, for
  8521. * performance. The return value must NOT be mutated, and should be treated as
  8522. * an immutable borrow. If you want to take ownership, you must make your own
  8523. * copy.
  8524. */
  8525. MappingList.prototype.toArray = function MappingList_toArray() {
  8526. if (!this._sorted) {
  8527. this._array.sort(util.compareByGeneratedPositionsInflated);
  8528. this._sorted = true;
  8529. }
  8530. return this._array;
  8531. };
  8532. mappingList.MappingList = MappingList;
  8533. return mappingList;
  8534. }
  8535. /* -*- Mode: js; js-indent-level: 2; -*- */
  8536. var hasRequiredSourceMapGenerator;
  8537. function requireSourceMapGenerator () {
  8538. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8539. hasRequiredSourceMapGenerator = 1;
  8540. /*
  8541. * Copyright 2011 Mozilla Foundation and contributors
  8542. * Licensed under the New BSD license. See LICENSE or:
  8543. * http://opensource.org/licenses/BSD-3-Clause
  8544. */
  8545. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8546. var util = /*@__PURE__*/ requireUtil$1();
  8547. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8548. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8549. /**
  8550. * An instance of the SourceMapGenerator represents a source map which is
  8551. * being built incrementally. You may pass an object with the following
  8552. * properties:
  8553. *
  8554. * - file: The filename of the generated source.
  8555. * - sourceRoot: A root for all relative URLs in this source map.
  8556. */
  8557. function SourceMapGenerator(aArgs) {
  8558. if (!aArgs) {
  8559. aArgs = {};
  8560. }
  8561. this._file = util.getArg(aArgs, 'file', null);
  8562. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8563. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8564. this._sources = new ArraySet();
  8565. this._names = new ArraySet();
  8566. this._mappings = new MappingList();
  8567. this._sourcesContents = null;
  8568. }
  8569. SourceMapGenerator.prototype._version = 3;
  8570. /**
  8571. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8572. *
  8573. * @param aSourceMapConsumer The SourceMap.
  8574. */
  8575. SourceMapGenerator.fromSourceMap =
  8576. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8577. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8578. var generator = new SourceMapGenerator({
  8579. file: aSourceMapConsumer.file,
  8580. sourceRoot: sourceRoot
  8581. });
  8582. aSourceMapConsumer.eachMapping(function (mapping) {
  8583. var newMapping = {
  8584. generated: {
  8585. line: mapping.generatedLine,
  8586. column: mapping.generatedColumn
  8587. }
  8588. };
  8589. if (mapping.source != null) {
  8590. newMapping.source = mapping.source;
  8591. if (sourceRoot != null) {
  8592. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8593. }
  8594. newMapping.original = {
  8595. line: mapping.originalLine,
  8596. column: mapping.originalColumn
  8597. };
  8598. if (mapping.name != null) {
  8599. newMapping.name = mapping.name;
  8600. }
  8601. }
  8602. generator.addMapping(newMapping);
  8603. });
  8604. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8605. var sourceRelative = sourceFile;
  8606. if (sourceRoot !== null) {
  8607. sourceRelative = util.relative(sourceRoot, sourceFile);
  8608. }
  8609. if (!generator._sources.has(sourceRelative)) {
  8610. generator._sources.add(sourceRelative);
  8611. }
  8612. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8613. if (content != null) {
  8614. generator.setSourceContent(sourceFile, content);
  8615. }
  8616. });
  8617. return generator;
  8618. };
  8619. /**
  8620. * Add a single mapping from original source line and column to the generated
  8621. * source's line and column for this source map being created. The mapping
  8622. * object should have the following properties:
  8623. *
  8624. * - generated: An object with the generated line and column positions.
  8625. * - original: An object with the original line and column positions.
  8626. * - source: The original source file (relative to the sourceRoot).
  8627. * - name: An optional original token name for this mapping.
  8628. */
  8629. SourceMapGenerator.prototype.addMapping =
  8630. function SourceMapGenerator_addMapping(aArgs) {
  8631. var generated = util.getArg(aArgs, 'generated');
  8632. var original = util.getArg(aArgs, 'original', null);
  8633. var source = util.getArg(aArgs, 'source', null);
  8634. var name = util.getArg(aArgs, 'name', null);
  8635. if (!this._skipValidation) {
  8636. this._validateMapping(generated, original, source, name);
  8637. }
  8638. if (source != null) {
  8639. source = String(source);
  8640. if (!this._sources.has(source)) {
  8641. this._sources.add(source);
  8642. }
  8643. }
  8644. if (name != null) {
  8645. name = String(name);
  8646. if (!this._names.has(name)) {
  8647. this._names.add(name);
  8648. }
  8649. }
  8650. this._mappings.add({
  8651. generatedLine: generated.line,
  8652. generatedColumn: generated.column,
  8653. originalLine: original != null && original.line,
  8654. originalColumn: original != null && original.column,
  8655. source: source,
  8656. name: name
  8657. });
  8658. };
  8659. /**
  8660. * Set the source content for a source file.
  8661. */
  8662. SourceMapGenerator.prototype.setSourceContent =
  8663. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8664. var source = aSourceFile;
  8665. if (this._sourceRoot != null) {
  8666. source = util.relative(this._sourceRoot, source);
  8667. }
  8668. if (aSourceContent != null) {
  8669. // Add the source content to the _sourcesContents map.
  8670. // Create a new _sourcesContents map if the property is null.
  8671. if (!this._sourcesContents) {
  8672. this._sourcesContents = Object.create(null);
  8673. }
  8674. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8675. } else if (this._sourcesContents) {
  8676. // Remove the source file from the _sourcesContents map.
  8677. // If the _sourcesContents map is empty, set the property to null.
  8678. delete this._sourcesContents[util.toSetString(source)];
  8679. if (Object.keys(this._sourcesContents).length === 0) {
  8680. this._sourcesContents = null;
  8681. }
  8682. }
  8683. };
  8684. /**
  8685. * Applies the mappings of a sub-source-map for a specific source file to the
  8686. * source map being generated. Each mapping to the supplied source file is
  8687. * rewritten using the supplied source map. Note: The resolution for the
  8688. * resulting mappings is the minimium of this map and the supplied map.
  8689. *
  8690. * @param aSourceMapConsumer The source map to be applied.
  8691. * @param aSourceFile Optional. The filename of the source file.
  8692. * If omitted, SourceMapConsumer's file property will be used.
  8693. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8694. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8695. * This parameter is needed when the two source maps aren't in the same
  8696. * directory, and the source map to be applied contains relative source
  8697. * paths. If so, those relative source paths need to be rewritten
  8698. * relative to the SourceMapGenerator.
  8699. */
  8700. SourceMapGenerator.prototype.applySourceMap =
  8701. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8702. var sourceFile = aSourceFile;
  8703. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8704. if (aSourceFile == null) {
  8705. if (aSourceMapConsumer.file == null) {
  8706. throw new Error(
  8707. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8708. 'or the source map\'s "file" property. Both were omitted.'
  8709. );
  8710. }
  8711. sourceFile = aSourceMapConsumer.file;
  8712. }
  8713. var sourceRoot = this._sourceRoot;
  8714. // Make "sourceFile" relative if an absolute Url is passed.
  8715. if (sourceRoot != null) {
  8716. sourceFile = util.relative(sourceRoot, sourceFile);
  8717. }
  8718. // Applying the SourceMap can add and remove items from the sources and
  8719. // the names array.
  8720. var newSources = new ArraySet();
  8721. var newNames = new ArraySet();
  8722. // Find mappings for the "sourceFile"
  8723. this._mappings.unsortedForEach(function (mapping) {
  8724. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8725. // Check if it can be mapped by the source map, then update the mapping.
  8726. var original = aSourceMapConsumer.originalPositionFor({
  8727. line: mapping.originalLine,
  8728. column: mapping.originalColumn
  8729. });
  8730. if (original.source != null) {
  8731. // Copy mapping
  8732. mapping.source = original.source;
  8733. if (aSourceMapPath != null) {
  8734. mapping.source = util.join(aSourceMapPath, mapping.source);
  8735. }
  8736. if (sourceRoot != null) {
  8737. mapping.source = util.relative(sourceRoot, mapping.source);
  8738. }
  8739. mapping.originalLine = original.line;
  8740. mapping.originalColumn = original.column;
  8741. if (original.name != null) {
  8742. mapping.name = original.name;
  8743. }
  8744. }
  8745. }
  8746. var source = mapping.source;
  8747. if (source != null && !newSources.has(source)) {
  8748. newSources.add(source);
  8749. }
  8750. var name = mapping.name;
  8751. if (name != null && !newNames.has(name)) {
  8752. newNames.add(name);
  8753. }
  8754. }, this);
  8755. this._sources = newSources;
  8756. this._names = newNames;
  8757. // Copy sourcesContents of applied map.
  8758. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8759. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8760. if (content != null) {
  8761. if (aSourceMapPath != null) {
  8762. sourceFile = util.join(aSourceMapPath, sourceFile);
  8763. }
  8764. if (sourceRoot != null) {
  8765. sourceFile = util.relative(sourceRoot, sourceFile);
  8766. }
  8767. this.setSourceContent(sourceFile, content);
  8768. }
  8769. }, this);
  8770. };
  8771. /**
  8772. * A mapping can have one of the three levels of data:
  8773. *
  8774. * 1. Just the generated position.
  8775. * 2. The Generated position, original position, and original source.
  8776. * 3. Generated and original position, original source, as well as a name
  8777. * token.
  8778. *
  8779. * To maintain consistency, we validate that any new mapping being added falls
  8780. * in to one of these categories.
  8781. */
  8782. SourceMapGenerator.prototype._validateMapping =
  8783. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8784. aName) {
  8785. // When aOriginal is truthy but has empty values for .line and .column,
  8786. // it is most likely a programmer error. In this case we throw a very
  8787. // specific error message to try to guide them the right way.
  8788. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8789. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8790. throw new Error(
  8791. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8792. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8793. 'null for the original mapping instead of an object with empty or null values.'
  8794. );
  8795. }
  8796. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8797. && aGenerated.line > 0 && aGenerated.column >= 0
  8798. && !aOriginal && !aSource && !aName) {
  8799. // Case 1.
  8800. return;
  8801. }
  8802. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8803. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8804. && aGenerated.line > 0 && aGenerated.column >= 0
  8805. && aOriginal.line > 0 && aOriginal.column >= 0
  8806. && aSource) {
  8807. // Cases 2 and 3.
  8808. return;
  8809. }
  8810. else {
  8811. throw new Error('Invalid mapping: ' + JSON.stringify({
  8812. generated: aGenerated,
  8813. source: aSource,
  8814. original: aOriginal,
  8815. name: aName
  8816. }));
  8817. }
  8818. };
  8819. /**
  8820. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8821. * specified by the source map format.
  8822. */
  8823. SourceMapGenerator.prototype._serializeMappings =
  8824. function SourceMapGenerator_serializeMappings() {
  8825. var previousGeneratedColumn = 0;
  8826. var previousGeneratedLine = 1;
  8827. var previousOriginalColumn = 0;
  8828. var previousOriginalLine = 0;
  8829. var previousName = 0;
  8830. var previousSource = 0;
  8831. var result = '';
  8832. var next;
  8833. var mapping;
  8834. var nameIdx;
  8835. var sourceIdx;
  8836. var mappings = this._mappings.toArray();
  8837. for (var i = 0, len = mappings.length; i < len; i++) {
  8838. mapping = mappings[i];
  8839. next = '';
  8840. if (mapping.generatedLine !== previousGeneratedLine) {
  8841. previousGeneratedColumn = 0;
  8842. while (mapping.generatedLine !== previousGeneratedLine) {
  8843. next += ';';
  8844. previousGeneratedLine++;
  8845. }
  8846. }
  8847. else {
  8848. if (i > 0) {
  8849. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8850. continue;
  8851. }
  8852. next += ',';
  8853. }
  8854. }
  8855. next += base64VLQ.encode(mapping.generatedColumn
  8856. - previousGeneratedColumn);
  8857. previousGeneratedColumn = mapping.generatedColumn;
  8858. if (mapping.source != null) {
  8859. sourceIdx = this._sources.indexOf(mapping.source);
  8860. next += base64VLQ.encode(sourceIdx - previousSource);
  8861. previousSource = sourceIdx;
  8862. // lines are stored 0-based in SourceMap spec version 3
  8863. next += base64VLQ.encode(mapping.originalLine - 1
  8864. - previousOriginalLine);
  8865. previousOriginalLine = mapping.originalLine - 1;
  8866. next += base64VLQ.encode(mapping.originalColumn
  8867. - previousOriginalColumn);
  8868. previousOriginalColumn = mapping.originalColumn;
  8869. if (mapping.name != null) {
  8870. nameIdx = this._names.indexOf(mapping.name);
  8871. next += base64VLQ.encode(nameIdx - previousName);
  8872. previousName = nameIdx;
  8873. }
  8874. }
  8875. result += next;
  8876. }
  8877. return result;
  8878. };
  8879. SourceMapGenerator.prototype._generateSourcesContent =
  8880. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8881. return aSources.map(function (source) {
  8882. if (!this._sourcesContents) {
  8883. return null;
  8884. }
  8885. if (aSourceRoot != null) {
  8886. source = util.relative(aSourceRoot, source);
  8887. }
  8888. var key = util.toSetString(source);
  8889. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8890. ? this._sourcesContents[key]
  8891. : null;
  8892. }, this);
  8893. };
  8894. /**
  8895. * Externalize the source map.
  8896. */
  8897. SourceMapGenerator.prototype.toJSON =
  8898. function SourceMapGenerator_toJSON() {
  8899. var map = {
  8900. version: this._version,
  8901. sources: this._sources.toArray(),
  8902. names: this._names.toArray(),
  8903. mappings: this._serializeMappings()
  8904. };
  8905. if (this._file != null) {
  8906. map.file = this._file;
  8907. }
  8908. if (this._sourceRoot != null) {
  8909. map.sourceRoot = this._sourceRoot;
  8910. }
  8911. if (this._sourcesContents) {
  8912. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8913. }
  8914. return map;
  8915. };
  8916. /**
  8917. * Render the source map being generated to a string.
  8918. */
  8919. SourceMapGenerator.prototype.toString =
  8920. function SourceMapGenerator_toString() {
  8921. return JSON.stringify(this.toJSON());
  8922. };
  8923. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  8924. return sourceMapGenerator;
  8925. }
  8926. var sourceMapConsumer = {};
  8927. var binarySearch = {};
  8928. /* -*- Mode: js; js-indent-level: 2; -*- */
  8929. var hasRequiredBinarySearch;
  8930. function requireBinarySearch () {
  8931. if (hasRequiredBinarySearch) return binarySearch;
  8932. hasRequiredBinarySearch = 1;
  8933. (function (exports$1) {
  8934. /*
  8935. * Copyright 2011 Mozilla Foundation and contributors
  8936. * Licensed under the New BSD license. See LICENSE or:
  8937. * http://opensource.org/licenses/BSD-3-Clause
  8938. */
  8939. exports$1.GREATEST_LOWER_BOUND = 1;
  8940. exports$1.LEAST_UPPER_BOUND = 2;
  8941. /**
  8942. * Recursive implementation of binary search.
  8943. *
  8944. * @param aLow Indices here and lower do not contain the needle.
  8945. * @param aHigh Indices here and higher do not contain the needle.
  8946. * @param aNeedle The element being searched for.
  8947. * @param aHaystack The non-empty array being searched.
  8948. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8949. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8950. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8951. * closest element that is smaller than or greater than the one we are
  8952. * searching for, respectively, if the exact element cannot be found.
  8953. */
  8954. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8955. // This function terminates when one of the following is true:
  8956. //
  8957. // 1. We find the exact element we are looking for.
  8958. //
  8959. // 2. We did not find the exact element, but we can return the index of
  8960. // the next-closest element.
  8961. //
  8962. // 3. We did not find the exact element, and there is no next-closest
  8963. // element than the one we are searching for, so we return -1.
  8964. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  8965. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  8966. if (cmp === 0) {
  8967. // Found the element we are looking for.
  8968. return mid;
  8969. }
  8970. else if (cmp > 0) {
  8971. // Our needle is greater than aHaystack[mid].
  8972. if (aHigh - mid > 1) {
  8973. // The element is in the upper half.
  8974. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  8975. }
  8976. // The exact needle element was not found in this haystack. Determine if
  8977. // we are in termination case (3) or (2) and return the appropriate thing.
  8978. if (aBias == exports$1.LEAST_UPPER_BOUND) {
  8979. return aHigh < aHaystack.length ? aHigh : -1;
  8980. } else {
  8981. return mid;
  8982. }
  8983. }
  8984. else {
  8985. // Our needle is less than aHaystack[mid].
  8986. if (mid - aLow > 1) {
  8987. // The element is in the lower half.
  8988. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  8989. }
  8990. // we are in termination case (3) or (2) and return the appropriate thing.
  8991. if (aBias == exports$1.LEAST_UPPER_BOUND) {
  8992. return mid;
  8993. } else {
  8994. return aLow < 0 ? -1 : aLow;
  8995. }
  8996. }
  8997. }
  8998. /**
  8999. * This is an implementation of binary search which will always try and return
  9000. * the index of the closest element if there is no exact hit. This is because
  9001. * mappings between original and generated line/col pairs are single points,
  9002. * and there is an implicit region between each of them, so a miss just means
  9003. * that you aren't on the very start of a region.
  9004. *
  9005. * @param aNeedle The element you are looking for.
  9006. * @param aHaystack The array that is being searched.
  9007. * @param aCompare A function which takes the needle and an element in the
  9008. * array and returns -1, 0, or 1 depending on whether the needle is less
  9009. * than, equal to, or greater than the element, respectively.
  9010. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9011. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9012. * closest element that is smaller than or greater than the one we are
  9013. * searching for, respectively, if the exact element cannot be found.
  9014. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  9015. */
  9016. exports$1.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  9017. if (aHaystack.length === 0) {
  9018. return -1;
  9019. }
  9020. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  9021. aCompare, aBias || exports$1.GREATEST_LOWER_BOUND);
  9022. if (index < 0) {
  9023. return -1;
  9024. }
  9025. // We have found either the exact element, or the next-closest element than
  9026. // the one we are searching for. However, there may be more than one such
  9027. // element. Make sure we always return the smallest of these.
  9028. while (index - 1 >= 0) {
  9029. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  9030. break;
  9031. }
  9032. --index;
  9033. }
  9034. return index;
  9035. };
  9036. } (binarySearch));
  9037. return binarySearch;
  9038. }
  9039. var quickSort = {};
  9040. /* -*- Mode: js; js-indent-level: 2; -*- */
  9041. var hasRequiredQuickSort;
  9042. function requireQuickSort () {
  9043. if (hasRequiredQuickSort) return quickSort;
  9044. hasRequiredQuickSort = 1;
  9045. /*
  9046. * Copyright 2011 Mozilla Foundation and contributors
  9047. * Licensed under the New BSD license. See LICENSE or:
  9048. * http://opensource.org/licenses/BSD-3-Clause
  9049. */
  9050. // It turns out that some (most?) JavaScript engines don't self-host
  9051. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9052. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9053. // custom comparator function, calling back and forth between the VM's C++ and
  9054. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9055. // worse generated code for the comparator function than would be optimal. In
  9056. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9057. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9058. // a ~3500ms mean speed-up in `bench/bench.html`.
  9059. /**
  9060. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9061. *
  9062. * @param {Array} ary
  9063. * The array.
  9064. * @param {Number} x
  9065. * The index of the first item.
  9066. * @param {Number} y
  9067. * The index of the second item.
  9068. */
  9069. function swap(ary, x, y) {
  9070. var temp = ary[x];
  9071. ary[x] = ary[y];
  9072. ary[y] = temp;
  9073. }
  9074. /**
  9075. * Returns a random integer within the range `low .. high` inclusive.
  9076. *
  9077. * @param {Number} low
  9078. * The lower bound on the range.
  9079. * @param {Number} high
  9080. * The upper bound on the range.
  9081. */
  9082. function randomIntInRange(low, high) {
  9083. return Math.round(low + (Math.random() * (high - low)));
  9084. }
  9085. /**
  9086. * The Quick Sort algorithm.
  9087. *
  9088. * @param {Array} ary
  9089. * An array to sort.
  9090. * @param {function} comparator
  9091. * Function to use to compare two items.
  9092. * @param {Number} p
  9093. * Start index of the array
  9094. * @param {Number} r
  9095. * End index of the array
  9096. */
  9097. function doQuickSort(ary, comparator, p, r) {
  9098. // If our lower bound is less than our upper bound, we (1) partition the
  9099. // array into two pieces and (2) recurse on each half. If it is not, this is
  9100. // the empty array and our base case.
  9101. if (p < r) {
  9102. // (1) Partitioning.
  9103. //
  9104. // The partitioning chooses a pivot between `p` and `r` and moves all
  9105. // elements that are less than or equal to the pivot to the before it, and
  9106. // all the elements that are greater than it after it. The effect is that
  9107. // once partition is done, the pivot is in the exact place it will be when
  9108. // the array is put in sorted order, and it will not need to be moved
  9109. // again. This runs in O(n) time.
  9110. // Always choose a random pivot so that an input array which is reverse
  9111. // sorted does not cause O(n^2) running time.
  9112. var pivotIndex = randomIntInRange(p, r);
  9113. var i = p - 1;
  9114. swap(ary, pivotIndex, r);
  9115. var pivot = ary[r];
  9116. // Immediately after `j` is incremented in this loop, the following hold
  9117. // true:
  9118. //
  9119. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9120. //
  9121. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9122. for (var j = p; j < r; j++) {
  9123. if (comparator(ary[j], pivot) <= 0) {
  9124. i += 1;
  9125. swap(ary, i, j);
  9126. }
  9127. }
  9128. swap(ary, i + 1, j);
  9129. var q = i + 1;
  9130. // (2) Recurse on each half.
  9131. doQuickSort(ary, comparator, p, q - 1);
  9132. doQuickSort(ary, comparator, q + 1, r);
  9133. }
  9134. }
  9135. /**
  9136. * Sort the given array in-place with the given comparator function.
  9137. *
  9138. * @param {Array} ary
  9139. * An array to sort.
  9140. * @param {function} comparator
  9141. * Function to use to compare two items.
  9142. */
  9143. quickSort.quickSort = function (ary, comparator) {
  9144. doQuickSort(ary, comparator, 0, ary.length - 1);
  9145. };
  9146. return quickSort;
  9147. }
  9148. /* -*- Mode: js; js-indent-level: 2; -*- */
  9149. var hasRequiredSourceMapConsumer;
  9150. function requireSourceMapConsumer () {
  9151. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9152. hasRequiredSourceMapConsumer = 1;
  9153. /*
  9154. * Copyright 2011 Mozilla Foundation and contributors
  9155. * Licensed under the New BSD license. See LICENSE or:
  9156. * http://opensource.org/licenses/BSD-3-Clause
  9157. */
  9158. var util = /*@__PURE__*/ requireUtil$1();
  9159. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9160. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9161. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9162. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9163. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9164. var sourceMap = aSourceMap;
  9165. if (typeof aSourceMap === 'string') {
  9166. sourceMap = util.parseSourceMapInput(aSourceMap);
  9167. }
  9168. return sourceMap.sections != null
  9169. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9170. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9171. }
  9172. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9173. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9174. };
  9175. /**
  9176. * The version of the source mapping spec that we are consuming.
  9177. */
  9178. SourceMapConsumer.prototype._version = 3;
  9179. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9180. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9181. // are lazily instantiated, accessed via the `_generatedMappings` and
  9182. // `_originalMappings` getters respectively, and we only parse the mappings
  9183. // and create these arrays once queried for a source location. We jump through
  9184. // these hoops because there can be many thousands of mappings, and parsing
  9185. // them is expensive, so we only want to do it if we must.
  9186. //
  9187. // Each object in the arrays is of the form:
  9188. //
  9189. // {
  9190. // generatedLine: The line number in the generated code,
  9191. // generatedColumn: The column number in the generated code,
  9192. // source: The path to the original source file that generated this
  9193. // chunk of code,
  9194. // originalLine: The line number in the original source that
  9195. // corresponds to this chunk of generated code,
  9196. // originalColumn: The column number in the original source that
  9197. // corresponds to this chunk of generated code,
  9198. // name: The name of the original symbol which generated this chunk of
  9199. // code.
  9200. // }
  9201. //
  9202. // All properties except for `generatedLine` and `generatedColumn` can be
  9203. // `null`.
  9204. //
  9205. // `_generatedMappings` is ordered by the generated positions.
  9206. //
  9207. // `_originalMappings` is ordered by the original positions.
  9208. SourceMapConsumer.prototype.__generatedMappings = null;
  9209. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9210. configurable: true,
  9211. enumerable: true,
  9212. get: function () {
  9213. if (!this.__generatedMappings) {
  9214. this._parseMappings(this._mappings, this.sourceRoot);
  9215. }
  9216. return this.__generatedMappings;
  9217. }
  9218. });
  9219. SourceMapConsumer.prototype.__originalMappings = null;
  9220. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9221. configurable: true,
  9222. enumerable: true,
  9223. get: function () {
  9224. if (!this.__originalMappings) {
  9225. this._parseMappings(this._mappings, this.sourceRoot);
  9226. }
  9227. return this.__originalMappings;
  9228. }
  9229. });
  9230. SourceMapConsumer.prototype._charIsMappingSeparator =
  9231. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9232. var c = aStr.charAt(index);
  9233. return c === ";" || c === ",";
  9234. };
  9235. /**
  9236. * Parse the mappings in a string in to a data structure which we can easily
  9237. * query (the ordered arrays in the `this.__generatedMappings` and
  9238. * `this.__originalMappings` properties).
  9239. */
  9240. SourceMapConsumer.prototype._parseMappings =
  9241. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9242. throw new Error("Subclasses must implement _parseMappings");
  9243. };
  9244. SourceMapConsumer.GENERATED_ORDER = 1;
  9245. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9246. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9247. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9248. /**
  9249. * Iterate over each mapping between an original source/line/column and a
  9250. * generated line/column in this source map.
  9251. *
  9252. * @param Function aCallback
  9253. * The function that is called with each mapping.
  9254. * @param Object aContext
  9255. * Optional. If specified, this object will be the value of `this` every
  9256. * time that `aCallback` is called.
  9257. * @param aOrder
  9258. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9259. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9260. * iterate over the mappings sorted by the generated file's line/column
  9261. * order or the original's source/line/column order, respectively. Defaults to
  9262. * `SourceMapConsumer.GENERATED_ORDER`.
  9263. */
  9264. SourceMapConsumer.prototype.eachMapping =
  9265. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9266. var context = aContext || null;
  9267. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9268. var mappings;
  9269. switch (order) {
  9270. case SourceMapConsumer.GENERATED_ORDER:
  9271. mappings = this._generatedMappings;
  9272. break;
  9273. case SourceMapConsumer.ORIGINAL_ORDER:
  9274. mappings = this._originalMappings;
  9275. break;
  9276. default:
  9277. throw new Error("Unknown order of iteration.");
  9278. }
  9279. var sourceRoot = this.sourceRoot;
  9280. mappings.map(function (mapping) {
  9281. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9282. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9283. return {
  9284. source: source,
  9285. generatedLine: mapping.generatedLine,
  9286. generatedColumn: mapping.generatedColumn,
  9287. originalLine: mapping.originalLine,
  9288. originalColumn: mapping.originalColumn,
  9289. name: mapping.name === null ? null : this._names.at(mapping.name)
  9290. };
  9291. }, this).forEach(aCallback, context);
  9292. };
  9293. /**
  9294. * Returns all generated line and column information for the original source,
  9295. * line, and column provided. If no column is provided, returns all mappings
  9296. * corresponding to a either the line we are searching for or the next
  9297. * closest line that has any mappings. Otherwise, returns all mappings
  9298. * corresponding to the given line and either the column we are searching for
  9299. * or the next closest column that has any offsets.
  9300. *
  9301. * The only argument is an object with the following properties:
  9302. *
  9303. * - source: The filename of the original source.
  9304. * - line: The line number in the original source. The line number is 1-based.
  9305. * - column: Optional. the column number in the original source.
  9306. * The column number is 0-based.
  9307. *
  9308. * and an array of objects is returned, each with the following properties:
  9309. *
  9310. * - line: The line number in the generated source, or null. The
  9311. * line number is 1-based.
  9312. * - column: The column number in the generated source, or null.
  9313. * The column number is 0-based.
  9314. */
  9315. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9316. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9317. var line = util.getArg(aArgs, 'line');
  9318. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9319. // returns the index of the closest mapping less than the needle. By
  9320. // setting needle.originalColumn to 0, we thus find the last mapping for
  9321. // the given line, provided such a mapping exists.
  9322. var needle = {
  9323. source: util.getArg(aArgs, 'source'),
  9324. originalLine: line,
  9325. originalColumn: util.getArg(aArgs, 'column', 0)
  9326. };
  9327. needle.source = this._findSourceIndex(needle.source);
  9328. if (needle.source < 0) {
  9329. return [];
  9330. }
  9331. var mappings = [];
  9332. var index = this._findMapping(needle,
  9333. this._originalMappings,
  9334. "originalLine",
  9335. "originalColumn",
  9336. util.compareByOriginalPositions,
  9337. binarySearch.LEAST_UPPER_BOUND);
  9338. if (index >= 0) {
  9339. var mapping = this._originalMappings[index];
  9340. if (aArgs.column === undefined) {
  9341. var originalLine = mapping.originalLine;
  9342. // Iterate until either we run out of mappings, or we run into
  9343. // a mapping for a different line than the one we found. Since
  9344. // mappings are sorted, this is guaranteed to find all mappings for
  9345. // the line we found.
  9346. while (mapping && mapping.originalLine === originalLine) {
  9347. mappings.push({
  9348. line: util.getArg(mapping, 'generatedLine', null),
  9349. column: util.getArg(mapping, 'generatedColumn', null),
  9350. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9351. });
  9352. mapping = this._originalMappings[++index];
  9353. }
  9354. } else {
  9355. var originalColumn = mapping.originalColumn;
  9356. // Iterate until either we run out of mappings, or we run into
  9357. // a mapping for a different line than the one we were searching for.
  9358. // Since mappings are sorted, this is guaranteed to find all mappings for
  9359. // the line we are searching for.
  9360. while (mapping &&
  9361. mapping.originalLine === line &&
  9362. mapping.originalColumn == originalColumn) {
  9363. mappings.push({
  9364. line: util.getArg(mapping, 'generatedLine', null),
  9365. column: util.getArg(mapping, 'generatedColumn', null),
  9366. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9367. });
  9368. mapping = this._originalMappings[++index];
  9369. }
  9370. }
  9371. }
  9372. return mappings;
  9373. };
  9374. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9375. /**
  9376. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9377. * query for information about the original file positions by giving it a file
  9378. * position in the generated source.
  9379. *
  9380. * The first parameter is the raw source map (either as a JSON string, or
  9381. * already parsed to an object). According to the spec, source maps have the
  9382. * following attributes:
  9383. *
  9384. * - version: Which version of the source map spec this map is following.
  9385. * - sources: An array of URLs to the original source files.
  9386. * - names: An array of identifiers which can be referrenced by individual mappings.
  9387. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9388. * - sourcesContent: Optional. An array of contents of the original source files.
  9389. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9390. * - file: Optional. The generated file this source map is associated with.
  9391. *
  9392. * Here is an example source map, taken from the source map spec[0]:
  9393. *
  9394. * {
  9395. * version : 3,
  9396. * file: "out.js",
  9397. * sourceRoot : "",
  9398. * sources: ["foo.js", "bar.js"],
  9399. * names: ["src", "maps", "are", "fun"],
  9400. * mappings: "AA,AB;;ABCDE;"
  9401. * }
  9402. *
  9403. * The second parameter, if given, is a string whose value is the URL
  9404. * at which the source map was found. This URL is used to compute the
  9405. * sources array.
  9406. *
  9407. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9408. */
  9409. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9410. var sourceMap = aSourceMap;
  9411. if (typeof aSourceMap === 'string') {
  9412. sourceMap = util.parseSourceMapInput(aSourceMap);
  9413. }
  9414. var version = util.getArg(sourceMap, 'version');
  9415. var sources = util.getArg(sourceMap, 'sources');
  9416. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9417. // requires the array) to play nice here.
  9418. var names = util.getArg(sourceMap, 'names', []);
  9419. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9420. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9421. var mappings = util.getArg(sourceMap, 'mappings');
  9422. var file = util.getArg(sourceMap, 'file', null);
  9423. // Once again, Sass deviates from the spec and supplies the version as a
  9424. // string rather than a number, so we use loose equality checking here.
  9425. if (version != this._version) {
  9426. throw new Error('Unsupported version: ' + version);
  9427. }
  9428. if (sourceRoot) {
  9429. sourceRoot = util.normalize(sourceRoot);
  9430. }
  9431. sources = sources
  9432. .map(String)
  9433. // Some source maps produce relative source paths like "./foo.js" instead of
  9434. // "foo.js". Normalize these first so that future comparisons will succeed.
  9435. // See bugzil.la/1090768.
  9436. .map(util.normalize)
  9437. // Always ensure that absolute sources are internally stored relative to
  9438. // the source root, if the source root is absolute. Not doing this would
  9439. // be particularly problematic when the source root is a prefix of the
  9440. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9441. .map(function (source) {
  9442. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9443. ? util.relative(sourceRoot, source)
  9444. : source;
  9445. });
  9446. // Pass `true` below to allow duplicate names and sources. While source maps
  9447. // are intended to be compressed and deduplicated, the TypeScript compiler
  9448. // sometimes generates source maps with duplicates in them. See Github issue
  9449. // #72 and bugzil.la/889492.
  9450. this._names = ArraySet.fromArray(names.map(String), true);
  9451. this._sources = ArraySet.fromArray(sources, true);
  9452. this._absoluteSources = this._sources.toArray().map(function (s) {
  9453. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9454. });
  9455. this.sourceRoot = sourceRoot;
  9456. this.sourcesContent = sourcesContent;
  9457. this._mappings = mappings;
  9458. this._sourceMapURL = aSourceMapURL;
  9459. this.file = file;
  9460. }
  9461. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9462. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9463. /**
  9464. * Utility function to find the index of a source. Returns -1 if not
  9465. * found.
  9466. */
  9467. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9468. var relativeSource = aSource;
  9469. if (this.sourceRoot != null) {
  9470. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9471. }
  9472. if (this._sources.has(relativeSource)) {
  9473. return this._sources.indexOf(relativeSource);
  9474. }
  9475. // Maybe aSource is an absolute URL as returned by |sources|. In
  9476. // this case we can't simply undo the transform.
  9477. var i;
  9478. for (i = 0; i < this._absoluteSources.length; ++i) {
  9479. if (this._absoluteSources[i] == aSource) {
  9480. return i;
  9481. }
  9482. }
  9483. return -1;
  9484. };
  9485. /**
  9486. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9487. *
  9488. * @param SourceMapGenerator aSourceMap
  9489. * The source map that will be consumed.
  9490. * @param String aSourceMapURL
  9491. * The URL at which the source map can be found (optional)
  9492. * @returns BasicSourceMapConsumer
  9493. */
  9494. BasicSourceMapConsumer.fromSourceMap =
  9495. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9496. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9497. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9498. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9499. smc.sourceRoot = aSourceMap._sourceRoot;
  9500. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9501. smc.sourceRoot);
  9502. smc.file = aSourceMap._file;
  9503. smc._sourceMapURL = aSourceMapURL;
  9504. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9505. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9506. });
  9507. // Because we are modifying the entries (by converting string sources and
  9508. // names to indices into the sources and names ArraySets), we have to make
  9509. // a copy of the entry or else bad things happen. Shared mutable state
  9510. // strikes again! See github issue #191.
  9511. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9512. var destGeneratedMappings = smc.__generatedMappings = [];
  9513. var destOriginalMappings = smc.__originalMappings = [];
  9514. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9515. var srcMapping = generatedMappings[i];
  9516. var destMapping = new Mapping;
  9517. destMapping.generatedLine = srcMapping.generatedLine;
  9518. destMapping.generatedColumn = srcMapping.generatedColumn;
  9519. if (srcMapping.source) {
  9520. destMapping.source = sources.indexOf(srcMapping.source);
  9521. destMapping.originalLine = srcMapping.originalLine;
  9522. destMapping.originalColumn = srcMapping.originalColumn;
  9523. if (srcMapping.name) {
  9524. destMapping.name = names.indexOf(srcMapping.name);
  9525. }
  9526. destOriginalMappings.push(destMapping);
  9527. }
  9528. destGeneratedMappings.push(destMapping);
  9529. }
  9530. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9531. return smc;
  9532. };
  9533. /**
  9534. * The version of the source mapping spec that we are consuming.
  9535. */
  9536. BasicSourceMapConsumer.prototype._version = 3;
  9537. /**
  9538. * The list of original sources.
  9539. */
  9540. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9541. get: function () {
  9542. return this._absoluteSources.slice();
  9543. }
  9544. });
  9545. /**
  9546. * Provide the JIT with a nice shape / hidden class.
  9547. */
  9548. function Mapping() {
  9549. this.generatedLine = 0;
  9550. this.generatedColumn = 0;
  9551. this.source = null;
  9552. this.originalLine = null;
  9553. this.originalColumn = null;
  9554. this.name = null;
  9555. }
  9556. /**
  9557. * Parse the mappings in a string in to a data structure which we can easily
  9558. * query (the ordered arrays in the `this.__generatedMappings` and
  9559. * `this.__originalMappings` properties).
  9560. */
  9561. BasicSourceMapConsumer.prototype._parseMappings =
  9562. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9563. var generatedLine = 1;
  9564. var previousGeneratedColumn = 0;
  9565. var previousOriginalLine = 0;
  9566. var previousOriginalColumn = 0;
  9567. var previousSource = 0;
  9568. var previousName = 0;
  9569. var length = aStr.length;
  9570. var index = 0;
  9571. var cachedSegments = {};
  9572. var temp = {};
  9573. var originalMappings = [];
  9574. var generatedMappings = [];
  9575. var mapping, str, segment, end, value;
  9576. while (index < length) {
  9577. if (aStr.charAt(index) === ';') {
  9578. generatedLine++;
  9579. index++;
  9580. previousGeneratedColumn = 0;
  9581. }
  9582. else if (aStr.charAt(index) === ',') {
  9583. index++;
  9584. }
  9585. else {
  9586. mapping = new Mapping();
  9587. mapping.generatedLine = generatedLine;
  9588. // Because each offset is encoded relative to the previous one,
  9589. // many segments often have the same encoding. We can exploit this
  9590. // fact by caching the parsed variable length fields of each segment,
  9591. // allowing us to avoid a second parse if we encounter the same
  9592. // segment again.
  9593. for (end = index; end < length; end++) {
  9594. if (this._charIsMappingSeparator(aStr, end)) {
  9595. break;
  9596. }
  9597. }
  9598. str = aStr.slice(index, end);
  9599. segment = cachedSegments[str];
  9600. if (segment) {
  9601. index += str.length;
  9602. } else {
  9603. segment = [];
  9604. while (index < end) {
  9605. base64VLQ.decode(aStr, index, temp);
  9606. value = temp.value;
  9607. index = temp.rest;
  9608. segment.push(value);
  9609. }
  9610. if (segment.length === 2) {
  9611. throw new Error('Found a source, but no line and column');
  9612. }
  9613. if (segment.length === 3) {
  9614. throw new Error('Found a source and line, but no column');
  9615. }
  9616. cachedSegments[str] = segment;
  9617. }
  9618. // Generated column.
  9619. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9620. previousGeneratedColumn = mapping.generatedColumn;
  9621. if (segment.length > 1) {
  9622. // Original source.
  9623. mapping.source = previousSource + segment[1];
  9624. previousSource += segment[1];
  9625. // Original line.
  9626. mapping.originalLine = previousOriginalLine + segment[2];
  9627. previousOriginalLine = mapping.originalLine;
  9628. // Lines are stored 0-based
  9629. mapping.originalLine += 1;
  9630. // Original column.
  9631. mapping.originalColumn = previousOriginalColumn + segment[3];
  9632. previousOriginalColumn = mapping.originalColumn;
  9633. if (segment.length > 4) {
  9634. // Original name.
  9635. mapping.name = previousName + segment[4];
  9636. previousName += segment[4];
  9637. }
  9638. }
  9639. generatedMappings.push(mapping);
  9640. if (typeof mapping.originalLine === 'number') {
  9641. originalMappings.push(mapping);
  9642. }
  9643. }
  9644. }
  9645. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9646. this.__generatedMappings = generatedMappings;
  9647. quickSort(originalMappings, util.compareByOriginalPositions);
  9648. this.__originalMappings = originalMappings;
  9649. };
  9650. /**
  9651. * Find the mapping that best matches the hypothetical "needle" mapping that
  9652. * we are searching for in the given "haystack" of mappings.
  9653. */
  9654. BasicSourceMapConsumer.prototype._findMapping =
  9655. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9656. aColumnName, aComparator, aBias) {
  9657. // To return the position we are searching for, we must first find the
  9658. // mapping for the given position and then return the opposite position it
  9659. // points to. Because the mappings are sorted, we can use binary search to
  9660. // find the best mapping.
  9661. if (aNeedle[aLineName] <= 0) {
  9662. throw new TypeError('Line must be greater than or equal to 1, got '
  9663. + aNeedle[aLineName]);
  9664. }
  9665. if (aNeedle[aColumnName] < 0) {
  9666. throw new TypeError('Column must be greater than or equal to 0, got '
  9667. + aNeedle[aColumnName]);
  9668. }
  9669. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9670. };
  9671. /**
  9672. * Compute the last column for each generated mapping. The last column is
  9673. * inclusive.
  9674. */
  9675. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9676. function SourceMapConsumer_computeColumnSpans() {
  9677. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9678. var mapping = this._generatedMappings[index];
  9679. // Mappings do not contain a field for the last generated columnt. We
  9680. // can come up with an optimistic estimate, however, by assuming that
  9681. // mappings are contiguous (i.e. given two consecutive mappings, the
  9682. // first mapping ends where the second one starts).
  9683. if (index + 1 < this._generatedMappings.length) {
  9684. var nextMapping = this._generatedMappings[index + 1];
  9685. if (mapping.generatedLine === nextMapping.generatedLine) {
  9686. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9687. continue;
  9688. }
  9689. }
  9690. // The last mapping for each line spans the entire line.
  9691. mapping.lastGeneratedColumn = Infinity;
  9692. }
  9693. };
  9694. /**
  9695. * Returns the original source, line, and column information for the generated
  9696. * source's line and column positions provided. The only argument is an object
  9697. * with the following properties:
  9698. *
  9699. * - line: The line number in the generated source. The line number
  9700. * is 1-based.
  9701. * - column: The column number in the generated source. The column
  9702. * number is 0-based.
  9703. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9704. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9705. * closest element that is smaller than or greater than the one we are
  9706. * searching for, respectively, if the exact element cannot be found.
  9707. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9708. *
  9709. * and an object is returned with the following properties:
  9710. *
  9711. * - source: The original source file, or null.
  9712. * - line: The line number in the original source, or null. The
  9713. * line number is 1-based.
  9714. * - column: The column number in the original source, or null. The
  9715. * column number is 0-based.
  9716. * - name: The original identifier, or null.
  9717. */
  9718. BasicSourceMapConsumer.prototype.originalPositionFor =
  9719. function SourceMapConsumer_originalPositionFor(aArgs) {
  9720. var needle = {
  9721. generatedLine: util.getArg(aArgs, 'line'),
  9722. generatedColumn: util.getArg(aArgs, 'column')
  9723. };
  9724. var index = this._findMapping(
  9725. needle,
  9726. this._generatedMappings,
  9727. "generatedLine",
  9728. "generatedColumn",
  9729. util.compareByGeneratedPositionsDeflated,
  9730. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9731. );
  9732. if (index >= 0) {
  9733. var mapping = this._generatedMappings[index];
  9734. if (mapping.generatedLine === needle.generatedLine) {
  9735. var source = util.getArg(mapping, 'source', null);
  9736. if (source !== null) {
  9737. source = this._sources.at(source);
  9738. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9739. }
  9740. var name = util.getArg(mapping, 'name', null);
  9741. if (name !== null) {
  9742. name = this._names.at(name);
  9743. }
  9744. return {
  9745. source: source,
  9746. line: util.getArg(mapping, 'originalLine', null),
  9747. column: util.getArg(mapping, 'originalColumn', null),
  9748. name: name
  9749. };
  9750. }
  9751. }
  9752. return {
  9753. source: null,
  9754. line: null,
  9755. column: null,
  9756. name: null
  9757. };
  9758. };
  9759. /**
  9760. * Return true if we have the source content for every source in the source
  9761. * map, false otherwise.
  9762. */
  9763. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9764. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9765. if (!this.sourcesContent) {
  9766. return false;
  9767. }
  9768. return this.sourcesContent.length >= this._sources.size() &&
  9769. !this.sourcesContent.some(function (sc) { return sc == null; });
  9770. };
  9771. /**
  9772. * Returns the original source content. The only argument is the url of the
  9773. * original source file. Returns null if no original source content is
  9774. * available.
  9775. */
  9776. BasicSourceMapConsumer.prototype.sourceContentFor =
  9777. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9778. if (!this.sourcesContent) {
  9779. return null;
  9780. }
  9781. var index = this._findSourceIndex(aSource);
  9782. if (index >= 0) {
  9783. return this.sourcesContent[index];
  9784. }
  9785. var relativeSource = aSource;
  9786. if (this.sourceRoot != null) {
  9787. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9788. }
  9789. var url;
  9790. if (this.sourceRoot != null
  9791. && (url = util.urlParse(this.sourceRoot))) {
  9792. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9793. // many users. We can help them out when they expect file:// URIs to
  9794. // behave like it would if they were running a local HTTP server. See
  9795. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9796. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9797. if (url.scheme == "file"
  9798. && this._sources.has(fileUriAbsPath)) {
  9799. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9800. }
  9801. if ((!url.path || url.path == "/")
  9802. && this._sources.has("/" + relativeSource)) {
  9803. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9804. }
  9805. }
  9806. // This function is used recursively from
  9807. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9808. // don't want to throw if we can't find the source - we just want to
  9809. // return null, so we provide a flag to exit gracefully.
  9810. if (nullOnMissing) {
  9811. return null;
  9812. }
  9813. else {
  9814. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9815. }
  9816. };
  9817. /**
  9818. * Returns the generated line and column information for the original source,
  9819. * line, and column positions provided. The only argument is an object with
  9820. * the following properties:
  9821. *
  9822. * - source: The filename of the original source.
  9823. * - line: The line number in the original source. The line number
  9824. * is 1-based.
  9825. * - column: The column number in the original source. The column
  9826. * number is 0-based.
  9827. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9828. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9829. * closest element that is smaller than or greater than the one we are
  9830. * searching for, respectively, if the exact element cannot be found.
  9831. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9832. *
  9833. * and an object is returned with the following properties:
  9834. *
  9835. * - line: The line number in the generated source, or null. The
  9836. * line number is 1-based.
  9837. * - column: The column number in the generated source, or null.
  9838. * The column number is 0-based.
  9839. */
  9840. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9841. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9842. var source = util.getArg(aArgs, 'source');
  9843. source = this._findSourceIndex(source);
  9844. if (source < 0) {
  9845. return {
  9846. line: null,
  9847. column: null,
  9848. lastColumn: null
  9849. };
  9850. }
  9851. var needle = {
  9852. source: source,
  9853. originalLine: util.getArg(aArgs, 'line'),
  9854. originalColumn: util.getArg(aArgs, 'column')
  9855. };
  9856. var index = this._findMapping(
  9857. needle,
  9858. this._originalMappings,
  9859. "originalLine",
  9860. "originalColumn",
  9861. util.compareByOriginalPositions,
  9862. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9863. );
  9864. if (index >= 0) {
  9865. var mapping = this._originalMappings[index];
  9866. if (mapping.source === needle.source) {
  9867. return {
  9868. line: util.getArg(mapping, 'generatedLine', null),
  9869. column: util.getArg(mapping, 'generatedColumn', null),
  9870. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9871. };
  9872. }
  9873. }
  9874. return {
  9875. line: null,
  9876. column: null,
  9877. lastColumn: null
  9878. };
  9879. };
  9880. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9881. /**
  9882. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9883. * we can query for information. It differs from BasicSourceMapConsumer in
  9884. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9885. * input.
  9886. *
  9887. * The first parameter is a raw source map (either as a JSON string, or already
  9888. * parsed to an object). According to the spec for indexed source maps, they
  9889. * have the following attributes:
  9890. *
  9891. * - version: Which version of the source map spec this map is following.
  9892. * - file: Optional. The generated file this source map is associated with.
  9893. * - sections: A list of section definitions.
  9894. *
  9895. * Each value under the "sections" field has two fields:
  9896. * - offset: The offset into the original specified at which this section
  9897. * begins to apply, defined as an object with a "line" and "column"
  9898. * field.
  9899. * - map: A source map definition. This source map could also be indexed,
  9900. * but doesn't have to be.
  9901. *
  9902. * Instead of the "map" field, it's also possible to have a "url" field
  9903. * specifying a URL to retrieve a source map from, but that's currently
  9904. * unsupported.
  9905. *
  9906. * Here's an example source map, taken from the source map spec[0], but
  9907. * modified to omit a section which uses the "url" field.
  9908. *
  9909. * {
  9910. * version : 3,
  9911. * file: "app.js",
  9912. * sections: [{
  9913. * offset: {line:100, column:10},
  9914. * map: {
  9915. * version : 3,
  9916. * file: "section.js",
  9917. * sources: ["foo.js", "bar.js"],
  9918. * names: ["src", "maps", "are", "fun"],
  9919. * mappings: "AAAA,E;;ABCDE;"
  9920. * }
  9921. * }],
  9922. * }
  9923. *
  9924. * The second parameter, if given, is a string whose value is the URL
  9925. * at which the source map was found. This URL is used to compute the
  9926. * sources array.
  9927. *
  9928. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9929. */
  9930. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9931. var sourceMap = aSourceMap;
  9932. if (typeof aSourceMap === 'string') {
  9933. sourceMap = util.parseSourceMapInput(aSourceMap);
  9934. }
  9935. var version = util.getArg(sourceMap, 'version');
  9936. var sections = util.getArg(sourceMap, 'sections');
  9937. if (version != this._version) {
  9938. throw new Error('Unsupported version: ' + version);
  9939. }
  9940. this._sources = new ArraySet();
  9941. this._names = new ArraySet();
  9942. var lastOffset = {
  9943. line: -1,
  9944. column: 0
  9945. };
  9946. this._sections = sections.map(function (s) {
  9947. if (s.url) {
  9948. // The url field will require support for asynchronicity.
  9949. // See https://github.com/mozilla/source-map/issues/16
  9950. throw new Error('Support for url field in sections not implemented.');
  9951. }
  9952. var offset = util.getArg(s, 'offset');
  9953. var offsetLine = util.getArg(offset, 'line');
  9954. var offsetColumn = util.getArg(offset, 'column');
  9955. if (offsetLine < lastOffset.line ||
  9956. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9957. throw new Error('Section offsets must be ordered and non-overlapping.');
  9958. }
  9959. lastOffset = offset;
  9960. return {
  9961. generatedOffset: {
  9962. // The offset fields are 0-based, but we use 1-based indices when
  9963. // encoding/decoding from VLQ.
  9964. generatedLine: offsetLine + 1,
  9965. generatedColumn: offsetColumn + 1
  9966. },
  9967. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  9968. }
  9969. });
  9970. }
  9971. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9972. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  9973. /**
  9974. * The version of the source mapping spec that we are consuming.
  9975. */
  9976. IndexedSourceMapConsumer.prototype._version = 3;
  9977. /**
  9978. * The list of original sources.
  9979. */
  9980. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  9981. get: function () {
  9982. var sources = [];
  9983. for (var i = 0; i < this._sections.length; i++) {
  9984. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  9985. sources.push(this._sections[i].consumer.sources[j]);
  9986. }
  9987. }
  9988. return sources;
  9989. }
  9990. });
  9991. /**
  9992. * Returns the original source, line, and column information for the generated
  9993. * source's line and column positions provided. The only argument is an object
  9994. * with the following properties:
  9995. *
  9996. * - line: The line number in the generated source. The line number
  9997. * is 1-based.
  9998. * - column: The column number in the generated source. The column
  9999. * number is 0-based.
  10000. *
  10001. * and an object is returned with the following properties:
  10002. *
  10003. * - source: The original source file, or null.
  10004. * - line: The line number in the original source, or null. The
  10005. * line number is 1-based.
  10006. * - column: The column number in the original source, or null. The
  10007. * column number is 0-based.
  10008. * - name: The original identifier, or null.
  10009. */
  10010. IndexedSourceMapConsumer.prototype.originalPositionFor =
  10011. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  10012. var needle = {
  10013. generatedLine: util.getArg(aArgs, 'line'),
  10014. generatedColumn: util.getArg(aArgs, 'column')
  10015. };
  10016. // Find the section containing the generated position we're trying to map
  10017. // to an original position.
  10018. var sectionIndex = binarySearch.search(needle, this._sections,
  10019. function(needle, section) {
  10020. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  10021. if (cmp) {
  10022. return cmp;
  10023. }
  10024. return (needle.generatedColumn -
  10025. section.generatedOffset.generatedColumn);
  10026. });
  10027. var section = this._sections[sectionIndex];
  10028. if (!section) {
  10029. return {
  10030. source: null,
  10031. line: null,
  10032. column: null,
  10033. name: null
  10034. };
  10035. }
  10036. return section.consumer.originalPositionFor({
  10037. line: needle.generatedLine -
  10038. (section.generatedOffset.generatedLine - 1),
  10039. column: needle.generatedColumn -
  10040. (section.generatedOffset.generatedLine === needle.generatedLine
  10041. ? section.generatedOffset.generatedColumn - 1
  10042. : 0),
  10043. bias: aArgs.bias
  10044. });
  10045. };
  10046. /**
  10047. * Return true if we have the source content for every source in the source
  10048. * map, false otherwise.
  10049. */
  10050. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10051. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10052. return this._sections.every(function (s) {
  10053. return s.consumer.hasContentsOfAllSources();
  10054. });
  10055. };
  10056. /**
  10057. * Returns the original source content. The only argument is the url of the
  10058. * original source file. Returns null if no original source content is
  10059. * available.
  10060. */
  10061. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10062. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10063. for (var i = 0; i < this._sections.length; i++) {
  10064. var section = this._sections[i];
  10065. var content = section.consumer.sourceContentFor(aSource, true);
  10066. if (content) {
  10067. return content;
  10068. }
  10069. }
  10070. if (nullOnMissing) {
  10071. return null;
  10072. }
  10073. else {
  10074. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10075. }
  10076. };
  10077. /**
  10078. * Returns the generated line and column information for the original source,
  10079. * line, and column positions provided. The only argument is an object with
  10080. * the following properties:
  10081. *
  10082. * - source: The filename of the original source.
  10083. * - line: The line number in the original source. The line number
  10084. * is 1-based.
  10085. * - column: The column number in the original source. The column
  10086. * number is 0-based.
  10087. *
  10088. * and an object is returned with the following properties:
  10089. *
  10090. * - line: The line number in the generated source, or null. The
  10091. * line number is 1-based.
  10092. * - column: The column number in the generated source, or null.
  10093. * The column number is 0-based.
  10094. */
  10095. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10096. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10097. for (var i = 0; i < this._sections.length; i++) {
  10098. var section = this._sections[i];
  10099. // Only consider this section if the requested source is in the list of
  10100. // sources of the consumer.
  10101. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10102. continue;
  10103. }
  10104. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10105. if (generatedPosition) {
  10106. var ret = {
  10107. line: generatedPosition.line +
  10108. (section.generatedOffset.generatedLine - 1),
  10109. column: generatedPosition.column +
  10110. (section.generatedOffset.generatedLine === generatedPosition.line
  10111. ? section.generatedOffset.generatedColumn - 1
  10112. : 0)
  10113. };
  10114. return ret;
  10115. }
  10116. }
  10117. return {
  10118. line: null,
  10119. column: null
  10120. };
  10121. };
  10122. /**
  10123. * Parse the mappings in a string in to a data structure which we can easily
  10124. * query (the ordered arrays in the `this.__generatedMappings` and
  10125. * `this.__originalMappings` properties).
  10126. */
  10127. IndexedSourceMapConsumer.prototype._parseMappings =
  10128. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10129. this.__generatedMappings = [];
  10130. this.__originalMappings = [];
  10131. for (var i = 0; i < this._sections.length; i++) {
  10132. var section = this._sections[i];
  10133. var sectionMappings = section.consumer._generatedMappings;
  10134. for (var j = 0; j < sectionMappings.length; j++) {
  10135. var mapping = sectionMappings[j];
  10136. var source = section.consumer._sources.at(mapping.source);
  10137. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10138. this._sources.add(source);
  10139. source = this._sources.indexOf(source);
  10140. var name = null;
  10141. if (mapping.name) {
  10142. name = section.consumer._names.at(mapping.name);
  10143. this._names.add(name);
  10144. name = this._names.indexOf(name);
  10145. }
  10146. // The mappings coming from the consumer for the section have
  10147. // generated positions relative to the start of the section, so we
  10148. // need to offset them to be relative to the start of the concatenated
  10149. // generated file.
  10150. var adjustedMapping = {
  10151. source: source,
  10152. generatedLine: mapping.generatedLine +
  10153. (section.generatedOffset.generatedLine - 1),
  10154. generatedColumn: mapping.generatedColumn +
  10155. (section.generatedOffset.generatedLine === mapping.generatedLine
  10156. ? section.generatedOffset.generatedColumn - 1
  10157. : 0),
  10158. originalLine: mapping.originalLine,
  10159. originalColumn: mapping.originalColumn,
  10160. name: name
  10161. };
  10162. this.__generatedMappings.push(adjustedMapping);
  10163. if (typeof adjustedMapping.originalLine === 'number') {
  10164. this.__originalMappings.push(adjustedMapping);
  10165. }
  10166. }
  10167. }
  10168. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10169. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10170. };
  10171. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10172. return sourceMapConsumer;
  10173. }
  10174. var sourceNode = {};
  10175. /* -*- Mode: js; js-indent-level: 2; -*- */
  10176. var hasRequiredSourceNode;
  10177. function requireSourceNode () {
  10178. if (hasRequiredSourceNode) return sourceNode;
  10179. hasRequiredSourceNode = 1;
  10180. /*
  10181. * Copyright 2011 Mozilla Foundation and contributors
  10182. * Licensed under the New BSD license. See LICENSE or:
  10183. * http://opensource.org/licenses/BSD-3-Clause
  10184. */
  10185. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10186. var util = /*@__PURE__*/ requireUtil$1();
  10187. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10188. // operating systems these days (capturing the result).
  10189. var REGEX_NEWLINE = /(\r?\n)/;
  10190. // Newline character code for charCodeAt() comparisons
  10191. var NEWLINE_CODE = 10;
  10192. // Private symbol for identifying `SourceNode`s when multiple versions of
  10193. // the source-map library are loaded. This MUST NOT CHANGE across
  10194. // versions!
  10195. var isSourceNode = "$$$isSourceNode$$$";
  10196. /**
  10197. * SourceNodes provide a way to abstract over interpolating/concatenating
  10198. * snippets of generated JavaScript source code while maintaining the line and
  10199. * column information associated with the original source code.
  10200. *
  10201. * @param aLine The original line number.
  10202. * @param aColumn The original column number.
  10203. * @param aSource The original source's filename.
  10204. * @param aChunks Optional. An array of strings which are snippets of
  10205. * generated JS, or other SourceNodes.
  10206. * @param aName The original identifier.
  10207. */
  10208. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10209. this.children = [];
  10210. this.sourceContents = {};
  10211. this.line = aLine == null ? null : aLine;
  10212. this.column = aColumn == null ? null : aColumn;
  10213. this.source = aSource == null ? null : aSource;
  10214. this.name = aName == null ? null : aName;
  10215. this[isSourceNode] = true;
  10216. if (aChunks != null) this.add(aChunks);
  10217. }
  10218. /**
  10219. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10220. *
  10221. * @param aGeneratedCode The generated code
  10222. * @param aSourceMapConsumer The SourceMap for the generated code
  10223. * @param aRelativePath Optional. The path that relative sources in the
  10224. * SourceMapConsumer should be relative to.
  10225. */
  10226. SourceNode.fromStringWithSourceMap =
  10227. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10228. // The SourceNode we want to fill with the generated code
  10229. // and the SourceMap
  10230. var node = new SourceNode();
  10231. // All even indices of this array are one line of the generated code,
  10232. // while all odd indices are the newlines between two adjacent lines
  10233. // (since `REGEX_NEWLINE` captures its match).
  10234. // Processed fragments are accessed by calling `shiftNextLine`.
  10235. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10236. var remainingLinesIndex = 0;
  10237. var shiftNextLine = function() {
  10238. var lineContents = getNextLine();
  10239. // The last line of a file might not have a newline.
  10240. var newLine = getNextLine() || "";
  10241. return lineContents + newLine;
  10242. function getNextLine() {
  10243. return remainingLinesIndex < remainingLines.length ?
  10244. remainingLines[remainingLinesIndex++] : undefined;
  10245. }
  10246. };
  10247. // We need to remember the position of "remainingLines"
  10248. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10249. // The generate SourceNodes we need a code range.
  10250. // To extract it current and last mapping is used.
  10251. // Here we store the last mapping.
  10252. var lastMapping = null;
  10253. aSourceMapConsumer.eachMapping(function (mapping) {
  10254. if (lastMapping !== null) {
  10255. // We add the code from "lastMapping" to "mapping":
  10256. // First check if there is a new line in between.
  10257. if (lastGeneratedLine < mapping.generatedLine) {
  10258. // Associate first line with "lastMapping"
  10259. addMappingWithCode(lastMapping, shiftNextLine());
  10260. lastGeneratedLine++;
  10261. lastGeneratedColumn = 0;
  10262. // The remaining code is added without mapping
  10263. } else {
  10264. // There is no new line in between.
  10265. // Associate the code between "lastGeneratedColumn" and
  10266. // "mapping.generatedColumn" with "lastMapping"
  10267. var nextLine = remainingLines[remainingLinesIndex] || '';
  10268. var code = nextLine.substr(0, mapping.generatedColumn -
  10269. lastGeneratedColumn);
  10270. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10271. lastGeneratedColumn);
  10272. lastGeneratedColumn = mapping.generatedColumn;
  10273. addMappingWithCode(lastMapping, code);
  10274. // No more remaining code, continue
  10275. lastMapping = mapping;
  10276. return;
  10277. }
  10278. }
  10279. // We add the generated code until the first mapping
  10280. // to the SourceNode without any mapping.
  10281. // Each line is added as separate string.
  10282. while (lastGeneratedLine < mapping.generatedLine) {
  10283. node.add(shiftNextLine());
  10284. lastGeneratedLine++;
  10285. }
  10286. if (lastGeneratedColumn < mapping.generatedColumn) {
  10287. var nextLine = remainingLines[remainingLinesIndex] || '';
  10288. node.add(nextLine.substr(0, mapping.generatedColumn));
  10289. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10290. lastGeneratedColumn = mapping.generatedColumn;
  10291. }
  10292. lastMapping = mapping;
  10293. }, this);
  10294. // We have processed all mappings.
  10295. if (remainingLinesIndex < remainingLines.length) {
  10296. if (lastMapping) {
  10297. // Associate the remaining code in the current line with "lastMapping"
  10298. addMappingWithCode(lastMapping, shiftNextLine());
  10299. }
  10300. // and add the remaining lines without any mapping
  10301. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10302. }
  10303. // Copy sourcesContent into SourceNode
  10304. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10305. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10306. if (content != null) {
  10307. if (aRelativePath != null) {
  10308. sourceFile = util.join(aRelativePath, sourceFile);
  10309. }
  10310. node.setSourceContent(sourceFile, content);
  10311. }
  10312. });
  10313. return node;
  10314. function addMappingWithCode(mapping, code) {
  10315. if (mapping === null || mapping.source === undefined) {
  10316. node.add(code);
  10317. } else {
  10318. var source = aRelativePath
  10319. ? util.join(aRelativePath, mapping.source)
  10320. : mapping.source;
  10321. node.add(new SourceNode(mapping.originalLine,
  10322. mapping.originalColumn,
  10323. source,
  10324. code,
  10325. mapping.name));
  10326. }
  10327. }
  10328. };
  10329. /**
  10330. * Add a chunk of generated JS to this source node.
  10331. *
  10332. * @param aChunk A string snippet of generated JS code, another instance of
  10333. * SourceNode, or an array where each member is one of those things.
  10334. */
  10335. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10336. if (Array.isArray(aChunk)) {
  10337. aChunk.forEach(function (chunk) {
  10338. this.add(chunk);
  10339. }, this);
  10340. }
  10341. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10342. if (aChunk) {
  10343. this.children.push(aChunk);
  10344. }
  10345. }
  10346. else {
  10347. throw new TypeError(
  10348. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10349. );
  10350. }
  10351. return this;
  10352. };
  10353. /**
  10354. * Add a chunk of generated JS to the beginning of this source node.
  10355. *
  10356. * @param aChunk A string snippet of generated JS code, another instance of
  10357. * SourceNode, or an array where each member is one of those things.
  10358. */
  10359. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10360. if (Array.isArray(aChunk)) {
  10361. for (var i = aChunk.length-1; i >= 0; i--) {
  10362. this.prepend(aChunk[i]);
  10363. }
  10364. }
  10365. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10366. this.children.unshift(aChunk);
  10367. }
  10368. else {
  10369. throw new TypeError(
  10370. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10371. );
  10372. }
  10373. return this;
  10374. };
  10375. /**
  10376. * Walk over the tree of JS snippets in this node and its children. The
  10377. * walking function is called once for each snippet of JS and is passed that
  10378. * snippet and the its original associated source's line/column location.
  10379. *
  10380. * @param aFn The traversal function.
  10381. */
  10382. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10383. var chunk;
  10384. for (var i = 0, len = this.children.length; i < len; i++) {
  10385. chunk = this.children[i];
  10386. if (chunk[isSourceNode]) {
  10387. chunk.walk(aFn);
  10388. }
  10389. else {
  10390. if (chunk !== '') {
  10391. aFn(chunk, { source: this.source,
  10392. line: this.line,
  10393. column: this.column,
  10394. name: this.name });
  10395. }
  10396. }
  10397. }
  10398. };
  10399. /**
  10400. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10401. * each of `this.children`.
  10402. *
  10403. * @param aSep The separator.
  10404. */
  10405. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10406. var newChildren;
  10407. var i;
  10408. var len = this.children.length;
  10409. if (len > 0) {
  10410. newChildren = [];
  10411. for (i = 0; i < len-1; i++) {
  10412. newChildren.push(this.children[i]);
  10413. newChildren.push(aSep);
  10414. }
  10415. newChildren.push(this.children[i]);
  10416. this.children = newChildren;
  10417. }
  10418. return this;
  10419. };
  10420. /**
  10421. * Call String.prototype.replace on the very right-most source snippet. Useful
  10422. * for trimming whitespace from the end of a source node, etc.
  10423. *
  10424. * @param aPattern The pattern to replace.
  10425. * @param aReplacement The thing to replace the pattern with.
  10426. */
  10427. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10428. var lastChild = this.children[this.children.length - 1];
  10429. if (lastChild[isSourceNode]) {
  10430. lastChild.replaceRight(aPattern, aReplacement);
  10431. }
  10432. else if (typeof lastChild === 'string') {
  10433. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10434. }
  10435. else {
  10436. this.children.push(''.replace(aPattern, aReplacement));
  10437. }
  10438. return this;
  10439. };
  10440. /**
  10441. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10442. * in the sourcesContent field.
  10443. *
  10444. * @param aSourceFile The filename of the source file
  10445. * @param aSourceContent The content of the source file
  10446. */
  10447. SourceNode.prototype.setSourceContent =
  10448. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10449. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10450. };
  10451. /**
  10452. * Walk over the tree of SourceNodes. The walking function is called for each
  10453. * source file content and is passed the filename and source content.
  10454. *
  10455. * @param aFn The traversal function.
  10456. */
  10457. SourceNode.prototype.walkSourceContents =
  10458. function SourceNode_walkSourceContents(aFn) {
  10459. for (var i = 0, len = this.children.length; i < len; i++) {
  10460. if (this.children[i][isSourceNode]) {
  10461. this.children[i].walkSourceContents(aFn);
  10462. }
  10463. }
  10464. var sources = Object.keys(this.sourceContents);
  10465. for (var i = 0, len = sources.length; i < len; i++) {
  10466. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10467. }
  10468. };
  10469. /**
  10470. * Return the string representation of this source node. Walks over the tree
  10471. * and concatenates all the various snippets together to one string.
  10472. */
  10473. SourceNode.prototype.toString = function SourceNode_toString() {
  10474. var str = "";
  10475. this.walk(function (chunk) {
  10476. str += chunk;
  10477. });
  10478. return str;
  10479. };
  10480. /**
  10481. * Returns the string representation of this source node along with a source
  10482. * map.
  10483. */
  10484. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10485. var generated = {
  10486. code: "",
  10487. line: 1,
  10488. column: 0
  10489. };
  10490. var map = new SourceMapGenerator(aArgs);
  10491. var sourceMappingActive = false;
  10492. var lastOriginalSource = null;
  10493. var lastOriginalLine = null;
  10494. var lastOriginalColumn = null;
  10495. var lastOriginalName = null;
  10496. this.walk(function (chunk, original) {
  10497. generated.code += chunk;
  10498. if (original.source !== null
  10499. && original.line !== null
  10500. && original.column !== null) {
  10501. if(lastOriginalSource !== original.source
  10502. || lastOriginalLine !== original.line
  10503. || lastOriginalColumn !== original.column
  10504. || lastOriginalName !== original.name) {
  10505. map.addMapping({
  10506. source: original.source,
  10507. original: {
  10508. line: original.line,
  10509. column: original.column
  10510. },
  10511. generated: {
  10512. line: generated.line,
  10513. column: generated.column
  10514. },
  10515. name: original.name
  10516. });
  10517. }
  10518. lastOriginalSource = original.source;
  10519. lastOriginalLine = original.line;
  10520. lastOriginalColumn = original.column;
  10521. lastOriginalName = original.name;
  10522. sourceMappingActive = true;
  10523. } else if (sourceMappingActive) {
  10524. map.addMapping({
  10525. generated: {
  10526. line: generated.line,
  10527. column: generated.column
  10528. }
  10529. });
  10530. lastOriginalSource = null;
  10531. sourceMappingActive = false;
  10532. }
  10533. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10534. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10535. generated.line++;
  10536. generated.column = 0;
  10537. // Mappings end at eol
  10538. if (idx + 1 === length) {
  10539. lastOriginalSource = null;
  10540. sourceMappingActive = false;
  10541. } else if (sourceMappingActive) {
  10542. map.addMapping({
  10543. source: original.source,
  10544. original: {
  10545. line: original.line,
  10546. column: original.column
  10547. },
  10548. generated: {
  10549. line: generated.line,
  10550. column: generated.column
  10551. },
  10552. name: original.name
  10553. });
  10554. }
  10555. } else {
  10556. generated.column++;
  10557. }
  10558. }
  10559. });
  10560. this.walkSourceContents(function (sourceFile, sourceContent) {
  10561. map.setSourceContent(sourceFile, sourceContent);
  10562. });
  10563. return { code: generated.code, map: map };
  10564. };
  10565. sourceNode.SourceNode = SourceNode;
  10566. return sourceNode;
  10567. }
  10568. /*
  10569. * Copyright 2009-2011 Mozilla Foundation and contributors
  10570. * Licensed under the New BSD license. See LICENSE.txt or:
  10571. * http://opensource.org/licenses/BSD-3-Clause
  10572. */
  10573. var hasRequiredSourceMap;
  10574. function requireSourceMap () {
  10575. if (hasRequiredSourceMap) return sourceMap;
  10576. hasRequiredSourceMap = 1;
  10577. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10578. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10579. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10580. return sourceMap;
  10581. }
  10582. var mergeSourceMap;
  10583. var hasRequiredMergeSourceMap;
  10584. function requireMergeSourceMap () {
  10585. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10586. hasRequiredMergeSourceMap = 1;
  10587. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10588. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10589. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10590. mergeSourceMap = merge;
  10591. /**
  10592. * Merge old source map and new source map and return merged.
  10593. * If old or new source map value is falsy, return another one as it is.
  10594. *
  10595. * @param {object|string} [oldMap] old source map object
  10596. * @param {object|string} [newmap] new source map object
  10597. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10598. */
  10599. function merge(oldMap, newMap) {
  10600. if (!oldMap) return newMap
  10601. if (!newMap) return oldMap
  10602. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10603. var newMapConsumer = new SourceMapConsumer(newMap);
  10604. var mergedMapGenerator = new SourceMapGenerator();
  10605. // iterate on new map and overwrite original position of new map with one of old map
  10606. newMapConsumer.eachMapping(function(m) {
  10607. // pass when `originalLine` is null.
  10608. // It occurs in case that the node does not have origin in original code.
  10609. if (m.originalLine == null) return
  10610. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10611. line: m.originalLine,
  10612. column: m.originalColumn
  10613. });
  10614. if (origPosInOldMap.source == null) return
  10615. mergedMapGenerator.addMapping({
  10616. original: {
  10617. line: origPosInOldMap.line,
  10618. column: origPosInOldMap.column
  10619. },
  10620. generated: {
  10621. line: m.generatedLine,
  10622. column: m.generatedColumn
  10623. },
  10624. source: origPosInOldMap.source,
  10625. name: origPosInOldMap.name
  10626. });
  10627. });
  10628. var consumers = [oldMapConsumer, newMapConsumer];
  10629. consumers.forEach(function(consumer) {
  10630. consumer.sources.forEach(function(sourceFile) {
  10631. mergedMapGenerator._sources.add(sourceFile);
  10632. var sourceContent = consumer.sourceContentFor(sourceFile);
  10633. if (sourceContent != null) {
  10634. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10635. }
  10636. });
  10637. });
  10638. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10639. mergedMapGenerator._file = oldMap.file;
  10640. return JSON.parse(mergedMapGenerator.toString())
  10641. }
  10642. return mergeSourceMap;
  10643. }
  10644. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10645. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10646. const scss = (source, map, options, load = require) => {
  10647. const nodeSass = load("sass");
  10648. const { compileString, renderSync } = nodeSass;
  10649. const data = getSource(source, options.filename, options.additionalData);
  10650. let css;
  10651. let dependencies;
  10652. let sourceMap;
  10653. try {
  10654. if (compileString) {
  10655. const { pathToFileURL, fileURLToPath } = load("url");
  10656. const result = compileString(data, {
  10657. ...options,
  10658. url: pathToFileURL(options.filename),
  10659. sourceMap: !!map
  10660. });
  10661. css = result.css;
  10662. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10663. sourceMap = map ? result.sourceMap : void 0;
  10664. } else {
  10665. const result = renderSync({
  10666. ...options,
  10667. data,
  10668. file: options.filename,
  10669. outFile: options.filename,
  10670. sourceMap: !!map
  10671. });
  10672. css = result.css.toString();
  10673. dependencies = result.stats.includedFiles;
  10674. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10675. }
  10676. if (map) {
  10677. return {
  10678. code: css,
  10679. errors: [],
  10680. dependencies,
  10681. map: merge(map, sourceMap)
  10682. };
  10683. }
  10684. return { code: css, errors: [], dependencies };
  10685. } catch (e) {
  10686. return { code: "", errors: [e], dependencies: [] };
  10687. }
  10688. };
  10689. const sass = (source, map, options, load) => scss(
  10690. source,
  10691. map,
  10692. {
  10693. ...options,
  10694. indentedSyntax: true
  10695. },
  10696. load
  10697. );
  10698. const less = (source, map, options, load = require) => {
  10699. const nodeLess = load("less");
  10700. let result;
  10701. let error = null;
  10702. nodeLess.render(
  10703. getSource(source, options.filename, options.additionalData),
  10704. { ...options, syncImport: true },
  10705. (err, output) => {
  10706. error = err;
  10707. result = output;
  10708. }
  10709. );
  10710. if (error) return { code: "", errors: [error], dependencies: [] };
  10711. const dependencies = result.imports;
  10712. if (map) {
  10713. return {
  10714. code: result.css.toString(),
  10715. map: merge(map, result.map),
  10716. errors: [],
  10717. dependencies
  10718. };
  10719. }
  10720. return {
  10721. code: result.css.toString(),
  10722. errors: [],
  10723. dependencies
  10724. };
  10725. };
  10726. const styl = (source, map, options, load = require) => {
  10727. const nodeStylus = load("stylus");
  10728. try {
  10729. const ref = nodeStylus(source, options);
  10730. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10731. const result = ref.render();
  10732. const dependencies = ref.deps();
  10733. if (map) {
  10734. return {
  10735. code: result,
  10736. map: merge(map, ref.sourcemap),
  10737. errors: [],
  10738. dependencies
  10739. };
  10740. }
  10741. return { code: result, errors: [], dependencies };
  10742. } catch (e) {
  10743. return { code: "", errors: [e], dependencies: [] };
  10744. }
  10745. };
  10746. function getSource(source, filename, additionalData) {
  10747. if (!additionalData) return source;
  10748. if (shared.isFunction(additionalData)) {
  10749. return additionalData(source, filename);
  10750. }
  10751. return additionalData + source;
  10752. }
  10753. const processors = {
  10754. less,
  10755. sass,
  10756. scss,
  10757. styl,
  10758. stylus: styl
  10759. };
  10760. var build = {exports: {}};
  10761. var fs = {};
  10762. var hasRequiredFs;
  10763. function requireFs () {
  10764. if (hasRequiredFs) return fs;
  10765. hasRequiredFs = 1;
  10766. Object.defineProperty(fs, "__esModule", {
  10767. value: true
  10768. });
  10769. fs.getFileSystem = getFileSystem;
  10770. fs.setFileSystem = setFileSystem;
  10771. let fileSystem = {
  10772. readFile: () => {
  10773. throw Error("readFile not implemented");
  10774. },
  10775. writeFile: () => {
  10776. throw Error("writeFile not implemented");
  10777. }
  10778. };
  10779. function setFileSystem(fs) {
  10780. fileSystem.readFile = fs.readFile;
  10781. fileSystem.writeFile = fs.writeFile;
  10782. }
  10783. function getFileSystem() {
  10784. return fileSystem;
  10785. }
  10786. return fs;
  10787. }
  10788. var pluginFactory = {};
  10789. var unquote = {};
  10790. var hasRequiredUnquote;
  10791. function requireUnquote () {
  10792. if (hasRequiredUnquote) return unquote;
  10793. hasRequiredUnquote = 1;
  10794. Object.defineProperty(unquote, "__esModule", {
  10795. value: true
  10796. });
  10797. unquote.default = unquote$1;
  10798. // copied from https://github.com/lakenen/node-unquote
  10799. const reg = /['"]/;
  10800. function unquote$1(str) {
  10801. if (!str) {
  10802. return "";
  10803. }
  10804. if (reg.test(str.charAt(0))) {
  10805. str = str.substr(1);
  10806. }
  10807. if (reg.test(str.charAt(str.length - 1))) {
  10808. str = str.substr(0, str.length - 1);
  10809. }
  10810. return str;
  10811. }
  10812. return unquote;
  10813. }
  10814. var Parser = {};
  10815. var replaceValueSymbols_1;
  10816. var hasRequiredReplaceValueSymbols;
  10817. function requireReplaceValueSymbols () {
  10818. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10819. hasRequiredReplaceValueSymbols = 1;
  10820. const matchValueName = /[$]?[\w-]+/g;
  10821. const replaceValueSymbols = (value, replacements) => {
  10822. let matches;
  10823. while ((matches = matchValueName.exec(value))) {
  10824. const replacement = replacements[matches[0]];
  10825. if (replacement) {
  10826. value =
  10827. value.slice(0, matches.index) +
  10828. replacement +
  10829. value.slice(matchValueName.lastIndex);
  10830. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10831. }
  10832. }
  10833. return value;
  10834. };
  10835. replaceValueSymbols_1 = replaceValueSymbols;
  10836. return replaceValueSymbols_1;
  10837. }
  10838. var replaceSymbols_1;
  10839. var hasRequiredReplaceSymbols;
  10840. function requireReplaceSymbols () {
  10841. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10842. hasRequiredReplaceSymbols = 1;
  10843. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10844. const replaceSymbols = (css, replacements) => {
  10845. css.walk((node) => {
  10846. if (node.type === "decl" && node.value) {
  10847. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10848. } else if (node.type === "rule" && node.selector) {
  10849. node.selector = replaceValueSymbols(
  10850. node.selector.toString(),
  10851. replacements
  10852. );
  10853. } else if (node.type === "atrule" && node.params) {
  10854. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10855. }
  10856. });
  10857. };
  10858. replaceSymbols_1 = replaceSymbols;
  10859. return replaceSymbols_1;
  10860. }
  10861. var extractICSS_1;
  10862. var hasRequiredExtractICSS;
  10863. function requireExtractICSS () {
  10864. if (hasRequiredExtractICSS) return extractICSS_1;
  10865. hasRequiredExtractICSS = 1;
  10866. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10867. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10868. const getDeclsObject = (rule) => {
  10869. const object = {};
  10870. rule.walkDecls((decl) => {
  10871. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10872. object[before + decl.prop] = decl.value;
  10873. });
  10874. return object;
  10875. };
  10876. /**
  10877. *
  10878. * @param {string} css
  10879. * @param {boolean} removeRules
  10880. * @param {'auto' | 'rule' | 'at-rule'} mode
  10881. */
  10882. const extractICSS = (css, removeRules = true, mode = "auto") => {
  10883. const icssImports = {};
  10884. const icssExports = {};
  10885. function addImports(node, path) {
  10886. const unquoted = path.replace(/'|"/g, "");
  10887. icssImports[unquoted] = Object.assign(
  10888. icssImports[unquoted] || {},
  10889. getDeclsObject(node)
  10890. );
  10891. if (removeRules) {
  10892. node.remove();
  10893. }
  10894. }
  10895. function addExports(node) {
  10896. Object.assign(icssExports, getDeclsObject(node));
  10897. if (removeRules) {
  10898. node.remove();
  10899. }
  10900. }
  10901. css.each((node) => {
  10902. if (node.type === "rule" && mode !== "at-rule") {
  10903. if (node.selector.slice(0, 7) === ":import") {
  10904. const matches = importPattern.exec(node.selector);
  10905. if (matches) {
  10906. addImports(node, matches[1]);
  10907. }
  10908. }
  10909. if (node.selector === ":export") {
  10910. addExports(node);
  10911. }
  10912. }
  10913. if (node.type === "atrule" && mode !== "rule") {
  10914. if (node.name === "icss-import") {
  10915. const matches = balancedQuotes.exec(node.params);
  10916. if (matches) {
  10917. addImports(node, matches[1]);
  10918. }
  10919. }
  10920. if (node.name === "icss-export") {
  10921. addExports(node);
  10922. }
  10923. }
  10924. });
  10925. return { icssImports, icssExports };
  10926. };
  10927. extractICSS_1 = extractICSS;
  10928. return extractICSS_1;
  10929. }
  10930. var createICSSRules_1;
  10931. var hasRequiredCreateICSSRules;
  10932. function requireCreateICSSRules () {
  10933. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  10934. hasRequiredCreateICSSRules = 1;
  10935. const createImports = (imports, postcss, mode = "rule") => {
  10936. return Object.keys(imports).map((path) => {
  10937. const aliases = imports[path];
  10938. const declarations = Object.keys(aliases).map((key) =>
  10939. postcss.decl({
  10940. prop: key,
  10941. value: aliases[key],
  10942. raws: { before: "\n " },
  10943. })
  10944. );
  10945. const hasDeclarations = declarations.length > 0;
  10946. const rule =
  10947. mode === "rule"
  10948. ? postcss.rule({
  10949. selector: `:import('${path}')`,
  10950. raws: { after: hasDeclarations ? "\n" : "" },
  10951. })
  10952. : postcss.atRule({
  10953. name: "icss-import",
  10954. params: `'${path}'`,
  10955. raws: { after: hasDeclarations ? "\n" : "" },
  10956. });
  10957. if (hasDeclarations) {
  10958. rule.append(declarations);
  10959. }
  10960. return rule;
  10961. });
  10962. };
  10963. const createExports = (exports$1, postcss, mode = "rule") => {
  10964. const declarations = Object.keys(exports$1).map((key) =>
  10965. postcss.decl({
  10966. prop: key,
  10967. value: exports$1[key],
  10968. raws: { before: "\n " },
  10969. })
  10970. );
  10971. if (declarations.length === 0) {
  10972. return [];
  10973. }
  10974. const rule =
  10975. mode === "rule"
  10976. ? postcss.rule({
  10977. selector: `:export`,
  10978. raws: { after: "\n" },
  10979. })
  10980. : postcss.atRule({
  10981. name: "icss-export",
  10982. raws: { after: "\n" },
  10983. });
  10984. rule.append(declarations);
  10985. return [rule];
  10986. };
  10987. const createICSSRules = (imports, exports$1, postcss, mode) => [
  10988. ...createImports(imports, postcss, mode),
  10989. ...createExports(exports$1, postcss, mode),
  10990. ];
  10991. createICSSRules_1 = createICSSRules;
  10992. return createICSSRules_1;
  10993. }
  10994. var src$4;
  10995. var hasRequiredSrc$4;
  10996. function requireSrc$4 () {
  10997. if (hasRequiredSrc$4) return src$4;
  10998. hasRequiredSrc$4 = 1;
  10999. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  11000. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  11001. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  11002. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  11003. src$4 = {
  11004. replaceValueSymbols,
  11005. replaceSymbols,
  11006. extractICSS,
  11007. createICSSRules,
  11008. };
  11009. return src$4;
  11010. }
  11011. var hasRequiredParser$1;
  11012. function requireParser$1 () {
  11013. if (hasRequiredParser$1) return Parser;
  11014. hasRequiredParser$1 = 1;
  11015. Object.defineProperty(Parser, "__esModule", {
  11016. value: true
  11017. });
  11018. Parser.default = void 0;
  11019. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  11020. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11021. const importRegexp = /^:import\((.+)\)$/;
  11022. let Parser$1 = class Parser {
  11023. constructor(pathFetcher, trace) {
  11024. this.pathFetcher = pathFetcher;
  11025. this.plugin = this.plugin.bind(this);
  11026. this.exportTokens = {};
  11027. this.translations = {};
  11028. this.trace = trace;
  11029. }
  11030. plugin() {
  11031. const parser = this;
  11032. return {
  11033. postcssPlugin: "css-modules-parser",
  11034. async OnceExit(css) {
  11035. await Promise.all(parser.fetchAllImports(css));
  11036. parser.linkImportedSymbols(css);
  11037. return parser.extractExports(css);
  11038. }
  11039. };
  11040. }
  11041. fetchAllImports(css) {
  11042. let imports = [];
  11043. css.each(node => {
  11044. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11045. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11046. }
  11047. });
  11048. return imports;
  11049. }
  11050. linkImportedSymbols(css) {
  11051. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11052. }
  11053. extractExports(css) {
  11054. css.each(node => {
  11055. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11056. });
  11057. }
  11058. handleExport(exportNode) {
  11059. exportNode.each(decl => {
  11060. if (decl.type == "decl") {
  11061. Object.keys(this.translations).forEach(translation => {
  11062. decl.value = decl.value.replace(translation, this.translations[translation]);
  11063. });
  11064. this.exportTokens[decl.prop] = decl.value;
  11065. }
  11066. });
  11067. exportNode.remove();
  11068. }
  11069. async fetchImport(importNode, relativeTo, depNr) {
  11070. const file = importNode.selector.match(importRegexp)[1];
  11071. const depTrace = this.trace + String.fromCharCode(depNr);
  11072. const exports$1 = await this.pathFetcher(file, relativeTo, depTrace);
  11073. try {
  11074. importNode.each(decl => {
  11075. if (decl.type == "decl") {
  11076. this.translations[decl.prop] = exports$1[decl.value];
  11077. }
  11078. });
  11079. importNode.remove();
  11080. } catch (err) {
  11081. console.log(err);
  11082. }
  11083. }
  11084. };
  11085. Parser.default = Parser$1;
  11086. return Parser;
  11087. }
  11088. var saveJSON = {};
  11089. var hasRequiredSaveJSON;
  11090. function requireSaveJSON () {
  11091. if (hasRequiredSaveJSON) return saveJSON;
  11092. hasRequiredSaveJSON = 1;
  11093. Object.defineProperty(saveJSON, "__esModule", {
  11094. value: true
  11095. });
  11096. saveJSON.default = saveJSON$1;
  11097. var _fs = /*@__PURE__*/ requireFs();
  11098. function saveJSON$1(cssFile, json) {
  11099. return new Promise((resolve, reject) => {
  11100. const {
  11101. writeFile
  11102. } = (0, _fs.getFileSystem)();
  11103. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11104. });
  11105. }
  11106. return saveJSON;
  11107. }
  11108. var localsConvention = {};
  11109. /**
  11110. * lodash (Custom Build) <https://lodash.com/>
  11111. * Build: `lodash modularize exports="npm" -o ./`
  11112. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11113. * Released under MIT license <https://lodash.com/license>
  11114. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11115. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11116. */
  11117. var lodash_camelcase;
  11118. var hasRequiredLodash_camelcase;
  11119. function requireLodash_camelcase () {
  11120. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11121. hasRequiredLodash_camelcase = 1;
  11122. /** `Object#toString` result references. */
  11123. var symbolTag = '[object Symbol]';
  11124. /** Used to match words composed of alphanumeric characters. */
  11125. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11126. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11127. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11128. /** Used to compose unicode character classes. */
  11129. var rsAstralRange = '\\ud800-\\udfff',
  11130. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11131. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11132. rsDingbatRange = '\\u2700-\\u27bf',
  11133. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11134. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11135. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11136. rsPunctuationRange = '\\u2000-\\u206f',
  11137. 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',
  11138. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11139. rsVarRange = '\\ufe0e\\ufe0f',
  11140. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11141. /** Used to compose unicode capture groups. */
  11142. var rsApos = "['\u2019]",
  11143. rsAstral = '[' + rsAstralRange + ']',
  11144. rsBreak = '[' + rsBreakRange + ']',
  11145. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11146. rsDigits = '\\d+',
  11147. rsDingbat = '[' + rsDingbatRange + ']',
  11148. rsLower = '[' + rsLowerRange + ']',
  11149. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11150. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11151. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11152. rsNonAstral = '[^' + rsAstralRange + ']',
  11153. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11154. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11155. rsUpper = '[' + rsUpperRange + ']',
  11156. rsZWJ = '\\u200d';
  11157. /** Used to compose unicode regexes. */
  11158. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11159. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11160. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11161. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11162. reOptMod = rsModifier + '?',
  11163. rsOptVar = '[' + rsVarRange + ']?',
  11164. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11165. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11166. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11167. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11168. /** Used to match apostrophes. */
  11169. var reApos = RegExp(rsApos, 'g');
  11170. /**
  11171. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11172. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11173. */
  11174. var reComboMark = RegExp(rsCombo, 'g');
  11175. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11176. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11177. /** Used to match complex or compound words. */
  11178. var reUnicodeWord = RegExp([
  11179. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11180. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11181. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11182. rsUpper + '+' + rsOptUpperContr,
  11183. rsDigits,
  11184. rsEmoji
  11185. ].join('|'), 'g');
  11186. /** 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/). */
  11187. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11188. /** Used to detect strings that need a more robust regexp to match words. */
  11189. 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 ]/;
  11190. /** Used to map Latin Unicode letters to basic Latin letters. */
  11191. var deburredLetters = {
  11192. // Latin-1 Supplement block.
  11193. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11194. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11195. '\xc7': 'C', '\xe7': 'c',
  11196. '\xd0': 'D', '\xf0': 'd',
  11197. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11198. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11199. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11200. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11201. '\xd1': 'N', '\xf1': 'n',
  11202. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11203. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11204. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11205. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11206. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11207. '\xc6': 'Ae', '\xe6': 'ae',
  11208. '\xde': 'Th', '\xfe': 'th',
  11209. '\xdf': 'ss',
  11210. // Latin Extended-A block.
  11211. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11212. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11213. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11214. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11215. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11216. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11217. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11218. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11219. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11220. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11221. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11222. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11223. '\u0134': 'J', '\u0135': 'j',
  11224. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11225. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11226. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11227. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11228. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11229. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11230. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11231. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11232. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11233. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11234. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11235. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11236. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11237. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11238. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11239. '\u0174': 'W', '\u0175': 'w',
  11240. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11241. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11242. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11243. '\u0132': 'IJ', '\u0133': 'ij',
  11244. '\u0152': 'Oe', '\u0153': 'oe',
  11245. '\u0149': "'n", '\u017f': 'ss'
  11246. };
  11247. /** Detect free variable `global` from Node.js. */
  11248. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11249. /** Detect free variable `self`. */
  11250. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11251. /** Used as a reference to the global object. */
  11252. var root = freeGlobal || freeSelf || Function('return this')();
  11253. /**
  11254. * A specialized version of `_.reduce` for arrays without support for
  11255. * iteratee shorthands.
  11256. *
  11257. * @private
  11258. * @param {Array} [array] The array to iterate over.
  11259. * @param {Function} iteratee The function invoked per iteration.
  11260. * @param {*} [accumulator] The initial value.
  11261. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11262. * the initial value.
  11263. * @returns {*} Returns the accumulated value.
  11264. */
  11265. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11266. var index = -1,
  11267. length = array ? array.length : 0;
  11268. while (++index < length) {
  11269. accumulator = iteratee(accumulator, array[index], index, array);
  11270. }
  11271. return accumulator;
  11272. }
  11273. /**
  11274. * Converts an ASCII `string` to an array.
  11275. *
  11276. * @private
  11277. * @param {string} string The string to convert.
  11278. * @returns {Array} Returns the converted array.
  11279. */
  11280. function asciiToArray(string) {
  11281. return string.split('');
  11282. }
  11283. /**
  11284. * Splits an ASCII `string` into an array of its words.
  11285. *
  11286. * @private
  11287. * @param {string} The string to inspect.
  11288. * @returns {Array} Returns the words of `string`.
  11289. */
  11290. function asciiWords(string) {
  11291. return string.match(reAsciiWord) || [];
  11292. }
  11293. /**
  11294. * The base implementation of `_.propertyOf` without support for deep paths.
  11295. *
  11296. * @private
  11297. * @param {Object} object The object to query.
  11298. * @returns {Function} Returns the new accessor function.
  11299. */
  11300. function basePropertyOf(object) {
  11301. return function(key) {
  11302. return object == null ? undefined : object[key];
  11303. };
  11304. }
  11305. /**
  11306. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11307. * letters to basic Latin letters.
  11308. *
  11309. * @private
  11310. * @param {string} letter The matched letter to deburr.
  11311. * @returns {string} Returns the deburred letter.
  11312. */
  11313. var deburrLetter = basePropertyOf(deburredLetters);
  11314. /**
  11315. * Checks if `string` contains Unicode symbols.
  11316. *
  11317. * @private
  11318. * @param {string} string The string to inspect.
  11319. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11320. */
  11321. function hasUnicode(string) {
  11322. return reHasUnicode.test(string);
  11323. }
  11324. /**
  11325. * Checks if `string` contains a word composed of Unicode symbols.
  11326. *
  11327. * @private
  11328. * @param {string} string The string to inspect.
  11329. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11330. */
  11331. function hasUnicodeWord(string) {
  11332. return reHasUnicodeWord.test(string);
  11333. }
  11334. /**
  11335. * Converts `string` to an array.
  11336. *
  11337. * @private
  11338. * @param {string} string The string to convert.
  11339. * @returns {Array} Returns the converted array.
  11340. */
  11341. function stringToArray(string) {
  11342. return hasUnicode(string)
  11343. ? unicodeToArray(string)
  11344. : asciiToArray(string);
  11345. }
  11346. /**
  11347. * Converts a Unicode `string` to an array.
  11348. *
  11349. * @private
  11350. * @param {string} string The string to convert.
  11351. * @returns {Array} Returns the converted array.
  11352. */
  11353. function unicodeToArray(string) {
  11354. return string.match(reUnicode) || [];
  11355. }
  11356. /**
  11357. * Splits a Unicode `string` into an array of its words.
  11358. *
  11359. * @private
  11360. * @param {string} The string to inspect.
  11361. * @returns {Array} Returns the words of `string`.
  11362. */
  11363. function unicodeWords(string) {
  11364. return string.match(reUnicodeWord) || [];
  11365. }
  11366. /** Used for built-in method references. */
  11367. var objectProto = Object.prototype;
  11368. /**
  11369. * Used to resolve the
  11370. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11371. * of values.
  11372. */
  11373. var objectToString = objectProto.toString;
  11374. /** Built-in value references. */
  11375. var Symbol = root.Symbol;
  11376. /** Used to convert symbols to primitives and strings. */
  11377. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11378. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11379. /**
  11380. * The base implementation of `_.slice` without an iteratee call guard.
  11381. *
  11382. * @private
  11383. * @param {Array} array The array to slice.
  11384. * @param {number} [start=0] The start position.
  11385. * @param {number} [end=array.length] The end position.
  11386. * @returns {Array} Returns the slice of `array`.
  11387. */
  11388. function baseSlice(array, start, end) {
  11389. var index = -1,
  11390. length = array.length;
  11391. if (start < 0) {
  11392. start = -start > length ? 0 : (length + start);
  11393. }
  11394. end = end > length ? length : end;
  11395. if (end < 0) {
  11396. end += length;
  11397. }
  11398. length = start > end ? 0 : ((end - start) >>> 0);
  11399. start >>>= 0;
  11400. var result = Array(length);
  11401. while (++index < length) {
  11402. result[index] = array[index + start];
  11403. }
  11404. return result;
  11405. }
  11406. /**
  11407. * The base implementation of `_.toString` which doesn't convert nullish
  11408. * values to empty strings.
  11409. *
  11410. * @private
  11411. * @param {*} value The value to process.
  11412. * @returns {string} Returns the string.
  11413. */
  11414. function baseToString(value) {
  11415. // Exit early for strings to avoid a performance hit in some environments.
  11416. if (typeof value == 'string') {
  11417. return value;
  11418. }
  11419. if (isSymbol(value)) {
  11420. return symbolToString ? symbolToString.call(value) : '';
  11421. }
  11422. var result = (value + '');
  11423. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  11424. }
  11425. /**
  11426. * Casts `array` to a slice if it's needed.
  11427. *
  11428. * @private
  11429. * @param {Array} array The array to inspect.
  11430. * @param {number} start The start position.
  11431. * @param {number} [end=array.length] The end position.
  11432. * @returns {Array} Returns the cast slice.
  11433. */
  11434. function castSlice(array, start, end) {
  11435. var length = array.length;
  11436. end = end === undefined ? length : end;
  11437. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11438. }
  11439. /**
  11440. * Creates a function like `_.lowerFirst`.
  11441. *
  11442. * @private
  11443. * @param {string} methodName The name of the `String` case method to use.
  11444. * @returns {Function} Returns the new case function.
  11445. */
  11446. function createCaseFirst(methodName) {
  11447. return function(string) {
  11448. string = toString(string);
  11449. var strSymbols = hasUnicode(string)
  11450. ? stringToArray(string)
  11451. : undefined;
  11452. var chr = strSymbols
  11453. ? strSymbols[0]
  11454. : string.charAt(0);
  11455. var trailing = strSymbols
  11456. ? castSlice(strSymbols, 1).join('')
  11457. : string.slice(1);
  11458. return chr[methodName]() + trailing;
  11459. };
  11460. }
  11461. /**
  11462. * Creates a function like `_.camelCase`.
  11463. *
  11464. * @private
  11465. * @param {Function} callback The function to combine each word.
  11466. * @returns {Function} Returns the new compounder function.
  11467. */
  11468. function createCompounder(callback) {
  11469. return function(string) {
  11470. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11471. };
  11472. }
  11473. /**
  11474. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11475. * and has a `typeof` result of "object".
  11476. *
  11477. * @static
  11478. * @memberOf _
  11479. * @since 4.0.0
  11480. * @category Lang
  11481. * @param {*} value The value to check.
  11482. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11483. * @example
  11484. *
  11485. * _.isObjectLike({});
  11486. * // => true
  11487. *
  11488. * _.isObjectLike([1, 2, 3]);
  11489. * // => true
  11490. *
  11491. * _.isObjectLike(_.noop);
  11492. * // => false
  11493. *
  11494. * _.isObjectLike(null);
  11495. * // => false
  11496. */
  11497. function isObjectLike(value) {
  11498. return !!value && typeof value == 'object';
  11499. }
  11500. /**
  11501. * Checks if `value` is classified as a `Symbol` primitive or object.
  11502. *
  11503. * @static
  11504. * @memberOf _
  11505. * @since 4.0.0
  11506. * @category Lang
  11507. * @param {*} value The value to check.
  11508. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11509. * @example
  11510. *
  11511. * _.isSymbol(Symbol.iterator);
  11512. * // => true
  11513. *
  11514. * _.isSymbol('abc');
  11515. * // => false
  11516. */
  11517. function isSymbol(value) {
  11518. return typeof value == 'symbol' ||
  11519. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11520. }
  11521. /**
  11522. * Converts `value` to a string. An empty string is returned for `null`
  11523. * and `undefined` values. The sign of `-0` is preserved.
  11524. *
  11525. * @static
  11526. * @memberOf _
  11527. * @since 4.0.0
  11528. * @category Lang
  11529. * @param {*} value The value to process.
  11530. * @returns {string} Returns the string.
  11531. * @example
  11532. *
  11533. * _.toString(null);
  11534. * // => ''
  11535. *
  11536. * _.toString(-0);
  11537. * // => '-0'
  11538. *
  11539. * _.toString([1, 2, 3]);
  11540. * // => '1,2,3'
  11541. */
  11542. function toString(value) {
  11543. return value == null ? '' : baseToString(value);
  11544. }
  11545. /**
  11546. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11547. *
  11548. * @static
  11549. * @memberOf _
  11550. * @since 3.0.0
  11551. * @category String
  11552. * @param {string} [string=''] The string to convert.
  11553. * @returns {string} Returns the camel cased string.
  11554. * @example
  11555. *
  11556. * _.camelCase('Foo Bar');
  11557. * // => 'fooBar'
  11558. *
  11559. * _.camelCase('--foo-bar--');
  11560. * // => 'fooBar'
  11561. *
  11562. * _.camelCase('__FOO_BAR__');
  11563. * // => 'fooBar'
  11564. */
  11565. var camelCase = createCompounder(function(result, word, index) {
  11566. word = word.toLowerCase();
  11567. return result + (index ? capitalize(word) : word);
  11568. });
  11569. /**
  11570. * Converts the first character of `string` to upper case and the remaining
  11571. * to lower case.
  11572. *
  11573. * @static
  11574. * @memberOf _
  11575. * @since 3.0.0
  11576. * @category String
  11577. * @param {string} [string=''] The string to capitalize.
  11578. * @returns {string} Returns the capitalized string.
  11579. * @example
  11580. *
  11581. * _.capitalize('FRED');
  11582. * // => 'Fred'
  11583. */
  11584. function capitalize(string) {
  11585. return upperFirst(toString(string).toLowerCase());
  11586. }
  11587. /**
  11588. * Deburrs `string` by converting
  11589. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11590. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11591. * letters to basic Latin letters and removing
  11592. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11593. *
  11594. * @static
  11595. * @memberOf _
  11596. * @since 3.0.0
  11597. * @category String
  11598. * @param {string} [string=''] The string to deburr.
  11599. * @returns {string} Returns the deburred string.
  11600. * @example
  11601. *
  11602. * _.deburr('déjà vu');
  11603. * // => 'deja vu'
  11604. */
  11605. function deburr(string) {
  11606. string = toString(string);
  11607. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11608. }
  11609. /**
  11610. * Converts the first character of `string` to upper case.
  11611. *
  11612. * @static
  11613. * @memberOf _
  11614. * @since 4.0.0
  11615. * @category String
  11616. * @param {string} [string=''] The string to convert.
  11617. * @returns {string} Returns the converted string.
  11618. * @example
  11619. *
  11620. * _.upperFirst('fred');
  11621. * // => 'Fred'
  11622. *
  11623. * _.upperFirst('FRED');
  11624. * // => 'FRED'
  11625. */
  11626. var upperFirst = createCaseFirst('toUpperCase');
  11627. /**
  11628. * Splits `string` into an array of its words.
  11629. *
  11630. * @static
  11631. * @memberOf _
  11632. * @since 3.0.0
  11633. * @category String
  11634. * @param {string} [string=''] The string to inspect.
  11635. * @param {RegExp|string} [pattern] The pattern to match words.
  11636. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11637. * @returns {Array} Returns the words of `string`.
  11638. * @example
  11639. *
  11640. * _.words('fred, barney, & pebbles');
  11641. * // => ['fred', 'barney', 'pebbles']
  11642. *
  11643. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11644. * // => ['fred', 'barney', '&', 'pebbles']
  11645. */
  11646. function words(string, pattern, guard) {
  11647. string = toString(string);
  11648. pattern = pattern;
  11649. if (pattern === undefined) {
  11650. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11651. }
  11652. return string.match(pattern) || [];
  11653. }
  11654. lodash_camelcase = camelCase;
  11655. return lodash_camelcase;
  11656. }
  11657. var hasRequiredLocalsConvention;
  11658. function requireLocalsConvention () {
  11659. if (hasRequiredLocalsConvention) return localsConvention;
  11660. hasRequiredLocalsConvention = 1;
  11661. Object.defineProperty(localsConvention, "__esModule", {
  11662. value: true
  11663. });
  11664. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11665. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11666. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11667. function dashesCamelCase(string) {
  11668. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11669. }
  11670. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11671. const isFunc = typeof localsConvention === "function";
  11672. return (tokens, [className, value]) => {
  11673. if (isFunc) {
  11674. const convention = localsConvention(className, value, inputFile);
  11675. tokens[convention] = value;
  11676. return tokens;
  11677. }
  11678. switch (localsConvention) {
  11679. case "camelCase":
  11680. tokens[className] = value;
  11681. tokens[(0, _lodash.default)(className)] = value;
  11682. break;
  11683. case "camelCaseOnly":
  11684. tokens[(0, _lodash.default)(className)] = value;
  11685. break;
  11686. case "dashes":
  11687. tokens[className] = value;
  11688. tokens[dashesCamelCase(className)] = value;
  11689. break;
  11690. case "dashesOnly":
  11691. tokens[dashesCamelCase(className)] = value;
  11692. break;
  11693. }
  11694. return tokens;
  11695. };
  11696. }
  11697. return localsConvention;
  11698. }
  11699. var FileSystemLoader = {};
  11700. var hasRequiredFileSystemLoader;
  11701. function requireFileSystemLoader () {
  11702. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11703. hasRequiredFileSystemLoader = 1;
  11704. Object.defineProperty(FileSystemLoader, "__esModule", {
  11705. value: true
  11706. });
  11707. FileSystemLoader.default = void 0;
  11708. var _postcss = _interopRequireDefault(require$$0$1);
  11709. var _path = _interopRequireDefault(path$1);
  11710. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  11711. var _fs = /*@__PURE__*/ requireFs();
  11712. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11713. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11714. class Core {
  11715. constructor(plugins) {
  11716. this.plugins = plugins || Core.defaultPlugins;
  11717. }
  11718. async load(sourceString, sourcePath, trace, pathFetcher) {
  11719. const parser = new _Parser.default(pathFetcher, trace);
  11720. const plugins = this.plugins.concat([parser.plugin()]);
  11721. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11722. from: sourcePath
  11723. });
  11724. return {
  11725. injectableSource: result.css,
  11726. exportTokens: parser.exportTokens
  11727. };
  11728. }
  11729. } // Sorts dependencies in the following way:
  11730. // AAA comes before AA and A
  11731. // AB comes after AA and before A
  11732. // All Bs come after all As
  11733. // This ensures that the files are always returned in the following order:
  11734. // - In the order they were required, except
  11735. // - After all their dependencies
  11736. const traceKeySorter = (a, b) => {
  11737. if (a.length < b.length) {
  11738. return a < b.substring(0, a.length) ? -1 : 1;
  11739. }
  11740. if (a.length > b.length) {
  11741. return a.substring(0, b.length) <= b ? -1 : 1;
  11742. }
  11743. return a < b ? -1 : 1;
  11744. };
  11745. let FileSystemLoader$1 = class FileSystemLoader {
  11746. constructor(root, plugins, fileResolve) {
  11747. if (root === "/" && process.platform === "win32") {
  11748. const cwdDrive = process.cwd().slice(0, 3);
  11749. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11750. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11751. }
  11752. root = cwdDrive;
  11753. }
  11754. this.root = root;
  11755. this.fileResolve = fileResolve;
  11756. this.sources = {};
  11757. this.traces = {};
  11758. this.importNr = 0;
  11759. this.core = new Core(plugins);
  11760. this.tokensByFile = {};
  11761. this.fs = (0, _fs.getFileSystem)();
  11762. }
  11763. async fetch(_newPath, relativeTo, _trace) {
  11764. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11765. const trace = _trace || String.fromCharCode(this.importNr++);
  11766. const useFileResolve = typeof this.fileResolve === "function";
  11767. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11768. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11769. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11770. }
  11771. const relativeDir = _path.default.dirname(relativeTo);
  11772. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11773. 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
  11774. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11775. try {
  11776. fileRelativePath = require.resolve(newPath);
  11777. } catch (e) {// noop
  11778. }
  11779. }
  11780. const tokens = this.tokensByFile[fileRelativePath];
  11781. if (tokens) return tokens;
  11782. return new Promise((resolve, reject) => {
  11783. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11784. if (err) reject(err);
  11785. const {
  11786. injectableSource,
  11787. exportTokens
  11788. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11789. this.sources[fileRelativePath] = injectableSource;
  11790. this.traces[trace] = fileRelativePath;
  11791. this.tokensByFile[fileRelativePath] = exportTokens;
  11792. resolve(exportTokens);
  11793. });
  11794. });
  11795. }
  11796. get finalSource() {
  11797. const traces = this.traces;
  11798. const sources = this.sources;
  11799. let written = new Set();
  11800. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11801. const filename = traces[key];
  11802. if (written.has(filename)) {
  11803. return null;
  11804. }
  11805. written.add(filename);
  11806. return sources[filename];
  11807. }).join("");
  11808. }
  11809. };
  11810. FileSystemLoader.default = FileSystemLoader$1;
  11811. return FileSystemLoader;
  11812. }
  11813. var scoping = {};
  11814. var src$3 = {exports: {}};
  11815. var topologicalSort_1;
  11816. var hasRequiredTopologicalSort;
  11817. function requireTopologicalSort () {
  11818. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11819. hasRequiredTopologicalSort = 1;
  11820. const PERMANENT_MARKER = 2;
  11821. const TEMPORARY_MARKER = 1;
  11822. function createError(node, graph) {
  11823. const er = new Error("Nondeterministic import's order");
  11824. const related = graph[node];
  11825. const relatedNode = related.find(
  11826. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11827. );
  11828. er.nodes = [node, relatedNode];
  11829. return er;
  11830. }
  11831. function walkGraph(node, graph, state, result, strict) {
  11832. if (state[node] === PERMANENT_MARKER) {
  11833. return;
  11834. }
  11835. if (state[node] === TEMPORARY_MARKER) {
  11836. if (strict) {
  11837. return createError(node, graph);
  11838. }
  11839. return;
  11840. }
  11841. state[node] = TEMPORARY_MARKER;
  11842. const children = graph[node];
  11843. const length = children.length;
  11844. for (let i = 0; i < length; ++i) {
  11845. const error = walkGraph(children[i], graph, state, result, strict);
  11846. if (error instanceof Error) {
  11847. return error;
  11848. }
  11849. }
  11850. state[node] = PERMANENT_MARKER;
  11851. result.push(node);
  11852. }
  11853. function topologicalSort(graph, strict) {
  11854. const result = [];
  11855. const state = {};
  11856. const nodes = Object.keys(graph);
  11857. const length = nodes.length;
  11858. for (let i = 0; i < length; ++i) {
  11859. const er = walkGraph(nodes[i], graph, state, result, strict);
  11860. if (er instanceof Error) {
  11861. return er;
  11862. }
  11863. }
  11864. return result;
  11865. }
  11866. topologicalSort_1 = topologicalSort;
  11867. return topologicalSort_1;
  11868. }
  11869. var hasRequiredSrc$3;
  11870. function requireSrc$3 () {
  11871. if (hasRequiredSrc$3) return src$3.exports;
  11872. hasRequiredSrc$3 = 1;
  11873. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  11874. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11875. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11876. const VISITED_MARKER = 1;
  11877. /**
  11878. * :import('G') {}
  11879. *
  11880. * Rule
  11881. * composes: ... from 'A'
  11882. * composes: ... from 'B'
  11883. * Rule
  11884. * composes: ... from 'A'
  11885. * composes: ... from 'A'
  11886. * composes: ... from 'C'
  11887. *
  11888. * Results in:
  11889. *
  11890. * graph: {
  11891. * G: [],
  11892. * A: [],
  11893. * B: ['A'],
  11894. * C: ['A'],
  11895. * }
  11896. */
  11897. function addImportToGraph(importId, parentId, graph, visited) {
  11898. const siblingsId = parentId + "_" + "siblings";
  11899. const visitedId = parentId + "_" + importId;
  11900. if (visited[visitedId] !== VISITED_MARKER) {
  11901. if (!Array.isArray(visited[siblingsId])) {
  11902. visited[siblingsId] = [];
  11903. }
  11904. const siblings = visited[siblingsId];
  11905. if (Array.isArray(graph[importId])) {
  11906. graph[importId] = graph[importId].concat(siblings);
  11907. } else {
  11908. graph[importId] = siblings.slice();
  11909. }
  11910. visited[visitedId] = VISITED_MARKER;
  11911. siblings.push(importId);
  11912. }
  11913. }
  11914. src$3.exports = (options = {}) => {
  11915. let importIndex = 0;
  11916. const createImportedName =
  11917. typeof options.createImportedName !== "function"
  11918. ? (importName /*, path*/) =>
  11919. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11920. : options.createImportedName;
  11921. const failOnWrongOrder = options.failOnWrongOrder;
  11922. return {
  11923. postcssPlugin: "postcss-modules-extract-imports",
  11924. prepare() {
  11925. const graph = {};
  11926. const visited = {};
  11927. const existingImports = {};
  11928. const importDecls = {};
  11929. const imports = {};
  11930. return {
  11931. Once(root, postcss) {
  11932. // Check the existing imports order and save refs
  11933. root.walkRules((rule) => {
  11934. const matches = icssImport.exec(rule.selector);
  11935. if (matches) {
  11936. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11937. const importPath = doubleQuotePath || singleQuotePath;
  11938. addImportToGraph(importPath, "root", graph, visited);
  11939. existingImports[importPath] = rule;
  11940. }
  11941. });
  11942. root.walkDecls(/^composes$/, (declaration) => {
  11943. const multiple = declaration.value.split(",");
  11944. const values = [];
  11945. multiple.forEach((value) => {
  11946. const matches = value.trim().match(matchImports);
  11947. if (!matches) {
  11948. values.push(value);
  11949. return;
  11950. }
  11951. let tmpSymbols;
  11952. let [
  11953. ,
  11954. /*match*/ symbols,
  11955. doubleQuotePath,
  11956. singleQuotePath,
  11957. global,
  11958. ] = matches;
  11959. if (global) {
  11960. // Composing globals simply means changing these classes to wrap them in global(name)
  11961. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  11962. } else {
  11963. const importPath = doubleQuotePath || singleQuotePath;
  11964. let parent = declaration.parent;
  11965. let parentIndexes = "";
  11966. while (parent.type !== "root") {
  11967. parentIndexes =
  11968. parent.parent.index(parent) + "_" + parentIndexes;
  11969. parent = parent.parent;
  11970. }
  11971. const { selector } = declaration.parent;
  11972. const parentRule = `_${parentIndexes}${selector}`;
  11973. addImportToGraph(importPath, parentRule, graph, visited);
  11974. importDecls[importPath] = declaration;
  11975. imports[importPath] = imports[importPath] || {};
  11976. tmpSymbols = symbols.split(/\s+/).map((s) => {
  11977. if (!imports[importPath][s]) {
  11978. imports[importPath][s] = createImportedName(s, importPath);
  11979. }
  11980. return imports[importPath][s];
  11981. });
  11982. }
  11983. values.push(tmpSymbols.join(" "));
  11984. });
  11985. declaration.value = values.join(", ");
  11986. });
  11987. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  11988. if (importsOrder instanceof Error) {
  11989. const importPath = importsOrder.nodes.find((importPath) =>
  11990. // eslint-disable-next-line no-prototype-builtins
  11991. importDecls.hasOwnProperty(importPath)
  11992. );
  11993. const decl = importDecls[importPath];
  11994. throw decl.error(
  11995. "Failed to resolve order of composed modules " +
  11996. importsOrder.nodes
  11997. .map((importPath) => "`" + importPath + "`")
  11998. .join(", ") +
  11999. ".",
  12000. {
  12001. plugin: "postcss-modules-extract-imports",
  12002. word: "composes",
  12003. }
  12004. );
  12005. }
  12006. let lastImportRule;
  12007. importsOrder.forEach((path) => {
  12008. const importedSymbols = imports[path];
  12009. let rule = existingImports[path];
  12010. if (!rule && importedSymbols) {
  12011. rule = postcss.rule({
  12012. selector: `:import("${path}")`,
  12013. raws: { after: "\n" },
  12014. });
  12015. if (lastImportRule) {
  12016. root.insertAfter(lastImportRule, rule);
  12017. } else {
  12018. root.prepend(rule);
  12019. }
  12020. }
  12021. lastImportRule = rule;
  12022. if (!importedSymbols) {
  12023. return;
  12024. }
  12025. Object.keys(importedSymbols).forEach((importedSymbol) => {
  12026. rule.append(
  12027. postcss.decl({
  12028. value: importedSymbol,
  12029. prop: importedSymbols[importedSymbol],
  12030. raws: { before: "\n " },
  12031. })
  12032. );
  12033. });
  12034. });
  12035. },
  12036. };
  12037. },
  12038. };
  12039. };
  12040. src$3.exports.postcss = true;
  12041. return src$3.exports;
  12042. }
  12043. var wasmHash = {exports: {}};
  12044. /*
  12045. MIT License http://www.opensource.org/licenses/mit-license.php
  12046. Author Tobias Koppers @sokra
  12047. */
  12048. var hasRequiredWasmHash;
  12049. function requireWasmHash () {
  12050. if (hasRequiredWasmHash) return wasmHash.exports;
  12051. hasRequiredWasmHash = 1;
  12052. // 65536 is the size of a wasm memory page
  12053. // 64 is the maximum chunk size for every possible wasm hash implementation
  12054. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12055. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12056. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
  12057. class WasmHash {
  12058. /**
  12059. * @param {WebAssembly.Instance} instance wasm instance
  12060. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12061. * @param {number} chunkSize size of data chunks passed to wasm
  12062. * @param {number} digestSize size of digest returned by wasm
  12063. */
  12064. constructor(instance, instancesPool, chunkSize, digestSize) {
  12065. const exports$1 = /** @type {any} */ (instance.exports);
  12066. exports$1.init();
  12067. this.exports = exports$1;
  12068. this.mem = Buffer.from(exports$1.memory.buffer, 0, 65536);
  12069. this.buffered = 0;
  12070. this.instancesPool = instancesPool;
  12071. this.chunkSize = chunkSize;
  12072. this.digestSize = digestSize;
  12073. }
  12074. reset() {
  12075. this.buffered = 0;
  12076. this.exports.init();
  12077. }
  12078. /**
  12079. * @param {Buffer | string} data data
  12080. * @param {BufferEncoding=} encoding encoding
  12081. * @returns {this} itself
  12082. */
  12083. update(data, encoding) {
  12084. if (typeof data === "string") {
  12085. while (data.length > MAX_SHORT_STRING) {
  12086. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12087. data = data.slice(MAX_SHORT_STRING);
  12088. }
  12089. this._updateWithShortString(data, encoding);
  12090. return this;
  12091. }
  12092. this._updateWithBuffer(data);
  12093. return this;
  12094. }
  12095. /**
  12096. * @param {string} data data
  12097. * @param {BufferEncoding=} encoding encoding
  12098. * @returns {void}
  12099. */
  12100. _updateWithShortString(data, encoding) {
  12101. const { exports: exports$1, buffered, mem, chunkSize } = this;
  12102. let endPos;
  12103. if (data.length < 70) {
  12104. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12105. endPos = buffered;
  12106. for (let i = 0; i < data.length; i++) {
  12107. const cc = data.charCodeAt(i);
  12108. if (cc < 0x80) {
  12109. mem[endPos++] = cc;
  12110. } else if (cc < 0x800) {
  12111. mem[endPos] = (cc >> 6) | 0xc0;
  12112. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12113. endPos += 2;
  12114. } else {
  12115. // bail-out for weird chars
  12116. endPos += mem.write(data.slice(i), endPos, encoding);
  12117. break;
  12118. }
  12119. }
  12120. } else if (encoding === "latin1") {
  12121. endPos = buffered;
  12122. for (let i = 0; i < data.length; i++) {
  12123. const cc = data.charCodeAt(i);
  12124. mem[endPos++] = cc;
  12125. }
  12126. } else {
  12127. endPos = buffered + mem.write(data, buffered, encoding);
  12128. }
  12129. } else {
  12130. endPos = buffered + mem.write(data, buffered, encoding);
  12131. }
  12132. if (endPos < chunkSize) {
  12133. this.buffered = endPos;
  12134. } else {
  12135. const l = endPos & ~(this.chunkSize - 1);
  12136. exports$1.update(l);
  12137. const newBuffered = endPos - l;
  12138. this.buffered = newBuffered;
  12139. if (newBuffered > 0) {
  12140. mem.copyWithin(0, l, endPos);
  12141. }
  12142. }
  12143. }
  12144. /**
  12145. * @param {Buffer} data data
  12146. * @returns {void}
  12147. */
  12148. _updateWithBuffer(data) {
  12149. const { exports: exports$1, buffered, mem } = this;
  12150. const length = data.length;
  12151. if (buffered + length < this.chunkSize) {
  12152. data.copy(mem, buffered, 0, length);
  12153. this.buffered += length;
  12154. } else {
  12155. const l = (buffered + length) & ~(this.chunkSize - 1);
  12156. if (l > 65536) {
  12157. let i = 65536 - buffered;
  12158. data.copy(mem, buffered, 0, i);
  12159. exports$1.update(65536);
  12160. const stop = l - buffered - 65536;
  12161. while (i < stop) {
  12162. data.copy(mem, 0, i, i + 65536);
  12163. exports$1.update(65536);
  12164. i += 65536;
  12165. }
  12166. data.copy(mem, 0, i, l - buffered);
  12167. exports$1.update(l - buffered - i);
  12168. } else {
  12169. data.copy(mem, buffered, 0, l - buffered);
  12170. exports$1.update(l);
  12171. }
  12172. const newBuffered = length + buffered - l;
  12173. this.buffered = newBuffered;
  12174. if (newBuffered > 0) {
  12175. data.copy(mem, 0, length - newBuffered, length);
  12176. }
  12177. }
  12178. }
  12179. digest(type) {
  12180. const { exports: exports$1, buffered, mem, digestSize } = this;
  12181. exports$1.final(buffered);
  12182. this.instancesPool.push(this);
  12183. const hex = mem.toString("latin1", 0, digestSize);
  12184. if (type === "hex") {
  12185. return hex;
  12186. }
  12187. if (type === "binary" || !type) {
  12188. return Buffer.from(hex, "hex");
  12189. }
  12190. return Buffer.from(hex, "hex").toString(type);
  12191. }
  12192. }
  12193. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12194. if (instancesPool.length > 0) {
  12195. const old = instancesPool.pop();
  12196. old.reset();
  12197. return old;
  12198. } else {
  12199. return new WasmHash(
  12200. new WebAssembly.Instance(wasmModule),
  12201. instancesPool,
  12202. chunkSize,
  12203. digestSize
  12204. );
  12205. }
  12206. };
  12207. wasmHash.exports = create;
  12208. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12209. return wasmHash.exports;
  12210. }
  12211. /*
  12212. MIT License http://www.opensource.org/licenses/mit-license.php
  12213. Author Tobias Koppers @sokra
  12214. */
  12215. var xxhash64_1;
  12216. var hasRequiredXxhash64;
  12217. function requireXxhash64 () {
  12218. if (hasRequiredXxhash64) return xxhash64_1;
  12219. hasRequiredXxhash64 = 1;
  12220. const create = /*@__PURE__*/ requireWasmHash();
  12221. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12222. const xxhash64 = new WebAssembly.Module(
  12223. Buffer.from(
  12224. // 1173 bytes
  12225. "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",
  12226. "base64"
  12227. )
  12228. );
  12229. //#endregion
  12230. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12231. return xxhash64_1;
  12232. }
  12233. var BatchedHash_1;
  12234. var hasRequiredBatchedHash;
  12235. function requireBatchedHash () {
  12236. if (hasRequiredBatchedHash) return BatchedHash_1;
  12237. hasRequiredBatchedHash = 1;
  12238. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12239. class BatchedHash {
  12240. constructor(hash) {
  12241. this.string = undefined;
  12242. this.encoding = undefined;
  12243. this.hash = hash;
  12244. }
  12245. /**
  12246. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12247. * @param {string|Buffer} data data
  12248. * @param {string=} inputEncoding data encoding
  12249. * @returns {this} updated hash
  12250. */
  12251. update(data, inputEncoding) {
  12252. if (this.string !== undefined) {
  12253. if (
  12254. typeof data === "string" &&
  12255. inputEncoding === this.encoding &&
  12256. this.string.length + data.length < MAX_SHORT_STRING
  12257. ) {
  12258. this.string += data;
  12259. return this;
  12260. }
  12261. this.hash.update(this.string, this.encoding);
  12262. this.string = undefined;
  12263. }
  12264. if (typeof data === "string") {
  12265. if (
  12266. data.length < MAX_SHORT_STRING &&
  12267. // base64 encoding is not valid since it may contain padding chars
  12268. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12269. ) {
  12270. this.string = data;
  12271. this.encoding = inputEncoding;
  12272. } else {
  12273. this.hash.update(data, inputEncoding);
  12274. }
  12275. } else {
  12276. this.hash.update(data);
  12277. }
  12278. return this;
  12279. }
  12280. /**
  12281. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12282. * @param {string=} encoding encoding of the return value
  12283. * @returns {string|Buffer} digest
  12284. */
  12285. digest(encoding) {
  12286. if (this.string !== undefined) {
  12287. this.hash.update(this.string, this.encoding);
  12288. }
  12289. return this.hash.digest(encoding);
  12290. }
  12291. }
  12292. BatchedHash_1 = BatchedHash;
  12293. return BatchedHash_1;
  12294. }
  12295. /*
  12296. MIT License http://www.opensource.org/licenses/mit-license.php
  12297. Author Tobias Koppers @sokra
  12298. */
  12299. var md4_1;
  12300. var hasRequiredMd4;
  12301. function requireMd4 () {
  12302. if (hasRequiredMd4) return md4_1;
  12303. hasRequiredMd4 = 1;
  12304. const create = /*@__PURE__*/ requireWasmHash();
  12305. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12306. const md4 = new WebAssembly.Module(
  12307. Buffer.from(
  12308. // 2150 bytes
  12309. "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=",
  12310. "base64"
  12311. )
  12312. );
  12313. //#endregion
  12314. md4_1 = create.bind(null, md4, [], 64, 32);
  12315. return md4_1;
  12316. }
  12317. var BulkUpdateDecorator_1;
  12318. var hasRequiredBulkUpdateDecorator;
  12319. function requireBulkUpdateDecorator () {
  12320. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12321. hasRequiredBulkUpdateDecorator = 1;
  12322. const BULK_SIZE = 2000;
  12323. // We are using an object instead of a Map as this will stay static during the runtime
  12324. // so access to it can be optimized by v8
  12325. const digestCaches = {};
  12326. class BulkUpdateDecorator {
  12327. /**
  12328. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12329. * @param {string=} hashKey key for caching
  12330. */
  12331. constructor(hashOrFactory, hashKey) {
  12332. this.hashKey = hashKey;
  12333. if (typeof hashOrFactory === "function") {
  12334. this.hashFactory = hashOrFactory;
  12335. this.hash = undefined;
  12336. } else {
  12337. this.hashFactory = undefined;
  12338. this.hash = hashOrFactory;
  12339. }
  12340. this.buffer = "";
  12341. }
  12342. /**
  12343. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12344. * @param {string|Buffer} data data
  12345. * @param {string=} inputEncoding data encoding
  12346. * @returns {this} updated hash
  12347. */
  12348. update(data, inputEncoding) {
  12349. if (
  12350. inputEncoding !== undefined ||
  12351. typeof data !== "string" ||
  12352. data.length > BULK_SIZE
  12353. ) {
  12354. if (this.hash === undefined) {
  12355. this.hash = this.hashFactory();
  12356. }
  12357. if (this.buffer.length > 0) {
  12358. this.hash.update(this.buffer);
  12359. this.buffer = "";
  12360. }
  12361. this.hash.update(data, inputEncoding);
  12362. } else {
  12363. this.buffer += data;
  12364. if (this.buffer.length > BULK_SIZE) {
  12365. if (this.hash === undefined) {
  12366. this.hash = this.hashFactory();
  12367. }
  12368. this.hash.update(this.buffer);
  12369. this.buffer = "";
  12370. }
  12371. }
  12372. return this;
  12373. }
  12374. /**
  12375. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12376. * @param {string=} encoding encoding of the return value
  12377. * @returns {string|Buffer} digest
  12378. */
  12379. digest(encoding) {
  12380. let digestCache;
  12381. const buffer = this.buffer;
  12382. if (this.hash === undefined) {
  12383. // short data for hash, we can use caching
  12384. const cacheKey = `${this.hashKey}-${encoding}`;
  12385. digestCache = digestCaches[cacheKey];
  12386. if (digestCache === undefined) {
  12387. digestCache = digestCaches[cacheKey] = new Map();
  12388. }
  12389. const cacheEntry = digestCache.get(buffer);
  12390. if (cacheEntry !== undefined) {
  12391. return cacheEntry;
  12392. }
  12393. this.hash = this.hashFactory();
  12394. }
  12395. if (buffer.length > 0) {
  12396. this.hash.update(buffer);
  12397. }
  12398. const digestResult = this.hash.digest(encoding);
  12399. if (digestCache !== undefined) {
  12400. digestCache.set(buffer, digestResult);
  12401. }
  12402. return digestResult;
  12403. }
  12404. }
  12405. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12406. return BulkUpdateDecorator_1;
  12407. }
  12408. var getHashDigest_1;
  12409. var hasRequiredGetHashDigest;
  12410. function requireGetHashDigest () {
  12411. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12412. hasRequiredGetHashDigest = 1;
  12413. const baseEncodeTables = {
  12414. 26: "abcdefghijklmnopqrstuvwxyz",
  12415. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12416. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12417. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12418. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12419. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12420. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12421. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12422. };
  12423. /**
  12424. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12425. * @param {number} divisor The divisor
  12426. * @return {number} Modulo (remainder) of the division
  12427. */
  12428. function divmod32(uint32Array, divisor) {
  12429. let carry = 0;
  12430. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12431. const value = carry * 0x100000000 + uint32Array[i];
  12432. carry = value % divisor;
  12433. uint32Array[i] = Math.floor(value / divisor);
  12434. }
  12435. return carry;
  12436. }
  12437. function encodeBufferToBase(buffer, base, length) {
  12438. const encodeTable = baseEncodeTables[base];
  12439. if (!encodeTable) {
  12440. throw new Error("Unknown encoding base" + base);
  12441. }
  12442. // Input bits are only enough to generate this many characters
  12443. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12444. length = Math.min(length, limit);
  12445. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12446. // Fewer numbers in the array means faster math.
  12447. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12448. // Make sure the input buffer data is copied and is not mutated by reference.
  12449. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12450. buffer.copy(Buffer.from(uint32Array.buffer));
  12451. let output = "";
  12452. for (let i = 0; i < length; i++) {
  12453. output = encodeTable[divmod32(uint32Array, base)] + output;
  12454. }
  12455. return output;
  12456. }
  12457. let crypto = undefined;
  12458. let createXXHash64 = undefined;
  12459. let createMd4 = undefined;
  12460. let BatchedHash = undefined;
  12461. let BulkUpdateDecorator = undefined;
  12462. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12463. algorithm = algorithm || "xxhash64";
  12464. maxLength = maxLength || 9999;
  12465. let hash;
  12466. if (algorithm === "xxhash64") {
  12467. if (createXXHash64 === undefined) {
  12468. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12469. if (BatchedHash === undefined) {
  12470. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12471. }
  12472. }
  12473. hash = new BatchedHash(createXXHash64());
  12474. } else if (algorithm === "md4") {
  12475. if (createMd4 === undefined) {
  12476. createMd4 = /*@__PURE__*/ requireMd4();
  12477. if (BatchedHash === undefined) {
  12478. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12479. }
  12480. }
  12481. hash = new BatchedHash(createMd4());
  12482. } else if (algorithm === "native-md4") {
  12483. if (typeof crypto === "undefined") {
  12484. crypto = require("crypto");
  12485. if (BulkUpdateDecorator === undefined) {
  12486. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12487. }
  12488. }
  12489. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12490. } else {
  12491. if (typeof crypto === "undefined") {
  12492. crypto = require("crypto");
  12493. if (BulkUpdateDecorator === undefined) {
  12494. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12495. }
  12496. }
  12497. hash = new BulkUpdateDecorator(
  12498. () => crypto.createHash(algorithm),
  12499. algorithm
  12500. );
  12501. }
  12502. hash.update(buffer);
  12503. if (
  12504. digestType === "base26" ||
  12505. digestType === "base32" ||
  12506. digestType === "base36" ||
  12507. digestType === "base49" ||
  12508. digestType === "base52" ||
  12509. digestType === "base58" ||
  12510. digestType === "base62" ||
  12511. digestType === "base64safe"
  12512. ) {
  12513. return encodeBufferToBase(
  12514. hash.digest(),
  12515. digestType === "base64safe" ? 64 : digestType.substr(4),
  12516. maxLength
  12517. );
  12518. }
  12519. return hash.digest(digestType || "hex").substr(0, maxLength);
  12520. }
  12521. getHashDigest_1 = getHashDigest;
  12522. return getHashDigest_1;
  12523. }
  12524. var interpolateName_1;
  12525. var hasRequiredInterpolateName;
  12526. function requireInterpolateName () {
  12527. if (hasRequiredInterpolateName) return interpolateName_1;
  12528. hasRequiredInterpolateName = 1;
  12529. const path = path$1;
  12530. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12531. function interpolateName(loaderContext, name, options = {}) {
  12532. let filename;
  12533. const hasQuery =
  12534. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12535. if (typeof name === "function") {
  12536. filename = name(
  12537. loaderContext.resourcePath,
  12538. hasQuery ? loaderContext.resourceQuery : undefined
  12539. );
  12540. } else {
  12541. filename = name || "[hash].[ext]";
  12542. }
  12543. const context = options.context;
  12544. const content = options.content;
  12545. const regExp = options.regExp;
  12546. let ext = "bin";
  12547. let basename = "file";
  12548. let directory = "";
  12549. let folder = "";
  12550. let query = "";
  12551. if (loaderContext.resourcePath) {
  12552. const parsed = path.parse(loaderContext.resourcePath);
  12553. let resourcePath = loaderContext.resourcePath;
  12554. if (parsed.ext) {
  12555. ext = parsed.ext.substr(1);
  12556. }
  12557. if (parsed.dir) {
  12558. basename = parsed.name;
  12559. resourcePath = parsed.dir + path.sep;
  12560. }
  12561. if (typeof context !== "undefined") {
  12562. directory = path
  12563. .relative(context, resourcePath + "_")
  12564. .replace(/\\/g, "/")
  12565. .replace(/\.\.(\/)?/g, "_$1");
  12566. directory = directory.substr(0, directory.length - 1);
  12567. } else {
  12568. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12569. }
  12570. if (directory.length <= 1) {
  12571. directory = "";
  12572. } else {
  12573. // directory.length > 1
  12574. folder = path.basename(directory);
  12575. }
  12576. }
  12577. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12578. query = loaderContext.resourceQuery;
  12579. const hashIdx = query.indexOf("#");
  12580. if (hashIdx >= 0) {
  12581. query = query.substr(0, hashIdx);
  12582. }
  12583. }
  12584. let url = filename;
  12585. if (content) {
  12586. // Match hash template
  12587. url = url
  12588. // `hash` and `contenthash` are same in `loader-utils` context
  12589. // let's keep `hash` for backward compatibility
  12590. .replace(
  12591. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12592. (all, hashType, digestType, maxLength) =>
  12593. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12594. );
  12595. }
  12596. url = url
  12597. .replace(/\[ext\]/gi, () => ext)
  12598. .replace(/\[name\]/gi, () => basename)
  12599. .replace(/\[path\]/gi, () => directory)
  12600. .replace(/\[folder\]/gi, () => folder)
  12601. .replace(/\[query\]/gi, () => query);
  12602. if (regExp && loaderContext.resourcePath) {
  12603. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12604. match &&
  12605. match.forEach((matched, i) => {
  12606. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12607. });
  12608. }
  12609. if (
  12610. typeof loaderContext.options === "object" &&
  12611. typeof loaderContext.options.customInterpolateName === "function"
  12612. ) {
  12613. url = loaderContext.options.customInterpolateName.call(
  12614. loaderContext,
  12615. url,
  12616. name,
  12617. options
  12618. );
  12619. }
  12620. return url;
  12621. }
  12622. interpolateName_1 = interpolateName;
  12623. return interpolateName_1;
  12624. }
  12625. var genericNames;
  12626. var hasRequiredGenericNames;
  12627. function requireGenericNames () {
  12628. if (hasRequiredGenericNames) return genericNames;
  12629. hasRequiredGenericNames = 1;
  12630. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12631. var path = path$1;
  12632. /**
  12633. * @param {string} pattern
  12634. * @param {object} options
  12635. * @param {string} options.context
  12636. * @param {string} options.hashPrefix
  12637. * @return {function}
  12638. */
  12639. genericNames = function createGenerator(pattern, options) {
  12640. options = options || {};
  12641. var context =
  12642. options && typeof options.context === "string"
  12643. ? options.context
  12644. : process.cwd();
  12645. var hashPrefix =
  12646. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12647. /**
  12648. * @param {string} localName Usually a class name
  12649. * @param {string} filepath Absolute path
  12650. * @return {string}
  12651. */
  12652. return function generate(localName, filepath) {
  12653. var name = pattern.replace(/\[local\]/gi, localName);
  12654. var loaderContext = {
  12655. resourcePath: filepath,
  12656. };
  12657. var loaderOptions = {
  12658. content:
  12659. hashPrefix +
  12660. path.relative(context, filepath).replace(/\\/g, "/") +
  12661. "\x00" +
  12662. localName,
  12663. context: context,
  12664. };
  12665. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12666. return genericName
  12667. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12668. .replace(/^((-?[0-9])|--)/, "_$1");
  12669. };
  12670. };
  12671. return genericNames;
  12672. }
  12673. var src$2 = {exports: {}};
  12674. var dist = {exports: {}};
  12675. var processor = {exports: {}};
  12676. var parser = {exports: {}};
  12677. var root = {exports: {}};
  12678. var container = {exports: {}};
  12679. var node = {exports: {}};
  12680. var util = {};
  12681. var unesc = {exports: {}};
  12682. var hasRequiredUnesc;
  12683. function requireUnesc () {
  12684. if (hasRequiredUnesc) return unesc.exports;
  12685. hasRequiredUnesc = 1;
  12686. (function (module, exports$1) {
  12687. exports$1.__esModule = true;
  12688. exports$1["default"] = unesc;
  12689. // Many thanks for this post which made this migration much easier.
  12690. // https://mathiasbynens.be/notes/css-escapes
  12691. /**
  12692. *
  12693. * @param {string} str
  12694. * @returns {[string, number]|undefined}
  12695. */
  12696. function gobbleHex(str) {
  12697. var lower = str.toLowerCase();
  12698. var hex = '';
  12699. var spaceTerminated = false;
  12700. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  12701. var code = lower.charCodeAt(i);
  12702. // check to see if we are dealing with a valid hex char [a-f|0-9]
  12703. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  12704. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  12705. spaceTerminated = code === 32;
  12706. if (!valid) {
  12707. break;
  12708. }
  12709. hex += lower[i];
  12710. }
  12711. if (hex.length === 0) {
  12712. return undefined;
  12713. }
  12714. var codePoint = parseInt(hex, 16);
  12715. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  12716. // Add special case for
  12717. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  12718. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  12719. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  12720. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  12721. }
  12722. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  12723. }
  12724. var CONTAINS_ESCAPE = /\\/;
  12725. function unesc(str) {
  12726. var needToProcess = CONTAINS_ESCAPE.test(str);
  12727. if (!needToProcess) {
  12728. return str;
  12729. }
  12730. var ret = "";
  12731. for (var i = 0; i < str.length; i++) {
  12732. if (str[i] === "\\") {
  12733. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  12734. if (gobbled !== undefined) {
  12735. ret += gobbled[0];
  12736. i += gobbled[1];
  12737. continue;
  12738. }
  12739. // Retain a pair of \\ if double escaped `\\\\`
  12740. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  12741. if (str[i + 1] === "\\") {
  12742. ret += "\\";
  12743. i++;
  12744. continue;
  12745. }
  12746. // if \\ is at the end of the string retain it
  12747. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  12748. if (str.length === i + 1) {
  12749. ret += str[i];
  12750. }
  12751. continue;
  12752. }
  12753. ret += str[i];
  12754. }
  12755. return ret;
  12756. }
  12757. module.exports = exports$1.default;
  12758. } (unesc, unesc.exports));
  12759. return unesc.exports;
  12760. }
  12761. var getProp = {exports: {}};
  12762. var hasRequiredGetProp;
  12763. function requireGetProp () {
  12764. if (hasRequiredGetProp) return getProp.exports;
  12765. hasRequiredGetProp = 1;
  12766. (function (module, exports$1) {
  12767. exports$1.__esModule = true;
  12768. exports$1["default"] = getProp;
  12769. function getProp(obj) {
  12770. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12771. props[_key - 1] = arguments[_key];
  12772. }
  12773. while (props.length > 0) {
  12774. var prop = props.shift();
  12775. if (!obj[prop]) {
  12776. return undefined;
  12777. }
  12778. obj = obj[prop];
  12779. }
  12780. return obj;
  12781. }
  12782. module.exports = exports$1.default;
  12783. } (getProp, getProp.exports));
  12784. return getProp.exports;
  12785. }
  12786. var ensureObject = {exports: {}};
  12787. var hasRequiredEnsureObject;
  12788. function requireEnsureObject () {
  12789. if (hasRequiredEnsureObject) return ensureObject.exports;
  12790. hasRequiredEnsureObject = 1;
  12791. (function (module, exports$1) {
  12792. exports$1.__esModule = true;
  12793. exports$1["default"] = ensureObject;
  12794. function ensureObject(obj) {
  12795. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12796. props[_key - 1] = arguments[_key];
  12797. }
  12798. while (props.length > 0) {
  12799. var prop = props.shift();
  12800. if (!obj[prop]) {
  12801. obj[prop] = {};
  12802. }
  12803. obj = obj[prop];
  12804. }
  12805. }
  12806. module.exports = exports$1.default;
  12807. } (ensureObject, ensureObject.exports));
  12808. return ensureObject.exports;
  12809. }
  12810. var stripComments = {exports: {}};
  12811. var hasRequiredStripComments;
  12812. function requireStripComments () {
  12813. if (hasRequiredStripComments) return stripComments.exports;
  12814. hasRequiredStripComments = 1;
  12815. (function (module, exports$1) {
  12816. exports$1.__esModule = true;
  12817. exports$1["default"] = stripComments;
  12818. function stripComments(str) {
  12819. var s = "";
  12820. var commentStart = str.indexOf("/*");
  12821. var lastEnd = 0;
  12822. while (commentStart >= 0) {
  12823. s = s + str.slice(lastEnd, commentStart);
  12824. var commentEnd = str.indexOf("*/", commentStart + 2);
  12825. if (commentEnd < 0) {
  12826. return s;
  12827. }
  12828. lastEnd = commentEnd + 2;
  12829. commentStart = str.indexOf("/*", lastEnd);
  12830. }
  12831. s = s + str.slice(lastEnd);
  12832. return s;
  12833. }
  12834. module.exports = exports$1.default;
  12835. } (stripComments, stripComments.exports));
  12836. return stripComments.exports;
  12837. }
  12838. var hasRequiredUtil;
  12839. function requireUtil () {
  12840. if (hasRequiredUtil) return util;
  12841. hasRequiredUtil = 1;
  12842. util.__esModule = true;
  12843. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  12844. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  12845. util.unesc = _unesc["default"];
  12846. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  12847. util.getProp = _getProp["default"];
  12848. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  12849. util.ensureObject = _ensureObject["default"];
  12850. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  12851. util.stripComments = _stripComments["default"];
  12852. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  12853. return util;
  12854. }
  12855. var hasRequiredNode;
  12856. function requireNode () {
  12857. if (hasRequiredNode) return node.exports;
  12858. hasRequiredNode = 1;
  12859. (function (module, exports$1) {
  12860. exports$1.__esModule = true;
  12861. exports$1["default"] = void 0;
  12862. var _util = /*@__PURE__*/ requireUtil();
  12863. 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); } }
  12864. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12865. var cloneNode = function cloneNode(obj, parent) {
  12866. if (typeof obj !== 'object' || obj === null) {
  12867. return obj;
  12868. }
  12869. var cloned = new obj.constructor();
  12870. for (var i in obj) {
  12871. if (!obj.hasOwnProperty(i)) {
  12872. continue;
  12873. }
  12874. var value = obj[i];
  12875. var type = typeof value;
  12876. if (i === 'parent' && type === 'object') {
  12877. if (parent) {
  12878. cloned[i] = parent;
  12879. }
  12880. } else if (value instanceof Array) {
  12881. cloned[i] = value.map(function (j) {
  12882. return cloneNode(j, cloned);
  12883. });
  12884. } else {
  12885. cloned[i] = cloneNode(value, cloned);
  12886. }
  12887. }
  12888. return cloned;
  12889. };
  12890. var Node = /*#__PURE__*/function () {
  12891. function Node(opts) {
  12892. if (opts === void 0) {
  12893. opts = {};
  12894. }
  12895. Object.assign(this, opts);
  12896. this.spaces = this.spaces || {};
  12897. this.spaces.before = this.spaces.before || '';
  12898. this.spaces.after = this.spaces.after || '';
  12899. }
  12900. var _proto = Node.prototype;
  12901. _proto.remove = function remove() {
  12902. if (this.parent) {
  12903. this.parent.removeChild(this);
  12904. }
  12905. this.parent = undefined;
  12906. return this;
  12907. };
  12908. _proto.replaceWith = function replaceWith() {
  12909. if (this.parent) {
  12910. for (var index in arguments) {
  12911. this.parent.insertBefore(this, arguments[index]);
  12912. }
  12913. this.remove();
  12914. }
  12915. return this;
  12916. };
  12917. _proto.next = function next() {
  12918. return this.parent.at(this.parent.index(this) + 1);
  12919. };
  12920. _proto.prev = function prev() {
  12921. return this.parent.at(this.parent.index(this) - 1);
  12922. };
  12923. _proto.clone = function clone(overrides) {
  12924. if (overrides === void 0) {
  12925. overrides = {};
  12926. }
  12927. var cloned = cloneNode(this);
  12928. for (var name in overrides) {
  12929. cloned[name] = overrides[name];
  12930. }
  12931. return cloned;
  12932. }
  12933. /**
  12934. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12935. * This allows non standard syntax to be appended to an existing property
  12936. * by specifying the escaped value. By specifying the escaped value,
  12937. * illegal characters are allowed to be directly inserted into css output.
  12938. * @param {string} name the property to set
  12939. * @param {any} value the unescaped value of the property
  12940. * @param {string} valueEscaped optional. the escaped value of the property.
  12941. */;
  12942. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  12943. if (!this.raws) {
  12944. this.raws = {};
  12945. }
  12946. var originalValue = this[name];
  12947. var originalEscaped = this.raws[name];
  12948. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  12949. if (originalEscaped || valueEscaped !== value) {
  12950. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  12951. } else {
  12952. delete this.raws[name]; // delete any escaped value that was created by the setter.
  12953. }
  12954. }
  12955. /**
  12956. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12957. * This allows the escaped value to be specified directly, allowing illegal
  12958. * characters to be directly inserted into css output.
  12959. * @param {string} name the property to set
  12960. * @param {any} value the unescaped value of the property
  12961. * @param {string} valueEscaped the escaped value of the property.
  12962. */;
  12963. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  12964. if (!this.raws) {
  12965. this.raws = {};
  12966. }
  12967. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  12968. this.raws[name] = valueEscaped;
  12969. }
  12970. /**
  12971. * When you want a value to passed through to CSS directly. This method
  12972. * deletes the corresponding raw value causing the stringifier to fallback
  12973. * to the unescaped value.
  12974. * @param {string} name the property to set.
  12975. * @param {any} value The value that is both escaped and unescaped.
  12976. */;
  12977. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  12978. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  12979. if (this.raws) {
  12980. delete this.raws[name];
  12981. }
  12982. }
  12983. /**
  12984. *
  12985. * @param {number} line The number (starting with 1)
  12986. * @param {number} column The column number (starting with 1)
  12987. */;
  12988. _proto.isAtPosition = function isAtPosition(line, column) {
  12989. if (this.source && this.source.start && this.source.end) {
  12990. if (this.source.start.line > line) {
  12991. return false;
  12992. }
  12993. if (this.source.end.line < line) {
  12994. return false;
  12995. }
  12996. if (this.source.start.line === line && this.source.start.column > column) {
  12997. return false;
  12998. }
  12999. if (this.source.end.line === line && this.source.end.column < column) {
  13000. return false;
  13001. }
  13002. return true;
  13003. }
  13004. return undefined;
  13005. };
  13006. _proto.stringifyProperty = function stringifyProperty(name) {
  13007. return this.raws && this.raws[name] || this[name];
  13008. };
  13009. _proto.valueToString = function valueToString() {
  13010. return String(this.stringifyProperty("value"));
  13011. };
  13012. _proto.toString = function toString() {
  13013. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  13014. };
  13015. _createClass(Node, [{
  13016. key: "rawSpaceBefore",
  13017. get: function get() {
  13018. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  13019. if (rawSpace === undefined) {
  13020. rawSpace = this.spaces && this.spaces.before;
  13021. }
  13022. return rawSpace || "";
  13023. },
  13024. set: function set(raw) {
  13025. (0, _util.ensureObject)(this, "raws", "spaces");
  13026. this.raws.spaces.before = raw;
  13027. }
  13028. }, {
  13029. key: "rawSpaceAfter",
  13030. get: function get() {
  13031. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  13032. if (rawSpace === undefined) {
  13033. rawSpace = this.spaces.after;
  13034. }
  13035. return rawSpace || "";
  13036. },
  13037. set: function set(raw) {
  13038. (0, _util.ensureObject)(this, "raws", "spaces");
  13039. this.raws.spaces.after = raw;
  13040. }
  13041. }]);
  13042. return Node;
  13043. }();
  13044. exports$1["default"] = Node;
  13045. module.exports = exports$1.default;
  13046. } (node, node.exports));
  13047. return node.exports;
  13048. }
  13049. var types$1 = {};
  13050. var hasRequiredTypes;
  13051. function requireTypes () {
  13052. if (hasRequiredTypes) return types$1;
  13053. hasRequiredTypes = 1;
  13054. types$1.__esModule = true;
  13055. 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;
  13056. var TAG = 'tag';
  13057. types$1.TAG = TAG;
  13058. var STRING = 'string';
  13059. types$1.STRING = STRING;
  13060. var SELECTOR = 'selector';
  13061. types$1.SELECTOR = SELECTOR;
  13062. var ROOT = 'root';
  13063. types$1.ROOT = ROOT;
  13064. var PSEUDO = 'pseudo';
  13065. types$1.PSEUDO = PSEUDO;
  13066. var NESTING = 'nesting';
  13067. types$1.NESTING = NESTING;
  13068. var ID = 'id';
  13069. types$1.ID = ID;
  13070. var COMMENT = 'comment';
  13071. types$1.COMMENT = COMMENT;
  13072. var COMBINATOR = 'combinator';
  13073. types$1.COMBINATOR = COMBINATOR;
  13074. var CLASS = 'class';
  13075. types$1.CLASS = CLASS;
  13076. var ATTRIBUTE = 'attribute';
  13077. types$1.ATTRIBUTE = ATTRIBUTE;
  13078. var UNIVERSAL = 'universal';
  13079. types$1.UNIVERSAL = UNIVERSAL;
  13080. return types$1;
  13081. }
  13082. var hasRequiredContainer;
  13083. function requireContainer () {
  13084. if (hasRequiredContainer) return container.exports;
  13085. hasRequiredContainer = 1;
  13086. (function (module, exports$1) {
  13087. exports$1.__esModule = true;
  13088. exports$1["default"] = void 0;
  13089. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13090. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13091. 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); }
  13092. 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; }
  13093. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13094. 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."); }
  13095. 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); }
  13096. 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; }
  13097. 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); } }
  13098. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13099. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13100. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13101. var Container = /*#__PURE__*/function (_Node) {
  13102. _inheritsLoose(Container, _Node);
  13103. function Container(opts) {
  13104. var _this;
  13105. _this = _Node.call(this, opts) || this;
  13106. if (!_this.nodes) {
  13107. _this.nodes = [];
  13108. }
  13109. return _this;
  13110. }
  13111. var _proto = Container.prototype;
  13112. _proto.append = function append(selector) {
  13113. selector.parent = this;
  13114. this.nodes.push(selector);
  13115. return this;
  13116. };
  13117. _proto.prepend = function prepend(selector) {
  13118. selector.parent = this;
  13119. this.nodes.unshift(selector);
  13120. return this;
  13121. };
  13122. _proto.at = function at(index) {
  13123. return this.nodes[index];
  13124. };
  13125. _proto.index = function index(child) {
  13126. if (typeof child === 'number') {
  13127. return child;
  13128. }
  13129. return this.nodes.indexOf(child);
  13130. };
  13131. _proto.removeChild = function removeChild(child) {
  13132. child = this.index(child);
  13133. this.at(child).parent = undefined;
  13134. this.nodes.splice(child, 1);
  13135. var index;
  13136. for (var id in this.indexes) {
  13137. index = this.indexes[id];
  13138. if (index >= child) {
  13139. this.indexes[id] = index - 1;
  13140. }
  13141. }
  13142. return this;
  13143. };
  13144. _proto.removeAll = function removeAll() {
  13145. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13146. var node = _step.value;
  13147. node.parent = undefined;
  13148. }
  13149. this.nodes = [];
  13150. return this;
  13151. };
  13152. _proto.empty = function empty() {
  13153. return this.removeAll();
  13154. };
  13155. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13156. newNode.parent = this;
  13157. var oldIndex = this.index(oldNode);
  13158. this.nodes.splice(oldIndex + 1, 0, newNode);
  13159. newNode.parent = this;
  13160. var index;
  13161. for (var id in this.indexes) {
  13162. index = this.indexes[id];
  13163. if (oldIndex <= index) {
  13164. this.indexes[id] = index + 1;
  13165. }
  13166. }
  13167. return this;
  13168. };
  13169. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13170. newNode.parent = this;
  13171. var oldIndex = this.index(oldNode);
  13172. this.nodes.splice(oldIndex, 0, newNode);
  13173. newNode.parent = this;
  13174. var index;
  13175. for (var id in this.indexes) {
  13176. index = this.indexes[id];
  13177. if (index <= oldIndex) {
  13178. this.indexes[id] = index + 1;
  13179. }
  13180. }
  13181. return this;
  13182. };
  13183. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13184. var found = undefined;
  13185. this.each(function (node) {
  13186. if (node.atPosition) {
  13187. var foundChild = node.atPosition(line, col);
  13188. if (foundChild) {
  13189. found = foundChild;
  13190. return false;
  13191. }
  13192. } else if (node.isAtPosition(line, col)) {
  13193. found = node;
  13194. return false;
  13195. }
  13196. });
  13197. return found;
  13198. }
  13199. /**
  13200. * Return the most specific node at the line and column number given.
  13201. * The source location is based on the original parsed location, locations aren't
  13202. * updated as selector nodes are mutated.
  13203. *
  13204. * Note that this location is relative to the location of the first character
  13205. * of the selector, and not the location of the selector in the overall document
  13206. * when used in conjunction with postcss.
  13207. *
  13208. * If not found, returns undefined.
  13209. * @param {number} line The line number of the node to find. (1-based index)
  13210. * @param {number} col The column number of the node to find. (1-based index)
  13211. */;
  13212. _proto.atPosition = function atPosition(line, col) {
  13213. if (this.isAtPosition(line, col)) {
  13214. return this._findChildAtPosition(line, col) || this;
  13215. } else {
  13216. return undefined;
  13217. }
  13218. };
  13219. _proto._inferEndPosition = function _inferEndPosition() {
  13220. if (this.last && this.last.source && this.last.source.end) {
  13221. this.source = this.source || {};
  13222. this.source.end = this.source.end || {};
  13223. Object.assign(this.source.end, this.last.source.end);
  13224. }
  13225. };
  13226. _proto.each = function each(callback) {
  13227. if (!this.lastEach) {
  13228. this.lastEach = 0;
  13229. }
  13230. if (!this.indexes) {
  13231. this.indexes = {};
  13232. }
  13233. this.lastEach++;
  13234. var id = this.lastEach;
  13235. this.indexes[id] = 0;
  13236. if (!this.length) {
  13237. return undefined;
  13238. }
  13239. var index, result;
  13240. while (this.indexes[id] < this.length) {
  13241. index = this.indexes[id];
  13242. result = callback(this.at(index), index);
  13243. if (result === false) {
  13244. break;
  13245. }
  13246. this.indexes[id] += 1;
  13247. }
  13248. delete this.indexes[id];
  13249. if (result === false) {
  13250. return false;
  13251. }
  13252. };
  13253. _proto.walk = function walk(callback) {
  13254. return this.each(function (node, i) {
  13255. var result = callback(node, i);
  13256. if (result !== false && node.length) {
  13257. result = node.walk(callback);
  13258. }
  13259. if (result === false) {
  13260. return false;
  13261. }
  13262. });
  13263. };
  13264. _proto.walkAttributes = function walkAttributes(callback) {
  13265. var _this2 = this;
  13266. return this.walk(function (selector) {
  13267. if (selector.type === types.ATTRIBUTE) {
  13268. return callback.call(_this2, selector);
  13269. }
  13270. });
  13271. };
  13272. _proto.walkClasses = function walkClasses(callback) {
  13273. var _this3 = this;
  13274. return this.walk(function (selector) {
  13275. if (selector.type === types.CLASS) {
  13276. return callback.call(_this3, selector);
  13277. }
  13278. });
  13279. };
  13280. _proto.walkCombinators = function walkCombinators(callback) {
  13281. var _this4 = this;
  13282. return this.walk(function (selector) {
  13283. if (selector.type === types.COMBINATOR) {
  13284. return callback.call(_this4, selector);
  13285. }
  13286. });
  13287. };
  13288. _proto.walkComments = function walkComments(callback) {
  13289. var _this5 = this;
  13290. return this.walk(function (selector) {
  13291. if (selector.type === types.COMMENT) {
  13292. return callback.call(_this5, selector);
  13293. }
  13294. });
  13295. };
  13296. _proto.walkIds = function walkIds(callback) {
  13297. var _this6 = this;
  13298. return this.walk(function (selector) {
  13299. if (selector.type === types.ID) {
  13300. return callback.call(_this6, selector);
  13301. }
  13302. });
  13303. };
  13304. _proto.walkNesting = function walkNesting(callback) {
  13305. var _this7 = this;
  13306. return this.walk(function (selector) {
  13307. if (selector.type === types.NESTING) {
  13308. return callback.call(_this7, selector);
  13309. }
  13310. });
  13311. };
  13312. _proto.walkPseudos = function walkPseudos(callback) {
  13313. var _this8 = this;
  13314. return this.walk(function (selector) {
  13315. if (selector.type === types.PSEUDO) {
  13316. return callback.call(_this8, selector);
  13317. }
  13318. });
  13319. };
  13320. _proto.walkTags = function walkTags(callback) {
  13321. var _this9 = this;
  13322. return this.walk(function (selector) {
  13323. if (selector.type === types.TAG) {
  13324. return callback.call(_this9, selector);
  13325. }
  13326. });
  13327. };
  13328. _proto.walkUniversals = function walkUniversals(callback) {
  13329. var _this10 = this;
  13330. return this.walk(function (selector) {
  13331. if (selector.type === types.UNIVERSAL) {
  13332. return callback.call(_this10, selector);
  13333. }
  13334. });
  13335. };
  13336. _proto.split = function split(callback) {
  13337. var _this11 = this;
  13338. var current = [];
  13339. return this.reduce(function (memo, node, index) {
  13340. var split = callback.call(_this11, node);
  13341. current.push(node);
  13342. if (split) {
  13343. memo.push(current);
  13344. current = [];
  13345. } else if (index === _this11.length - 1) {
  13346. memo.push(current);
  13347. }
  13348. return memo;
  13349. }, []);
  13350. };
  13351. _proto.map = function map(callback) {
  13352. return this.nodes.map(callback);
  13353. };
  13354. _proto.reduce = function reduce(callback, memo) {
  13355. return this.nodes.reduce(callback, memo);
  13356. };
  13357. _proto.every = function every(callback) {
  13358. return this.nodes.every(callback);
  13359. };
  13360. _proto.some = function some(callback) {
  13361. return this.nodes.some(callback);
  13362. };
  13363. _proto.filter = function filter(callback) {
  13364. return this.nodes.filter(callback);
  13365. };
  13366. _proto.sort = function sort(callback) {
  13367. return this.nodes.sort(callback);
  13368. };
  13369. _proto.toString = function toString() {
  13370. return this.map(String).join('');
  13371. };
  13372. _createClass(Container, [{
  13373. key: "first",
  13374. get: function get() {
  13375. return this.at(0);
  13376. }
  13377. }, {
  13378. key: "last",
  13379. get: function get() {
  13380. return this.at(this.length - 1);
  13381. }
  13382. }, {
  13383. key: "length",
  13384. get: function get() {
  13385. return this.nodes.length;
  13386. }
  13387. }]);
  13388. return Container;
  13389. }(_node["default"]);
  13390. exports$1["default"] = Container;
  13391. module.exports = exports$1.default;
  13392. } (container, container.exports));
  13393. return container.exports;
  13394. }
  13395. var hasRequiredRoot;
  13396. function requireRoot () {
  13397. if (hasRequiredRoot) return root.exports;
  13398. hasRequiredRoot = 1;
  13399. (function (module, exports$1) {
  13400. exports$1.__esModule = true;
  13401. exports$1["default"] = void 0;
  13402. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13403. var _types = /*@__PURE__*/ requireTypes();
  13404. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13405. 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); } }
  13406. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13407. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13408. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13409. var Root = /*#__PURE__*/function (_Container) {
  13410. _inheritsLoose(Root, _Container);
  13411. function Root(opts) {
  13412. var _this;
  13413. _this = _Container.call(this, opts) || this;
  13414. _this.type = _types.ROOT;
  13415. return _this;
  13416. }
  13417. var _proto = Root.prototype;
  13418. _proto.toString = function toString() {
  13419. var str = this.reduce(function (memo, selector) {
  13420. memo.push(String(selector));
  13421. return memo;
  13422. }, []).join(',');
  13423. return this.trailingComma ? str + ',' : str;
  13424. };
  13425. _proto.error = function error(message, options) {
  13426. if (this._error) {
  13427. return this._error(message, options);
  13428. } else {
  13429. return new Error(message);
  13430. }
  13431. };
  13432. _createClass(Root, [{
  13433. key: "errorGenerator",
  13434. set: function set(handler) {
  13435. this._error = handler;
  13436. }
  13437. }]);
  13438. return Root;
  13439. }(_container["default"]);
  13440. exports$1["default"] = Root;
  13441. module.exports = exports$1.default;
  13442. } (root, root.exports));
  13443. return root.exports;
  13444. }
  13445. var selector = {exports: {}};
  13446. var hasRequiredSelector;
  13447. function requireSelector () {
  13448. if (hasRequiredSelector) return selector.exports;
  13449. hasRequiredSelector = 1;
  13450. (function (module, exports$1) {
  13451. exports$1.__esModule = true;
  13452. exports$1["default"] = void 0;
  13453. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13454. var _types = /*@__PURE__*/ requireTypes();
  13455. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13456. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13457. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13458. var Selector = /*#__PURE__*/function (_Container) {
  13459. _inheritsLoose(Selector, _Container);
  13460. function Selector(opts) {
  13461. var _this;
  13462. _this = _Container.call(this, opts) || this;
  13463. _this.type = _types.SELECTOR;
  13464. return _this;
  13465. }
  13466. return Selector;
  13467. }(_container["default"]);
  13468. exports$1["default"] = Selector;
  13469. module.exports = exports$1.default;
  13470. } (selector, selector.exports));
  13471. return selector.exports;
  13472. }
  13473. var className = {exports: {}};
  13474. var hasRequiredClassName;
  13475. function requireClassName () {
  13476. if (hasRequiredClassName) return className.exports;
  13477. hasRequiredClassName = 1;
  13478. (function (module, exports$1) {
  13479. exports$1.__esModule = true;
  13480. exports$1["default"] = void 0;
  13481. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13482. var _util = /*@__PURE__*/ requireUtil();
  13483. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13484. var _types = /*@__PURE__*/ requireTypes();
  13485. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13486. 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); } }
  13487. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13488. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13489. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13490. var ClassName = /*#__PURE__*/function (_Node) {
  13491. _inheritsLoose(ClassName, _Node);
  13492. function ClassName(opts) {
  13493. var _this;
  13494. _this = _Node.call(this, opts) || this;
  13495. _this.type = _types.CLASS;
  13496. _this._constructed = true;
  13497. return _this;
  13498. }
  13499. var _proto = ClassName.prototype;
  13500. _proto.valueToString = function valueToString() {
  13501. return '.' + _Node.prototype.valueToString.call(this);
  13502. };
  13503. _createClass(ClassName, [{
  13504. key: "value",
  13505. get: function get() {
  13506. return this._value;
  13507. },
  13508. set: function set(v) {
  13509. if (this._constructed) {
  13510. var escaped = (0, _cssesc["default"])(v, {
  13511. isIdentifier: true
  13512. });
  13513. if (escaped !== v) {
  13514. (0, _util.ensureObject)(this, "raws");
  13515. this.raws.value = escaped;
  13516. } else if (this.raws) {
  13517. delete this.raws.value;
  13518. }
  13519. }
  13520. this._value = v;
  13521. }
  13522. }]);
  13523. return ClassName;
  13524. }(_node["default"]);
  13525. exports$1["default"] = ClassName;
  13526. module.exports = exports$1.default;
  13527. } (className, className.exports));
  13528. return className.exports;
  13529. }
  13530. var comment = {exports: {}};
  13531. var hasRequiredComment;
  13532. function requireComment () {
  13533. if (hasRequiredComment) return comment.exports;
  13534. hasRequiredComment = 1;
  13535. (function (module, exports$1) {
  13536. exports$1.__esModule = true;
  13537. exports$1["default"] = void 0;
  13538. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13539. var _types = /*@__PURE__*/ requireTypes();
  13540. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13541. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13542. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13543. var Comment = /*#__PURE__*/function (_Node) {
  13544. _inheritsLoose(Comment, _Node);
  13545. function Comment(opts) {
  13546. var _this;
  13547. _this = _Node.call(this, opts) || this;
  13548. _this.type = _types.COMMENT;
  13549. return _this;
  13550. }
  13551. return Comment;
  13552. }(_node["default"]);
  13553. exports$1["default"] = Comment;
  13554. module.exports = exports$1.default;
  13555. } (comment, comment.exports));
  13556. return comment.exports;
  13557. }
  13558. var id = {exports: {}};
  13559. var hasRequiredId;
  13560. function requireId () {
  13561. if (hasRequiredId) return id.exports;
  13562. hasRequiredId = 1;
  13563. (function (module, exports$1) {
  13564. exports$1.__esModule = true;
  13565. exports$1["default"] = void 0;
  13566. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13567. var _types = /*@__PURE__*/ requireTypes();
  13568. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13569. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13570. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13571. var ID = /*#__PURE__*/function (_Node) {
  13572. _inheritsLoose(ID, _Node);
  13573. function ID(opts) {
  13574. var _this;
  13575. _this = _Node.call(this, opts) || this;
  13576. _this.type = _types.ID;
  13577. return _this;
  13578. }
  13579. var _proto = ID.prototype;
  13580. _proto.valueToString = function valueToString() {
  13581. return '#' + _Node.prototype.valueToString.call(this);
  13582. };
  13583. return ID;
  13584. }(_node["default"]);
  13585. exports$1["default"] = ID;
  13586. module.exports = exports$1.default;
  13587. } (id, id.exports));
  13588. return id.exports;
  13589. }
  13590. var tag = {exports: {}};
  13591. var namespace = {exports: {}};
  13592. var hasRequiredNamespace;
  13593. function requireNamespace () {
  13594. if (hasRequiredNamespace) return namespace.exports;
  13595. hasRequiredNamespace = 1;
  13596. (function (module, exports$1) {
  13597. exports$1.__esModule = true;
  13598. exports$1["default"] = void 0;
  13599. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13600. var _util = /*@__PURE__*/ requireUtil();
  13601. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13602. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13603. 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); } }
  13604. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13605. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13606. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13607. var Namespace = /*#__PURE__*/function (_Node) {
  13608. _inheritsLoose(Namespace, _Node);
  13609. function Namespace() {
  13610. return _Node.apply(this, arguments) || this;
  13611. }
  13612. var _proto = Namespace.prototype;
  13613. _proto.qualifiedName = function qualifiedName(value) {
  13614. if (this.namespace) {
  13615. return this.namespaceString + "|" + value;
  13616. } else {
  13617. return value;
  13618. }
  13619. };
  13620. _proto.valueToString = function valueToString() {
  13621. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  13622. };
  13623. _createClass(Namespace, [{
  13624. key: "namespace",
  13625. get: function get() {
  13626. return this._namespace;
  13627. },
  13628. set: function set(namespace) {
  13629. if (namespace === true || namespace === "*" || namespace === "&") {
  13630. this._namespace = namespace;
  13631. if (this.raws) {
  13632. delete this.raws.namespace;
  13633. }
  13634. return;
  13635. }
  13636. var escaped = (0, _cssesc["default"])(namespace, {
  13637. isIdentifier: true
  13638. });
  13639. this._namespace = namespace;
  13640. if (escaped !== namespace) {
  13641. (0, _util.ensureObject)(this, "raws");
  13642. this.raws.namespace = escaped;
  13643. } else if (this.raws) {
  13644. delete this.raws.namespace;
  13645. }
  13646. }
  13647. }, {
  13648. key: "ns",
  13649. get: function get() {
  13650. return this._namespace;
  13651. },
  13652. set: function set(namespace) {
  13653. this.namespace = namespace;
  13654. }
  13655. }, {
  13656. key: "namespaceString",
  13657. get: function get() {
  13658. if (this.namespace) {
  13659. var ns = this.stringifyProperty("namespace");
  13660. if (ns === true) {
  13661. return '';
  13662. } else {
  13663. return ns;
  13664. }
  13665. } else {
  13666. return '';
  13667. }
  13668. }
  13669. }]);
  13670. return Namespace;
  13671. }(_node["default"]);
  13672. exports$1["default"] = Namespace;
  13673. module.exports = exports$1.default;
  13674. } (namespace, namespace.exports));
  13675. return namespace.exports;
  13676. }
  13677. var hasRequiredTag;
  13678. function requireTag () {
  13679. if (hasRequiredTag) return tag.exports;
  13680. hasRequiredTag = 1;
  13681. (function (module, exports$1) {
  13682. exports$1.__esModule = true;
  13683. exports$1["default"] = void 0;
  13684. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13685. var _types = /*@__PURE__*/ requireTypes();
  13686. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13687. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13688. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13689. var Tag = /*#__PURE__*/function (_Namespace) {
  13690. _inheritsLoose(Tag, _Namespace);
  13691. function Tag(opts) {
  13692. var _this;
  13693. _this = _Namespace.call(this, opts) || this;
  13694. _this.type = _types.TAG;
  13695. return _this;
  13696. }
  13697. return Tag;
  13698. }(_namespace["default"]);
  13699. exports$1["default"] = Tag;
  13700. module.exports = exports$1.default;
  13701. } (tag, tag.exports));
  13702. return tag.exports;
  13703. }
  13704. var string = {exports: {}};
  13705. var hasRequiredString;
  13706. function requireString () {
  13707. if (hasRequiredString) return string.exports;
  13708. hasRequiredString = 1;
  13709. (function (module, exports$1) {
  13710. exports$1.__esModule = true;
  13711. exports$1["default"] = void 0;
  13712. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13713. var _types = /*@__PURE__*/ requireTypes();
  13714. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13715. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13716. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13717. var String = /*#__PURE__*/function (_Node) {
  13718. _inheritsLoose(String, _Node);
  13719. function String(opts) {
  13720. var _this;
  13721. _this = _Node.call(this, opts) || this;
  13722. _this.type = _types.STRING;
  13723. return _this;
  13724. }
  13725. return String;
  13726. }(_node["default"]);
  13727. exports$1["default"] = String;
  13728. module.exports = exports$1.default;
  13729. } (string, string.exports));
  13730. return string.exports;
  13731. }
  13732. var pseudo = {exports: {}};
  13733. var hasRequiredPseudo;
  13734. function requirePseudo () {
  13735. if (hasRequiredPseudo) return pseudo.exports;
  13736. hasRequiredPseudo = 1;
  13737. (function (module, exports$1) {
  13738. exports$1.__esModule = true;
  13739. exports$1["default"] = void 0;
  13740. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13741. var _types = /*@__PURE__*/ requireTypes();
  13742. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13743. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13744. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13745. var Pseudo = /*#__PURE__*/function (_Container) {
  13746. _inheritsLoose(Pseudo, _Container);
  13747. function Pseudo(opts) {
  13748. var _this;
  13749. _this = _Container.call(this, opts) || this;
  13750. _this.type = _types.PSEUDO;
  13751. return _this;
  13752. }
  13753. var _proto = Pseudo.prototype;
  13754. _proto.toString = function toString() {
  13755. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  13756. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  13757. };
  13758. return Pseudo;
  13759. }(_container["default"]);
  13760. exports$1["default"] = Pseudo;
  13761. module.exports = exports$1.default;
  13762. } (pseudo, pseudo.exports));
  13763. return pseudo.exports;
  13764. }
  13765. var attribute = {};
  13766. var hasRequiredAttribute;
  13767. function requireAttribute () {
  13768. if (hasRequiredAttribute) return attribute;
  13769. hasRequiredAttribute = 1;
  13770. (function (exports$1) {
  13771. exports$1.__esModule = true;
  13772. exports$1["default"] = void 0;
  13773. exports$1.unescapeValue = unescapeValue;
  13774. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13775. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13776. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13777. var _types = /*@__PURE__*/ requireTypes();
  13778. var _CSSESC_QUOTE_OPTIONS;
  13779. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13780. 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); } }
  13781. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13782. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13783. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13784. var deprecate = /*@__PURE__*/ requireNode$1();
  13785. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  13786. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  13787. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  13788. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  13789. function unescapeValue(value) {
  13790. var deprecatedUsage = false;
  13791. var quoteMark = null;
  13792. var unescaped = value;
  13793. var m = unescaped.match(WRAPPED_IN_QUOTES);
  13794. if (m) {
  13795. quoteMark = m[1];
  13796. unescaped = m[2];
  13797. }
  13798. unescaped = (0, _unesc["default"])(unescaped);
  13799. if (unescaped !== value) {
  13800. deprecatedUsage = true;
  13801. }
  13802. return {
  13803. deprecatedUsage: deprecatedUsage,
  13804. unescaped: unescaped,
  13805. quoteMark: quoteMark
  13806. };
  13807. }
  13808. function handleDeprecatedContructorOpts(opts) {
  13809. if (opts.quoteMark !== undefined) {
  13810. return opts;
  13811. }
  13812. if (opts.value === undefined) {
  13813. return opts;
  13814. }
  13815. warnOfDeprecatedConstructor();
  13816. var _unescapeValue = unescapeValue(opts.value),
  13817. quoteMark = _unescapeValue.quoteMark,
  13818. unescaped = _unescapeValue.unescaped;
  13819. if (!opts.raws) {
  13820. opts.raws = {};
  13821. }
  13822. if (opts.raws.value === undefined) {
  13823. opts.raws.value = opts.value;
  13824. }
  13825. opts.value = unescaped;
  13826. opts.quoteMark = quoteMark;
  13827. return opts;
  13828. }
  13829. var Attribute = /*#__PURE__*/function (_Namespace) {
  13830. _inheritsLoose(Attribute, _Namespace);
  13831. function Attribute(opts) {
  13832. var _this;
  13833. if (opts === void 0) {
  13834. opts = {};
  13835. }
  13836. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  13837. _this.type = _types.ATTRIBUTE;
  13838. _this.raws = _this.raws || {};
  13839. Object.defineProperty(_this.raws, 'unquoted', {
  13840. get: deprecate(function () {
  13841. return _this.value;
  13842. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  13843. set: deprecate(function () {
  13844. return _this.value;
  13845. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  13846. });
  13847. _this._constructed = true;
  13848. return _this;
  13849. }
  13850. /**
  13851. * Returns the Attribute's value quoted such that it would be legal to use
  13852. * in the value of a css file. The original value's quotation setting
  13853. * used for stringification is left unchanged. See `setValue(value, options)`
  13854. * if you want to control the quote settings of a new value for the attribute.
  13855. *
  13856. * You can also change the quotation used for the current value by setting quoteMark.
  13857. *
  13858. * Options:
  13859. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  13860. * option is not set, the original value for quoteMark will be used. If
  13861. * indeterminate, a double quote is used. The legal values are:
  13862. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  13863. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  13864. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  13865. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  13866. * over the quoteMark option value.
  13867. * * smart {boolean} - if true, will select a quote mark based on the value
  13868. * and the other options specified here. See the `smartQuoteMark()`
  13869. * method.
  13870. **/
  13871. var _proto = Attribute.prototype;
  13872. _proto.getQuotedValue = function getQuotedValue(options) {
  13873. if (options === void 0) {
  13874. options = {};
  13875. }
  13876. var quoteMark = this._determineQuoteMark(options);
  13877. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  13878. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  13879. return escaped;
  13880. };
  13881. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  13882. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  13883. }
  13884. /**
  13885. * Set the unescaped value with the specified quotation options. The value
  13886. * provided must not include any wrapping quote marks -- those quotes will
  13887. * be interpreted as part of the value and escaped accordingly.
  13888. */;
  13889. _proto.setValue = function setValue(value, options) {
  13890. if (options === void 0) {
  13891. options = {};
  13892. }
  13893. this._value = value;
  13894. this._quoteMark = this._determineQuoteMark(options);
  13895. this._syncRawValue();
  13896. }
  13897. /**
  13898. * Intelligently select a quoteMark value based on the value's contents. If
  13899. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  13900. * mark will be picked that minimizes the number of escapes.
  13901. *
  13902. * If there's no clear winner, the quote mark from these options is used,
  13903. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  13904. * true). If the quoteMark is unspecified, a double quote is used.
  13905. *
  13906. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  13907. * from the quoteValue method.
  13908. */;
  13909. _proto.smartQuoteMark = function smartQuoteMark(options) {
  13910. var v = this.value;
  13911. var numSingleQuotes = v.replace(/[^']/g, '').length;
  13912. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  13913. if (numSingleQuotes + numDoubleQuotes === 0) {
  13914. var escaped = (0, _cssesc["default"])(v, {
  13915. isIdentifier: true
  13916. });
  13917. if (escaped === v) {
  13918. return Attribute.NO_QUOTE;
  13919. } else {
  13920. var pref = this.preferredQuoteMark(options);
  13921. if (pref === Attribute.NO_QUOTE) {
  13922. // pick a quote mark that isn't none and see if it's smaller
  13923. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  13924. var opts = CSSESC_QUOTE_OPTIONS[quote];
  13925. var quoteValue = (0, _cssesc["default"])(v, opts);
  13926. if (quoteValue.length < escaped.length) {
  13927. return quote;
  13928. }
  13929. }
  13930. return pref;
  13931. }
  13932. } else if (numDoubleQuotes === numSingleQuotes) {
  13933. return this.preferredQuoteMark(options);
  13934. } else if (numDoubleQuotes < numSingleQuotes) {
  13935. return Attribute.DOUBLE_QUOTE;
  13936. } else {
  13937. return Attribute.SINGLE_QUOTE;
  13938. }
  13939. }
  13940. /**
  13941. * Selects the preferred quote mark based on the options and the current quote mark value.
  13942. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  13943. * instead.
  13944. */;
  13945. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  13946. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  13947. if (quoteMark === undefined) {
  13948. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  13949. }
  13950. if (quoteMark === undefined) {
  13951. quoteMark = Attribute.DOUBLE_QUOTE;
  13952. }
  13953. return quoteMark;
  13954. };
  13955. _proto._syncRawValue = function _syncRawValue() {
  13956. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  13957. if (rawValue === this._value) {
  13958. if (this.raws) {
  13959. delete this.raws.value;
  13960. }
  13961. } else {
  13962. this.raws.value = rawValue;
  13963. }
  13964. };
  13965. _proto._handleEscapes = function _handleEscapes(prop, value) {
  13966. if (this._constructed) {
  13967. var escaped = (0, _cssesc["default"])(value, {
  13968. isIdentifier: true
  13969. });
  13970. if (escaped !== value) {
  13971. this.raws[prop] = escaped;
  13972. } else {
  13973. delete this.raws[prop];
  13974. }
  13975. }
  13976. };
  13977. _proto._spacesFor = function _spacesFor(name) {
  13978. var attrSpaces = {
  13979. before: '',
  13980. after: ''
  13981. };
  13982. var spaces = this.spaces[name] || {};
  13983. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  13984. return Object.assign(attrSpaces, spaces, rawSpaces);
  13985. };
  13986. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  13987. if (spaceName === void 0) {
  13988. spaceName = name;
  13989. }
  13990. if (concat === void 0) {
  13991. concat = defaultAttrConcat;
  13992. }
  13993. var attrSpaces = this._spacesFor(spaceName);
  13994. return concat(this.stringifyProperty(name), attrSpaces);
  13995. }
  13996. /**
  13997. * returns the offset of the attribute part specified relative to the
  13998. * start of the node of the output string.
  13999. *
  14000. * * "ns" - alias for "namespace"
  14001. * * "namespace" - the namespace if it exists.
  14002. * * "attribute" - the attribute name
  14003. * * "attributeNS" - the start of the attribute or its namespace
  14004. * * "operator" - the match operator of the attribute
  14005. * * "value" - The value (string or identifier)
  14006. * * "insensitive" - the case insensitivity flag;
  14007. * @param part One of the possible values inside an attribute.
  14008. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  14009. */;
  14010. _proto.offsetOf = function offsetOf(name) {
  14011. var count = 1;
  14012. var attributeSpaces = this._spacesFor("attribute");
  14013. count += attributeSpaces.before.length;
  14014. if (name === "namespace" || name === "ns") {
  14015. return this.namespace ? count : -1;
  14016. }
  14017. if (name === "attributeNS") {
  14018. return count;
  14019. }
  14020. count += this.namespaceString.length;
  14021. if (this.namespace) {
  14022. count += 1;
  14023. }
  14024. if (name === "attribute") {
  14025. return count;
  14026. }
  14027. count += this.stringifyProperty("attribute").length;
  14028. count += attributeSpaces.after.length;
  14029. var operatorSpaces = this._spacesFor("operator");
  14030. count += operatorSpaces.before.length;
  14031. var operator = this.stringifyProperty("operator");
  14032. if (name === "operator") {
  14033. return operator ? count : -1;
  14034. }
  14035. count += operator.length;
  14036. count += operatorSpaces.after.length;
  14037. var valueSpaces = this._spacesFor("value");
  14038. count += valueSpaces.before.length;
  14039. var value = this.stringifyProperty("value");
  14040. if (name === "value") {
  14041. return value ? count : -1;
  14042. }
  14043. count += value.length;
  14044. count += valueSpaces.after.length;
  14045. var insensitiveSpaces = this._spacesFor("insensitive");
  14046. count += insensitiveSpaces.before.length;
  14047. if (name === "insensitive") {
  14048. return this.insensitive ? count : -1;
  14049. }
  14050. return -1;
  14051. };
  14052. _proto.toString = function toString() {
  14053. var _this2 = this;
  14054. var selector = [this.rawSpaceBefore, '['];
  14055. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14056. if (this.operator && (this.value || this.value === '')) {
  14057. selector.push(this._stringFor('operator'));
  14058. selector.push(this._stringFor('value'));
  14059. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14060. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14061. attrSpaces.before = " ";
  14062. }
  14063. return defaultAttrConcat(attrValue, attrSpaces);
  14064. }));
  14065. }
  14066. selector.push(']');
  14067. selector.push(this.rawSpaceAfter);
  14068. return selector.join('');
  14069. };
  14070. _createClass(Attribute, [{
  14071. key: "quoted",
  14072. get: function get() {
  14073. var qm = this.quoteMark;
  14074. return qm === "'" || qm === '"';
  14075. },
  14076. set: function set(value) {
  14077. warnOfDeprecatedQuotedAssignment();
  14078. }
  14079. /**
  14080. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14081. * returns `null` if the value is not quoted.
  14082. * returns `undefined` if the quotation state is unknown (this can happen when
  14083. * the attribute is constructed without specifying a quote mark.)
  14084. */
  14085. }, {
  14086. key: "quoteMark",
  14087. get: function get() {
  14088. return this._quoteMark;
  14089. }
  14090. /**
  14091. * Set the quote mark to be used by this attribute's value.
  14092. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14093. * value is updated accordingly.
  14094. *
  14095. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14096. */,
  14097. set: function set(quoteMark) {
  14098. if (!this._constructed) {
  14099. this._quoteMark = quoteMark;
  14100. return;
  14101. }
  14102. if (this._quoteMark !== quoteMark) {
  14103. this._quoteMark = quoteMark;
  14104. this._syncRawValue();
  14105. }
  14106. }
  14107. }, {
  14108. key: "qualifiedAttribute",
  14109. get: function get() {
  14110. return this.qualifiedName(this.raws.attribute || this.attribute);
  14111. }
  14112. }, {
  14113. key: "insensitiveFlag",
  14114. get: function get() {
  14115. return this.insensitive ? 'i' : '';
  14116. }
  14117. }, {
  14118. key: "value",
  14119. get: function get() {
  14120. return this._value;
  14121. },
  14122. set:
  14123. /**
  14124. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14125. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14126. * is unescaped during parsing and any quote marks are removed.
  14127. *
  14128. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14129. * a deprecation warning is raised when the new value contains any characters that would
  14130. * require escaping (including if it contains wrapped quotes).
  14131. *
  14132. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14133. * how the new value is quoted.
  14134. */
  14135. function set(v) {
  14136. if (this._constructed) {
  14137. var _unescapeValue2 = unescapeValue(v),
  14138. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14139. unescaped = _unescapeValue2.unescaped,
  14140. quoteMark = _unescapeValue2.quoteMark;
  14141. if (deprecatedUsage) {
  14142. warnOfDeprecatedValueAssignment();
  14143. }
  14144. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14145. return;
  14146. }
  14147. this._value = unescaped;
  14148. this._quoteMark = quoteMark;
  14149. this._syncRawValue();
  14150. } else {
  14151. this._value = v;
  14152. }
  14153. }
  14154. }, {
  14155. key: "insensitive",
  14156. get: function get() {
  14157. return this._insensitive;
  14158. }
  14159. /**
  14160. * Set the case insensitive flag.
  14161. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14162. * of the attribute is updated accordingly.
  14163. *
  14164. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14165. */,
  14166. set: function set(insensitive) {
  14167. if (!insensitive) {
  14168. this._insensitive = false;
  14169. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14170. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14171. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14172. this.raws.insensitiveFlag = undefined;
  14173. }
  14174. }
  14175. this._insensitive = insensitive;
  14176. }
  14177. }, {
  14178. key: "attribute",
  14179. get: function get() {
  14180. return this._attribute;
  14181. },
  14182. set: function set(name) {
  14183. this._handleEscapes("attribute", name);
  14184. this._attribute = name;
  14185. }
  14186. }]);
  14187. return Attribute;
  14188. }(_namespace["default"]);
  14189. exports$1["default"] = Attribute;
  14190. Attribute.NO_QUOTE = null;
  14191. Attribute.SINGLE_QUOTE = "'";
  14192. Attribute.DOUBLE_QUOTE = '"';
  14193. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14194. "'": {
  14195. quotes: 'single',
  14196. wrap: true
  14197. },
  14198. '"': {
  14199. quotes: 'double',
  14200. wrap: true
  14201. }
  14202. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14203. isIdentifier: true
  14204. }, _CSSESC_QUOTE_OPTIONS);
  14205. function defaultAttrConcat(attrValue, attrSpaces) {
  14206. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14207. }
  14208. } (attribute));
  14209. return attribute;
  14210. }
  14211. var universal = {exports: {}};
  14212. var hasRequiredUniversal;
  14213. function requireUniversal () {
  14214. if (hasRequiredUniversal) return universal.exports;
  14215. hasRequiredUniversal = 1;
  14216. (function (module, exports$1) {
  14217. exports$1.__esModule = true;
  14218. exports$1["default"] = void 0;
  14219. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14220. var _types = /*@__PURE__*/ requireTypes();
  14221. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14222. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14223. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14224. var Universal = /*#__PURE__*/function (_Namespace) {
  14225. _inheritsLoose(Universal, _Namespace);
  14226. function Universal(opts) {
  14227. var _this;
  14228. _this = _Namespace.call(this, opts) || this;
  14229. _this.type = _types.UNIVERSAL;
  14230. _this.value = '*';
  14231. return _this;
  14232. }
  14233. return Universal;
  14234. }(_namespace["default"]);
  14235. exports$1["default"] = Universal;
  14236. module.exports = exports$1.default;
  14237. } (universal, universal.exports));
  14238. return universal.exports;
  14239. }
  14240. var combinator = {exports: {}};
  14241. var hasRequiredCombinator;
  14242. function requireCombinator () {
  14243. if (hasRequiredCombinator) return combinator.exports;
  14244. hasRequiredCombinator = 1;
  14245. (function (module, exports$1) {
  14246. exports$1.__esModule = true;
  14247. exports$1["default"] = void 0;
  14248. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14249. var _types = /*@__PURE__*/ requireTypes();
  14250. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14251. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14252. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14253. var Combinator = /*#__PURE__*/function (_Node) {
  14254. _inheritsLoose(Combinator, _Node);
  14255. function Combinator(opts) {
  14256. var _this;
  14257. _this = _Node.call(this, opts) || this;
  14258. _this.type = _types.COMBINATOR;
  14259. return _this;
  14260. }
  14261. return Combinator;
  14262. }(_node["default"]);
  14263. exports$1["default"] = Combinator;
  14264. module.exports = exports$1.default;
  14265. } (combinator, combinator.exports));
  14266. return combinator.exports;
  14267. }
  14268. var nesting = {exports: {}};
  14269. var hasRequiredNesting;
  14270. function requireNesting () {
  14271. if (hasRequiredNesting) return nesting.exports;
  14272. hasRequiredNesting = 1;
  14273. (function (module, exports$1) {
  14274. exports$1.__esModule = true;
  14275. exports$1["default"] = void 0;
  14276. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14277. var _types = /*@__PURE__*/ requireTypes();
  14278. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14279. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14280. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14281. var Nesting = /*#__PURE__*/function (_Node) {
  14282. _inheritsLoose(Nesting, _Node);
  14283. function Nesting(opts) {
  14284. var _this;
  14285. _this = _Node.call(this, opts) || this;
  14286. _this.type = _types.NESTING;
  14287. _this.value = '&';
  14288. return _this;
  14289. }
  14290. return Nesting;
  14291. }(_node["default"]);
  14292. exports$1["default"] = Nesting;
  14293. module.exports = exports$1.default;
  14294. } (nesting, nesting.exports));
  14295. return nesting.exports;
  14296. }
  14297. var sortAscending = {exports: {}};
  14298. var hasRequiredSortAscending;
  14299. function requireSortAscending () {
  14300. if (hasRequiredSortAscending) return sortAscending.exports;
  14301. hasRequiredSortAscending = 1;
  14302. (function (module, exports$1) {
  14303. exports$1.__esModule = true;
  14304. exports$1["default"] = sortAscending;
  14305. function sortAscending(list) {
  14306. return list.sort(function (a, b) {
  14307. return a - b;
  14308. });
  14309. }
  14310. module.exports = exports$1.default;
  14311. } (sortAscending, sortAscending.exports));
  14312. return sortAscending.exports;
  14313. }
  14314. var tokenize = {};
  14315. var tokenTypes = {};
  14316. var hasRequiredTokenTypes;
  14317. function requireTokenTypes () {
  14318. if (hasRequiredTokenTypes) return tokenTypes;
  14319. hasRequiredTokenTypes = 1;
  14320. tokenTypes.__esModule = true;
  14321. 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;
  14322. var ampersand = 38; // `&`.charCodeAt(0);
  14323. tokenTypes.ampersand = ampersand;
  14324. var asterisk = 42; // `*`.charCodeAt(0);
  14325. tokenTypes.asterisk = asterisk;
  14326. var at = 64; // `@`.charCodeAt(0);
  14327. tokenTypes.at = at;
  14328. var comma = 44; // `,`.charCodeAt(0);
  14329. tokenTypes.comma = comma;
  14330. var colon = 58; // `:`.charCodeAt(0);
  14331. tokenTypes.colon = colon;
  14332. var semicolon = 59; // `;`.charCodeAt(0);
  14333. tokenTypes.semicolon = semicolon;
  14334. var openParenthesis = 40; // `(`.charCodeAt(0);
  14335. tokenTypes.openParenthesis = openParenthesis;
  14336. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14337. tokenTypes.closeParenthesis = closeParenthesis;
  14338. var openSquare = 91; // `[`.charCodeAt(0);
  14339. tokenTypes.openSquare = openSquare;
  14340. var closeSquare = 93; // `]`.charCodeAt(0);
  14341. tokenTypes.closeSquare = closeSquare;
  14342. var dollar = 36; // `$`.charCodeAt(0);
  14343. tokenTypes.dollar = dollar;
  14344. var tilde = 126; // `~`.charCodeAt(0);
  14345. tokenTypes.tilde = tilde;
  14346. var caret = 94; // `^`.charCodeAt(0);
  14347. tokenTypes.caret = caret;
  14348. var plus = 43; // `+`.charCodeAt(0);
  14349. tokenTypes.plus = plus;
  14350. var equals = 61; // `=`.charCodeAt(0);
  14351. tokenTypes.equals = equals;
  14352. var pipe = 124; // `|`.charCodeAt(0);
  14353. tokenTypes.pipe = pipe;
  14354. var greaterThan = 62; // `>`.charCodeAt(0);
  14355. tokenTypes.greaterThan = greaterThan;
  14356. var space = 32; // ` `.charCodeAt(0);
  14357. tokenTypes.space = space;
  14358. var singleQuote = 39; // `'`.charCodeAt(0);
  14359. tokenTypes.singleQuote = singleQuote;
  14360. var doubleQuote = 34; // `"`.charCodeAt(0);
  14361. tokenTypes.doubleQuote = doubleQuote;
  14362. var slash = 47; // `/`.charCodeAt(0);
  14363. tokenTypes.slash = slash;
  14364. var bang = 33; // `!`.charCodeAt(0);
  14365. tokenTypes.bang = bang;
  14366. var backslash = 92; // '\\'.charCodeAt(0);
  14367. tokenTypes.backslash = backslash;
  14368. var cr = 13; // '\r'.charCodeAt(0);
  14369. tokenTypes.cr = cr;
  14370. var feed = 12; // '\f'.charCodeAt(0);
  14371. tokenTypes.feed = feed;
  14372. var newline = 10; // '\n'.charCodeAt(0);
  14373. tokenTypes.newline = newline;
  14374. var tab = 9; // '\t'.charCodeAt(0);
  14375. // Expose aliases primarily for readability.
  14376. tokenTypes.tab = tab;
  14377. var str = singleQuote;
  14378. // No good single character representation!
  14379. tokenTypes.str = str;
  14380. var comment = -1;
  14381. tokenTypes.comment = comment;
  14382. var word = -2;
  14383. tokenTypes.word = word;
  14384. var combinator = -3;
  14385. tokenTypes.combinator = combinator;
  14386. return tokenTypes;
  14387. }
  14388. var hasRequiredTokenize;
  14389. function requireTokenize () {
  14390. if (hasRequiredTokenize) return tokenize;
  14391. hasRequiredTokenize = 1;
  14392. (function (exports$1) {
  14393. exports$1.__esModule = true;
  14394. exports$1.FIELDS = void 0;
  14395. exports$1["default"] = tokenize;
  14396. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14397. var _unescapable, _wordDelimiters;
  14398. 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); }
  14399. 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; }
  14400. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14401. 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);
  14402. var hex = {};
  14403. var hexChars = "0123456789abcdefABCDEF";
  14404. for (var i = 0; i < hexChars.length; i++) {
  14405. hex[hexChars.charCodeAt(i)] = true;
  14406. }
  14407. /**
  14408. * Returns the last index of the bar css word
  14409. * @param {string} css The string in which the word begins
  14410. * @param {number} start The index into the string where word's first letter occurs
  14411. */
  14412. function consumeWord(css, start) {
  14413. var next = start;
  14414. var code;
  14415. do {
  14416. code = css.charCodeAt(next);
  14417. if (wordDelimiters[code]) {
  14418. return next - 1;
  14419. } else if (code === t.backslash) {
  14420. next = consumeEscape(css, next) + 1;
  14421. } else {
  14422. // All other characters are part of the word
  14423. next++;
  14424. }
  14425. } while (next < css.length);
  14426. return next - 1;
  14427. }
  14428. /**
  14429. * Returns the last index of the escape sequence
  14430. * @param {string} css The string in which the sequence begins
  14431. * @param {number} start The index into the string where escape character (`\`) occurs.
  14432. */
  14433. function consumeEscape(css, start) {
  14434. var next = start;
  14435. var code = css.charCodeAt(next + 1);
  14436. if (unescapable[code]) ; else if (hex[code]) {
  14437. var hexDigits = 0;
  14438. // consume up to 6 hex chars
  14439. do {
  14440. next++;
  14441. hexDigits++;
  14442. code = css.charCodeAt(next + 1);
  14443. } while (hex[code] && hexDigits < 6);
  14444. // if fewer than 6 hex chars, a trailing space ends the escape
  14445. if (hexDigits < 6 && code === t.space) {
  14446. next++;
  14447. }
  14448. } else {
  14449. // the next char is part of the current word
  14450. next++;
  14451. }
  14452. return next;
  14453. }
  14454. var FIELDS = {
  14455. TYPE: 0,
  14456. START_LINE: 1,
  14457. START_COL: 2,
  14458. END_LINE: 3,
  14459. END_COL: 4,
  14460. START_POS: 5,
  14461. END_POS: 6
  14462. };
  14463. exports$1.FIELDS = FIELDS;
  14464. function tokenize(input) {
  14465. var tokens = [];
  14466. var css = input.css.valueOf();
  14467. var _css = css,
  14468. length = _css.length;
  14469. var offset = -1;
  14470. var line = 1;
  14471. var start = 0;
  14472. var end = 0;
  14473. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14474. function unclosed(what, fix) {
  14475. if (input.safe) {
  14476. // fyi: this is never set to true.
  14477. css += fix;
  14478. next = css.length - 1;
  14479. } else {
  14480. throw input.error('Unclosed ' + what, line, start - offset, start);
  14481. }
  14482. }
  14483. while (start < length) {
  14484. code = css.charCodeAt(start);
  14485. if (code === t.newline) {
  14486. offset = start;
  14487. line += 1;
  14488. }
  14489. switch (code) {
  14490. case t.space:
  14491. case t.tab:
  14492. case t.newline:
  14493. case t.cr:
  14494. case t.feed:
  14495. next = start;
  14496. do {
  14497. next += 1;
  14498. code = css.charCodeAt(next);
  14499. if (code === t.newline) {
  14500. offset = next;
  14501. line += 1;
  14502. }
  14503. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  14504. tokenType = t.space;
  14505. endLine = line;
  14506. endColumn = next - offset - 1;
  14507. end = next;
  14508. break;
  14509. case t.plus:
  14510. case t.greaterThan:
  14511. case t.tilde:
  14512. case t.pipe:
  14513. next = start;
  14514. do {
  14515. next += 1;
  14516. code = css.charCodeAt(next);
  14517. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  14518. tokenType = t.combinator;
  14519. endLine = line;
  14520. endColumn = start - offset;
  14521. end = next;
  14522. break;
  14523. // Consume these characters as single tokens.
  14524. case t.asterisk:
  14525. case t.ampersand:
  14526. case t.bang:
  14527. case t.comma:
  14528. case t.equals:
  14529. case t.dollar:
  14530. case t.caret:
  14531. case t.openSquare:
  14532. case t.closeSquare:
  14533. case t.colon:
  14534. case t.semicolon:
  14535. case t.openParenthesis:
  14536. case t.closeParenthesis:
  14537. next = start;
  14538. tokenType = code;
  14539. endLine = line;
  14540. endColumn = start - offset;
  14541. end = next + 1;
  14542. break;
  14543. case t.singleQuote:
  14544. case t.doubleQuote:
  14545. quote = code === t.singleQuote ? "'" : '"';
  14546. next = start;
  14547. do {
  14548. escaped = false;
  14549. next = css.indexOf(quote, next + 1);
  14550. if (next === -1) {
  14551. unclosed('quote', quote);
  14552. }
  14553. escapePos = next;
  14554. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  14555. escapePos -= 1;
  14556. escaped = !escaped;
  14557. }
  14558. } while (escaped);
  14559. tokenType = t.str;
  14560. endLine = line;
  14561. endColumn = start - offset;
  14562. end = next + 1;
  14563. break;
  14564. default:
  14565. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  14566. next = css.indexOf('*/', start + 2) + 1;
  14567. if (next === 0) {
  14568. unclosed('comment', '*/');
  14569. }
  14570. content = css.slice(start, next + 1);
  14571. lines = content.split('\n');
  14572. last = lines.length - 1;
  14573. if (last > 0) {
  14574. nextLine = line + last;
  14575. nextOffset = next - lines[last].length;
  14576. } else {
  14577. nextLine = line;
  14578. nextOffset = offset;
  14579. }
  14580. tokenType = t.comment;
  14581. line = nextLine;
  14582. endLine = nextLine;
  14583. endColumn = next - nextOffset;
  14584. } else if (code === t.slash) {
  14585. next = start;
  14586. tokenType = code;
  14587. endLine = line;
  14588. endColumn = start - offset;
  14589. end = next + 1;
  14590. } else {
  14591. next = consumeWord(css, start);
  14592. tokenType = t.word;
  14593. endLine = line;
  14594. endColumn = next - offset;
  14595. }
  14596. end = next + 1;
  14597. break;
  14598. }
  14599. // Ensure that the token structure remains consistent
  14600. tokens.push([tokenType,
  14601. // [0] Token type
  14602. line,
  14603. // [1] Starting line
  14604. start - offset,
  14605. // [2] Starting column
  14606. endLine,
  14607. // [3] Ending line
  14608. endColumn,
  14609. // [4] Ending column
  14610. start,
  14611. // [5] Start position / Source index
  14612. end // [6] End position
  14613. ]);
  14614. // Reset offset for the next token
  14615. if (nextOffset) {
  14616. offset = nextOffset;
  14617. nextOffset = null;
  14618. }
  14619. start = end;
  14620. }
  14621. return tokens;
  14622. }
  14623. } (tokenize));
  14624. return tokenize;
  14625. }
  14626. var hasRequiredParser;
  14627. function requireParser () {
  14628. if (hasRequiredParser) return parser.exports;
  14629. hasRequiredParser = 1;
  14630. (function (module, exports$1) {
  14631. exports$1.__esModule = true;
  14632. exports$1["default"] = void 0;
  14633. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  14634. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  14635. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  14636. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  14637. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  14638. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  14639. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  14640. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  14641. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  14642. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  14643. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  14644. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  14645. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  14646. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  14647. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14648. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  14649. var _util = /*@__PURE__*/ requireUtil();
  14650. var _WHITESPACE_TOKENS, _Object$assign;
  14651. 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); }
  14652. 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; }
  14653. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14654. 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); } }
  14655. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14656. 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);
  14657. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  14658. function tokenStart(token) {
  14659. return {
  14660. line: token[_tokenize.FIELDS.START_LINE],
  14661. column: token[_tokenize.FIELDS.START_COL]
  14662. };
  14663. }
  14664. function tokenEnd(token) {
  14665. return {
  14666. line: token[_tokenize.FIELDS.END_LINE],
  14667. column: token[_tokenize.FIELDS.END_COL]
  14668. };
  14669. }
  14670. function getSource(startLine, startColumn, endLine, endColumn) {
  14671. return {
  14672. start: {
  14673. line: startLine,
  14674. column: startColumn
  14675. },
  14676. end: {
  14677. line: endLine,
  14678. column: endColumn
  14679. }
  14680. };
  14681. }
  14682. function getTokenSource(token) {
  14683. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  14684. }
  14685. function getTokenSourceSpan(startToken, endToken) {
  14686. if (!startToken) {
  14687. return undefined;
  14688. }
  14689. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  14690. }
  14691. function unescapeProp(node, prop) {
  14692. var value = node[prop];
  14693. if (typeof value !== "string") {
  14694. return;
  14695. }
  14696. if (value.indexOf("\\") !== -1) {
  14697. (0, _util.ensureObject)(node, 'raws');
  14698. node[prop] = (0, _util.unesc)(value);
  14699. if (node.raws[prop] === undefined) {
  14700. node.raws[prop] = value;
  14701. }
  14702. }
  14703. return node;
  14704. }
  14705. function indexesOf(array, item) {
  14706. var i = -1;
  14707. var indexes = [];
  14708. while ((i = array.indexOf(item, i + 1)) !== -1) {
  14709. indexes.push(i);
  14710. }
  14711. return indexes;
  14712. }
  14713. function uniqs() {
  14714. var list = Array.prototype.concat.apply([], arguments);
  14715. return list.filter(function (item, i) {
  14716. return i === list.indexOf(item);
  14717. });
  14718. }
  14719. var Parser = /*#__PURE__*/function () {
  14720. function Parser(rule, options) {
  14721. if (options === void 0) {
  14722. options = {};
  14723. }
  14724. this.rule = rule;
  14725. this.options = Object.assign({
  14726. lossy: false,
  14727. safe: false
  14728. }, options);
  14729. this.position = 0;
  14730. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  14731. this.tokens = (0, _tokenize["default"])({
  14732. css: this.css,
  14733. error: this._errorGenerator(),
  14734. safe: this.options.safe
  14735. });
  14736. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  14737. this.root = new _root["default"]({
  14738. source: rootSource
  14739. });
  14740. this.root.errorGenerator = this._errorGenerator();
  14741. var selector = new _selector["default"]({
  14742. source: {
  14743. start: {
  14744. line: 1,
  14745. column: 1
  14746. }
  14747. },
  14748. sourceIndex: 0
  14749. });
  14750. this.root.append(selector);
  14751. this.current = selector;
  14752. this.loop();
  14753. }
  14754. var _proto = Parser.prototype;
  14755. _proto._errorGenerator = function _errorGenerator() {
  14756. var _this = this;
  14757. return function (message, errorOptions) {
  14758. if (typeof _this.rule === 'string') {
  14759. return new Error(message);
  14760. }
  14761. return _this.rule.error(message, errorOptions);
  14762. };
  14763. };
  14764. _proto.attribute = function attribute() {
  14765. var attr = [];
  14766. var startingToken = this.currToken;
  14767. this.position++;
  14768. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14769. attr.push(this.currToken);
  14770. this.position++;
  14771. }
  14772. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14773. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  14774. }
  14775. var len = attr.length;
  14776. var node = {
  14777. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  14778. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  14779. };
  14780. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  14781. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  14782. }
  14783. var pos = 0;
  14784. var spaceBefore = '';
  14785. var commentBefore = '';
  14786. var lastAdded = null;
  14787. var spaceAfterMeaningfulToken = false;
  14788. while (pos < len) {
  14789. var token = attr[pos];
  14790. var content = this.content(token);
  14791. var next = attr[pos + 1];
  14792. switch (token[_tokenize.FIELDS.TYPE]) {
  14793. case tokens.space:
  14794. // if (
  14795. // len === 1 ||
  14796. // pos === 0 && this.content(next) === '|'
  14797. // ) {
  14798. // return this.expected('attribute', token[TOKEN.START_POS], content);
  14799. // }
  14800. spaceAfterMeaningfulToken = true;
  14801. if (this.options.lossy) {
  14802. break;
  14803. }
  14804. if (lastAdded) {
  14805. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  14806. var prevContent = node.spaces[lastAdded].after || '';
  14807. node.spaces[lastAdded].after = prevContent + content;
  14808. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  14809. if (existingComment) {
  14810. node.raws.spaces[lastAdded].after = existingComment + content;
  14811. }
  14812. } else {
  14813. spaceBefore = spaceBefore + content;
  14814. commentBefore = commentBefore + content;
  14815. }
  14816. break;
  14817. case tokens.asterisk:
  14818. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14819. node.operator = content;
  14820. lastAdded = 'operator';
  14821. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  14822. if (spaceBefore) {
  14823. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14824. node.spaces.attribute.before = spaceBefore;
  14825. spaceBefore = '';
  14826. }
  14827. if (commentBefore) {
  14828. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14829. node.raws.spaces.attribute.before = spaceBefore;
  14830. commentBefore = '';
  14831. }
  14832. node.namespace = (node.namespace || "") + content;
  14833. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  14834. if (rawValue) {
  14835. node.raws.namespace += content;
  14836. }
  14837. lastAdded = 'namespace';
  14838. }
  14839. spaceAfterMeaningfulToken = false;
  14840. break;
  14841. case tokens.dollar:
  14842. if (lastAdded === "value") {
  14843. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  14844. node.value += "$";
  14845. if (oldRawValue) {
  14846. node.raws.value = oldRawValue + "$";
  14847. }
  14848. break;
  14849. }
  14850. // Falls through
  14851. case tokens.caret:
  14852. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14853. node.operator = content;
  14854. lastAdded = 'operator';
  14855. }
  14856. spaceAfterMeaningfulToken = false;
  14857. break;
  14858. case tokens.combinator:
  14859. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14860. node.operator = content;
  14861. lastAdded = 'operator';
  14862. }
  14863. if (content !== '|') {
  14864. spaceAfterMeaningfulToken = false;
  14865. break;
  14866. }
  14867. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14868. node.operator = content;
  14869. lastAdded = 'operator';
  14870. } else if (!node.namespace && !node.attribute) {
  14871. node.namespace = true;
  14872. }
  14873. spaceAfterMeaningfulToken = false;
  14874. break;
  14875. case tokens.word:
  14876. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  14877. // this look-ahead probably fails with comment nodes involved.
  14878. !node.operator && !node.namespace) {
  14879. node.namespace = content;
  14880. lastAdded = 'namespace';
  14881. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  14882. if (spaceBefore) {
  14883. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14884. node.spaces.attribute.before = spaceBefore;
  14885. spaceBefore = '';
  14886. }
  14887. if (commentBefore) {
  14888. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14889. node.raws.spaces.attribute.before = commentBefore;
  14890. commentBefore = '';
  14891. }
  14892. node.attribute = (node.attribute || "") + content;
  14893. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  14894. if (_rawValue) {
  14895. node.raws.attribute += content;
  14896. }
  14897. lastAdded = 'attribute';
  14898. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  14899. var _unescaped = (0, _util.unesc)(content);
  14900. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  14901. var oldValue = node.value || '';
  14902. node.value = oldValue + _unescaped;
  14903. node.quoteMark = null;
  14904. if (_unescaped !== content || _oldRawValue) {
  14905. (0, _util.ensureObject)(node, 'raws');
  14906. node.raws.value = (_oldRawValue || oldValue) + content;
  14907. }
  14908. lastAdded = 'value';
  14909. } else {
  14910. var insensitive = content === 'i' || content === "I";
  14911. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  14912. node.insensitive = insensitive;
  14913. if (!insensitive || content === "I") {
  14914. (0, _util.ensureObject)(node, 'raws');
  14915. node.raws.insensitiveFlag = content;
  14916. }
  14917. lastAdded = 'insensitive';
  14918. if (spaceBefore) {
  14919. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  14920. node.spaces.insensitive.before = spaceBefore;
  14921. spaceBefore = '';
  14922. }
  14923. if (commentBefore) {
  14924. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  14925. node.raws.spaces.insensitive.before = commentBefore;
  14926. commentBefore = '';
  14927. }
  14928. } else if (node.value || node.value === '') {
  14929. lastAdded = 'value';
  14930. node.value += content;
  14931. if (node.raws.value) {
  14932. node.raws.value += content;
  14933. }
  14934. }
  14935. }
  14936. spaceAfterMeaningfulToken = false;
  14937. break;
  14938. case tokens.str:
  14939. if (!node.attribute || !node.operator) {
  14940. return this.error("Expected an attribute followed by an operator preceding the string.", {
  14941. index: token[_tokenize.FIELDS.START_POS]
  14942. });
  14943. }
  14944. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  14945. unescaped = _unescapeValue.unescaped,
  14946. quoteMark = _unescapeValue.quoteMark;
  14947. node.value = unescaped;
  14948. node.quoteMark = quoteMark;
  14949. lastAdded = 'value';
  14950. (0, _util.ensureObject)(node, 'raws');
  14951. node.raws.value = content;
  14952. spaceAfterMeaningfulToken = false;
  14953. break;
  14954. case tokens.equals:
  14955. if (!node.attribute) {
  14956. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  14957. }
  14958. if (node.value) {
  14959. return this.error('Unexpected "=" found; an operator was already defined.', {
  14960. index: token[_tokenize.FIELDS.START_POS]
  14961. });
  14962. }
  14963. node.operator = node.operator ? node.operator + content : content;
  14964. lastAdded = 'operator';
  14965. spaceAfterMeaningfulToken = false;
  14966. break;
  14967. case tokens.comment:
  14968. if (lastAdded) {
  14969. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  14970. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  14971. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  14972. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  14973. node.raws.spaces[lastAdded].after = rawLastComment + content;
  14974. } else {
  14975. var lastValue = node[lastAdded] || '';
  14976. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  14977. (0, _util.ensureObject)(node, 'raws');
  14978. node.raws[lastAdded] = rawLastValue + content;
  14979. }
  14980. } else {
  14981. commentBefore = commentBefore + content;
  14982. }
  14983. break;
  14984. default:
  14985. return this.error("Unexpected \"" + content + "\" found.", {
  14986. index: token[_tokenize.FIELDS.START_POS]
  14987. });
  14988. }
  14989. pos++;
  14990. }
  14991. unescapeProp(node, "attribute");
  14992. unescapeProp(node, "namespace");
  14993. this.newNode(new _attribute["default"](node));
  14994. this.position++;
  14995. }
  14996. /**
  14997. * return a node containing meaningless garbage up to (but not including) the specified token position.
  14998. * if the token position is negative, all remaining tokens are consumed.
  14999. *
  15000. * This returns an array containing a single string node if all whitespace,
  15001. * otherwise an array of comment nodes with space before and after.
  15002. *
  15003. * These tokens are not added to the current selector, the caller can add them or use them to amend
  15004. * a previous node's space metadata.
  15005. *
  15006. * In lossy mode, this returns only comments.
  15007. */;
  15008. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  15009. if (stopPosition < 0) {
  15010. stopPosition = this.tokens.length;
  15011. }
  15012. var startPosition = this.position;
  15013. var nodes = [];
  15014. var space = "";
  15015. var lastComment = undefined;
  15016. do {
  15017. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  15018. if (!this.options.lossy) {
  15019. space += this.content();
  15020. }
  15021. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  15022. var spaces = {};
  15023. if (space) {
  15024. spaces.before = space;
  15025. space = "";
  15026. }
  15027. lastComment = new _comment["default"]({
  15028. value: this.content(),
  15029. source: getTokenSource(this.currToken),
  15030. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15031. spaces: spaces
  15032. });
  15033. nodes.push(lastComment);
  15034. }
  15035. } while (++this.position < stopPosition);
  15036. if (space) {
  15037. if (lastComment) {
  15038. lastComment.spaces.after = space;
  15039. } else if (!this.options.lossy) {
  15040. var firstToken = this.tokens[startPosition];
  15041. var lastToken = this.tokens[this.position - 1];
  15042. nodes.push(new _string["default"]({
  15043. value: '',
  15044. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15045. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15046. spaces: {
  15047. before: space,
  15048. after: ''
  15049. }
  15050. }));
  15051. }
  15052. }
  15053. return nodes;
  15054. }
  15055. /**
  15056. *
  15057. * @param {*} nodes
  15058. */;
  15059. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15060. var _this2 = this;
  15061. if (requiredSpace === void 0) {
  15062. requiredSpace = false;
  15063. }
  15064. var space = "";
  15065. var rawSpace = "";
  15066. nodes.forEach(function (n) {
  15067. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15068. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15069. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15070. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15071. });
  15072. if (rawSpace === space) {
  15073. rawSpace = undefined;
  15074. }
  15075. var result = {
  15076. space: space,
  15077. rawSpace: rawSpace
  15078. };
  15079. return result;
  15080. };
  15081. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15082. if (position === void 0) {
  15083. position = this.position;
  15084. }
  15085. 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;
  15086. };
  15087. _proto.namedCombinator = function namedCombinator() {
  15088. if (this.isNamedCombinator()) {
  15089. var nameRaw = this.content(this.tokens[this.position + 1]);
  15090. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15091. var raws = {};
  15092. if (name !== nameRaw) {
  15093. raws.value = "/" + nameRaw + "/";
  15094. }
  15095. var node = new _combinator["default"]({
  15096. value: "/" + name + "/",
  15097. 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]),
  15098. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15099. raws: raws
  15100. });
  15101. this.position = this.position + 3;
  15102. return node;
  15103. } else {
  15104. this.unexpected();
  15105. }
  15106. };
  15107. _proto.combinator = function combinator() {
  15108. var _this3 = this;
  15109. if (this.content() === '|') {
  15110. return this.namespace();
  15111. }
  15112. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15113. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15114. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15115. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15116. if (nodes.length > 0) {
  15117. var last = this.current.last;
  15118. if (last) {
  15119. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15120. space = _this$convertWhitespa.space,
  15121. rawSpace = _this$convertWhitespa.rawSpace;
  15122. if (rawSpace !== undefined) {
  15123. last.rawSpaceAfter += rawSpace;
  15124. }
  15125. last.spaces.after += space;
  15126. } else {
  15127. nodes.forEach(function (n) {
  15128. return _this3.newNode(n);
  15129. });
  15130. }
  15131. }
  15132. return;
  15133. }
  15134. var firstToken = this.currToken;
  15135. var spaceOrDescendantSelectorNodes = undefined;
  15136. if (nextSigTokenPos > this.position) {
  15137. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15138. }
  15139. var node;
  15140. if (this.isNamedCombinator()) {
  15141. node = this.namedCombinator();
  15142. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15143. node = new _combinator["default"]({
  15144. value: this.content(),
  15145. source: getTokenSource(this.currToken),
  15146. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15147. });
  15148. this.position++;
  15149. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15150. this.unexpected();
  15151. }
  15152. if (node) {
  15153. if (spaceOrDescendantSelectorNodes) {
  15154. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15155. _space = _this$convertWhitespa2.space,
  15156. _rawSpace = _this$convertWhitespa2.rawSpace;
  15157. node.spaces.before = _space;
  15158. node.rawSpaceBefore = _rawSpace;
  15159. }
  15160. } else {
  15161. // descendant combinator
  15162. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15163. _space2 = _this$convertWhitespa3.space,
  15164. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15165. if (!_rawSpace2) {
  15166. _rawSpace2 = _space2;
  15167. }
  15168. var spaces = {};
  15169. var raws = {
  15170. spaces: {}
  15171. };
  15172. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15173. spaces.before = _space2.slice(0, _space2.length - 1);
  15174. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15175. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15176. spaces.after = _space2.slice(1);
  15177. raws.spaces.after = _rawSpace2.slice(1);
  15178. } else {
  15179. raws.value = _rawSpace2;
  15180. }
  15181. node = new _combinator["default"]({
  15182. value: ' ',
  15183. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15184. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15185. spaces: spaces,
  15186. raws: raws
  15187. });
  15188. }
  15189. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15190. node.spaces.after = this.optionalSpace(this.content());
  15191. this.position++;
  15192. }
  15193. return this.newNode(node);
  15194. };
  15195. _proto.comma = function comma() {
  15196. if (this.position === this.tokens.length - 1) {
  15197. this.root.trailingComma = true;
  15198. this.position++;
  15199. return;
  15200. }
  15201. this.current._inferEndPosition();
  15202. var selector = new _selector["default"]({
  15203. source: {
  15204. start: tokenStart(this.tokens[this.position + 1])
  15205. },
  15206. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15207. });
  15208. this.current.parent.append(selector);
  15209. this.current = selector;
  15210. this.position++;
  15211. };
  15212. _proto.comment = function comment() {
  15213. var current = this.currToken;
  15214. this.newNode(new _comment["default"]({
  15215. value: this.content(),
  15216. source: getTokenSource(current),
  15217. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15218. }));
  15219. this.position++;
  15220. };
  15221. _proto.error = function error(message, opts) {
  15222. throw this.root.error(message, opts);
  15223. };
  15224. _proto.missingBackslash = function missingBackslash() {
  15225. return this.error('Expected a backslash preceding the semicolon.', {
  15226. index: this.currToken[_tokenize.FIELDS.START_POS]
  15227. });
  15228. };
  15229. _proto.missingParenthesis = function missingParenthesis() {
  15230. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15231. };
  15232. _proto.missingSquareBracket = function missingSquareBracket() {
  15233. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15234. };
  15235. _proto.unexpected = function unexpected() {
  15236. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15237. };
  15238. _proto.unexpectedPipe = function unexpectedPipe() {
  15239. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15240. };
  15241. _proto.namespace = function namespace() {
  15242. var before = this.prevToken && this.content(this.prevToken) || true;
  15243. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15244. this.position++;
  15245. return this.word(before);
  15246. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15247. this.position++;
  15248. return this.universal(before);
  15249. }
  15250. this.unexpectedPipe();
  15251. };
  15252. _proto.nesting = function nesting() {
  15253. if (this.nextToken) {
  15254. var nextContent = this.content(this.nextToken);
  15255. if (nextContent === "|") {
  15256. this.position++;
  15257. return;
  15258. }
  15259. }
  15260. var current = this.currToken;
  15261. this.newNode(new _nesting["default"]({
  15262. value: this.content(),
  15263. source: getTokenSource(current),
  15264. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15265. }));
  15266. this.position++;
  15267. };
  15268. _proto.parentheses = function parentheses() {
  15269. var last = this.current.last;
  15270. var unbalanced = 1;
  15271. this.position++;
  15272. if (last && last.type === types.PSEUDO) {
  15273. var selector = new _selector["default"]({
  15274. source: {
  15275. start: tokenStart(this.tokens[this.position])
  15276. },
  15277. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15278. });
  15279. var cache = this.current;
  15280. last.append(selector);
  15281. this.current = selector;
  15282. while (this.position < this.tokens.length && unbalanced) {
  15283. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15284. unbalanced++;
  15285. }
  15286. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15287. unbalanced--;
  15288. }
  15289. if (unbalanced) {
  15290. this.parse();
  15291. } else {
  15292. this.current.source.end = tokenEnd(this.currToken);
  15293. this.current.parent.source.end = tokenEnd(this.currToken);
  15294. this.position++;
  15295. }
  15296. }
  15297. this.current = cache;
  15298. } else {
  15299. // I think this case should be an error. It's used to implement a basic parse of media queries
  15300. // but I don't think it's a good idea.
  15301. var parenStart = this.currToken;
  15302. var parenValue = "(";
  15303. var parenEnd;
  15304. while (this.position < this.tokens.length && unbalanced) {
  15305. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15306. unbalanced++;
  15307. }
  15308. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15309. unbalanced--;
  15310. }
  15311. parenEnd = this.currToken;
  15312. parenValue += this.parseParenthesisToken(this.currToken);
  15313. this.position++;
  15314. }
  15315. if (last) {
  15316. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15317. } else {
  15318. this.newNode(new _string["default"]({
  15319. value: parenValue,
  15320. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15321. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15322. }));
  15323. }
  15324. }
  15325. if (unbalanced) {
  15326. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15327. }
  15328. };
  15329. _proto.pseudo = function pseudo() {
  15330. var _this4 = this;
  15331. var pseudoStr = '';
  15332. var startingToken = this.currToken;
  15333. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15334. pseudoStr += this.content();
  15335. this.position++;
  15336. }
  15337. if (!this.currToken) {
  15338. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15339. }
  15340. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15341. this.splitWord(false, function (first, length) {
  15342. pseudoStr += first;
  15343. _this4.newNode(new _pseudo["default"]({
  15344. value: pseudoStr,
  15345. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15346. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15347. }));
  15348. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15349. _this4.error('Misplaced parenthesis.', {
  15350. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15351. });
  15352. }
  15353. });
  15354. } else {
  15355. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15356. }
  15357. };
  15358. _proto.space = function space() {
  15359. var content = this.content();
  15360. // Handle space before and after the selector
  15361. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15362. return node.type === 'comment';
  15363. })) {
  15364. this.spaces = this.optionalSpace(content);
  15365. this.position++;
  15366. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15367. this.current.last.spaces.after = this.optionalSpace(content);
  15368. this.position++;
  15369. } else {
  15370. this.combinator();
  15371. }
  15372. };
  15373. _proto.string = function string() {
  15374. var current = this.currToken;
  15375. this.newNode(new _string["default"]({
  15376. value: this.content(),
  15377. source: getTokenSource(current),
  15378. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15379. }));
  15380. this.position++;
  15381. };
  15382. _proto.universal = function universal(namespace) {
  15383. var nextToken = this.nextToken;
  15384. if (nextToken && this.content(nextToken) === '|') {
  15385. this.position++;
  15386. return this.namespace();
  15387. }
  15388. var current = this.currToken;
  15389. this.newNode(new _universal["default"]({
  15390. value: this.content(),
  15391. source: getTokenSource(current),
  15392. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15393. }), namespace);
  15394. this.position++;
  15395. };
  15396. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15397. var _this5 = this;
  15398. var nextToken = this.nextToken;
  15399. var word = this.content();
  15400. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15401. this.position++;
  15402. var current = this.content();
  15403. word += current;
  15404. if (current.lastIndexOf('\\') === current.length - 1) {
  15405. var next = this.nextToken;
  15406. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15407. word += this.requiredSpace(this.content(next));
  15408. this.position++;
  15409. }
  15410. }
  15411. nextToken = this.nextToken;
  15412. }
  15413. var hasClass = indexesOf(word, '.').filter(function (i) {
  15414. // Allow escaped dot within class name
  15415. var escapedDot = word[i - 1] === '\\';
  15416. // Allow decimal numbers percent in @keyframes
  15417. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15418. return !escapedDot && !isKeyframesPercent;
  15419. });
  15420. var hasId = indexesOf(word, '#').filter(function (i) {
  15421. return word[i - 1] !== '\\';
  15422. });
  15423. // Eliminate Sass interpolations from the list of id indexes
  15424. var interpolations = indexesOf(word, '#{');
  15425. if (interpolations.length) {
  15426. hasId = hasId.filter(function (hashIndex) {
  15427. return !~interpolations.indexOf(hashIndex);
  15428. });
  15429. }
  15430. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15431. indices.forEach(function (ind, i) {
  15432. var index = indices[i + 1] || word.length;
  15433. var value = word.slice(ind, index);
  15434. if (i === 0 && firstCallback) {
  15435. return firstCallback.call(_this5, value, indices.length);
  15436. }
  15437. var node;
  15438. var current = _this5.currToken;
  15439. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15440. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15441. if (~hasClass.indexOf(ind)) {
  15442. var classNameOpts = {
  15443. value: value.slice(1),
  15444. source: source,
  15445. sourceIndex: sourceIndex
  15446. };
  15447. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15448. } else if (~hasId.indexOf(ind)) {
  15449. var idOpts = {
  15450. value: value.slice(1),
  15451. source: source,
  15452. sourceIndex: sourceIndex
  15453. };
  15454. node = new _id["default"](unescapeProp(idOpts, "value"));
  15455. } else {
  15456. var tagOpts = {
  15457. value: value,
  15458. source: source,
  15459. sourceIndex: sourceIndex
  15460. };
  15461. unescapeProp(tagOpts, "value");
  15462. node = new _tag["default"](tagOpts);
  15463. }
  15464. _this5.newNode(node, namespace);
  15465. // Ensure that the namespace is used only once
  15466. namespace = null;
  15467. });
  15468. this.position++;
  15469. };
  15470. _proto.word = function word(namespace) {
  15471. var nextToken = this.nextToken;
  15472. if (nextToken && this.content(nextToken) === '|') {
  15473. this.position++;
  15474. return this.namespace();
  15475. }
  15476. return this.splitWord(namespace);
  15477. };
  15478. _proto.loop = function loop() {
  15479. while (this.position < this.tokens.length) {
  15480. this.parse(true);
  15481. }
  15482. this.current._inferEndPosition();
  15483. return this.root;
  15484. };
  15485. _proto.parse = function parse(throwOnParenthesis) {
  15486. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  15487. case tokens.space:
  15488. this.space();
  15489. break;
  15490. case tokens.comment:
  15491. this.comment();
  15492. break;
  15493. case tokens.openParenthesis:
  15494. this.parentheses();
  15495. break;
  15496. case tokens.closeParenthesis:
  15497. if (throwOnParenthesis) {
  15498. this.missingParenthesis();
  15499. }
  15500. break;
  15501. case tokens.openSquare:
  15502. this.attribute();
  15503. break;
  15504. case tokens.dollar:
  15505. case tokens.caret:
  15506. case tokens.equals:
  15507. case tokens.word:
  15508. this.word();
  15509. break;
  15510. case tokens.colon:
  15511. this.pseudo();
  15512. break;
  15513. case tokens.comma:
  15514. this.comma();
  15515. break;
  15516. case tokens.asterisk:
  15517. this.universal();
  15518. break;
  15519. case tokens.ampersand:
  15520. this.nesting();
  15521. break;
  15522. case tokens.slash:
  15523. case tokens.combinator:
  15524. this.combinator();
  15525. break;
  15526. case tokens.str:
  15527. this.string();
  15528. break;
  15529. // These cases throw; no break needed.
  15530. case tokens.closeSquare:
  15531. this.missingSquareBracket();
  15532. case tokens.semicolon:
  15533. this.missingBackslash();
  15534. default:
  15535. this.unexpected();
  15536. }
  15537. }
  15538. /**
  15539. * Helpers
  15540. */;
  15541. _proto.expected = function expected(description, index, found) {
  15542. if (Array.isArray(description)) {
  15543. var last = description.pop();
  15544. description = description.join(', ') + " or " + last;
  15545. }
  15546. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  15547. if (!found) {
  15548. return this.error("Expected " + an + " " + description + ".", {
  15549. index: index
  15550. });
  15551. }
  15552. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  15553. index: index
  15554. });
  15555. };
  15556. _proto.requiredSpace = function requiredSpace(space) {
  15557. return this.options.lossy ? ' ' : space;
  15558. };
  15559. _proto.optionalSpace = function optionalSpace(space) {
  15560. return this.options.lossy ? '' : space;
  15561. };
  15562. _proto.lossySpace = function lossySpace(space, required) {
  15563. if (this.options.lossy) {
  15564. return required ? ' ' : '';
  15565. } else {
  15566. return space;
  15567. }
  15568. };
  15569. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  15570. var content = this.content(token);
  15571. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  15572. return this.requiredSpace(content);
  15573. } else {
  15574. return content;
  15575. }
  15576. };
  15577. _proto.newNode = function newNode(node, namespace) {
  15578. if (namespace) {
  15579. if (/^ +$/.test(namespace)) {
  15580. if (!this.options.lossy) {
  15581. this.spaces = (this.spaces || '') + namespace;
  15582. }
  15583. namespace = true;
  15584. }
  15585. node.namespace = namespace;
  15586. unescapeProp(node, "namespace");
  15587. }
  15588. if (this.spaces) {
  15589. node.spaces.before = this.spaces;
  15590. this.spaces = '';
  15591. }
  15592. return this.current.append(node);
  15593. };
  15594. _proto.content = function content(token) {
  15595. if (token === void 0) {
  15596. token = this.currToken;
  15597. }
  15598. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  15599. };
  15600. /**
  15601. * returns the index of the next non-whitespace, non-comment token.
  15602. * returns -1 if no meaningful token is found.
  15603. */
  15604. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  15605. if (startPosition === void 0) {
  15606. startPosition = this.position + 1;
  15607. }
  15608. var searchPosition = startPosition;
  15609. while (searchPosition < this.tokens.length) {
  15610. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  15611. searchPosition++;
  15612. continue;
  15613. } else {
  15614. return searchPosition;
  15615. }
  15616. }
  15617. return -1;
  15618. };
  15619. _createClass(Parser, [{
  15620. key: "currToken",
  15621. get: function get() {
  15622. return this.tokens[this.position];
  15623. }
  15624. }, {
  15625. key: "nextToken",
  15626. get: function get() {
  15627. return this.tokens[this.position + 1];
  15628. }
  15629. }, {
  15630. key: "prevToken",
  15631. get: function get() {
  15632. return this.tokens[this.position - 1];
  15633. }
  15634. }]);
  15635. return Parser;
  15636. }();
  15637. exports$1["default"] = Parser;
  15638. module.exports = exports$1.default;
  15639. } (parser, parser.exports));
  15640. return parser.exports;
  15641. }
  15642. var hasRequiredProcessor;
  15643. function requireProcessor () {
  15644. if (hasRequiredProcessor) return processor.exports;
  15645. hasRequiredProcessor = 1;
  15646. (function (module, exports$1) {
  15647. exports$1.__esModule = true;
  15648. exports$1["default"] = void 0;
  15649. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  15650. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15651. var Processor = /*#__PURE__*/function () {
  15652. function Processor(func, options) {
  15653. this.func = func || function noop() {};
  15654. this.funcRes = null;
  15655. this.options = options;
  15656. }
  15657. var _proto = Processor.prototype;
  15658. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  15659. if (options === void 0) {
  15660. options = {};
  15661. }
  15662. var merged = Object.assign({}, this.options, options);
  15663. if (merged.updateSelector === false) {
  15664. return false;
  15665. } else {
  15666. return typeof rule !== "string";
  15667. }
  15668. };
  15669. _proto._isLossy = function _isLossy(options) {
  15670. if (options === void 0) {
  15671. options = {};
  15672. }
  15673. var merged = Object.assign({}, this.options, options);
  15674. if (merged.lossless === false) {
  15675. return true;
  15676. } else {
  15677. return false;
  15678. }
  15679. };
  15680. _proto._root = function _root(rule, options) {
  15681. if (options === void 0) {
  15682. options = {};
  15683. }
  15684. var parser = new _parser["default"](rule, this._parseOptions(options));
  15685. return parser.root;
  15686. };
  15687. _proto._parseOptions = function _parseOptions(options) {
  15688. return {
  15689. lossy: this._isLossy(options)
  15690. };
  15691. };
  15692. _proto._run = function _run(rule, options) {
  15693. var _this = this;
  15694. if (options === void 0) {
  15695. options = {};
  15696. }
  15697. return new Promise(function (resolve, reject) {
  15698. try {
  15699. var root = _this._root(rule, options);
  15700. Promise.resolve(_this.func(root)).then(function (transform) {
  15701. var string = undefined;
  15702. if (_this._shouldUpdateSelector(rule, options)) {
  15703. string = root.toString();
  15704. rule.selector = string;
  15705. }
  15706. return {
  15707. transform: transform,
  15708. root: root,
  15709. string: string
  15710. };
  15711. }).then(resolve, reject);
  15712. } catch (e) {
  15713. reject(e);
  15714. return;
  15715. }
  15716. });
  15717. };
  15718. _proto._runSync = function _runSync(rule, options) {
  15719. if (options === void 0) {
  15720. options = {};
  15721. }
  15722. var root = this._root(rule, options);
  15723. var transform = this.func(root);
  15724. if (transform && typeof transform.then === "function") {
  15725. throw new Error("Selector processor returned a promise to a synchronous call.");
  15726. }
  15727. var string = undefined;
  15728. if (options.updateSelector && typeof rule !== "string") {
  15729. string = root.toString();
  15730. rule.selector = string;
  15731. }
  15732. return {
  15733. transform: transform,
  15734. root: root,
  15735. string: string
  15736. };
  15737. }
  15738. /**
  15739. * Process rule into a selector AST.
  15740. *
  15741. * @param rule {postcss.Rule | string} The css selector to be processed
  15742. * @param options The options for processing
  15743. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  15744. */;
  15745. _proto.ast = function ast(rule, options) {
  15746. return this._run(rule, options).then(function (result) {
  15747. return result.root;
  15748. });
  15749. }
  15750. /**
  15751. * Process rule into a selector AST synchronously.
  15752. *
  15753. * @param rule {postcss.Rule | string} The css selector to be processed
  15754. * @param options The options for processing
  15755. * @returns {parser.Root} The AST of the selector after processing it.
  15756. */;
  15757. _proto.astSync = function astSync(rule, options) {
  15758. return this._runSync(rule, options).root;
  15759. }
  15760. /**
  15761. * Process a selector into a transformed value asynchronously
  15762. *
  15763. * @param rule {postcss.Rule | string} The css selector to be processed
  15764. * @param options The options for processing
  15765. * @returns {Promise<any>} The value returned by the processor.
  15766. */;
  15767. _proto.transform = function transform(rule, options) {
  15768. return this._run(rule, options).then(function (result) {
  15769. return result.transform;
  15770. });
  15771. }
  15772. /**
  15773. * Process a selector into a transformed value synchronously.
  15774. *
  15775. * @param rule {postcss.Rule | string} The css selector to be processed
  15776. * @param options The options for processing
  15777. * @returns {any} The value returned by the processor.
  15778. */;
  15779. _proto.transformSync = function transformSync(rule, options) {
  15780. return this._runSync(rule, options).transform;
  15781. }
  15782. /**
  15783. * Process a selector into a new selector string asynchronously.
  15784. *
  15785. * @param rule {postcss.Rule | string} The css selector to be processed
  15786. * @param options The options for processing
  15787. * @returns {string} the selector after processing.
  15788. */;
  15789. _proto.process = function process(rule, options) {
  15790. return this._run(rule, options).then(function (result) {
  15791. return result.string || result.root.toString();
  15792. });
  15793. }
  15794. /**
  15795. * Process a selector into a new selector string synchronously.
  15796. *
  15797. * @param rule {postcss.Rule | string} The css selector to be processed
  15798. * @param options The options for processing
  15799. * @returns {string} the selector after processing.
  15800. */;
  15801. _proto.processSync = function processSync(rule, options) {
  15802. var result = this._runSync(rule, options);
  15803. return result.string || result.root.toString();
  15804. };
  15805. return Processor;
  15806. }();
  15807. exports$1["default"] = Processor;
  15808. module.exports = exports$1.default;
  15809. } (processor, processor.exports));
  15810. return processor.exports;
  15811. }
  15812. var selectors = {};
  15813. var constructors = {};
  15814. var hasRequiredConstructors;
  15815. function requireConstructors () {
  15816. if (hasRequiredConstructors) return constructors;
  15817. hasRequiredConstructors = 1;
  15818. constructors.__esModule = true;
  15819. 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;
  15820. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  15821. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15822. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15823. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15824. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15825. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15826. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15827. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15828. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15829. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15830. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15831. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15832. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15833. var attribute = function attribute(opts) {
  15834. return new _attribute["default"](opts);
  15835. };
  15836. constructors.attribute = attribute;
  15837. var className = function className(opts) {
  15838. return new _className["default"](opts);
  15839. };
  15840. constructors.className = className;
  15841. var combinator = function combinator(opts) {
  15842. return new _combinator["default"](opts);
  15843. };
  15844. constructors.combinator = combinator;
  15845. var comment = function comment(opts) {
  15846. return new _comment["default"](opts);
  15847. };
  15848. constructors.comment = comment;
  15849. var id = function id(opts) {
  15850. return new _id["default"](opts);
  15851. };
  15852. constructors.id = id;
  15853. var nesting = function nesting(opts) {
  15854. return new _nesting["default"](opts);
  15855. };
  15856. constructors.nesting = nesting;
  15857. var pseudo = function pseudo(opts) {
  15858. return new _pseudo["default"](opts);
  15859. };
  15860. constructors.pseudo = pseudo;
  15861. var root = function root(opts) {
  15862. return new _root["default"](opts);
  15863. };
  15864. constructors.root = root;
  15865. var selector = function selector(opts) {
  15866. return new _selector["default"](opts);
  15867. };
  15868. constructors.selector = selector;
  15869. var string = function string(opts) {
  15870. return new _string["default"](opts);
  15871. };
  15872. constructors.string = string;
  15873. var tag = function tag(opts) {
  15874. return new _tag["default"](opts);
  15875. };
  15876. constructors.tag = tag;
  15877. var universal = function universal(opts) {
  15878. return new _universal["default"](opts);
  15879. };
  15880. constructors.universal = universal;
  15881. return constructors;
  15882. }
  15883. var guards = {};
  15884. var hasRequiredGuards;
  15885. function requireGuards () {
  15886. if (hasRequiredGuards) return guards;
  15887. hasRequiredGuards = 1;
  15888. guards.__esModule = true;
  15889. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  15890. guards.isContainer = isContainer;
  15891. guards.isIdentifier = void 0;
  15892. guards.isNamespace = isNamespace;
  15893. guards.isNesting = void 0;
  15894. guards.isNode = isNode;
  15895. guards.isPseudo = void 0;
  15896. guards.isPseudoClass = isPseudoClass;
  15897. guards.isPseudoElement = isPseudoElement;
  15898. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  15899. var _types = /*@__PURE__*/ requireTypes();
  15900. var _IS_TYPE;
  15901. 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);
  15902. function isNode(node) {
  15903. return typeof node === "object" && IS_TYPE[node.type];
  15904. }
  15905. function isNodeType(type, node) {
  15906. return isNode(node) && node.type === type;
  15907. }
  15908. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  15909. guards.isAttribute = isAttribute;
  15910. var isClassName = isNodeType.bind(null, _types.CLASS);
  15911. guards.isClassName = isClassName;
  15912. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  15913. guards.isCombinator = isCombinator;
  15914. var isComment = isNodeType.bind(null, _types.COMMENT);
  15915. guards.isComment = isComment;
  15916. var isIdentifier = isNodeType.bind(null, _types.ID);
  15917. guards.isIdentifier = isIdentifier;
  15918. var isNesting = isNodeType.bind(null, _types.NESTING);
  15919. guards.isNesting = isNesting;
  15920. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  15921. guards.isPseudo = isPseudo;
  15922. var isRoot = isNodeType.bind(null, _types.ROOT);
  15923. guards.isRoot = isRoot;
  15924. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  15925. guards.isSelector = isSelector;
  15926. var isString = isNodeType.bind(null, _types.STRING);
  15927. guards.isString = isString;
  15928. var isTag = isNodeType.bind(null, _types.TAG);
  15929. guards.isTag = isTag;
  15930. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  15931. guards.isUniversal = isUniversal;
  15932. function isPseudoElement(node) {
  15933. 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");
  15934. }
  15935. function isPseudoClass(node) {
  15936. return isPseudo(node) && !isPseudoElement(node);
  15937. }
  15938. function isContainer(node) {
  15939. return !!(isNode(node) && node.walk);
  15940. }
  15941. function isNamespace(node) {
  15942. return isAttribute(node) || isTag(node);
  15943. }
  15944. return guards;
  15945. }
  15946. var hasRequiredSelectors;
  15947. function requireSelectors () {
  15948. if (hasRequiredSelectors) return selectors;
  15949. hasRequiredSelectors = 1;
  15950. (function (exports$1) {
  15951. exports$1.__esModule = true;
  15952. var _types = /*@__PURE__*/ requireTypes();
  15953. Object.keys(_types).forEach(function (key) {
  15954. if (key === "default" || key === "__esModule") return;
  15955. if (key in exports$1 && exports$1[key] === _types[key]) return;
  15956. exports$1[key] = _types[key];
  15957. });
  15958. var _constructors = /*@__PURE__*/ requireConstructors();
  15959. Object.keys(_constructors).forEach(function (key) {
  15960. if (key === "default" || key === "__esModule") return;
  15961. if (key in exports$1 && exports$1[key] === _constructors[key]) return;
  15962. exports$1[key] = _constructors[key];
  15963. });
  15964. var _guards = /*@__PURE__*/ requireGuards();
  15965. Object.keys(_guards).forEach(function (key) {
  15966. if (key === "default" || key === "__esModule") return;
  15967. if (key in exports$1 && exports$1[key] === _guards[key]) return;
  15968. exports$1[key] = _guards[key];
  15969. });
  15970. } (selectors));
  15971. return selectors;
  15972. }
  15973. var hasRequiredDist;
  15974. function requireDist () {
  15975. if (hasRequiredDist) return dist.exports;
  15976. hasRequiredDist = 1;
  15977. (function (module, exports$1) {
  15978. exports$1.__esModule = true;
  15979. exports$1["default"] = void 0;
  15980. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  15981. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  15982. 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); }
  15983. 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; }
  15984. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15985. var parser = function parser(processor) {
  15986. return new _processor["default"](processor);
  15987. };
  15988. Object.assign(parser, selectors);
  15989. delete parser.__esModule;
  15990. var _default = parser;
  15991. exports$1["default"] = _default;
  15992. module.exports = exports$1.default;
  15993. } (dist, dist.exports));
  15994. return dist.exports;
  15995. }
  15996. var parse;
  15997. var hasRequiredParse;
  15998. function requireParse () {
  15999. if (hasRequiredParse) return parse;
  16000. hasRequiredParse = 1;
  16001. var openParentheses = "(".charCodeAt(0);
  16002. var closeParentheses = ")".charCodeAt(0);
  16003. var singleQuote = "'".charCodeAt(0);
  16004. var doubleQuote = '"'.charCodeAt(0);
  16005. var backslash = "\\".charCodeAt(0);
  16006. var slash = "/".charCodeAt(0);
  16007. var comma = ",".charCodeAt(0);
  16008. var colon = ":".charCodeAt(0);
  16009. var star = "*".charCodeAt(0);
  16010. var uLower = "u".charCodeAt(0);
  16011. var uUpper = "U".charCodeAt(0);
  16012. var plus = "+".charCodeAt(0);
  16013. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  16014. parse = function(input) {
  16015. var tokens = [];
  16016. var value = input;
  16017. var next,
  16018. quote,
  16019. prev,
  16020. token,
  16021. escape,
  16022. escapePos,
  16023. whitespacePos,
  16024. parenthesesOpenPos;
  16025. var pos = 0;
  16026. var code = value.charCodeAt(pos);
  16027. var max = value.length;
  16028. var stack = [{ nodes: tokens }];
  16029. var balanced = 0;
  16030. var parent;
  16031. var name = "";
  16032. var before = "";
  16033. var after = "";
  16034. while (pos < max) {
  16035. // Whitespaces
  16036. if (code <= 32) {
  16037. next = pos;
  16038. do {
  16039. next += 1;
  16040. code = value.charCodeAt(next);
  16041. } while (code <= 32);
  16042. token = value.slice(pos, next);
  16043. prev = tokens[tokens.length - 1];
  16044. if (code === closeParentheses && balanced) {
  16045. after = token;
  16046. } else if (prev && prev.type === "div") {
  16047. prev.after = token;
  16048. prev.sourceEndIndex += token.length;
  16049. } else if (
  16050. code === comma ||
  16051. code === colon ||
  16052. (code === slash &&
  16053. value.charCodeAt(next + 1) !== star &&
  16054. (!parent ||
  16055. (parent && parent.type === "function" && parent.value !== "calc")))
  16056. ) {
  16057. before = token;
  16058. } else {
  16059. tokens.push({
  16060. type: "space",
  16061. sourceIndex: pos,
  16062. sourceEndIndex: next,
  16063. value: token
  16064. });
  16065. }
  16066. pos = next;
  16067. // Quotes
  16068. } else if (code === singleQuote || code === doubleQuote) {
  16069. next = pos;
  16070. quote = code === singleQuote ? "'" : '"';
  16071. token = {
  16072. type: "string",
  16073. sourceIndex: pos,
  16074. quote: quote
  16075. };
  16076. do {
  16077. escape = false;
  16078. next = value.indexOf(quote, next + 1);
  16079. if (~next) {
  16080. escapePos = next;
  16081. while (value.charCodeAt(escapePos - 1) === backslash) {
  16082. escapePos -= 1;
  16083. escape = !escape;
  16084. }
  16085. } else {
  16086. value += quote;
  16087. next = value.length - 1;
  16088. token.unclosed = true;
  16089. }
  16090. } while (escape);
  16091. token.value = value.slice(pos + 1, next);
  16092. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16093. tokens.push(token);
  16094. pos = next + 1;
  16095. code = value.charCodeAt(pos);
  16096. // Comments
  16097. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16098. next = value.indexOf("*/", pos);
  16099. token = {
  16100. type: "comment",
  16101. sourceIndex: pos,
  16102. sourceEndIndex: next + 2
  16103. };
  16104. if (next === -1) {
  16105. token.unclosed = true;
  16106. next = value.length;
  16107. token.sourceEndIndex = next;
  16108. }
  16109. token.value = value.slice(pos + 2, next);
  16110. tokens.push(token);
  16111. pos = next + 2;
  16112. code = value.charCodeAt(pos);
  16113. // Operation within calc
  16114. } else if (
  16115. (code === slash || code === star) &&
  16116. parent &&
  16117. parent.type === "function" &&
  16118. parent.value === "calc"
  16119. ) {
  16120. token = value[pos];
  16121. tokens.push({
  16122. type: "word",
  16123. sourceIndex: pos - before.length,
  16124. sourceEndIndex: pos + token.length,
  16125. value: token
  16126. });
  16127. pos += 1;
  16128. code = value.charCodeAt(pos);
  16129. // Dividers
  16130. } else if (code === slash || code === comma || code === colon) {
  16131. token = value[pos];
  16132. tokens.push({
  16133. type: "div",
  16134. sourceIndex: pos - before.length,
  16135. sourceEndIndex: pos + token.length,
  16136. value: token,
  16137. before: before,
  16138. after: ""
  16139. });
  16140. before = "";
  16141. pos += 1;
  16142. code = value.charCodeAt(pos);
  16143. // Open parentheses
  16144. } else if (openParentheses === code) {
  16145. // Whitespaces after open parentheses
  16146. next = pos;
  16147. do {
  16148. next += 1;
  16149. code = value.charCodeAt(next);
  16150. } while (code <= 32);
  16151. parenthesesOpenPos = pos;
  16152. token = {
  16153. type: "function",
  16154. sourceIndex: pos - name.length,
  16155. value: name,
  16156. before: value.slice(parenthesesOpenPos + 1, next)
  16157. };
  16158. pos = next;
  16159. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16160. next -= 1;
  16161. do {
  16162. escape = false;
  16163. next = value.indexOf(")", next + 1);
  16164. if (~next) {
  16165. escapePos = next;
  16166. while (value.charCodeAt(escapePos - 1) === backslash) {
  16167. escapePos -= 1;
  16168. escape = !escape;
  16169. }
  16170. } else {
  16171. value += ")";
  16172. next = value.length - 1;
  16173. token.unclosed = true;
  16174. }
  16175. } while (escape);
  16176. // Whitespaces before closed
  16177. whitespacePos = next;
  16178. do {
  16179. whitespacePos -= 1;
  16180. code = value.charCodeAt(whitespacePos);
  16181. } while (code <= 32);
  16182. if (parenthesesOpenPos < whitespacePos) {
  16183. if (pos !== whitespacePos + 1) {
  16184. token.nodes = [
  16185. {
  16186. type: "word",
  16187. sourceIndex: pos,
  16188. sourceEndIndex: whitespacePos + 1,
  16189. value: value.slice(pos, whitespacePos + 1)
  16190. }
  16191. ];
  16192. } else {
  16193. token.nodes = [];
  16194. }
  16195. if (token.unclosed && whitespacePos + 1 !== next) {
  16196. token.after = "";
  16197. token.nodes.push({
  16198. type: "space",
  16199. sourceIndex: whitespacePos + 1,
  16200. sourceEndIndex: next,
  16201. value: value.slice(whitespacePos + 1, next)
  16202. });
  16203. } else {
  16204. token.after = value.slice(whitespacePos + 1, next);
  16205. token.sourceEndIndex = next;
  16206. }
  16207. } else {
  16208. token.after = "";
  16209. token.nodes = [];
  16210. }
  16211. pos = next + 1;
  16212. token.sourceEndIndex = token.unclosed ? next : pos;
  16213. code = value.charCodeAt(pos);
  16214. tokens.push(token);
  16215. } else {
  16216. balanced += 1;
  16217. token.after = "";
  16218. token.sourceEndIndex = pos + 1;
  16219. tokens.push(token);
  16220. stack.push(token);
  16221. tokens = token.nodes = [];
  16222. parent = token;
  16223. }
  16224. name = "";
  16225. // Close parentheses
  16226. } else if (closeParentheses === code && balanced) {
  16227. pos += 1;
  16228. code = value.charCodeAt(pos);
  16229. parent.after = after;
  16230. parent.sourceEndIndex += after.length;
  16231. after = "";
  16232. balanced -= 1;
  16233. stack[stack.length - 1].sourceEndIndex = pos;
  16234. stack.pop();
  16235. parent = stack[balanced];
  16236. tokens = parent.nodes;
  16237. // Words
  16238. } else {
  16239. next = pos;
  16240. do {
  16241. if (code === backslash) {
  16242. next += 1;
  16243. }
  16244. next += 1;
  16245. code = value.charCodeAt(next);
  16246. } while (
  16247. next < max &&
  16248. !(
  16249. code <= 32 ||
  16250. code === singleQuote ||
  16251. code === doubleQuote ||
  16252. code === comma ||
  16253. code === colon ||
  16254. code === slash ||
  16255. code === openParentheses ||
  16256. (code === star &&
  16257. parent &&
  16258. parent.type === "function" &&
  16259. parent.value === "calc") ||
  16260. (code === slash &&
  16261. parent.type === "function" &&
  16262. parent.value === "calc") ||
  16263. (code === closeParentheses && balanced)
  16264. )
  16265. );
  16266. token = value.slice(pos, next);
  16267. if (openParentheses === code) {
  16268. name = token;
  16269. } else if (
  16270. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16271. plus === token.charCodeAt(1) &&
  16272. isUnicodeRange.test(token.slice(2))
  16273. ) {
  16274. tokens.push({
  16275. type: "unicode-range",
  16276. sourceIndex: pos,
  16277. sourceEndIndex: next,
  16278. value: token
  16279. });
  16280. } else {
  16281. tokens.push({
  16282. type: "word",
  16283. sourceIndex: pos,
  16284. sourceEndIndex: next,
  16285. value: token
  16286. });
  16287. }
  16288. pos = next;
  16289. }
  16290. }
  16291. for (pos = stack.length - 1; pos; pos -= 1) {
  16292. stack[pos].unclosed = true;
  16293. stack[pos].sourceEndIndex = value.length;
  16294. }
  16295. return stack[0].nodes;
  16296. };
  16297. return parse;
  16298. }
  16299. var walk$1;
  16300. var hasRequiredWalk;
  16301. function requireWalk () {
  16302. if (hasRequiredWalk) return walk$1;
  16303. hasRequiredWalk = 1;
  16304. walk$1 = function walk(nodes, cb, bubble) {
  16305. var i, max, node, result;
  16306. for (i = 0, max = nodes.length; i < max; i += 1) {
  16307. node = nodes[i];
  16308. if (!bubble) {
  16309. result = cb(node, i, nodes);
  16310. }
  16311. if (
  16312. result !== false &&
  16313. node.type === "function" &&
  16314. Array.isArray(node.nodes)
  16315. ) {
  16316. walk(node.nodes, cb, bubble);
  16317. }
  16318. if (bubble) {
  16319. cb(node, i, nodes);
  16320. }
  16321. }
  16322. };
  16323. return walk$1;
  16324. }
  16325. var stringify_1;
  16326. var hasRequiredStringify;
  16327. function requireStringify () {
  16328. if (hasRequiredStringify) return stringify_1;
  16329. hasRequiredStringify = 1;
  16330. function stringifyNode(node, custom) {
  16331. var type = node.type;
  16332. var value = node.value;
  16333. var buf;
  16334. var customResult;
  16335. if (custom && (customResult = custom(node)) !== undefined) {
  16336. return customResult;
  16337. } else if (type === "word" || type === "space") {
  16338. return value;
  16339. } else if (type === "string") {
  16340. buf = node.quote || "";
  16341. return buf + value + (node.unclosed ? "" : buf);
  16342. } else if (type === "comment") {
  16343. return "/*" + value + (node.unclosed ? "" : "*/");
  16344. } else if (type === "div") {
  16345. return (node.before || "") + value + (node.after || "");
  16346. } else if (Array.isArray(node.nodes)) {
  16347. buf = stringify(node.nodes, custom);
  16348. if (type !== "function") {
  16349. return buf;
  16350. }
  16351. return (
  16352. value +
  16353. "(" +
  16354. (node.before || "") +
  16355. buf +
  16356. (node.after || "") +
  16357. (node.unclosed ? "" : ")")
  16358. );
  16359. }
  16360. return value;
  16361. }
  16362. function stringify(nodes, custom) {
  16363. var result, i;
  16364. if (Array.isArray(nodes)) {
  16365. result = "";
  16366. for (i = nodes.length - 1; ~i; i -= 1) {
  16367. result = stringifyNode(nodes[i], custom) + result;
  16368. }
  16369. return result;
  16370. }
  16371. return stringifyNode(nodes, custom);
  16372. }
  16373. stringify_1 = stringify;
  16374. return stringify_1;
  16375. }
  16376. var unit;
  16377. var hasRequiredUnit;
  16378. function requireUnit () {
  16379. if (hasRequiredUnit) return unit;
  16380. hasRequiredUnit = 1;
  16381. var minus = "-".charCodeAt(0);
  16382. var plus = "+".charCodeAt(0);
  16383. var dot = ".".charCodeAt(0);
  16384. var exp = "e".charCodeAt(0);
  16385. var EXP = "E".charCodeAt(0);
  16386. // Check if three code points would start a number
  16387. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16388. function likeNumber(value) {
  16389. var code = value.charCodeAt(0);
  16390. var nextCode;
  16391. if (code === plus || code === minus) {
  16392. nextCode = value.charCodeAt(1);
  16393. if (nextCode >= 48 && nextCode <= 57) {
  16394. return true;
  16395. }
  16396. var nextNextCode = value.charCodeAt(2);
  16397. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16398. return true;
  16399. }
  16400. return false;
  16401. }
  16402. if (code === dot) {
  16403. nextCode = value.charCodeAt(1);
  16404. if (nextCode >= 48 && nextCode <= 57) {
  16405. return true;
  16406. }
  16407. return false;
  16408. }
  16409. if (code >= 48 && code <= 57) {
  16410. return true;
  16411. }
  16412. return false;
  16413. }
  16414. // Consume a number
  16415. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16416. unit = function(value) {
  16417. var pos = 0;
  16418. var length = value.length;
  16419. var code;
  16420. var nextCode;
  16421. var nextNextCode;
  16422. if (length === 0 || !likeNumber(value)) {
  16423. return false;
  16424. }
  16425. code = value.charCodeAt(pos);
  16426. if (code === plus || code === minus) {
  16427. pos++;
  16428. }
  16429. while (pos < length) {
  16430. code = value.charCodeAt(pos);
  16431. if (code < 48 || code > 57) {
  16432. break;
  16433. }
  16434. pos += 1;
  16435. }
  16436. code = value.charCodeAt(pos);
  16437. nextCode = value.charCodeAt(pos + 1);
  16438. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16439. pos += 2;
  16440. while (pos < length) {
  16441. code = value.charCodeAt(pos);
  16442. if (code < 48 || code > 57) {
  16443. break;
  16444. }
  16445. pos += 1;
  16446. }
  16447. }
  16448. code = value.charCodeAt(pos);
  16449. nextCode = value.charCodeAt(pos + 1);
  16450. nextNextCode = value.charCodeAt(pos + 2);
  16451. if (
  16452. (code === exp || code === EXP) &&
  16453. ((nextCode >= 48 && nextCode <= 57) ||
  16454. ((nextCode === plus || nextCode === minus) &&
  16455. nextNextCode >= 48 &&
  16456. nextNextCode <= 57))
  16457. ) {
  16458. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16459. while (pos < length) {
  16460. code = value.charCodeAt(pos);
  16461. if (code < 48 || code > 57) {
  16462. break;
  16463. }
  16464. pos += 1;
  16465. }
  16466. }
  16467. return {
  16468. number: value.slice(0, pos),
  16469. unit: value.slice(pos)
  16470. };
  16471. };
  16472. return unit;
  16473. }
  16474. var lib;
  16475. var hasRequiredLib;
  16476. function requireLib () {
  16477. if (hasRequiredLib) return lib;
  16478. hasRequiredLib = 1;
  16479. var parse = /*@__PURE__*/ requireParse();
  16480. var walk = /*@__PURE__*/ requireWalk();
  16481. var stringify = /*@__PURE__*/ requireStringify();
  16482. function ValueParser(value) {
  16483. if (this instanceof ValueParser) {
  16484. this.nodes = parse(value);
  16485. return this;
  16486. }
  16487. return new ValueParser(value);
  16488. }
  16489. ValueParser.prototype.toString = function() {
  16490. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  16491. };
  16492. ValueParser.prototype.walk = function(cb, bubble) {
  16493. walk(this.nodes, cb, bubble);
  16494. return this;
  16495. };
  16496. ValueParser.unit = /*@__PURE__*/ requireUnit();
  16497. ValueParser.walk = walk;
  16498. ValueParser.stringify = stringify;
  16499. lib = ValueParser;
  16500. return lib;
  16501. }
  16502. var hasRequiredSrc$2;
  16503. function requireSrc$2 () {
  16504. if (hasRequiredSrc$2) return src$2.exports;
  16505. hasRequiredSrc$2 = 1;
  16506. const selectorParser = /*@__PURE__*/ requireDist();
  16507. const valueParser = /*@__PURE__*/ requireLib();
  16508. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  16509. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  16510. function normalizeNodeArray(nodes) {
  16511. const array = [];
  16512. nodes.forEach((x) => {
  16513. if (Array.isArray(x)) {
  16514. normalizeNodeArray(x).forEach((item) => {
  16515. array.push(item);
  16516. });
  16517. } else if (x) {
  16518. array.push(x);
  16519. }
  16520. });
  16521. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  16522. array.pop();
  16523. }
  16524. return array;
  16525. }
  16526. function localizeNode(rule, mode, localAliasMap) {
  16527. const transform = (node, context) => {
  16528. if (context.ignoreNextSpacing && !isSpacing(node)) {
  16529. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  16530. }
  16531. if (context.enforceNoSpacing && isSpacing(node)) {
  16532. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  16533. }
  16534. let newNodes;
  16535. switch (node.type) {
  16536. case "root": {
  16537. let resultingGlobal;
  16538. context.hasPureGlobals = false;
  16539. newNodes = node.nodes.map((n) => {
  16540. const nContext = {
  16541. global: context.global,
  16542. lastWasSpacing: true,
  16543. hasLocals: false,
  16544. explicit: false,
  16545. };
  16546. n = transform(n, nContext);
  16547. if (typeof resultingGlobal === "undefined") {
  16548. resultingGlobal = nContext.global;
  16549. } else if (resultingGlobal !== nContext.global) {
  16550. throw new Error(
  16551. 'Inconsistent rule global/local result in rule "' +
  16552. node +
  16553. '" (multiple selectors must result in the same mode for the rule)'
  16554. );
  16555. }
  16556. if (!nContext.hasLocals) {
  16557. context.hasPureGlobals = true;
  16558. }
  16559. return n;
  16560. });
  16561. context.global = resultingGlobal;
  16562. node.nodes = normalizeNodeArray(newNodes);
  16563. break;
  16564. }
  16565. case "selector": {
  16566. newNodes = node.map((childNode) => transform(childNode, context));
  16567. node = node.clone();
  16568. node.nodes = normalizeNodeArray(newNodes);
  16569. break;
  16570. }
  16571. case "combinator": {
  16572. if (isSpacing(node)) {
  16573. if (context.ignoreNextSpacing) {
  16574. context.ignoreNextSpacing = false;
  16575. context.lastWasSpacing = false;
  16576. context.enforceNoSpacing = false;
  16577. return null;
  16578. }
  16579. context.lastWasSpacing = true;
  16580. return node;
  16581. }
  16582. break;
  16583. }
  16584. case "pseudo": {
  16585. let childContext;
  16586. const isNested = !!node.length;
  16587. const isScoped = node.value === ":local" || node.value === ":global";
  16588. const isImportExport =
  16589. node.value === ":import" || node.value === ":export";
  16590. if (isImportExport) {
  16591. context.hasLocals = true;
  16592. // :local(.foo)
  16593. } else if (isNested) {
  16594. if (isScoped) {
  16595. if (node.nodes.length === 0) {
  16596. throw new Error(`${node.value}() can't be empty`);
  16597. }
  16598. if (context.inside) {
  16599. throw new Error(
  16600. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16601. );
  16602. }
  16603. childContext = {
  16604. global: node.value === ":global",
  16605. inside: node.value,
  16606. hasLocals: false,
  16607. explicit: true,
  16608. };
  16609. newNodes = node
  16610. .map((childNode) => transform(childNode, childContext))
  16611. .reduce((acc, next) => acc.concat(next.nodes), []);
  16612. if (newNodes.length) {
  16613. const { before, after } = node.spaces;
  16614. const first = newNodes[0];
  16615. const last = newNodes[newNodes.length - 1];
  16616. first.spaces = { before, after: first.spaces.after };
  16617. last.spaces = { before: last.spaces.before, after };
  16618. }
  16619. node = newNodes;
  16620. break;
  16621. } else {
  16622. childContext = {
  16623. global: context.global,
  16624. inside: context.inside,
  16625. lastWasSpacing: true,
  16626. hasLocals: false,
  16627. explicit: context.explicit,
  16628. };
  16629. newNodes = node.map((childNode) => {
  16630. const newContext = {
  16631. ...childContext,
  16632. enforceNoSpacing: false,
  16633. };
  16634. const result = transform(childNode, newContext);
  16635. childContext.global = newContext.global;
  16636. childContext.hasLocals = newContext.hasLocals;
  16637. return result;
  16638. });
  16639. node = node.clone();
  16640. node.nodes = normalizeNodeArray(newNodes);
  16641. if (childContext.hasLocals) {
  16642. context.hasLocals = true;
  16643. }
  16644. }
  16645. break;
  16646. //:local .foo .bar
  16647. } else if (isScoped) {
  16648. if (context.inside) {
  16649. throw new Error(
  16650. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16651. );
  16652. }
  16653. const addBackSpacing = !!node.spaces.before;
  16654. context.ignoreNextSpacing = context.lastWasSpacing
  16655. ? node.value
  16656. : false;
  16657. context.enforceNoSpacing = context.lastWasSpacing
  16658. ? false
  16659. : node.value;
  16660. context.global = node.value === ":global";
  16661. context.explicit = true;
  16662. // because this node has spacing that is lost when we remove it
  16663. // we make up for it by adding an extra combinator in since adding
  16664. // spacing on the parent selector doesn't work
  16665. return addBackSpacing
  16666. ? selectorParser.combinator({ value: " " })
  16667. : null;
  16668. }
  16669. break;
  16670. }
  16671. case "id":
  16672. case "class": {
  16673. if (!node.value) {
  16674. throw new Error("Invalid class or id selector syntax");
  16675. }
  16676. if (context.global) {
  16677. break;
  16678. }
  16679. const isImportedValue = localAliasMap.has(node.value);
  16680. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  16681. if (!isImportedValue || isImportedWithExplicitScope) {
  16682. const innerNode = node.clone();
  16683. innerNode.spaces = { before: "", after: "" };
  16684. node = selectorParser.pseudo({
  16685. value: ":local",
  16686. nodes: [innerNode],
  16687. spaces: node.spaces,
  16688. });
  16689. context.hasLocals = true;
  16690. }
  16691. break;
  16692. }
  16693. case "nesting": {
  16694. if (node.value === "&") {
  16695. context.hasLocals = true;
  16696. }
  16697. }
  16698. }
  16699. context.lastWasSpacing = false;
  16700. context.ignoreNextSpacing = false;
  16701. context.enforceNoSpacing = false;
  16702. return node;
  16703. };
  16704. const rootContext = {
  16705. global: mode === "global",
  16706. hasPureGlobals: false,
  16707. };
  16708. rootContext.selector = selectorParser((root) => {
  16709. transform(root, rootContext);
  16710. }).processSync(rule, { updateSelector: false, lossless: true });
  16711. return rootContext;
  16712. }
  16713. function localizeDeclNode(node, context) {
  16714. switch (node.type) {
  16715. case "word":
  16716. if (context.localizeNextItem) {
  16717. if (!context.localAliasMap.has(node.value)) {
  16718. node.value = ":local(" + node.value + ")";
  16719. context.localizeNextItem = false;
  16720. }
  16721. }
  16722. break;
  16723. case "function":
  16724. if (
  16725. context.options &&
  16726. context.options.rewriteUrl &&
  16727. node.value.toLowerCase() === "url"
  16728. ) {
  16729. node.nodes.map((nestedNode) => {
  16730. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  16731. return;
  16732. }
  16733. let newUrl = context.options.rewriteUrl(
  16734. context.global,
  16735. nestedNode.value
  16736. );
  16737. switch (nestedNode.type) {
  16738. case "string":
  16739. if (nestedNode.quote === "'") {
  16740. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  16741. }
  16742. if (nestedNode.quote === '"') {
  16743. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  16744. }
  16745. break;
  16746. case "word":
  16747. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  16748. break;
  16749. }
  16750. nestedNode.value = newUrl;
  16751. });
  16752. }
  16753. break;
  16754. }
  16755. return node;
  16756. }
  16757. // `none` is special value, other is global values
  16758. const specialKeywords = [
  16759. "none",
  16760. "inherit",
  16761. "initial",
  16762. "revert",
  16763. "revert-layer",
  16764. "unset",
  16765. ];
  16766. function localizeDeclarationValues(localize, declaration, context) {
  16767. const valueNodes = valueParser(declaration.value);
  16768. valueNodes.walk((node, index, nodes) => {
  16769. if (
  16770. node.type === "function" &&
  16771. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  16772. ) {
  16773. return false;
  16774. }
  16775. if (
  16776. node.type === "word" &&
  16777. specialKeywords.includes(node.value.toLowerCase())
  16778. ) {
  16779. return;
  16780. }
  16781. const subContext = {
  16782. options: context.options,
  16783. global: context.global,
  16784. localizeNextItem: localize && !context.global,
  16785. localAliasMap: context.localAliasMap,
  16786. };
  16787. nodes[index] = localizeDeclNode(node, subContext);
  16788. });
  16789. declaration.value = valueNodes.toString();
  16790. }
  16791. function localizeDeclaration(declaration, context) {
  16792. const isAnimation = /animation$/i.test(declaration.prop);
  16793. if (isAnimation) {
  16794. // letter
  16795. // An uppercase letter or a lowercase letter.
  16796. //
  16797. // ident-start code point
  16798. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  16799. //
  16800. // ident code point
  16801. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  16802. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  16803. const validIdent =
  16804. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  16805. /*
  16806. The spec defines some keywords that you can use to describe properties such as the timing
  16807. function. These are still valid animation names, so as long as there is a property that accepts
  16808. a keyword, it is given priority. Only when all the properties that can take a keyword are
  16809. exhausted can the animation name be set to the keyword. I.e.
  16810. animation: infinite infinite;
  16811. The animation will repeat an infinite number of times from the first argument, and will have an
  16812. animation name of infinite from the second.
  16813. */
  16814. const animationKeywords = {
  16815. // animation-direction
  16816. $normal: 1,
  16817. $reverse: 1,
  16818. $alternate: 1,
  16819. "$alternate-reverse": 1,
  16820. // animation-fill-mode
  16821. $forwards: 1,
  16822. $backwards: 1,
  16823. $both: 1,
  16824. // animation-iteration-count
  16825. $infinite: 1,
  16826. // animation-play-state
  16827. $paused: 1,
  16828. $running: 1,
  16829. // animation-timing-function
  16830. $ease: 1,
  16831. "$ease-in": 1,
  16832. "$ease-out": 1,
  16833. "$ease-in-out": 1,
  16834. $linear: 1,
  16835. "$step-end": 1,
  16836. "$step-start": 1,
  16837. // Special
  16838. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  16839. // Global values
  16840. $initial: Infinity,
  16841. $inherit: Infinity,
  16842. $unset: Infinity,
  16843. $revert: Infinity,
  16844. "$revert-layer": Infinity,
  16845. };
  16846. let parsedAnimationKeywords = {};
  16847. const valueNodes = valueParser(declaration.value).walk((node) => {
  16848. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  16849. if (node.type === "div") {
  16850. parsedAnimationKeywords = {};
  16851. return;
  16852. }
  16853. // Do not handle nested functions
  16854. else if (node.type === "function") {
  16855. return false;
  16856. }
  16857. // Ignore all except word
  16858. else if (node.type !== "word") {
  16859. return;
  16860. }
  16861. const value = node.type === "word" ? node.value.toLowerCase() : null;
  16862. let shouldParseAnimationName = false;
  16863. if (value && validIdent.test(value)) {
  16864. if ("$" + value in animationKeywords) {
  16865. parsedAnimationKeywords["$" + value] =
  16866. "$" + value in parsedAnimationKeywords
  16867. ? parsedAnimationKeywords["$" + value] + 1
  16868. : 0;
  16869. shouldParseAnimationName =
  16870. parsedAnimationKeywords["$" + value] >=
  16871. animationKeywords["$" + value];
  16872. } else {
  16873. shouldParseAnimationName = true;
  16874. }
  16875. }
  16876. const subContext = {
  16877. options: context.options,
  16878. global: context.global,
  16879. localizeNextItem: shouldParseAnimationName && !context.global,
  16880. localAliasMap: context.localAliasMap,
  16881. };
  16882. return localizeDeclNode(node, subContext);
  16883. });
  16884. declaration.value = valueNodes.toString();
  16885. return;
  16886. }
  16887. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  16888. if (isAnimationName) {
  16889. return localizeDeclarationValues(true, declaration, context);
  16890. }
  16891. const hasUrl = /url\(/i.test(declaration.value);
  16892. if (hasUrl) {
  16893. return localizeDeclarationValues(false, declaration, context);
  16894. }
  16895. }
  16896. src$2.exports = (options = {}) => {
  16897. if (
  16898. options &&
  16899. options.mode &&
  16900. options.mode !== "global" &&
  16901. options.mode !== "local" &&
  16902. options.mode !== "pure"
  16903. ) {
  16904. throw new Error(
  16905. 'options.mode must be either "global", "local" or "pure" (default "local")'
  16906. );
  16907. }
  16908. const pureMode = options && options.mode === "pure";
  16909. const globalMode = options && options.mode === "global";
  16910. return {
  16911. postcssPlugin: "postcss-modules-local-by-default",
  16912. prepare() {
  16913. const localAliasMap = new Map();
  16914. return {
  16915. Once(root) {
  16916. const { icssImports } = extractICSS(root, false);
  16917. Object.keys(icssImports).forEach((key) => {
  16918. Object.keys(icssImports[key]).forEach((prop) => {
  16919. localAliasMap.set(prop, icssImports[key][prop]);
  16920. });
  16921. });
  16922. root.walkAtRules((atRule) => {
  16923. if (/keyframes$/i.test(atRule.name)) {
  16924. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  16925. atRule.params
  16926. );
  16927. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  16928. atRule.params
  16929. );
  16930. let globalKeyframes = globalMode;
  16931. if (globalMatch) {
  16932. if (pureMode) {
  16933. throw atRule.error(
  16934. "@keyframes :global(...) is not allowed in pure mode"
  16935. );
  16936. }
  16937. atRule.params = globalMatch[1];
  16938. globalKeyframes = true;
  16939. } else if (localMatch) {
  16940. atRule.params = localMatch[0];
  16941. globalKeyframes = false;
  16942. } else if (
  16943. atRule.params &&
  16944. !globalMode &&
  16945. !localAliasMap.has(atRule.params)
  16946. ) {
  16947. atRule.params = ":local(" + atRule.params + ")";
  16948. }
  16949. atRule.walkDecls((declaration) => {
  16950. localizeDeclaration(declaration, {
  16951. localAliasMap,
  16952. options: options,
  16953. global: globalKeyframes,
  16954. });
  16955. });
  16956. } else if (/scope$/i.test(atRule.name)) {
  16957. if (atRule.params) {
  16958. atRule.params = atRule.params
  16959. .split("to")
  16960. .map((item) => {
  16961. const selector = item.trim().slice(1, -1).trim();
  16962. const context = localizeNode(
  16963. selector,
  16964. options.mode,
  16965. localAliasMap
  16966. );
  16967. context.options = options;
  16968. context.localAliasMap = localAliasMap;
  16969. if (pureMode && context.hasPureGlobals) {
  16970. throw atRule.error(
  16971. 'Selector in at-rule"' +
  16972. selector +
  16973. '" is not pure ' +
  16974. "(pure selectors must contain at least one local class or id)"
  16975. );
  16976. }
  16977. return `(${context.selector})`;
  16978. })
  16979. .join(" to ");
  16980. }
  16981. atRule.nodes.forEach((declaration) => {
  16982. if (declaration.type === "decl") {
  16983. localizeDeclaration(declaration, {
  16984. localAliasMap,
  16985. options: options,
  16986. global: globalMode,
  16987. });
  16988. }
  16989. });
  16990. } else if (atRule.nodes) {
  16991. atRule.nodes.forEach((declaration) => {
  16992. if (declaration.type === "decl") {
  16993. localizeDeclaration(declaration, {
  16994. localAliasMap,
  16995. options: options,
  16996. global: globalMode,
  16997. });
  16998. }
  16999. });
  17000. }
  17001. });
  17002. root.walkRules((rule) => {
  17003. if (
  17004. rule.parent &&
  17005. rule.parent.type === "atrule" &&
  17006. /keyframes$/i.test(rule.parent.name)
  17007. ) {
  17008. // ignore keyframe rules
  17009. return;
  17010. }
  17011. const context = localizeNode(rule, options.mode, localAliasMap);
  17012. context.options = options;
  17013. context.localAliasMap = localAliasMap;
  17014. if (pureMode && context.hasPureGlobals) {
  17015. throw rule.error(
  17016. 'Selector "' +
  17017. rule.selector +
  17018. '" is not pure ' +
  17019. "(pure selectors must contain at least one local class or id)"
  17020. );
  17021. }
  17022. rule.selector = context.selector;
  17023. // Less-syntax mixins parse as rules with no nodes
  17024. if (rule.nodes) {
  17025. rule.nodes.forEach((declaration) =>
  17026. localizeDeclaration(declaration, context)
  17027. );
  17028. }
  17029. });
  17030. },
  17031. };
  17032. },
  17033. };
  17034. };
  17035. src$2.exports.postcss = true;
  17036. return src$2.exports;
  17037. }
  17038. var src$1;
  17039. var hasRequiredSrc$1;
  17040. function requireSrc$1 () {
  17041. if (hasRequiredSrc$1) return src$1;
  17042. hasRequiredSrc$1 = 1;
  17043. const selectorParser = /*@__PURE__*/ requireDist();
  17044. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17045. function isNestedRule(rule) {
  17046. if (!rule.parent || rule.parent.type === "root") {
  17047. return false;
  17048. }
  17049. if (rule.parent.type === "rule") {
  17050. return true;
  17051. }
  17052. return isNestedRule(rule.parent);
  17053. }
  17054. function getSingleLocalNamesForComposes(root, rule) {
  17055. if (isNestedRule(rule)) {
  17056. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17057. }
  17058. return root.nodes.map((node) => {
  17059. if (node.type !== "selector" || node.nodes.length !== 1) {
  17060. throw new Error(
  17061. `composition is only allowed when selector is single :local class name not in "${root}"`
  17062. );
  17063. }
  17064. node = node.nodes[0];
  17065. if (
  17066. node.type !== "pseudo" ||
  17067. node.value !== ":local" ||
  17068. node.nodes.length !== 1
  17069. ) {
  17070. throw new Error(
  17071. 'composition is only allowed when selector is single :local class name not in "' +
  17072. root +
  17073. '", "' +
  17074. node +
  17075. '" is weird'
  17076. );
  17077. }
  17078. node = node.first;
  17079. if (node.type !== "selector" || node.length !== 1) {
  17080. throw new Error(
  17081. 'composition is only allowed when selector is single :local class name not in "' +
  17082. root +
  17083. '", "' +
  17084. node +
  17085. '" is weird'
  17086. );
  17087. }
  17088. node = node.first;
  17089. if (node.type !== "class") {
  17090. // 'id' is not possible, because you can't compose ids
  17091. throw new Error(
  17092. 'composition is only allowed when selector is single :local class name not in "' +
  17093. root +
  17094. '", "' +
  17095. node +
  17096. '" is weird'
  17097. );
  17098. }
  17099. return node.value;
  17100. });
  17101. }
  17102. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17103. const unescapeRegExp = new RegExp(
  17104. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17105. "ig"
  17106. );
  17107. function unescape(str) {
  17108. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17109. const high = "0x" + escaped - 0x10000;
  17110. // NaN means non-codepoint
  17111. // Workaround erroneous numeric interpretation of +"0x"
  17112. return high !== high || escapedWhitespace
  17113. ? escaped
  17114. : high < 0
  17115. ? // BMP codepoint
  17116. String.fromCharCode(high + 0x10000)
  17117. : // Supplemental Plane codepoint (surrogate pair)
  17118. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17119. });
  17120. }
  17121. const plugin = (options = {}) => {
  17122. const generateScopedName =
  17123. (options && options.generateScopedName) || plugin.generateScopedName;
  17124. const generateExportEntry =
  17125. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17126. const exportGlobals = options && options.exportGlobals;
  17127. return {
  17128. postcssPlugin: "postcss-modules-scope",
  17129. Once(root, { rule }) {
  17130. const exports$1 = Object.create(null);
  17131. function exportScopedName(name, rawName, node) {
  17132. const scopedName = generateScopedName(
  17133. rawName ? rawName : name,
  17134. root.source.input.from,
  17135. root.source.input.css,
  17136. node
  17137. );
  17138. const exportEntry = generateExportEntry(
  17139. rawName ? rawName : name,
  17140. scopedName,
  17141. root.source.input.from,
  17142. root.source.input.css,
  17143. node
  17144. );
  17145. const { key, value } = exportEntry;
  17146. exports$1[key] = exports$1[key] || [];
  17147. if (exports$1[key].indexOf(value) < 0) {
  17148. exports$1[key].push(value);
  17149. }
  17150. return scopedName;
  17151. }
  17152. function localizeNode(node) {
  17153. switch (node.type) {
  17154. case "selector":
  17155. node.nodes = node.map((item) => localizeNode(item));
  17156. return node;
  17157. case "class":
  17158. return selectorParser.className({
  17159. value: exportScopedName(
  17160. node.value,
  17161. node.raws && node.raws.value ? node.raws.value : null,
  17162. node
  17163. ),
  17164. });
  17165. case "id": {
  17166. return selectorParser.id({
  17167. value: exportScopedName(
  17168. node.value,
  17169. node.raws && node.raws.value ? node.raws.value : null,
  17170. node
  17171. ),
  17172. });
  17173. }
  17174. case "attribute": {
  17175. if (node.attribute === "class" && node.operator === "=") {
  17176. return selectorParser.attribute({
  17177. attribute: node.attribute,
  17178. operator: node.operator,
  17179. quoteMark: "'",
  17180. value: exportScopedName(node.value, null, null),
  17181. });
  17182. }
  17183. }
  17184. }
  17185. throw new Error(
  17186. `${node.type} ("${node}") is not allowed in a :local block`
  17187. );
  17188. }
  17189. function traverseNode(node) {
  17190. switch (node.type) {
  17191. case "pseudo":
  17192. if (node.value === ":local") {
  17193. if (node.nodes.length !== 1) {
  17194. throw new Error('Unexpected comma (",") in :local block');
  17195. }
  17196. const selector = localizeNode(node.first);
  17197. // move the spaces that were around the pseudo selector to the first
  17198. // non-container node
  17199. selector.first.spaces = node.spaces;
  17200. const nextNode = node.next();
  17201. if (
  17202. nextNode &&
  17203. nextNode.type === "combinator" &&
  17204. nextNode.value === " " &&
  17205. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17206. ) {
  17207. selector.last.spaces.after = " ";
  17208. }
  17209. node.replaceWith(selector);
  17210. return;
  17211. }
  17212. /* falls through */
  17213. case "root":
  17214. case "selector": {
  17215. node.each((item) => traverseNode(item));
  17216. break;
  17217. }
  17218. case "id":
  17219. case "class":
  17220. if (exportGlobals) {
  17221. exports$1[node.value] = [node.value];
  17222. }
  17223. break;
  17224. }
  17225. return node;
  17226. }
  17227. // Find any :import and remember imported names
  17228. const importedNames = {};
  17229. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17230. rule.walkDecls((decl) => {
  17231. importedNames[decl.prop] = true;
  17232. });
  17233. });
  17234. // Find any :local selectors
  17235. root.walkRules((rule) => {
  17236. let parsedSelector = selectorParser().astSync(rule);
  17237. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17238. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17239. const localNames = getSingleLocalNamesForComposes(
  17240. parsedSelector,
  17241. decl.parent
  17242. );
  17243. const multiple = decl.value.split(",");
  17244. multiple.forEach((value) => {
  17245. const classes = value.trim().split(/\s+/);
  17246. classes.forEach((className) => {
  17247. const global = /^global\(([^)]+)\)$/.exec(className);
  17248. if (global) {
  17249. localNames.forEach((exportedName) => {
  17250. exports$1[exportedName].push(global[1]);
  17251. });
  17252. } else if (hasOwnProperty.call(importedNames, className)) {
  17253. localNames.forEach((exportedName) => {
  17254. exports$1[exportedName].push(className);
  17255. });
  17256. } else if (hasOwnProperty.call(exports$1, className)) {
  17257. localNames.forEach((exportedName) => {
  17258. exports$1[className].forEach((item) => {
  17259. exports$1[exportedName].push(item);
  17260. });
  17261. });
  17262. } else {
  17263. throw decl.error(
  17264. `referenced class name "${className}" in ${decl.prop} not found`
  17265. );
  17266. }
  17267. });
  17268. });
  17269. decl.remove();
  17270. });
  17271. // Find any :local values
  17272. rule.walkDecls((decl) => {
  17273. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17274. return;
  17275. }
  17276. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17277. tokens = tokens.map((token, idx) => {
  17278. if (idx === 0 || tokens[idx - 1] === ",") {
  17279. let result = token;
  17280. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17281. if (localMatch) {
  17282. const input = localMatch.input;
  17283. const matchPattern = localMatch[0];
  17284. const matchVal = localMatch[1];
  17285. const newVal = exportScopedName(matchVal);
  17286. result = input.replace(matchPattern, newVal);
  17287. } else {
  17288. return token;
  17289. }
  17290. return result;
  17291. } else {
  17292. return token;
  17293. }
  17294. });
  17295. decl.value = tokens.join("");
  17296. });
  17297. });
  17298. // Find any :local keyframes
  17299. root.walkAtRules(/keyframes$/i, (atRule) => {
  17300. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17301. if (!localMatch) {
  17302. return;
  17303. }
  17304. atRule.params = exportScopedName(localMatch[1]);
  17305. });
  17306. root.walkAtRules(/scope$/i, (atRule) => {
  17307. if (atRule.params) {
  17308. atRule.params = atRule.params
  17309. .split("to")
  17310. .map((item) => {
  17311. const selector = item.trim().slice(1, -1).trim();
  17312. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17313. if (!localMatch) {
  17314. return `(${selector})`;
  17315. }
  17316. let parsedSelector = selectorParser().astSync(selector);
  17317. return `(${traverseNode(parsedSelector).toString()})`;
  17318. })
  17319. .join(" to ");
  17320. }
  17321. });
  17322. // If we found any :locals, insert an :export rule
  17323. const exportedNames = Object.keys(exports$1);
  17324. if (exportedNames.length > 0) {
  17325. const exportRule = rule({ selector: ":export" });
  17326. exportedNames.forEach((exportedName) =>
  17327. exportRule.append({
  17328. prop: exportedName,
  17329. value: exports$1[exportedName].join(" "),
  17330. raws: { before: "\n " },
  17331. })
  17332. );
  17333. root.append(exportRule);
  17334. }
  17335. },
  17336. };
  17337. };
  17338. plugin.postcss = true;
  17339. plugin.generateScopedName = function (name, path) {
  17340. const sanitisedPath = path
  17341. .replace(/\.[^./\\]+$/, "")
  17342. .replace(/[\W_]+/g, "_")
  17343. .replace(/^_|_$/g, "");
  17344. return `_${sanitisedPath}__${name}`.trim();
  17345. };
  17346. plugin.generateExportEntry = function (name, scopedName) {
  17347. return {
  17348. key: unescape(name),
  17349. value: unescape(scopedName),
  17350. };
  17351. };
  17352. src$1 = plugin;
  17353. return src$1;
  17354. }
  17355. var stringHash;
  17356. var hasRequiredStringHash;
  17357. function requireStringHash () {
  17358. if (hasRequiredStringHash) return stringHash;
  17359. hasRequiredStringHash = 1;
  17360. function hash(str) {
  17361. var hash = 5381,
  17362. i = str.length;
  17363. while(i) {
  17364. hash = (hash * 33) ^ str.charCodeAt(--i);
  17365. }
  17366. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17367. * integers. Since we want the results to be always positive, convert the
  17368. * signed int to an unsigned by doing an unsigned bitshift. */
  17369. return hash >>> 0;
  17370. }
  17371. stringHash = hash;
  17372. return stringHash;
  17373. }
  17374. var src = {exports: {}};
  17375. var hasRequiredSrc;
  17376. function requireSrc () {
  17377. if (hasRequiredSrc) return src.exports;
  17378. hasRequiredSrc = 1;
  17379. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17380. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17381. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17382. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17383. src.exports = (options) => {
  17384. let importIndex = 0;
  17385. const createImportedName =
  17386. (options && options.createImportedName) ||
  17387. ((importName /*, path*/) =>
  17388. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17389. return {
  17390. postcssPlugin: "postcss-modules-values",
  17391. prepare(result) {
  17392. const importAliases = [];
  17393. const definitions = {};
  17394. return {
  17395. Once(root, postcss) {
  17396. root.walkAtRules(/value/i, (atRule) => {
  17397. const matches = atRule.params.match(matchImports);
  17398. if (matches) {
  17399. let [, /*match*/ aliases, path] = matches;
  17400. // We can use constants for path names
  17401. if (definitions[path]) {
  17402. path = definitions[path];
  17403. }
  17404. const imports = aliases
  17405. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17406. .split(/\s*,\s*/)
  17407. .map((alias) => {
  17408. const tokens = matchImport.exec(alias);
  17409. if (tokens) {
  17410. const [, /*match*/ theirName, myName = theirName] = tokens;
  17411. const importedName = createImportedName(myName);
  17412. definitions[myName] = importedName;
  17413. return { theirName, importedName };
  17414. } else {
  17415. throw new Error(`@import statement "${alias}" is invalid!`);
  17416. }
  17417. });
  17418. importAliases.push({ path, imports });
  17419. atRule.remove();
  17420. return;
  17421. }
  17422. if (atRule.params.indexOf("@value") !== -1) {
  17423. result.warn("Invalid value definition: " + atRule.params);
  17424. }
  17425. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17426. matchValueDefinition
  17427. );
  17428. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17429. if (normalizedValue.length === 0) {
  17430. result.warn("Invalid value definition: " + atRule.params);
  17431. atRule.remove();
  17432. return;
  17433. }
  17434. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17435. if (!isOnlySpace) {
  17436. value = value.trim();
  17437. }
  17438. // Add to the definitions, knowing that values can refer to each other
  17439. definitions[key] = ICSSUtils.replaceValueSymbols(
  17440. value,
  17441. definitions
  17442. );
  17443. atRule.remove();
  17444. });
  17445. /* If we have no definitions, don't continue */
  17446. if (!Object.keys(definitions).length) {
  17447. return;
  17448. }
  17449. /* Perform replacements */
  17450. ICSSUtils.replaceSymbols(root, definitions);
  17451. /* 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 */
  17452. const exportDeclarations = Object.keys(definitions).map((key) =>
  17453. postcss.decl({
  17454. value: definitions[key],
  17455. prop: key,
  17456. raws: { before: "\n " },
  17457. })
  17458. );
  17459. /* Add export rules if any */
  17460. if (exportDeclarations.length > 0) {
  17461. const exportRule = postcss.rule({
  17462. selector: ":export",
  17463. raws: { after: "\n" },
  17464. });
  17465. exportRule.append(exportDeclarations);
  17466. root.prepend(exportRule);
  17467. }
  17468. /* Add import rules */
  17469. importAliases.reverse().forEach(({ path, imports }) => {
  17470. const importRule = postcss.rule({
  17471. selector: `:import(${path})`,
  17472. raws: { after: "\n" },
  17473. });
  17474. imports.forEach(({ theirName, importedName }) => {
  17475. importRule.append({
  17476. value: theirName,
  17477. prop: importedName,
  17478. raws: { before: "\n " },
  17479. });
  17480. });
  17481. root.prepend(importRule);
  17482. });
  17483. },
  17484. };
  17485. },
  17486. };
  17487. };
  17488. src.exports.postcss = true;
  17489. return src.exports;
  17490. }
  17491. var hasRequiredScoping;
  17492. function requireScoping () {
  17493. if (hasRequiredScoping) return scoping;
  17494. hasRequiredScoping = 1;
  17495. Object.defineProperty(scoping, "__esModule", {
  17496. value: true
  17497. });
  17498. scoping.behaviours = void 0;
  17499. scoping.getDefaultPlugins = getDefaultPlugins;
  17500. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  17501. scoping.getScopedNameGenerator = getScopedNameGenerator;
  17502. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  17503. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  17504. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  17505. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  17506. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  17507. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  17508. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17509. const behaviours = {
  17510. LOCAL: "local",
  17511. GLOBAL: "global"
  17512. };
  17513. scoping.behaviours = behaviours;
  17514. function getDefaultPlugins({
  17515. behaviour,
  17516. generateScopedName,
  17517. exportGlobals
  17518. }) {
  17519. const scope = (0, _postcssModulesScope.default)({
  17520. generateScopedName,
  17521. exportGlobals
  17522. });
  17523. const plugins = {
  17524. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17525. mode: "local"
  17526. }), _postcssModulesExtractImports.default, scope],
  17527. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17528. mode: "global"
  17529. }), _postcssModulesExtractImports.default, scope]
  17530. };
  17531. return plugins[behaviour];
  17532. }
  17533. function isValidBehaviour(behaviour) {
  17534. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  17535. }
  17536. function getDefaultScopeBehaviour(scopeBehaviour) {
  17537. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  17538. }
  17539. function generateScopedNameDefault(name, filename, css) {
  17540. const i = css.indexOf(`.${name}`);
  17541. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  17542. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  17543. return `_${name}_${hash}_${lineNumber}`;
  17544. }
  17545. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  17546. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  17547. if (typeof scopedNameGenerator === "function") {
  17548. return scopedNameGenerator;
  17549. }
  17550. return (0, _genericNames.default)(scopedNameGenerator, {
  17551. context: process.cwd(),
  17552. hashPrefix: hashPrefix
  17553. });
  17554. }
  17555. return scoping;
  17556. }
  17557. var hasRequiredPluginFactory;
  17558. function requirePluginFactory () {
  17559. if (hasRequiredPluginFactory) return pluginFactory;
  17560. hasRequiredPluginFactory = 1;
  17561. Object.defineProperty(pluginFactory, "__esModule", {
  17562. value: true
  17563. });
  17564. pluginFactory.makePlugin = makePlugin;
  17565. var _postcss = _interopRequireDefault(require$$0$1);
  17566. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  17567. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  17568. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  17569. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  17570. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  17571. var _scoping = /*@__PURE__*/ requireScoping();
  17572. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17573. const PLUGIN_NAME = "postcss-modules";
  17574. function isGlobalModule(globalModules, inputFile) {
  17575. return globalModules.some(regex => inputFile.match(regex));
  17576. }
  17577. function getDefaultPluginsList(opts, inputFile) {
  17578. const globalModulesList = opts.globalModulePaths || null;
  17579. const exportGlobals = opts.exportGlobals || false;
  17580. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  17581. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  17582. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  17583. return (0, _scoping.getDefaultPlugins)({
  17584. behaviour: _scoping.behaviours.GLOBAL,
  17585. generateScopedName,
  17586. exportGlobals
  17587. });
  17588. }
  17589. return (0, _scoping.getDefaultPlugins)({
  17590. behaviour: defaultBehaviour,
  17591. generateScopedName,
  17592. exportGlobals
  17593. });
  17594. }
  17595. function getLoader(opts, plugins) {
  17596. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  17597. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  17598. }
  17599. function isOurPlugin(plugin) {
  17600. return plugin.postcssPlugin === PLUGIN_NAME;
  17601. }
  17602. function makePlugin(opts) {
  17603. return {
  17604. postcssPlugin: PLUGIN_NAME,
  17605. async OnceExit(css, {
  17606. result
  17607. }) {
  17608. const getJSON = opts.getJSON || _saveJSON.default;
  17609. const inputFile = css.source.input.file;
  17610. const pluginList = getDefaultPluginsList(opts, inputFile);
  17611. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  17612. if (resultPluginIndex === -1) {
  17613. throw new Error("Plugin missing from options.");
  17614. }
  17615. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  17616. const loaderPlugins = [...earlierPlugins, ...pluginList];
  17617. const loader = getLoader(opts, loaderPlugins);
  17618. const fetcher = async (file, relativeTo, depTrace) => {
  17619. const unquoteFile = (0, _unquote.default)(file);
  17620. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  17621. };
  17622. const parser = new _Parser.default(fetcher);
  17623. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  17624. from: inputFile
  17625. });
  17626. const out = loader.finalSource;
  17627. if (out) css.prepend(out);
  17628. if (opts.localsConvention) {
  17629. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  17630. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  17631. }
  17632. result.messages.push({
  17633. type: "export",
  17634. plugin: "postcss-modules",
  17635. exportTokens: parser.exportTokens
  17636. }); // getJSON may return a promise
  17637. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  17638. }
  17639. };
  17640. }
  17641. return pluginFactory;
  17642. }
  17643. var hasRequiredBuild;
  17644. function requireBuild () {
  17645. if (hasRequiredBuild) return build.exports;
  17646. hasRequiredBuild = 1;
  17647. var _fs = require$$0;
  17648. var _fs2 = /*@__PURE__*/ requireFs();
  17649. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  17650. (0, _fs2.setFileSystem)({
  17651. readFile: _fs.readFile,
  17652. writeFile: _fs.writeFile
  17653. });
  17654. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  17655. build.exports.postcss = true;
  17656. return build.exports;
  17657. }
  17658. var buildExports = /*@__PURE__*/ requireBuild();
  17659. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  17660. function compileStyle(options) {
  17661. return doCompileStyle({
  17662. ...options,
  17663. isAsync: false
  17664. });
  17665. }
  17666. function compileStyleAsync(options) {
  17667. return doCompileStyle({
  17668. ...options,
  17669. isAsync: true
  17670. });
  17671. }
  17672. function doCompileStyle(options) {
  17673. const {
  17674. filename,
  17675. id,
  17676. scoped = false,
  17677. trim = true,
  17678. isProd = false,
  17679. modules = false,
  17680. modulesOptions = {},
  17681. preprocessLang,
  17682. postcssOptions,
  17683. postcssPlugins
  17684. } = options;
  17685. const preprocessor = preprocessLang && processors[preprocessLang];
  17686. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  17687. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  17688. const source = preProcessedSource ? preProcessedSource.code : options.source;
  17689. const shortId = id.replace(/^data-v-/, "");
  17690. const longId = `data-v-${shortId}`;
  17691. const plugins = (postcssPlugins || []).slice();
  17692. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  17693. if (trim) {
  17694. plugins.push(trimPlugin());
  17695. }
  17696. if (scoped) {
  17697. plugins.push(scopedPlugin(longId));
  17698. }
  17699. let cssModules;
  17700. if (modules) {
  17701. if (!options.isAsync) {
  17702. throw new Error(
  17703. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  17704. );
  17705. }
  17706. plugins.push(
  17707. postcssModules({
  17708. ...modulesOptions,
  17709. getJSON: (_cssFileName, json) => {
  17710. cssModules = json;
  17711. }
  17712. })
  17713. );
  17714. }
  17715. const postCSSOptions = {
  17716. ...postcssOptions,
  17717. to: filename,
  17718. from: filename
  17719. };
  17720. if (map) {
  17721. postCSSOptions.map = {
  17722. inline: false,
  17723. annotation: false,
  17724. prev: map
  17725. };
  17726. }
  17727. let result;
  17728. let code;
  17729. let outMap;
  17730. const dependencies = new Set(
  17731. preProcessedSource ? preProcessedSource.dependencies : []
  17732. );
  17733. dependencies.delete(filename);
  17734. const errors = [];
  17735. if (preProcessedSource && preProcessedSource.errors.length) {
  17736. errors.push(...preProcessedSource.errors);
  17737. }
  17738. const recordPlainCssDependencies = (messages) => {
  17739. messages.forEach((msg) => {
  17740. if (msg.type === "dependency") {
  17741. dependencies.add(msg.file);
  17742. }
  17743. });
  17744. return dependencies;
  17745. };
  17746. try {
  17747. result = require$$0$1(plugins).process(source, postCSSOptions);
  17748. if (options.isAsync) {
  17749. return result.then((result2) => ({
  17750. code: result2.css || "",
  17751. map: result2.map && result2.map.toJSON(),
  17752. errors,
  17753. modules: cssModules,
  17754. rawResult: result2,
  17755. dependencies: recordPlainCssDependencies(result2.messages)
  17756. })).catch((error) => ({
  17757. code: "",
  17758. map: void 0,
  17759. errors: [...errors, error],
  17760. rawResult: void 0,
  17761. dependencies
  17762. }));
  17763. }
  17764. recordPlainCssDependencies(result.messages);
  17765. code = result.css;
  17766. outMap = result.map;
  17767. } catch (e) {
  17768. errors.push(e);
  17769. }
  17770. return {
  17771. code: code || ``,
  17772. map: outMap && outMap.toJSON(),
  17773. errors,
  17774. rawResult: result,
  17775. dependencies
  17776. };
  17777. }
  17778. function preprocess(options, preprocessor) {
  17779. return preprocessor(
  17780. options.source,
  17781. options.inMap || options.map,
  17782. {
  17783. filename: options.filename,
  17784. ...options.preprocessOptions
  17785. },
  17786. options.preprocessCustomRequire
  17787. );
  17788. }
  17789. const UNKNOWN_TYPE = "Unknown";
  17790. function resolveObjectKey(node, computed) {
  17791. switch (node.type) {
  17792. case "StringLiteral":
  17793. case "NumericLiteral":
  17794. return String(node.value);
  17795. case "Identifier":
  17796. if (!computed) return node.name;
  17797. }
  17798. return void 0;
  17799. }
  17800. function concatStrings(strs) {
  17801. return strs.filter((s) => !!s).join(", ");
  17802. }
  17803. function isLiteralNode(node) {
  17804. return node.type.endsWith("Literal");
  17805. }
  17806. function isCallOf(node, test) {
  17807. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  17808. }
  17809. function toRuntimeTypeString(types) {
  17810. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  17811. }
  17812. function getImportedName(specifier) {
  17813. if (specifier.type === "ImportSpecifier")
  17814. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  17815. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  17816. return "default";
  17817. }
  17818. function getId(node) {
  17819. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  17820. }
  17821. function getStringLiteralKey(node) {
  17822. 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;
  17823. }
  17824. const identity = (str) => str;
  17825. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  17826. const toLowerCase = (str) => str.toLowerCase();
  17827. function toFileNameLowerCase(x) {
  17828. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  17829. }
  17830. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  17831. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  17832. }
  17833. const normalize = (path$1.posix || path$1).normalize;
  17834. const windowsSlashRE = /\\/g;
  17835. function normalizePath(p) {
  17836. return normalize(p.replace(windowsSlashRE, "/"));
  17837. }
  17838. const joinPaths = (path$1.posix || path$1).join;
  17839. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  17840. function getEscapedPropName(key) {
  17841. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  17842. }
  17843. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  17844. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  17845. function analyzeScriptBindings(ast) {
  17846. for (const node of ast) {
  17847. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  17848. return analyzeBindingsFromOptions(node.declaration);
  17849. }
  17850. }
  17851. return {};
  17852. }
  17853. function analyzeBindingsFromOptions(node) {
  17854. const bindings = {};
  17855. Object.defineProperty(bindings, "__isScriptSetup", {
  17856. enumerable: false,
  17857. value: false
  17858. });
  17859. for (const property of node.properties) {
  17860. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  17861. if (property.key.name === "props") {
  17862. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17863. bindings[key] = "props";
  17864. }
  17865. } else if (property.key.name === "inject") {
  17866. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17867. bindings[key] = "options";
  17868. }
  17869. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  17870. for (const key of getObjectExpressionKeys(property.value)) {
  17871. bindings[key] = "options";
  17872. }
  17873. }
  17874. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  17875. for (const bodyItem of property.body.body) {
  17876. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  17877. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  17878. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  17879. }
  17880. }
  17881. }
  17882. }
  17883. }
  17884. return bindings;
  17885. }
  17886. function getObjectExpressionKeys(node) {
  17887. const keys = [];
  17888. for (const prop of node.properties) {
  17889. if (prop.type === "SpreadElement") continue;
  17890. const key = resolveObjectKey(prop.key, prop.computed);
  17891. if (key) keys.push(String(key));
  17892. }
  17893. return keys;
  17894. }
  17895. function getArrayExpressionKeys(node) {
  17896. const keys = [];
  17897. for (const element of node.elements) {
  17898. if (element && element.type === "StringLiteral") {
  17899. keys.push(element.value);
  17900. }
  17901. }
  17902. return keys;
  17903. }
  17904. function getObjectOrArrayExpressionKeys(value) {
  17905. if (value.type === "ArrayExpression") {
  17906. return getArrayExpressionKeys(value);
  17907. }
  17908. if (value.type === "ObjectExpression") {
  17909. return getObjectExpressionKeys(value);
  17910. }
  17911. return [];
  17912. }
  17913. var _a, _b;
  17914. class ScriptCompileContext {
  17915. constructor(descriptor, options) {
  17916. this.descriptor = descriptor;
  17917. this.options = options;
  17918. this.isCE = false;
  17919. this.source = this.descriptor.source;
  17920. this.filename = this.descriptor.filename;
  17921. this.s = new MagicString(this.source);
  17922. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  17923. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  17924. this.userImports = /* @__PURE__ */ Object.create(null);
  17925. // macros presence check
  17926. this.hasDefinePropsCall = false;
  17927. this.hasDefineEmitCall = false;
  17928. this.hasDefineExposeCall = false;
  17929. this.hasDefaultExportName = false;
  17930. this.hasDefaultExportRender = false;
  17931. this.hasDefineOptionsCall = false;
  17932. this.hasDefineSlotsCall = false;
  17933. this.hasDefineModelCall = false;
  17934. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  17935. // defineModel
  17936. this.modelDecls = /* @__PURE__ */ Object.create(null);
  17937. // codegen
  17938. this.bindingMetadata = {};
  17939. this.helperImports = /* @__PURE__ */ new Set();
  17940. const { script, scriptSetup } = descriptor;
  17941. const scriptLang = script && script.lang;
  17942. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  17943. this.isJS = isJS(scriptLang, scriptSetupLang);
  17944. this.isTS = isTS(scriptLang, scriptSetupLang);
  17945. const customElement = options.customElement;
  17946. const filename = this.descriptor.filename;
  17947. if (customElement) {
  17948. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  17949. }
  17950. const plugins = resolveParserPlugins(
  17951. scriptLang || scriptSetupLang,
  17952. options.babelParserPlugins
  17953. );
  17954. function parse(input, offset) {
  17955. try {
  17956. return parser$2.parse(input, {
  17957. plugins,
  17958. sourceType: "module"
  17959. }).program;
  17960. } catch (e) {
  17961. e.message = `[vue/compiler-sfc] ${e.message}
  17962. ${descriptor.filename}
  17963. ${shared.generateCodeFrame(
  17964. descriptor.source,
  17965. e.pos + offset,
  17966. e.pos + offset + 1
  17967. )}`;
  17968. throw e;
  17969. }
  17970. }
  17971. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  17972. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  17973. }
  17974. helper(key) {
  17975. this.helperImports.add(key);
  17976. return `_${key}`;
  17977. }
  17978. getString(node, scriptSetup = true) {
  17979. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  17980. return block.content.slice(node.start, node.end);
  17981. }
  17982. warn(msg, node, scope) {
  17983. warn(generateError(msg, node, this, scope));
  17984. }
  17985. error(msg, node, scope) {
  17986. throw new Error(
  17987. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  17988. );
  17989. }
  17990. }
  17991. function generateError(msg, node, ctx, scope) {
  17992. const offset = scope ? scope.offset : ctx.startOffset;
  17993. return `${msg}
  17994. ${(scope || ctx.descriptor).filename}
  17995. ${shared.generateCodeFrame(
  17996. (scope || ctx.descriptor).source,
  17997. node.start + offset,
  17998. node.end + offset
  17999. )}`;
  18000. }
  18001. function resolveParserPlugins(lang, userPlugins, dts = false) {
  18002. const plugins = [];
  18003. if (!userPlugins || !userPlugins.some(
  18004. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  18005. )) {
  18006. plugins.push("importAttributes");
  18007. }
  18008. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  18009. plugins.push("jsx");
  18010. } else if (userPlugins) {
  18011. userPlugins = userPlugins.filter((p) => p !== "jsx");
  18012. }
  18013. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "mtsx") {
  18014. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  18015. if (!userPlugins || !userPlugins.includes("decorators")) {
  18016. plugins.push("decorators-legacy");
  18017. }
  18018. }
  18019. if (userPlugins) {
  18020. plugins.push(...userPlugins);
  18021. }
  18022. return plugins;
  18023. }
  18024. function rewriteDefault(input, as, parserPlugins) {
  18025. const ast = parser$2.parse(input, {
  18026. sourceType: "module",
  18027. plugins: resolveParserPlugins("js", parserPlugins)
  18028. }).program.body;
  18029. const s = new MagicString(input);
  18030. rewriteDefaultAST(ast, s, as);
  18031. return s.toString();
  18032. }
  18033. function rewriteDefaultAST(ast, s, as) {
  18034. if (!hasDefaultExport(ast)) {
  18035. s.append(`
  18036. const ${as} = {}`);
  18037. return;
  18038. }
  18039. ast.forEach((node) => {
  18040. if (node.type === "ExportDefaultDeclaration") {
  18041. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  18042. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  18043. s.overwrite(start, node.declaration.id.start, ` class `);
  18044. s.append(`
  18045. const ${as} = ${node.declaration.id.name}`);
  18046. } else {
  18047. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18048. }
  18049. } else if (node.type === "ExportNamedDeclaration") {
  18050. for (const specifier of node.specifiers) {
  18051. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18052. if (node.source) {
  18053. if (specifier.local.name === "default") {
  18054. s.prepend(
  18055. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18056. `
  18057. );
  18058. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18059. s.remove(specifier.start, end2);
  18060. s.append(`
  18061. const ${as} = __VUE_DEFAULT__`);
  18062. continue;
  18063. } else {
  18064. s.prepend(
  18065. `import { ${s.slice(
  18066. specifier.local.start,
  18067. specifier.local.end
  18068. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18069. `
  18070. );
  18071. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18072. s.remove(specifier.start, end2);
  18073. s.append(`
  18074. const ${as} = __VUE_DEFAULT__`);
  18075. continue;
  18076. }
  18077. }
  18078. const end = specifierEnd(s, specifier.end, node.end);
  18079. s.remove(specifier.start, end);
  18080. s.append(`
  18081. const ${as} = ${specifier.local.name}`);
  18082. }
  18083. }
  18084. }
  18085. });
  18086. }
  18087. function hasDefaultExport(ast) {
  18088. for (const stmt of ast) {
  18089. if (stmt.type === "ExportDefaultDeclaration") {
  18090. return true;
  18091. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18092. (spec) => spec.exported.name === "default"
  18093. )) {
  18094. return true;
  18095. }
  18096. }
  18097. return false;
  18098. }
  18099. function specifierEnd(s, end, nodeEnd) {
  18100. let hasCommas = false;
  18101. let oldEnd = end;
  18102. while (end < nodeEnd) {
  18103. if (/\s/.test(s.slice(end, end + 1))) {
  18104. end++;
  18105. } else if (s.slice(end, end + 1) === ",") {
  18106. end++;
  18107. hasCommas = true;
  18108. break;
  18109. } else if (s.slice(end, end + 1) === "}") {
  18110. break;
  18111. }
  18112. }
  18113. return hasCommas ? end : oldEnd;
  18114. }
  18115. const normalScriptDefaultVar = `__default__`;
  18116. function processNormalScript(ctx, scopeId) {
  18117. var _a;
  18118. const script = ctx.descriptor.script;
  18119. try {
  18120. let content = script.content;
  18121. let map = script.map;
  18122. const scriptAst = ctx.scriptAst;
  18123. const bindings = analyzeScriptBindings(scriptAst.body);
  18124. const { cssVars } = ctx.descriptor;
  18125. const { genDefaultAs, isProd } = ctx.options;
  18126. if (cssVars.length || genDefaultAs) {
  18127. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18128. const s = new MagicString(content);
  18129. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18130. content = s.toString();
  18131. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18132. content += genNormalScriptCssVarsCode(
  18133. cssVars,
  18134. bindings,
  18135. scopeId,
  18136. !!isProd,
  18137. defaultVar
  18138. );
  18139. }
  18140. if (!genDefaultAs) {
  18141. content += `
  18142. export default ${defaultVar}`;
  18143. }
  18144. }
  18145. return {
  18146. ...script,
  18147. content,
  18148. map,
  18149. bindings,
  18150. scriptAst: scriptAst.body
  18151. };
  18152. } catch (e) {
  18153. return script;
  18154. }
  18155. }
  18156. const balanced = (a, b, str) => {
  18157. const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
  18158. const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
  18159. const r = ma !== null && mb != null && range(ma, mb, str);
  18160. return (r && {
  18161. start: r[0],
  18162. end: r[1],
  18163. pre: str.slice(0, r[0]),
  18164. body: str.slice(r[0] + ma.length, r[1]),
  18165. post: str.slice(r[1] + mb.length),
  18166. });
  18167. };
  18168. const maybeMatch = (reg, str) => {
  18169. const m = str.match(reg);
  18170. return m ? m[0] : null;
  18171. };
  18172. const range = (a, b, str) => {
  18173. let begs, beg, left, right = undefined, result;
  18174. let ai = str.indexOf(a);
  18175. let bi = str.indexOf(b, ai + 1);
  18176. let i = ai;
  18177. if (ai >= 0 && bi > 0) {
  18178. if (a === b) {
  18179. return [ai, bi];
  18180. }
  18181. begs = [];
  18182. left = str.length;
  18183. while (i >= 0 && !result) {
  18184. if (i === ai) {
  18185. begs.push(i);
  18186. ai = str.indexOf(a, i + 1);
  18187. }
  18188. else if (begs.length === 1) {
  18189. const r = begs.pop();
  18190. if (r !== undefined)
  18191. result = [r, bi];
  18192. }
  18193. else {
  18194. beg = begs.pop();
  18195. if (beg !== undefined && beg < left) {
  18196. left = beg;
  18197. right = bi;
  18198. }
  18199. bi = str.indexOf(b, i + 1);
  18200. }
  18201. i = ai < bi && ai >= 0 ? ai : bi;
  18202. }
  18203. if (begs.length && right !== undefined) {
  18204. result = [left, right];
  18205. }
  18206. }
  18207. return result;
  18208. };
  18209. const escSlash = '\0SLASH' + Math.random() + '\0';
  18210. const escOpen = '\0OPEN' + Math.random() + '\0';
  18211. const escClose = '\0CLOSE' + Math.random() + '\0';
  18212. const escComma = '\0COMMA' + Math.random() + '\0';
  18213. const escPeriod = '\0PERIOD' + Math.random() + '\0';
  18214. const escSlashPattern = new RegExp(escSlash, 'g');
  18215. const escOpenPattern = new RegExp(escOpen, 'g');
  18216. const escClosePattern = new RegExp(escClose, 'g');
  18217. const escCommaPattern = new RegExp(escComma, 'g');
  18218. const escPeriodPattern = new RegExp(escPeriod, 'g');
  18219. const slashPattern = /\\\\/g;
  18220. const openPattern = /\\{/g;
  18221. const closePattern = /\\}/g;
  18222. const commaPattern = /\\,/g;
  18223. const periodPattern = /\\./g;
  18224. function numeric(str) {
  18225. return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
  18226. }
  18227. function escapeBraces(str) {
  18228. return str
  18229. .replace(slashPattern, escSlash)
  18230. .replace(openPattern, escOpen)
  18231. .replace(closePattern, escClose)
  18232. .replace(commaPattern, escComma)
  18233. .replace(periodPattern, escPeriod);
  18234. }
  18235. function unescapeBraces(str) {
  18236. return str
  18237. .replace(escSlashPattern, '\\')
  18238. .replace(escOpenPattern, '{')
  18239. .replace(escClosePattern, '}')
  18240. .replace(escCommaPattern, ',')
  18241. .replace(escPeriodPattern, '.');
  18242. }
  18243. /**
  18244. * Basically just str.split(","), but handling cases
  18245. * where we have nested braced sections, which should be
  18246. * treated as individual members, like {a,{b,c},d}
  18247. */
  18248. function parseCommaParts(str) {
  18249. if (!str) {
  18250. return [''];
  18251. }
  18252. const parts = [];
  18253. const m = balanced('{', '}', str);
  18254. if (!m) {
  18255. return str.split(',');
  18256. }
  18257. const { pre, body, post } = m;
  18258. const p = pre.split(',');
  18259. p[p.length - 1] += '{' + body + '}';
  18260. const postParts = parseCommaParts(post);
  18261. if (post.length) {
  18262. p[p.length - 1] += postParts.shift();
  18263. p.push.apply(p, postParts);
  18264. }
  18265. parts.push.apply(parts, p);
  18266. return parts;
  18267. }
  18268. function expand(str) {
  18269. if (!str) {
  18270. return [];
  18271. }
  18272. // I don't know why Bash 4.3 does this, but it does.
  18273. // Anything starting with {} will have the first two bytes preserved
  18274. // but *only* at the top level, so {},a}b will not expand to anything,
  18275. // but a{},b}c will be expanded to [a}c,abc].
  18276. // One could argue that this is a bug in Bash, but since the goal of
  18277. // this module is to match Bash's rules, we escape a leading {}
  18278. if (str.slice(0, 2) === '{}') {
  18279. str = '\\{\\}' + str.slice(2);
  18280. }
  18281. return expand_(escapeBraces(str), true).map(unescapeBraces);
  18282. }
  18283. function embrace(str) {
  18284. return '{' + str + '}';
  18285. }
  18286. function isPadded(el) {
  18287. return /^-?0\d/.test(el);
  18288. }
  18289. function lte(i, y) {
  18290. return i <= y;
  18291. }
  18292. function gte(i, y) {
  18293. return i >= y;
  18294. }
  18295. function expand_(str, isTop) {
  18296. /** @type {string[]} */
  18297. const expansions = [];
  18298. const m = balanced('{', '}', str);
  18299. if (!m)
  18300. return [str];
  18301. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18302. const pre = m.pre;
  18303. const post = m.post.length ? expand_(m.post, false) : [''];
  18304. if (/\$$/.test(m.pre)) {
  18305. for (let k = 0; k < post.length; k++) {
  18306. const expansion = pre + '{' + m.body + '}' + post[k];
  18307. expansions.push(expansion);
  18308. }
  18309. }
  18310. else {
  18311. const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18312. const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18313. const isSequence = isNumericSequence || isAlphaSequence;
  18314. const isOptions = m.body.indexOf(',') >= 0;
  18315. if (!isSequence && !isOptions) {
  18316. // {a},b}
  18317. if (m.post.match(/,(?!,).*\}/)) {
  18318. str = m.pre + '{' + m.body + escClose + m.post;
  18319. return expand_(str);
  18320. }
  18321. return [str];
  18322. }
  18323. let n;
  18324. if (isSequence) {
  18325. n = m.body.split(/\.\./);
  18326. }
  18327. else {
  18328. n = parseCommaParts(m.body);
  18329. if (n.length === 1 && n[0] !== undefined) {
  18330. // x{{a,b}}y ==> x{a}y x{b}y
  18331. n = expand_(n[0], false).map(embrace);
  18332. //XXX is this necessary? Can't seem to hit it in tests.
  18333. /* c8 ignore start */
  18334. if (n.length === 1) {
  18335. return post.map(p => m.pre + n[0] + p);
  18336. }
  18337. /* c8 ignore stop */
  18338. }
  18339. }
  18340. // at this point, n is the parts, and we know it's not a comma set
  18341. // with a single entry.
  18342. let N;
  18343. if (isSequence && n[0] !== undefined && n[1] !== undefined) {
  18344. const x = numeric(n[0]);
  18345. const y = numeric(n[1]);
  18346. const width = Math.max(n[0].length, n[1].length);
  18347. let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1;
  18348. let test = lte;
  18349. const reverse = y < x;
  18350. if (reverse) {
  18351. incr *= -1;
  18352. test = gte;
  18353. }
  18354. const pad = n.some(isPadded);
  18355. N = [];
  18356. for (let i = x; test(i, y); i += incr) {
  18357. let c;
  18358. if (isAlphaSequence) {
  18359. c = String.fromCharCode(i);
  18360. if (c === '\\') {
  18361. c = '';
  18362. }
  18363. }
  18364. else {
  18365. c = String(i);
  18366. if (pad) {
  18367. const need = width - c.length;
  18368. if (need > 0) {
  18369. const z = new Array(need + 1).join('0');
  18370. if (i < 0) {
  18371. c = '-' + z + c.slice(1);
  18372. }
  18373. else {
  18374. c = z + c;
  18375. }
  18376. }
  18377. }
  18378. }
  18379. N.push(c);
  18380. }
  18381. }
  18382. else {
  18383. N = [];
  18384. for (let j = 0; j < n.length; j++) {
  18385. N.push.apply(N, expand_(n[j], false));
  18386. }
  18387. }
  18388. for (let j = 0; j < N.length; j++) {
  18389. for (let k = 0; k < post.length; k++) {
  18390. const expansion = pre + N[j] + post[k];
  18391. if (!isTop || isSequence || expansion) {
  18392. expansions.push(expansion);
  18393. }
  18394. }
  18395. }
  18396. }
  18397. return expansions;
  18398. }
  18399. const MAX_PATTERN_LENGTH = 1024 * 64;
  18400. const assertValidPattern = (pattern) => {
  18401. if (typeof pattern !== 'string') {
  18402. throw new TypeError('invalid pattern');
  18403. }
  18404. if (pattern.length > MAX_PATTERN_LENGTH) {
  18405. throw new TypeError('pattern is too long');
  18406. }
  18407. };
  18408. // translate the various posix character classes into unicode properties
  18409. // this works across all unicode locales
  18410. // { <posix class>: [<translation>, /u flag required, negated]
  18411. const posixClasses = {
  18412. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  18413. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  18414. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  18415. '[:blank:]': ['\\p{Zs}\\t', true],
  18416. '[:cntrl:]': ['\\p{Cc}', true],
  18417. '[:digit:]': ['\\p{Nd}', true],
  18418. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  18419. '[:lower:]': ['\\p{Ll}', true],
  18420. '[:print:]': ['\\p{C}', true],
  18421. '[:punct:]': ['\\p{P}', true],
  18422. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  18423. '[:upper:]': ['\\p{Lu}', true],
  18424. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  18425. '[:xdigit:]': ['A-Fa-f0-9', false],
  18426. };
  18427. // only need to escape a few things inside of brace expressions
  18428. // escapes: [ \ ] -
  18429. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  18430. // escape all regexp magic characters
  18431. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18432. // everything has already been escaped, we just have to join
  18433. const rangesToString = (ranges) => ranges.join('');
  18434. // takes a glob string at a posix brace expression, and returns
  18435. // an equivalent regular expression source, and boolean indicating
  18436. // whether the /u flag needs to be applied, and the number of chars
  18437. // consumed to parse the character class.
  18438. // This also removes out of order ranges, and returns ($.) if the
  18439. // entire class just no good.
  18440. const parseClass = (glob, position) => {
  18441. const pos = position;
  18442. /* c8 ignore start */
  18443. if (glob.charAt(pos) !== '[') {
  18444. throw new Error('not in a brace expression');
  18445. }
  18446. /* c8 ignore stop */
  18447. const ranges = [];
  18448. const negs = [];
  18449. let i = pos + 1;
  18450. let sawStart = false;
  18451. let uflag = false;
  18452. let escaping = false;
  18453. let negate = false;
  18454. let endPos = pos;
  18455. let rangeStart = '';
  18456. WHILE: while (i < glob.length) {
  18457. const c = glob.charAt(i);
  18458. if ((c === '!' || c === '^') && i === pos + 1) {
  18459. negate = true;
  18460. i++;
  18461. continue;
  18462. }
  18463. if (c === ']' && sawStart && !escaping) {
  18464. endPos = i + 1;
  18465. break;
  18466. }
  18467. sawStart = true;
  18468. if (c === '\\') {
  18469. if (!escaping) {
  18470. escaping = true;
  18471. i++;
  18472. continue;
  18473. }
  18474. // escaped \ char, fall through and treat like normal char
  18475. }
  18476. if (c === '[' && !escaping) {
  18477. // either a posix class, a collation equivalent, or just a [
  18478. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  18479. if (glob.startsWith(cls, i)) {
  18480. // invalid, [a-[] is fine, but not [a-[:alpha]]
  18481. if (rangeStart) {
  18482. return ['$.', false, glob.length - pos, true];
  18483. }
  18484. i += cls.length;
  18485. if (neg)
  18486. negs.push(unip);
  18487. else
  18488. ranges.push(unip);
  18489. uflag = uflag || u;
  18490. continue WHILE;
  18491. }
  18492. }
  18493. }
  18494. // now it's just a normal character, effectively
  18495. escaping = false;
  18496. if (rangeStart) {
  18497. // throw this range away if it's not valid, but others
  18498. // can still match.
  18499. if (c > rangeStart) {
  18500. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  18501. }
  18502. else if (c === rangeStart) {
  18503. ranges.push(braceEscape(c));
  18504. }
  18505. rangeStart = '';
  18506. i++;
  18507. continue;
  18508. }
  18509. // now might be the start of a range.
  18510. // can be either c-d or c-] or c<more...>] or c] at this point
  18511. if (glob.startsWith('-]', i + 1)) {
  18512. ranges.push(braceEscape(c + '-'));
  18513. i += 2;
  18514. continue;
  18515. }
  18516. if (glob.startsWith('-', i + 1)) {
  18517. rangeStart = c;
  18518. i += 2;
  18519. continue;
  18520. }
  18521. // not the start of a range, just a single character
  18522. ranges.push(braceEscape(c));
  18523. i++;
  18524. }
  18525. if (endPos < i) {
  18526. // didn't see the end of the class, not a valid class,
  18527. // but might still be valid as a literal match.
  18528. return ['', false, 0, false];
  18529. }
  18530. // if we got no ranges and no negates, then we have a range that
  18531. // cannot possibly match anything, and that poisons the whole glob
  18532. if (!ranges.length && !negs.length) {
  18533. return ['$.', false, glob.length - pos, true];
  18534. }
  18535. // if we got one positive range, and it's a single character, then that's
  18536. // not actually a magic pattern, it's just that one literal character.
  18537. // we should not treat that as "magic", we should just return the literal
  18538. // character. [_] is a perfectly valid way to escape glob magic chars.
  18539. if (negs.length === 0 &&
  18540. ranges.length === 1 &&
  18541. /^\\?.$/.test(ranges[0]) &&
  18542. !negate) {
  18543. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  18544. return [regexpEscape(r), false, endPos - pos, false];
  18545. }
  18546. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  18547. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  18548. const comb = ranges.length && negs.length
  18549. ? '(' + sranges + '|' + snegs + ')'
  18550. : ranges.length
  18551. ? sranges
  18552. : snegs;
  18553. return [comb, uflag, endPos - pos, true];
  18554. };
  18555. /**
  18556. * Un-escape a string that has been escaped with {@link escape}.
  18557. *
  18558. * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
  18559. * square-bracket escapes are removed, but not backslash escapes.
  18560. *
  18561. * For example, it will turn the string `'[*]'` into `*`, but it will not
  18562. * turn `'\\*'` into `'*'`, because `\` is a path separator in
  18563. * `windowsPathsNoEscape` mode.
  18564. *
  18565. * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
  18566. * backslash escapes are removed.
  18567. *
  18568. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  18569. * or unescaped.
  18570. *
  18571. * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
  18572. * unescaped.
  18573. */
  18574. const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
  18575. if (magicalBraces) {
  18576. return windowsPathsNoEscape
  18577. ? s.replace(/\[([^\/\\])\]/g, '$1')
  18578. : s
  18579. .replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2')
  18580. .replace(/\\([^\/])/g, '$1');
  18581. }
  18582. return windowsPathsNoEscape
  18583. ? s.replace(/\[([^\/\\{}])\]/g, '$1')
  18584. : s
  18585. .replace(/((?!\\).|^)\[([^\/\\{}])\]/g, '$1$2')
  18586. .replace(/\\([^\/{}])/g, '$1');
  18587. };
  18588. // parse a single path portion
  18589. const types = new Set(['!', '?', '+', '*', '@']);
  18590. const isExtglobType = (c) => types.has(c);
  18591. // Patterns that get prepended to bind to the start of either the
  18592. // entire string, or just a single path portion, to prevent dots
  18593. // and/or traversal patterns, when needed.
  18594. // Exts don't need the ^ or / bit, because the root binds that already.
  18595. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  18596. const startNoDot = '(?!\\.)';
  18597. // characters that indicate a start of pattern needs the "no dots" bit,
  18598. // because a dot *might* be matched. ( is not in the list, because in
  18599. // the case of a child extglob, it will handle the prevention itself.
  18600. const addPatternStart = new Set(['[', '.']);
  18601. // cases where traversal is A-OK, no dot prevention needed
  18602. const justDots = new Set(['..', '.']);
  18603. const reSpecials = new Set('().*{}+?[]^$\\!');
  18604. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18605. // any single thing other than /
  18606. const qmark$1 = '[^/]';
  18607. // * => any number of characters
  18608. const star$1 = qmark$1 + '*?';
  18609. // use + when we need to ensure that *something* matches, because the * is
  18610. // the only thing in the path portion.
  18611. const starNoEmpty = qmark$1 + '+?';
  18612. // remove the \ chars that we added if we end up doing a nonmagic compare
  18613. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  18614. class AST {
  18615. type;
  18616. #root;
  18617. #hasMagic;
  18618. #uflag = false;
  18619. #parts = [];
  18620. #parent;
  18621. #parentIndex;
  18622. #negs;
  18623. #filledNegs = false;
  18624. #options;
  18625. #toString;
  18626. // set to true if it's an extglob with no children
  18627. // (which really means one child of '')
  18628. #emptyExt = false;
  18629. constructor(type, parent, options = {}) {
  18630. this.type = type;
  18631. // extglobs are inherently magical
  18632. if (type)
  18633. this.#hasMagic = true;
  18634. this.#parent = parent;
  18635. this.#root = this.#parent ? this.#parent.#root : this;
  18636. this.#options = this.#root === this ? options : this.#root.#options;
  18637. this.#negs = this.#root === this ? [] : this.#root.#negs;
  18638. if (type === '!' && !this.#root.#filledNegs)
  18639. this.#negs.push(this);
  18640. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  18641. }
  18642. get hasMagic() {
  18643. /* c8 ignore start */
  18644. if (this.#hasMagic !== undefined)
  18645. return this.#hasMagic;
  18646. /* c8 ignore stop */
  18647. for (const p of this.#parts) {
  18648. if (typeof p === 'string')
  18649. continue;
  18650. if (p.type || p.hasMagic)
  18651. return (this.#hasMagic = true);
  18652. }
  18653. // note: will be undefined until we generate the regexp src and find out
  18654. return this.#hasMagic;
  18655. }
  18656. // reconstructs the pattern
  18657. toString() {
  18658. if (this.#toString !== undefined)
  18659. return this.#toString;
  18660. if (!this.type) {
  18661. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  18662. }
  18663. else {
  18664. return (this.#toString =
  18665. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  18666. }
  18667. }
  18668. #fillNegs() {
  18669. /* c8 ignore start */
  18670. if (this !== this.#root)
  18671. throw new Error('should only call on root');
  18672. if (this.#filledNegs)
  18673. return this;
  18674. /* c8 ignore stop */
  18675. // call toString() once to fill this out
  18676. this.toString();
  18677. this.#filledNegs = true;
  18678. let n;
  18679. while ((n = this.#negs.pop())) {
  18680. if (n.type !== '!')
  18681. continue;
  18682. // walk up the tree, appending everthing that comes AFTER parentIndex
  18683. let p = n;
  18684. let pp = p.#parent;
  18685. while (pp) {
  18686. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  18687. for (const part of n.#parts) {
  18688. /* c8 ignore start */
  18689. if (typeof part === 'string') {
  18690. throw new Error('string part in extglob AST??');
  18691. }
  18692. /* c8 ignore stop */
  18693. part.copyIn(pp.#parts[i]);
  18694. }
  18695. }
  18696. p = pp;
  18697. pp = p.#parent;
  18698. }
  18699. }
  18700. return this;
  18701. }
  18702. push(...parts) {
  18703. for (const p of parts) {
  18704. if (p === '')
  18705. continue;
  18706. /* c8 ignore start */
  18707. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  18708. throw new Error('invalid part: ' + p);
  18709. }
  18710. /* c8 ignore stop */
  18711. this.#parts.push(p);
  18712. }
  18713. }
  18714. toJSON() {
  18715. const ret = this.type === null
  18716. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  18717. : [this.type, ...this.#parts.map(p => p.toJSON())];
  18718. if (this.isStart() && !this.type)
  18719. ret.unshift([]);
  18720. if (this.isEnd() &&
  18721. (this === this.#root ||
  18722. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  18723. ret.push({});
  18724. }
  18725. return ret;
  18726. }
  18727. isStart() {
  18728. if (this.#root === this)
  18729. return true;
  18730. // if (this.type) return !!this.#parent?.isStart()
  18731. if (!this.#parent?.isStart())
  18732. return false;
  18733. if (this.#parentIndex === 0)
  18734. return true;
  18735. // if everything AHEAD of this is a negation, then it's still the "start"
  18736. const p = this.#parent;
  18737. for (let i = 0; i < this.#parentIndex; i++) {
  18738. const pp = p.#parts[i];
  18739. if (!(pp instanceof AST && pp.type === '!')) {
  18740. return false;
  18741. }
  18742. }
  18743. return true;
  18744. }
  18745. isEnd() {
  18746. if (this.#root === this)
  18747. return true;
  18748. if (this.#parent?.type === '!')
  18749. return true;
  18750. if (!this.#parent?.isEnd())
  18751. return false;
  18752. if (!this.type)
  18753. return this.#parent?.isEnd();
  18754. // if not root, it'll always have a parent
  18755. /* c8 ignore start */
  18756. const pl = this.#parent ? this.#parent.#parts.length : 0;
  18757. /* c8 ignore stop */
  18758. return this.#parentIndex === pl - 1;
  18759. }
  18760. copyIn(part) {
  18761. if (typeof part === 'string')
  18762. this.push(part);
  18763. else
  18764. this.push(part.clone(this));
  18765. }
  18766. clone(parent) {
  18767. const c = new AST(this.type, parent);
  18768. for (const p of this.#parts) {
  18769. c.copyIn(p);
  18770. }
  18771. return c;
  18772. }
  18773. static #parseAST(str, ast, pos, opt) {
  18774. let escaping = false;
  18775. let inBrace = false;
  18776. let braceStart = -1;
  18777. let braceNeg = false;
  18778. if (ast.type === null) {
  18779. // outside of a extglob, append until we find a start
  18780. let i = pos;
  18781. let acc = '';
  18782. while (i < str.length) {
  18783. const c = str.charAt(i++);
  18784. // still accumulate escapes at this point, but we do ignore
  18785. // starts that are escaped
  18786. if (escaping || c === '\\') {
  18787. escaping = !escaping;
  18788. acc += c;
  18789. continue;
  18790. }
  18791. if (inBrace) {
  18792. if (i === braceStart + 1) {
  18793. if (c === '^' || c === '!') {
  18794. braceNeg = true;
  18795. }
  18796. }
  18797. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18798. inBrace = false;
  18799. }
  18800. acc += c;
  18801. continue;
  18802. }
  18803. else if (c === '[') {
  18804. inBrace = true;
  18805. braceStart = i;
  18806. braceNeg = false;
  18807. acc += c;
  18808. continue;
  18809. }
  18810. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  18811. ast.push(acc);
  18812. acc = '';
  18813. const ext = new AST(c, ast);
  18814. i = AST.#parseAST(str, ext, i, opt);
  18815. ast.push(ext);
  18816. continue;
  18817. }
  18818. acc += c;
  18819. }
  18820. ast.push(acc);
  18821. return i;
  18822. }
  18823. // some kind of extglob, pos is at the (
  18824. // find the next | or )
  18825. let i = pos + 1;
  18826. let part = new AST(null, ast);
  18827. const parts = [];
  18828. let acc = '';
  18829. while (i < str.length) {
  18830. const c = str.charAt(i++);
  18831. // still accumulate escapes at this point, but we do ignore
  18832. // starts that are escaped
  18833. if (escaping || c === '\\') {
  18834. escaping = !escaping;
  18835. acc += c;
  18836. continue;
  18837. }
  18838. if (inBrace) {
  18839. if (i === braceStart + 1) {
  18840. if (c === '^' || c === '!') {
  18841. braceNeg = true;
  18842. }
  18843. }
  18844. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18845. inBrace = false;
  18846. }
  18847. acc += c;
  18848. continue;
  18849. }
  18850. else if (c === '[') {
  18851. inBrace = true;
  18852. braceStart = i;
  18853. braceNeg = false;
  18854. acc += c;
  18855. continue;
  18856. }
  18857. if (isExtglobType(c) && str.charAt(i) === '(') {
  18858. part.push(acc);
  18859. acc = '';
  18860. const ext = new AST(c, part);
  18861. part.push(ext);
  18862. i = AST.#parseAST(str, ext, i, opt);
  18863. continue;
  18864. }
  18865. if (c === '|') {
  18866. part.push(acc);
  18867. acc = '';
  18868. parts.push(part);
  18869. part = new AST(null, ast);
  18870. continue;
  18871. }
  18872. if (c === ')') {
  18873. if (acc === '' && ast.#parts.length === 0) {
  18874. ast.#emptyExt = true;
  18875. }
  18876. part.push(acc);
  18877. acc = '';
  18878. ast.push(...parts, part);
  18879. return i;
  18880. }
  18881. acc += c;
  18882. }
  18883. // unfinished extglob
  18884. // if we got here, it was a malformed extglob! not an extglob, but
  18885. // maybe something else in there.
  18886. ast.type = null;
  18887. ast.#hasMagic = undefined;
  18888. ast.#parts = [str.substring(pos - 1)];
  18889. return i;
  18890. }
  18891. static fromGlob(pattern, options = {}) {
  18892. const ast = new AST(null, undefined, options);
  18893. AST.#parseAST(pattern, ast, 0, options);
  18894. return ast;
  18895. }
  18896. // returns the regular expression if there's magic, or the unescaped
  18897. // string if not.
  18898. toMMPattern() {
  18899. // should only be called on root
  18900. /* c8 ignore start */
  18901. if (this !== this.#root)
  18902. return this.#root.toMMPattern();
  18903. /* c8 ignore stop */
  18904. const glob = this.toString();
  18905. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  18906. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  18907. // still need a regular expression if we have to case-insensitively
  18908. // match capital/lowercase characters.
  18909. const anyMagic = hasMagic ||
  18910. this.#hasMagic ||
  18911. (this.#options.nocase &&
  18912. !this.#options.nocaseMagicOnly &&
  18913. glob.toUpperCase() !== glob.toLowerCase());
  18914. if (!anyMagic) {
  18915. return body;
  18916. }
  18917. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  18918. return Object.assign(new RegExp(`^${re}$`, flags), {
  18919. _src: re,
  18920. _glob: glob,
  18921. });
  18922. }
  18923. get options() {
  18924. return this.#options;
  18925. }
  18926. // returns the string match, the regexp source, whether there's magic
  18927. // in the regexp (so a regular expression is required) and whether or
  18928. // not the uflag is needed for the regular expression (for posix classes)
  18929. // TODO: instead of injecting the start/end at this point, just return
  18930. // the BODY of the regexp, along with the start/end portions suitable
  18931. // for binding the start/end in either a joined full-path makeRe context
  18932. // (where we bind to (^|/), or a standalone matchPart context (where
  18933. // we bind to ^, and not /). Otherwise slashes get duped!
  18934. //
  18935. // In part-matching mode, the start is:
  18936. // - if not isStart: nothing
  18937. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  18938. // - if dots allowed or not possible: ^
  18939. // - if dots possible and not allowed: ^(?!\.)
  18940. // end is:
  18941. // - if not isEnd(): nothing
  18942. // - else: $
  18943. //
  18944. // In full-path matching mode, we put the slash at the START of the
  18945. // pattern, so start is:
  18946. // - if first pattern: same as part-matching mode
  18947. // - if not isStart(): nothing
  18948. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  18949. // - if dots allowed or not possible: /
  18950. // - if dots possible and not allowed: /(?!\.)
  18951. // end is:
  18952. // - if last pattern, same as part-matching mode
  18953. // - else nothing
  18954. //
  18955. // Always put the (?:$|/) on negated tails, though, because that has to be
  18956. // there to bind the end of the negated pattern portion, and it's easier to
  18957. // just stick it in now rather than try to inject it later in the middle of
  18958. // the pattern.
  18959. //
  18960. // We can just always return the same end, and leave it up to the caller
  18961. // to know whether it's going to be used joined or in parts.
  18962. // And, if the start is adjusted slightly, can do the same there:
  18963. // - if not isStart: nothing
  18964. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  18965. // - if dots allowed or not possible: (?:/|^)
  18966. // - if dots possible and not allowed: (?:/|^)(?!\.)
  18967. //
  18968. // But it's better to have a simpler binding without a conditional, for
  18969. // performance, so probably better to return both start options.
  18970. //
  18971. // Then the caller just ignores the end if it's not the first pattern,
  18972. // and the start always gets applied.
  18973. //
  18974. // But that's always going to be $ if it's the ending pattern, or nothing,
  18975. // so the caller can just attach $ at the end of the pattern when building.
  18976. //
  18977. // So the todo is:
  18978. // - better detect what kind of start is needed
  18979. // - return both flavors of starting pattern
  18980. // - attach $ at the end of the pattern when creating the actual RegExp
  18981. //
  18982. // Ah, but wait, no, that all only applies to the root when the first pattern
  18983. // is not an extglob. If the first pattern IS an extglob, then we need all
  18984. // that dot prevention biz to live in the extglob portions, because eg
  18985. // +(*|.x*) can match .xy but not .yx.
  18986. //
  18987. // So, return the two flavors if it's #root and the first child is not an
  18988. // AST, otherwise leave it to the child AST to handle it, and there,
  18989. // use the (?:^|/) style of start binding.
  18990. //
  18991. // Even simplified further:
  18992. // - Since the start for a join is eg /(?!\.) and the start for a part
  18993. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  18994. // or start or whatever) and prepend ^ or / at the Regexp construction.
  18995. toRegExpSource(allowDot) {
  18996. const dot = allowDot ?? !!this.#options.dot;
  18997. if (this.#root === this)
  18998. this.#fillNegs();
  18999. if (!this.type) {
  19000. const noEmpty = this.isStart() &&
  19001. this.isEnd() &&
  19002. !this.#parts.some(s => typeof s !== 'string');
  19003. const src = this.#parts
  19004. .map(p => {
  19005. const [re, _, hasMagic, uflag] = typeof p === 'string'
  19006. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  19007. : p.toRegExpSource(allowDot);
  19008. this.#hasMagic = this.#hasMagic || hasMagic;
  19009. this.#uflag = this.#uflag || uflag;
  19010. return re;
  19011. })
  19012. .join('');
  19013. let start = '';
  19014. if (this.isStart()) {
  19015. if (typeof this.#parts[0] === 'string') {
  19016. // this is the string that will match the start of the pattern,
  19017. // so we need to protect against dots and such.
  19018. // '.' and '..' cannot match unless the pattern is that exactly,
  19019. // even if it starts with . or dot:true is set.
  19020. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  19021. if (!dotTravAllowed) {
  19022. const aps = addPatternStart;
  19023. // check if we have a possibility of matching . or ..,
  19024. // and prevent that.
  19025. const needNoTrav =
  19026. // dots are allowed, and the pattern starts with [ or .
  19027. (dot && aps.has(src.charAt(0))) ||
  19028. // the pattern starts with \., and then [ or .
  19029. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  19030. // the pattern starts with \.\., and then [ or .
  19031. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  19032. // no need to prevent dots if it can't match a dot, or if a
  19033. // sub-pattern will be preventing it anyway.
  19034. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  19035. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  19036. }
  19037. }
  19038. }
  19039. // append the "end of path portion" pattern to negation tails
  19040. let end = '';
  19041. if (this.isEnd() &&
  19042. this.#root.#filledNegs &&
  19043. this.#parent?.type === '!') {
  19044. end = '(?:$|\\/)';
  19045. }
  19046. const final = start + src + end;
  19047. return [
  19048. final,
  19049. unescape(src),
  19050. (this.#hasMagic = !!this.#hasMagic),
  19051. this.#uflag,
  19052. ];
  19053. }
  19054. // We need to calculate the body *twice* if it's a repeat pattern
  19055. // at the start, once in nodot mode, then again in dot mode, so a
  19056. // pattern like *(?) can match 'x.y'
  19057. const repeated = this.type === '*' || this.type === '+';
  19058. // some kind of extglob
  19059. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  19060. let body = this.#partsToRegExp(dot);
  19061. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19062. // invalid extglob, has to at least be *something* present, if it's
  19063. // the entire path portion.
  19064. const s = this.toString();
  19065. this.#parts = [s];
  19066. this.type = null;
  19067. this.#hasMagic = undefined;
  19068. return [s, unescape(this.toString()), false, false];
  19069. }
  19070. // XXX abstract out this map method
  19071. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
  19072. ? ''
  19073. : this.#partsToRegExp(true);
  19074. if (bodyDotAllowed === body) {
  19075. bodyDotAllowed = '';
  19076. }
  19077. if (bodyDotAllowed) {
  19078. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19079. }
  19080. // an empty !() is exactly equivalent to a starNoEmpty
  19081. let final = '';
  19082. if (this.type === '!' && this.#emptyExt) {
  19083. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19084. }
  19085. else {
  19086. const close = this.type === '!'
  19087. ? // !() must match something,but !(x) can match ''
  19088. '))' +
  19089. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19090. star$1 +
  19091. ')'
  19092. : this.type === '@'
  19093. ? ')'
  19094. : this.type === '?'
  19095. ? ')?'
  19096. : this.type === '+' && bodyDotAllowed
  19097. ? ')'
  19098. : this.type === '*' && bodyDotAllowed
  19099. ? `)?`
  19100. : `)${this.type}`;
  19101. final = start + body + close;
  19102. }
  19103. return [
  19104. final,
  19105. unescape(body),
  19106. (this.#hasMagic = !!this.#hasMagic),
  19107. this.#uflag,
  19108. ];
  19109. }
  19110. #partsToRegExp(dot) {
  19111. return this.#parts
  19112. .map(p => {
  19113. // extglob ASTs should only contain parent ASTs
  19114. /* c8 ignore start */
  19115. if (typeof p === 'string') {
  19116. throw new Error('string type in extglob ast??');
  19117. }
  19118. /* c8 ignore stop */
  19119. // can ignore hasMagic, because extglobs are already always magic
  19120. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19121. this.#uflag = this.#uflag || uflag;
  19122. return re;
  19123. })
  19124. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19125. .join('|');
  19126. }
  19127. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19128. let escaping = false;
  19129. let re = '';
  19130. let uflag = false;
  19131. for (let i = 0; i < glob.length; i++) {
  19132. const c = glob.charAt(i);
  19133. if (escaping) {
  19134. escaping = false;
  19135. re += (reSpecials.has(c) ? '\\' : '') + c;
  19136. continue;
  19137. }
  19138. if (c === '\\') {
  19139. if (i === glob.length - 1) {
  19140. re += '\\\\';
  19141. }
  19142. else {
  19143. escaping = true;
  19144. }
  19145. continue;
  19146. }
  19147. if (c === '[') {
  19148. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  19149. if (consumed) {
  19150. re += src;
  19151. uflag = uflag || needUflag;
  19152. i += consumed - 1;
  19153. hasMagic = hasMagic || magic;
  19154. continue;
  19155. }
  19156. }
  19157. if (c === '*') {
  19158. re += noEmpty && glob === '*' ? starNoEmpty : star$1;
  19159. hasMagic = true;
  19160. continue;
  19161. }
  19162. if (c === '?') {
  19163. re += qmark$1;
  19164. hasMagic = true;
  19165. continue;
  19166. }
  19167. re += regExpEscape$1(c);
  19168. }
  19169. return [re, unescape(glob), !!hasMagic, uflag];
  19170. }
  19171. }
  19172. /**
  19173. * Escape all magic characters in a glob pattern.
  19174. *
  19175. * If the {@link MinimatchOptions.windowsPathsNoEscape}
  19176. * option is used, then characters are escaped by wrapping in `[]`, because
  19177. * a magic character wrapped in a character class can only be satisfied by
  19178. * that exact character. In this mode, `\` is _not_ escaped, because it is
  19179. * not interpreted as a magic character, but instead as a path separator.
  19180. *
  19181. * If the {@link MinimatchOptions.magicalBraces} option is used,
  19182. * then braces (`{` and `}`) will be escaped.
  19183. */
  19184. const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
  19185. // don't need to escape +@! because we escape the parens
  19186. // that make those magic, and escaping ! as [!] isn't valid,
  19187. // because [!]] is a valid glob class meaning not ']'.
  19188. if (magicalBraces) {
  19189. return windowsPathsNoEscape
  19190. ? s.replace(/[?*()[\]{}]/g, '[$&]')
  19191. : s.replace(/[?*()[\]\\{}]/g, '\\$&');
  19192. }
  19193. return windowsPathsNoEscape
  19194. ? s.replace(/[?*()[\]]/g, '[$&]')
  19195. : s.replace(/[?*()[\]\\]/g, '\\$&');
  19196. };
  19197. const minimatch = (p, pattern, options = {}) => {
  19198. assertValidPattern(pattern);
  19199. // shortcut: comments match nothing.
  19200. if (!options.nocomment && pattern.charAt(0) === '#') {
  19201. return false;
  19202. }
  19203. return new Minimatch(pattern, options).match(p);
  19204. };
  19205. // Optimized checking for the most common glob patterns.
  19206. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  19207. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  19208. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  19209. const starDotExtTestNocase = (ext) => {
  19210. ext = ext.toLowerCase();
  19211. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  19212. };
  19213. const starDotExtTestNocaseDot = (ext) => {
  19214. ext = ext.toLowerCase();
  19215. return (f) => f.toLowerCase().endsWith(ext);
  19216. };
  19217. const starDotStarRE = /^\*+\.\*+$/;
  19218. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  19219. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  19220. const dotStarRE = /^\.\*+$/;
  19221. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  19222. const starRE = /^\*+$/;
  19223. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  19224. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  19225. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  19226. const qmarksTestNocase = ([$0, ext = '']) => {
  19227. const noext = qmarksTestNoExt([$0]);
  19228. if (!ext)
  19229. return noext;
  19230. ext = ext.toLowerCase();
  19231. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19232. };
  19233. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  19234. const noext = qmarksTestNoExtDot([$0]);
  19235. if (!ext)
  19236. return noext;
  19237. ext = ext.toLowerCase();
  19238. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19239. };
  19240. const qmarksTestDot = ([$0, ext = '']) => {
  19241. const noext = qmarksTestNoExtDot([$0]);
  19242. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19243. };
  19244. const qmarksTest = ([$0, ext = '']) => {
  19245. const noext = qmarksTestNoExt([$0]);
  19246. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19247. };
  19248. const qmarksTestNoExt = ([$0]) => {
  19249. const len = $0.length;
  19250. return (f) => f.length === len && !f.startsWith('.');
  19251. };
  19252. const qmarksTestNoExtDot = ([$0]) => {
  19253. const len = $0.length;
  19254. return (f) => f.length === len && f !== '.' && f !== '..';
  19255. };
  19256. /* c8 ignore start */
  19257. const defaultPlatform = (typeof process === 'object' && process
  19258. ? (typeof process.env === 'object' &&
  19259. process.env &&
  19260. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  19261. process.platform
  19262. : 'posix');
  19263. const path = {
  19264. win32: { sep: '\\' },
  19265. posix: { sep: '/' },
  19266. };
  19267. /* c8 ignore stop */
  19268. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  19269. minimatch.sep = sep;
  19270. const GLOBSTAR = Symbol('globstar **');
  19271. minimatch.GLOBSTAR = GLOBSTAR;
  19272. // any single thing other than /
  19273. // don't need to escape / when using new RegExp()
  19274. const qmark = '[^/]';
  19275. // * => any number of characters
  19276. const star = qmark + '*?';
  19277. // ** when dots are allowed. Anything goes, except .. and .
  19278. // not (^ or / followed by one or two dots followed by $ or /),
  19279. // followed by anything, any number of times.
  19280. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  19281. // not a ^ or / followed by a dot,
  19282. // followed by anything, any number of times.
  19283. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  19284. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  19285. minimatch.filter = filter;
  19286. const ext = (a, b = {}) => Object.assign({}, a, b);
  19287. const defaults = (def) => {
  19288. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  19289. return minimatch;
  19290. }
  19291. const orig = minimatch;
  19292. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  19293. return Object.assign(m, {
  19294. Minimatch: class Minimatch extends orig.Minimatch {
  19295. constructor(pattern, options = {}) {
  19296. super(pattern, ext(def, options));
  19297. }
  19298. static defaults(options) {
  19299. return orig.defaults(ext(def, options)).Minimatch;
  19300. }
  19301. },
  19302. AST: class AST extends orig.AST {
  19303. /* c8 ignore start */
  19304. constructor(type, parent, options = {}) {
  19305. super(type, parent, ext(def, options));
  19306. }
  19307. /* c8 ignore stop */
  19308. static fromGlob(pattern, options = {}) {
  19309. return orig.AST.fromGlob(pattern, ext(def, options));
  19310. }
  19311. },
  19312. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  19313. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  19314. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  19315. defaults: (options) => orig.defaults(ext(def, options)),
  19316. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  19317. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  19318. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  19319. sep: orig.sep,
  19320. GLOBSTAR: GLOBSTAR,
  19321. });
  19322. };
  19323. minimatch.defaults = defaults;
  19324. // Brace expansion:
  19325. // a{b,c}d -> abd acd
  19326. // a{b,}c -> abc ac
  19327. // a{0..3}d -> a0d a1d a2d a3d
  19328. // a{b,c{d,e}f}g -> abg acdfg acefg
  19329. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19330. //
  19331. // Invalid sets are not expanded.
  19332. // a{2..}b -> a{2..}b
  19333. // a{b}c -> a{b}c
  19334. const braceExpand = (pattern, options = {}) => {
  19335. assertValidPattern(pattern);
  19336. // Thanks to Yeting Li <https://github.com/yetingli> for
  19337. // improving this regexp to avoid a ReDOS vulnerability.
  19338. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  19339. // shortcut. no need to expand.
  19340. return [pattern];
  19341. }
  19342. return expand(pattern);
  19343. };
  19344. minimatch.braceExpand = braceExpand;
  19345. // parse a component of the expanded set.
  19346. // At this point, no pattern may contain "/" in it
  19347. // so we're going to return a 2d array, where each entry is the full
  19348. // pattern, split on '/', and then turned into a regular expression.
  19349. // A regexp is made at the end which joins each array with an
  19350. // escaped /, and another full one which joins each regexp with |.
  19351. //
  19352. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19353. // when it is the *only* thing in a path portion. Otherwise, any series
  19354. // of * is equivalent to a single *. Globstar behavior is enabled by
  19355. // default, and can be disabled by setting options.noglobstar.
  19356. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  19357. minimatch.makeRe = makeRe;
  19358. const match = (list, pattern, options = {}) => {
  19359. const mm = new Minimatch(pattern, options);
  19360. list = list.filter(f => mm.match(f));
  19361. if (mm.options.nonull && !list.length) {
  19362. list.push(pattern);
  19363. }
  19364. return list;
  19365. };
  19366. minimatch.match = match;
  19367. // replace stuff like \* with *
  19368. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  19369. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19370. class Minimatch {
  19371. options;
  19372. set;
  19373. pattern;
  19374. windowsPathsNoEscape;
  19375. nonegate;
  19376. negate;
  19377. comment;
  19378. empty;
  19379. preserveMultipleSlashes;
  19380. partial;
  19381. globSet;
  19382. globParts;
  19383. nocase;
  19384. isWindows;
  19385. platform;
  19386. windowsNoMagicRoot;
  19387. regexp;
  19388. constructor(pattern, options = {}) {
  19389. assertValidPattern(pattern);
  19390. options = options || {};
  19391. this.options = options;
  19392. this.pattern = pattern;
  19393. this.platform = options.platform || defaultPlatform;
  19394. this.isWindows = this.platform === 'win32';
  19395. this.windowsPathsNoEscape =
  19396. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  19397. if (this.windowsPathsNoEscape) {
  19398. this.pattern = this.pattern.replace(/\\/g, '/');
  19399. }
  19400. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  19401. this.regexp = null;
  19402. this.negate = false;
  19403. this.nonegate = !!options.nonegate;
  19404. this.comment = false;
  19405. this.empty = false;
  19406. this.partial = !!options.partial;
  19407. this.nocase = !!this.options.nocase;
  19408. this.windowsNoMagicRoot =
  19409. options.windowsNoMagicRoot !== undefined
  19410. ? options.windowsNoMagicRoot
  19411. : !!(this.isWindows && this.nocase);
  19412. this.globSet = [];
  19413. this.globParts = [];
  19414. this.set = [];
  19415. // make the set of regexps etc.
  19416. this.make();
  19417. }
  19418. hasMagic() {
  19419. if (this.options.magicalBraces && this.set.length > 1) {
  19420. return true;
  19421. }
  19422. for (const pattern of this.set) {
  19423. for (const part of pattern) {
  19424. if (typeof part !== 'string')
  19425. return true;
  19426. }
  19427. }
  19428. return false;
  19429. }
  19430. debug(..._) { }
  19431. make() {
  19432. const pattern = this.pattern;
  19433. const options = this.options;
  19434. // empty patterns and comments match nothing.
  19435. if (!options.nocomment && pattern.charAt(0) === '#') {
  19436. this.comment = true;
  19437. return;
  19438. }
  19439. if (!pattern) {
  19440. this.empty = true;
  19441. return;
  19442. }
  19443. // step 1: figure out negation, etc.
  19444. this.parseNegate();
  19445. // step 2: expand braces
  19446. this.globSet = [...new Set(this.braceExpand())];
  19447. if (options.debug) {
  19448. this.debug = (...args) => console.error(...args);
  19449. }
  19450. this.debug(this.pattern, this.globSet);
  19451. // step 3: now we have a set, so turn each one into a series of
  19452. // path-portion matching patterns.
  19453. // These will be regexps, except in the case of "**", which is
  19454. // set to the GLOBSTAR object for globstar behavior,
  19455. // and will not contain any / characters
  19456. //
  19457. // First, we preprocess to make the glob pattern sets a bit simpler
  19458. // and deduped. There are some perf-killing patterns that can cause
  19459. // problems with a glob walk, but we can simplify them down a bit.
  19460. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  19461. this.globParts = this.preprocess(rawGlobParts);
  19462. this.debug(this.pattern, this.globParts);
  19463. // glob --> regexps
  19464. let set = this.globParts.map((s, _, __) => {
  19465. if (this.isWindows && this.windowsNoMagicRoot) {
  19466. // check if it's a drive or unc path.
  19467. const isUNC = s[0] === '' &&
  19468. s[1] === '' &&
  19469. (s[2] === '?' || !globMagic.test(s[2])) &&
  19470. !globMagic.test(s[3]);
  19471. const isDrive = /^[a-z]:/i.test(s[0]);
  19472. if (isUNC) {
  19473. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  19474. }
  19475. else if (isDrive) {
  19476. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  19477. }
  19478. }
  19479. return s.map(ss => this.parse(ss));
  19480. });
  19481. this.debug(this.pattern, set);
  19482. // filter out everything that didn't compile properly.
  19483. this.set = set.filter(s => s.indexOf(false) === -1);
  19484. // do not treat the ? in UNC paths as magic
  19485. if (this.isWindows) {
  19486. for (let i = 0; i < this.set.length; i++) {
  19487. const p = this.set[i];
  19488. if (p[0] === '' &&
  19489. p[1] === '' &&
  19490. this.globParts[i][2] === '?' &&
  19491. typeof p[3] === 'string' &&
  19492. /^[a-z]:$/i.test(p[3])) {
  19493. p[2] = '?';
  19494. }
  19495. }
  19496. }
  19497. this.debug(this.pattern, this.set);
  19498. }
  19499. // various transforms to equivalent pattern sets that are
  19500. // faster to process in a filesystem walk. The goal is to
  19501. // eliminate what we can, and push all ** patterns as far
  19502. // to the right as possible, even if it increases the number
  19503. // of patterns that we have to process.
  19504. preprocess(globParts) {
  19505. // if we're not in globstar mode, then turn all ** into *
  19506. if (this.options.noglobstar) {
  19507. for (let i = 0; i < globParts.length; i++) {
  19508. for (let j = 0; j < globParts[i].length; j++) {
  19509. if (globParts[i][j] === '**') {
  19510. globParts[i][j] = '*';
  19511. }
  19512. }
  19513. }
  19514. }
  19515. const { optimizationLevel = 1 } = this.options;
  19516. if (optimizationLevel >= 2) {
  19517. // aggressive optimization for the purpose of fs walking
  19518. globParts = this.firstPhasePreProcess(globParts);
  19519. globParts = this.secondPhasePreProcess(globParts);
  19520. }
  19521. else if (optimizationLevel >= 1) {
  19522. // just basic optimizations to remove some .. parts
  19523. globParts = this.levelOneOptimize(globParts);
  19524. }
  19525. else {
  19526. // just collapse multiple ** portions into one
  19527. globParts = this.adjascentGlobstarOptimize(globParts);
  19528. }
  19529. return globParts;
  19530. }
  19531. // just get rid of adjascent ** portions
  19532. adjascentGlobstarOptimize(globParts) {
  19533. return globParts.map(parts => {
  19534. let gs = -1;
  19535. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19536. let i = gs;
  19537. while (parts[i + 1] === '**') {
  19538. i++;
  19539. }
  19540. if (i !== gs) {
  19541. parts.splice(gs, i - gs);
  19542. }
  19543. }
  19544. return parts;
  19545. });
  19546. }
  19547. // get rid of adjascent ** and resolve .. portions
  19548. levelOneOptimize(globParts) {
  19549. return globParts.map(parts => {
  19550. parts = parts.reduce((set, part) => {
  19551. const prev = set[set.length - 1];
  19552. if (part === '**' && prev === '**') {
  19553. return set;
  19554. }
  19555. if (part === '..') {
  19556. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  19557. set.pop();
  19558. return set;
  19559. }
  19560. }
  19561. set.push(part);
  19562. return set;
  19563. }, []);
  19564. return parts.length === 0 ? [''] : parts;
  19565. });
  19566. }
  19567. levelTwoFileOptimize(parts) {
  19568. if (!Array.isArray(parts)) {
  19569. parts = this.slashSplit(parts);
  19570. }
  19571. let didSomething = false;
  19572. do {
  19573. didSomething = false;
  19574. // <pre>/<e>/<rest> -> <pre>/<rest>
  19575. if (!this.preserveMultipleSlashes) {
  19576. for (let i = 1; i < parts.length - 1; i++) {
  19577. const p = parts[i];
  19578. // don't squeeze out UNC patterns
  19579. if (i === 1 && p === '' && parts[0] === '')
  19580. continue;
  19581. if (p === '.' || p === '') {
  19582. didSomething = true;
  19583. parts.splice(i, 1);
  19584. i--;
  19585. }
  19586. }
  19587. if (parts[0] === '.' &&
  19588. parts.length === 2 &&
  19589. (parts[1] === '.' || parts[1] === '')) {
  19590. didSomething = true;
  19591. parts.pop();
  19592. }
  19593. }
  19594. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19595. let dd = 0;
  19596. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19597. const p = parts[dd - 1];
  19598. if (p && p !== '.' && p !== '..' && p !== '**') {
  19599. didSomething = true;
  19600. parts.splice(dd - 1, 2);
  19601. dd -= 2;
  19602. }
  19603. }
  19604. } while (didSomething);
  19605. return parts.length === 0 ? [''] : parts;
  19606. }
  19607. // First phase: single-pattern processing
  19608. // <pre> is 1 or more portions
  19609. // <rest> is 1 or more portions
  19610. // <p> is any portion other than ., .., '', or **
  19611. // <e> is . or ''
  19612. //
  19613. // **/.. is *brutal* for filesystem walking performance, because
  19614. // it effectively resets the recursive walk each time it occurs,
  19615. // and ** cannot be reduced out by a .. pattern part like a regexp
  19616. // or most strings (other than .., ., and '') can be.
  19617. //
  19618. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19619. // <pre>/<e>/<rest> -> <pre>/<rest>
  19620. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19621. // **/**/<rest> -> **/<rest>
  19622. //
  19623. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  19624. // this WOULD be allowed if ** did follow symlinks, or * didn't
  19625. firstPhasePreProcess(globParts) {
  19626. let didSomething = false;
  19627. do {
  19628. didSomething = false;
  19629. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19630. for (let parts of globParts) {
  19631. let gs = -1;
  19632. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19633. let gss = gs;
  19634. while (parts[gss + 1] === '**') {
  19635. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  19636. gss++;
  19637. }
  19638. // eg, if gs is 2 and gss is 4, that means we have 3 **
  19639. // parts, and can remove 2 of them.
  19640. if (gss > gs) {
  19641. parts.splice(gs + 1, gss - gs);
  19642. }
  19643. let next = parts[gs + 1];
  19644. const p = parts[gs + 2];
  19645. const p2 = parts[gs + 3];
  19646. if (next !== '..')
  19647. continue;
  19648. if (!p ||
  19649. p === '.' ||
  19650. p === '..' ||
  19651. !p2 ||
  19652. p2 === '.' ||
  19653. p2 === '..') {
  19654. continue;
  19655. }
  19656. didSomething = true;
  19657. // edit parts in place, and push the new one
  19658. parts.splice(gs, 1);
  19659. const other = parts.slice(0);
  19660. other[gs] = '**';
  19661. globParts.push(other);
  19662. gs--;
  19663. }
  19664. // <pre>/<e>/<rest> -> <pre>/<rest>
  19665. if (!this.preserveMultipleSlashes) {
  19666. for (let i = 1; i < parts.length - 1; i++) {
  19667. const p = parts[i];
  19668. // don't squeeze out UNC patterns
  19669. if (i === 1 && p === '' && parts[0] === '')
  19670. continue;
  19671. if (p === '.' || p === '') {
  19672. didSomething = true;
  19673. parts.splice(i, 1);
  19674. i--;
  19675. }
  19676. }
  19677. if (parts[0] === '.' &&
  19678. parts.length === 2 &&
  19679. (parts[1] === '.' || parts[1] === '')) {
  19680. didSomething = true;
  19681. parts.pop();
  19682. }
  19683. }
  19684. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19685. let dd = 0;
  19686. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19687. const p = parts[dd - 1];
  19688. if (p && p !== '.' && p !== '..' && p !== '**') {
  19689. didSomething = true;
  19690. const needDot = dd === 1 && parts[dd + 1] === '**';
  19691. const splin = needDot ? ['.'] : [];
  19692. parts.splice(dd - 1, 2, ...splin);
  19693. if (parts.length === 0)
  19694. parts.push('');
  19695. dd -= 2;
  19696. }
  19697. }
  19698. }
  19699. } while (didSomething);
  19700. return globParts;
  19701. }
  19702. // second phase: multi-pattern dedupes
  19703. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  19704. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  19705. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  19706. //
  19707. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  19708. // ^-- not valid because ** doens't follow symlinks
  19709. secondPhasePreProcess(globParts) {
  19710. for (let i = 0; i < globParts.length - 1; i++) {
  19711. for (let j = i + 1; j < globParts.length; j++) {
  19712. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  19713. if (matched) {
  19714. globParts[i] = [];
  19715. globParts[j] = matched;
  19716. break;
  19717. }
  19718. }
  19719. }
  19720. return globParts.filter(gs => gs.length);
  19721. }
  19722. partsMatch(a, b, emptyGSMatch = false) {
  19723. let ai = 0;
  19724. let bi = 0;
  19725. let result = [];
  19726. let which = '';
  19727. while (ai < a.length && bi < b.length) {
  19728. if (a[ai] === b[bi]) {
  19729. result.push(which === 'b' ? b[bi] : a[ai]);
  19730. ai++;
  19731. bi++;
  19732. }
  19733. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  19734. result.push(a[ai]);
  19735. ai++;
  19736. }
  19737. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  19738. result.push(b[bi]);
  19739. bi++;
  19740. }
  19741. else if (a[ai] === '*' &&
  19742. b[bi] &&
  19743. (this.options.dot || !b[bi].startsWith('.')) &&
  19744. b[bi] !== '**') {
  19745. if (which === 'b')
  19746. return false;
  19747. which = 'a';
  19748. result.push(a[ai]);
  19749. ai++;
  19750. bi++;
  19751. }
  19752. else if (b[bi] === '*' &&
  19753. a[ai] &&
  19754. (this.options.dot || !a[ai].startsWith('.')) &&
  19755. a[ai] !== '**') {
  19756. if (which === 'a')
  19757. return false;
  19758. which = 'b';
  19759. result.push(b[bi]);
  19760. ai++;
  19761. bi++;
  19762. }
  19763. else {
  19764. return false;
  19765. }
  19766. }
  19767. // if we fall out of the loop, it means they two are identical
  19768. // as long as their lengths match
  19769. return a.length === b.length && result;
  19770. }
  19771. parseNegate() {
  19772. if (this.nonegate)
  19773. return;
  19774. const pattern = this.pattern;
  19775. let negate = false;
  19776. let negateOffset = 0;
  19777. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  19778. negate = !negate;
  19779. negateOffset++;
  19780. }
  19781. if (negateOffset)
  19782. this.pattern = pattern.slice(negateOffset);
  19783. this.negate = negate;
  19784. }
  19785. // set partial to true to test if, for example,
  19786. // "/a/b" matches the start of "/*/b/*/d"
  19787. // Partial means, if you run out of file before you run
  19788. // out of pattern, then that's fine, as long as all
  19789. // the parts match.
  19790. matchOne(file, pattern, partial = false) {
  19791. const options = this.options;
  19792. // UNC paths like //?/X:/... can match X:/... and vice versa
  19793. // Drive letters in absolute drive or unc paths are always compared
  19794. // case-insensitively.
  19795. if (this.isWindows) {
  19796. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  19797. const fileUNC = !fileDrive &&
  19798. file[0] === '' &&
  19799. file[1] === '' &&
  19800. file[2] === '?' &&
  19801. /^[a-z]:$/i.test(file[3]);
  19802. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  19803. const patternUNC = !patternDrive &&
  19804. pattern[0] === '' &&
  19805. pattern[1] === '' &&
  19806. pattern[2] === '?' &&
  19807. typeof pattern[3] === 'string' &&
  19808. /^[a-z]:$/i.test(pattern[3]);
  19809. const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
  19810. const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
  19811. if (typeof fdi === 'number' && typeof pdi === 'number') {
  19812. const [fd, pd] = [file[fdi], pattern[pdi]];
  19813. if (fd.toLowerCase() === pd.toLowerCase()) {
  19814. pattern[pdi] = fd;
  19815. if (pdi > fdi) {
  19816. pattern = pattern.slice(pdi);
  19817. }
  19818. else if (fdi > pdi) {
  19819. file = file.slice(fdi);
  19820. }
  19821. }
  19822. }
  19823. }
  19824. // resolve and reduce . and .. portions in the file as well.
  19825. // don't need to do the second phase, because it's only one string[]
  19826. const { optimizationLevel = 1 } = this.options;
  19827. if (optimizationLevel >= 2) {
  19828. file = this.levelTwoFileOptimize(file);
  19829. }
  19830. this.debug('matchOne', this, { file, pattern });
  19831. this.debug('matchOne', file.length, pattern.length);
  19832. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  19833. this.debug('matchOne loop');
  19834. var p = pattern[pi];
  19835. var f = file[fi];
  19836. this.debug(pattern, p, f);
  19837. // should be impossible.
  19838. // some invalid regexp stuff in the set.
  19839. /* c8 ignore start */
  19840. if (p === false) {
  19841. return false;
  19842. }
  19843. /* c8 ignore stop */
  19844. if (p === GLOBSTAR) {
  19845. this.debug('GLOBSTAR', [pattern, p, f]);
  19846. // "**"
  19847. // a/**/b/**/c would match the following:
  19848. // a/b/x/y/z/c
  19849. // a/x/y/z/b/c
  19850. // a/b/x/b/x/c
  19851. // a/b/c
  19852. // To do this, take the rest of the pattern after
  19853. // the **, and see if it would match the file remainder.
  19854. // If so, return success.
  19855. // If not, the ** "swallows" a segment, and try again.
  19856. // This is recursively awful.
  19857. //
  19858. // a/**/b/**/c matching a/b/x/y/z/c
  19859. // - a matches a
  19860. // - doublestar
  19861. // - matchOne(b/x/y/z/c, b/**/c)
  19862. // - b matches b
  19863. // - doublestar
  19864. // - matchOne(x/y/z/c, c) -> no
  19865. // - matchOne(y/z/c, c) -> no
  19866. // - matchOne(z/c, c) -> no
  19867. // - matchOne(c, c) yes, hit
  19868. var fr = fi;
  19869. var pr = pi + 1;
  19870. if (pr === pl) {
  19871. this.debug('** at the end');
  19872. // a ** at the end will just swallow the rest.
  19873. // We have found a match.
  19874. // however, it will not swallow /.x, unless
  19875. // options.dot is set.
  19876. // . and .. are *never* matched by **, for explosively
  19877. // exponential reasons.
  19878. for (; fi < fl; fi++) {
  19879. if (file[fi] === '.' ||
  19880. file[fi] === '..' ||
  19881. (!options.dot && file[fi].charAt(0) === '.'))
  19882. return false;
  19883. }
  19884. return true;
  19885. }
  19886. // ok, let's see if we can swallow whatever we can.
  19887. while (fr < fl) {
  19888. var swallowee = file[fr];
  19889. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  19890. // XXX remove this slice. Just pass the start index.
  19891. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  19892. this.debug('globstar found match!', fr, fl, swallowee);
  19893. // found a match.
  19894. return true;
  19895. }
  19896. else {
  19897. // can't swallow "." or ".." ever.
  19898. // can only swallow ".foo" when explicitly asked.
  19899. if (swallowee === '.' ||
  19900. swallowee === '..' ||
  19901. (!options.dot && swallowee.charAt(0) === '.')) {
  19902. this.debug('dot detected!', file, fr, pattern, pr);
  19903. break;
  19904. }
  19905. // ** swallows a segment, and continue.
  19906. this.debug('globstar swallow a segment, and continue');
  19907. fr++;
  19908. }
  19909. }
  19910. // no match was found.
  19911. // However, in partial mode, we can't say this is necessarily over.
  19912. /* c8 ignore start */
  19913. if (partial) {
  19914. // ran out of file
  19915. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  19916. if (fr === fl) {
  19917. return true;
  19918. }
  19919. }
  19920. /* c8 ignore stop */
  19921. return false;
  19922. }
  19923. // something other than **
  19924. // non-magic patterns just have to match exactly
  19925. // patterns with magic have been turned into regexps.
  19926. let hit;
  19927. if (typeof p === 'string') {
  19928. hit = f === p;
  19929. this.debug('string match', p, f, hit);
  19930. }
  19931. else {
  19932. hit = p.test(f);
  19933. this.debug('pattern match', p, f, hit);
  19934. }
  19935. if (!hit)
  19936. return false;
  19937. }
  19938. // Note: ending in / means that we'll get a final ""
  19939. // at the end of the pattern. This can only match a
  19940. // corresponding "" at the end of the file.
  19941. // If the file ends in /, then it can only match a
  19942. // a pattern that ends in /, unless the pattern just
  19943. // doesn't have any more for it. But, a/b/ should *not*
  19944. // match "a/b/*", even though "" matches against the
  19945. // [^/]*? pattern, except in partial mode, where it might
  19946. // simply not be reached yet.
  19947. // However, a/b/ should still satisfy a/*
  19948. // now either we fell off the end of the pattern, or we're done.
  19949. if (fi === fl && pi === pl) {
  19950. // ran out of pattern and filename at the same time.
  19951. // an exact hit!
  19952. return true;
  19953. }
  19954. else if (fi === fl) {
  19955. // ran out of file, but still had pattern left.
  19956. // this is ok if we're doing the match as part of
  19957. // a glob fs traversal.
  19958. return partial;
  19959. }
  19960. else if (pi === pl) {
  19961. // ran out of pattern, still have file left.
  19962. // this is only acceptable if we're on the very last
  19963. // empty segment of a file with a trailing slash.
  19964. // a/* should match a/b/
  19965. return fi === fl - 1 && file[fi] === '';
  19966. /* c8 ignore start */
  19967. }
  19968. else {
  19969. // should be unreachable.
  19970. throw new Error('wtf?');
  19971. }
  19972. /* c8 ignore stop */
  19973. }
  19974. braceExpand() {
  19975. return braceExpand(this.pattern, this.options);
  19976. }
  19977. parse(pattern) {
  19978. assertValidPattern(pattern);
  19979. const options = this.options;
  19980. // shortcuts
  19981. if (pattern === '**')
  19982. return GLOBSTAR;
  19983. if (pattern === '')
  19984. return '';
  19985. // far and away, the most common glob pattern parts are
  19986. // *, *.*, and *.<ext> Add a fast check method for those.
  19987. let m;
  19988. let fastTest = null;
  19989. if ((m = pattern.match(starRE))) {
  19990. fastTest = options.dot ? starTestDot : starTest;
  19991. }
  19992. else if ((m = pattern.match(starDotExtRE))) {
  19993. fastTest = (options.nocase
  19994. ? options.dot
  19995. ? starDotExtTestNocaseDot
  19996. : starDotExtTestNocase
  19997. : options.dot
  19998. ? starDotExtTestDot
  19999. : starDotExtTest)(m[1]);
  20000. }
  20001. else if ((m = pattern.match(qmarksRE))) {
  20002. fastTest = (options.nocase
  20003. ? options.dot
  20004. ? qmarksTestNocaseDot
  20005. : qmarksTestNocase
  20006. : options.dot
  20007. ? qmarksTestDot
  20008. : qmarksTest)(m);
  20009. }
  20010. else if ((m = pattern.match(starDotStarRE))) {
  20011. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  20012. }
  20013. else if ((m = pattern.match(dotStarRE))) {
  20014. fastTest = dotStarTest;
  20015. }
  20016. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  20017. if (fastTest && typeof re === 'object') {
  20018. // Avoids overriding in frozen environments
  20019. Reflect.defineProperty(re, 'test', { value: fastTest });
  20020. }
  20021. return re;
  20022. }
  20023. makeRe() {
  20024. if (this.regexp || this.regexp === false)
  20025. return this.regexp;
  20026. // at this point, this.set is a 2d array of partial
  20027. // pattern strings, or "**".
  20028. //
  20029. // It's better to use .match(). This function shouldn't
  20030. // be used, really, but it's pretty convenient sometimes,
  20031. // when you just want to work with a regex.
  20032. const set = this.set;
  20033. if (!set.length) {
  20034. this.regexp = false;
  20035. return this.regexp;
  20036. }
  20037. const options = this.options;
  20038. const twoStar = options.noglobstar
  20039. ? star
  20040. : options.dot
  20041. ? twoStarDot
  20042. : twoStarNoDot;
  20043. const flags = new Set(options.nocase ? ['i'] : []);
  20044. // regexpify non-globstar patterns
  20045. // if ** is only item, then we just do one twoStar
  20046. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  20047. // if ** is last, append (\/twoStar|) to previous
  20048. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  20049. // then filter out GLOBSTAR symbols
  20050. let re = set
  20051. .map(pattern => {
  20052. const pp = pattern.map(p => {
  20053. if (p instanceof RegExp) {
  20054. for (const f of p.flags.split(''))
  20055. flags.add(f);
  20056. }
  20057. return typeof p === 'string'
  20058. ? regExpEscape(p)
  20059. : p === GLOBSTAR
  20060. ? GLOBSTAR
  20061. : p._src;
  20062. });
  20063. pp.forEach((p, i) => {
  20064. const next = pp[i + 1];
  20065. const prev = pp[i - 1];
  20066. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  20067. return;
  20068. }
  20069. if (prev === undefined) {
  20070. if (next !== undefined && next !== GLOBSTAR) {
  20071. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  20072. }
  20073. else {
  20074. pp[i] = twoStar;
  20075. }
  20076. }
  20077. else if (next === undefined) {
  20078. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
  20079. }
  20080. else if (next !== GLOBSTAR) {
  20081. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  20082. pp[i + 1] = GLOBSTAR;
  20083. }
  20084. });
  20085. const filtered = pp.filter(p => p !== GLOBSTAR);
  20086. // For partial matches, we need to make the pattern match
  20087. // any prefix of the full path. We do this by generating
  20088. // alternative patterns that match progressively longer prefixes.
  20089. if (this.partial && filtered.length >= 1) {
  20090. const prefixes = [];
  20091. for (let i = 1; i <= filtered.length; i++) {
  20092. prefixes.push(filtered.slice(0, i).join('/'));
  20093. }
  20094. return '(?:' + prefixes.join('|') + ')';
  20095. }
  20096. return filtered.join('/');
  20097. })
  20098. .join('|');
  20099. // need to wrap in parens if we had more than one thing with |,
  20100. // otherwise only the first will be anchored to ^ and the last to $
  20101. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  20102. // must match entire pattern
  20103. // ending in a * or ** will make it less strict.
  20104. re = '^' + open + re + close + '$';
  20105. // In partial mode, '/' should always match as it's a valid prefix for any pattern
  20106. if (this.partial) {
  20107. re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
  20108. }
  20109. // can match anything, as long as it's not this.
  20110. if (this.negate)
  20111. re = '^(?!' + re + ').+$';
  20112. try {
  20113. this.regexp = new RegExp(re, [...flags].join(''));
  20114. /* c8 ignore start */
  20115. }
  20116. catch (ex) {
  20117. // should be impossible
  20118. this.regexp = false;
  20119. }
  20120. /* c8 ignore stop */
  20121. return this.regexp;
  20122. }
  20123. slashSplit(p) {
  20124. // if p starts with // on windows, we preserve that
  20125. // so that UNC paths aren't broken. Otherwise, any number of
  20126. // / characters are coalesced into one, unless
  20127. // preserveMultipleSlashes is set to true.
  20128. if (this.preserveMultipleSlashes) {
  20129. return p.split('/');
  20130. }
  20131. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  20132. // add an extra '' for the one we lose
  20133. return ['', ...p.split(/\/+/)];
  20134. }
  20135. else {
  20136. return p.split(/\/+/);
  20137. }
  20138. }
  20139. match(f, partial = this.partial) {
  20140. this.debug('match', f, this.pattern);
  20141. // short-circuit in the case of busted things.
  20142. // comments, etc.
  20143. if (this.comment) {
  20144. return false;
  20145. }
  20146. if (this.empty) {
  20147. return f === '';
  20148. }
  20149. if (f === '/' && partial) {
  20150. return true;
  20151. }
  20152. const options = this.options;
  20153. // windows: need to use /, not \
  20154. if (this.isWindows) {
  20155. f = f.split('\\').join('/');
  20156. }
  20157. // treat the test path as a set of pathparts.
  20158. const ff = this.slashSplit(f);
  20159. this.debug(this.pattern, 'split', ff);
  20160. // just ONE of the pattern sets in this.set needs to match
  20161. // in order for it to be valid. If negating, then just one
  20162. // match means that we have failed.
  20163. // Either way, return on the first hit.
  20164. const set = this.set;
  20165. this.debug(this.pattern, 'set', set);
  20166. // Find the basename of the path by looking for the last non-empty segment
  20167. let filename = ff[ff.length - 1];
  20168. if (!filename) {
  20169. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  20170. filename = ff[i];
  20171. }
  20172. }
  20173. for (let i = 0; i < set.length; i++) {
  20174. const pattern = set[i];
  20175. let file = ff;
  20176. if (options.matchBase && pattern.length === 1) {
  20177. file = [filename];
  20178. }
  20179. const hit = this.matchOne(file, pattern, partial);
  20180. if (hit) {
  20181. if (options.flipNegate) {
  20182. return true;
  20183. }
  20184. return !this.negate;
  20185. }
  20186. }
  20187. // didn't get any hits. this is success if it's a negative
  20188. // pattern, failure otherwise.
  20189. if (options.flipNegate) {
  20190. return false;
  20191. }
  20192. return this.negate;
  20193. }
  20194. static defaults(def) {
  20195. return minimatch.defaults(def).Minimatch;
  20196. }
  20197. }
  20198. /* c8 ignore stop */
  20199. minimatch.AST = AST;
  20200. minimatch.Minimatch = Minimatch;
  20201. minimatch.escape = escape;
  20202. minimatch.unescape = unescape;
  20203. class TypeScope {
  20204. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  20205. this.filename = filename;
  20206. this.source = source;
  20207. this.offset = offset;
  20208. this.imports = imports;
  20209. this.types = types;
  20210. this.declares = declares;
  20211. this.isGenericScope = false;
  20212. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  20213. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  20214. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  20215. }
  20216. }
  20217. function resolveTypeElements(ctx, node, scope, typeParameters) {
  20218. const canCache = !typeParameters;
  20219. if (canCache && node._resolvedElements) {
  20220. return node._resolvedElements;
  20221. }
  20222. const resolved = innerResolveTypeElements(
  20223. ctx,
  20224. node,
  20225. node._ownerScope || scope || ctxToScope(ctx),
  20226. typeParameters
  20227. );
  20228. return canCache ? node._resolvedElements = resolved : resolved;
  20229. }
  20230. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  20231. var _a, _b;
  20232. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  20233. return { props: {} };
  20234. }
  20235. switch (node.type) {
  20236. case "TSTypeLiteral":
  20237. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  20238. case "TSInterfaceDeclaration":
  20239. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  20240. case "TSTypeAliasDeclaration":
  20241. case "TSTypeAnnotation":
  20242. case "TSParenthesizedType":
  20243. return resolveTypeElements(
  20244. ctx,
  20245. node.typeAnnotation,
  20246. scope,
  20247. typeParameters
  20248. );
  20249. case "TSFunctionType": {
  20250. return { props: {}, calls: [node] };
  20251. }
  20252. case "TSUnionType":
  20253. case "TSIntersectionType":
  20254. return mergeElements(
  20255. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  20256. node.type
  20257. );
  20258. case "TSMappedType":
  20259. return resolveMappedType(ctx, node, scope, typeParameters);
  20260. case "TSIndexedAccessType": {
  20261. const types = resolveIndexType(ctx, node, scope);
  20262. return mergeElements(
  20263. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  20264. "TSUnionType"
  20265. );
  20266. }
  20267. case "TSExpressionWithTypeArguments":
  20268. // referenced by interface extends
  20269. case "TSTypeReference": {
  20270. const typeName = getReferenceName(node);
  20271. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  20272. return resolveExtractPropTypes(
  20273. resolveTypeElements(
  20274. ctx,
  20275. node.typeParameters.params[0],
  20276. scope,
  20277. typeParameters
  20278. ),
  20279. scope
  20280. );
  20281. }
  20282. const resolved = resolveTypeReference(ctx, node, scope);
  20283. if (resolved) {
  20284. let typeParams;
  20285. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  20286. typeParams = /* @__PURE__ */ Object.create(null);
  20287. resolved.typeParameters.params.forEach((p, i) => {
  20288. let param = typeParameters && typeParameters[p.name];
  20289. if (!param) param = node.typeParameters.params[i];
  20290. typeParams[p.name] = param;
  20291. });
  20292. }
  20293. return resolveTypeElements(
  20294. ctx,
  20295. resolved,
  20296. resolved._ownerScope,
  20297. typeParams
  20298. );
  20299. } else {
  20300. if (typeof typeName === "string") {
  20301. if (typeParameters && typeParameters[typeName]) {
  20302. return resolveTypeElements(
  20303. ctx,
  20304. typeParameters[typeName],
  20305. scope,
  20306. typeParameters
  20307. );
  20308. }
  20309. if (
  20310. // @ts-expect-error
  20311. SupportedBuiltinsSet.has(typeName)
  20312. ) {
  20313. return resolveBuiltin(
  20314. ctx,
  20315. node,
  20316. typeName,
  20317. scope,
  20318. typeParameters
  20319. );
  20320. } else if (typeName === "ReturnType" && node.typeParameters) {
  20321. const ret = resolveReturnType(
  20322. ctx,
  20323. node.typeParameters.params[0],
  20324. scope
  20325. );
  20326. if (ret) {
  20327. return resolveTypeElements(ctx, ret, scope);
  20328. }
  20329. }
  20330. }
  20331. return ctx.error(
  20332. `Unresolvable type reference or unsupported built-in utility type`,
  20333. node,
  20334. scope
  20335. );
  20336. }
  20337. }
  20338. case "TSImportType": {
  20339. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  20340. return resolveExtractPropTypes(
  20341. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  20342. scope
  20343. );
  20344. }
  20345. const sourceScope = importSourceToScope(
  20346. ctx,
  20347. node.argument,
  20348. scope,
  20349. node.argument.value
  20350. );
  20351. const resolved = resolveTypeReference(ctx, node, sourceScope);
  20352. if (resolved) {
  20353. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20354. }
  20355. break;
  20356. }
  20357. case "TSTypeQuery":
  20358. {
  20359. const resolved = resolveTypeReference(ctx, node, scope);
  20360. if (resolved) {
  20361. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20362. }
  20363. }
  20364. break;
  20365. }
  20366. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  20367. }
  20368. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  20369. const res = { props: {} };
  20370. for (const e of elements) {
  20371. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  20372. if (typeParameters) {
  20373. scope = createChildScope(scope);
  20374. scope.isGenericScope = true;
  20375. Object.assign(scope.types, typeParameters);
  20376. }
  20377. e._ownerScope = scope;
  20378. const name = getStringLiteralKey(e);
  20379. if (name !== null) {
  20380. res.props[name] = e;
  20381. } else {
  20382. ctx.error(
  20383. `Unsupported computed key in type referenced by a macro`,
  20384. e.key,
  20385. scope
  20386. );
  20387. }
  20388. } else if (e.type === "TSCallSignatureDeclaration") {
  20389. (res.calls || (res.calls = [])).push(e);
  20390. }
  20391. }
  20392. return res;
  20393. }
  20394. function mergeElements(maps, type) {
  20395. if (maps.length === 1) return maps[0];
  20396. const res = { props: {} };
  20397. const { props: baseProps } = res;
  20398. for (const { props, calls } of maps) {
  20399. for (const key in props) {
  20400. if (!shared.hasOwn(baseProps, key)) {
  20401. baseProps[key] = props[key];
  20402. } else {
  20403. baseProps[key] = createProperty(
  20404. baseProps[key].key,
  20405. {
  20406. type,
  20407. // @ts-expect-error
  20408. types: [baseProps[key], props[key]]
  20409. },
  20410. baseProps[key]._ownerScope,
  20411. baseProps[key].optional || props[key].optional
  20412. );
  20413. }
  20414. }
  20415. if (calls) {
  20416. (res.calls || (res.calls = [])).push(...calls);
  20417. }
  20418. }
  20419. return res;
  20420. }
  20421. function createProperty(key, typeAnnotation, scope, optional) {
  20422. return {
  20423. type: "TSPropertySignature",
  20424. key,
  20425. kind: "get",
  20426. optional,
  20427. typeAnnotation: {
  20428. type: "TSTypeAnnotation",
  20429. typeAnnotation
  20430. },
  20431. _ownerScope: scope
  20432. };
  20433. }
  20434. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  20435. const base = typeElementsToMap(
  20436. ctx,
  20437. node.body.body,
  20438. node._ownerScope,
  20439. typeParameters
  20440. );
  20441. if (node.extends) {
  20442. for (const ext of node.extends) {
  20443. try {
  20444. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  20445. for (const key in props) {
  20446. if (!shared.hasOwn(base.props, key)) {
  20447. base.props[key] = props[key];
  20448. }
  20449. }
  20450. if (calls) {
  20451. ;
  20452. (base.calls || (base.calls = [])).push(...calls);
  20453. }
  20454. } catch (e) {
  20455. if (!ctx.silentOnExtendsFailure) {
  20456. ctx.error(
  20457. `Failed to resolve extends base type.
  20458. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  20459. interface Props extends /* @vue-ignore */ Base {}
  20460. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  20461. ext,
  20462. scope
  20463. );
  20464. }
  20465. }
  20466. }
  20467. }
  20468. return base;
  20469. }
  20470. function resolveMappedType(ctx, node, scope, typeParameters) {
  20471. const res = { props: {} };
  20472. let keys;
  20473. if (node.nameType) {
  20474. const { name, constraint } = node.typeParameter;
  20475. scope = createChildScope(scope);
  20476. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  20477. keys = resolveStringType(ctx, node.nameType, scope);
  20478. } else {
  20479. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  20480. }
  20481. for (const key of keys) {
  20482. res.props[key] = createProperty(
  20483. {
  20484. type: "Identifier",
  20485. name: key
  20486. },
  20487. node.typeAnnotation,
  20488. scope,
  20489. !!node.optional
  20490. );
  20491. }
  20492. return res;
  20493. }
  20494. function resolveIndexType(ctx, node, scope) {
  20495. var _a, _b;
  20496. if (node.indexType.type === "TSNumberKeyword") {
  20497. return resolveArrayElementType(ctx, node.objectType, scope);
  20498. }
  20499. const { indexType, objectType } = node;
  20500. const types = [];
  20501. let keys;
  20502. let resolved;
  20503. if (indexType.type === "TSStringKeyword") {
  20504. resolved = resolveTypeElements(ctx, objectType, scope);
  20505. keys = Object.keys(resolved.props);
  20506. } else {
  20507. keys = resolveStringType(ctx, indexType, scope);
  20508. resolved = resolveTypeElements(ctx, objectType, scope);
  20509. }
  20510. for (const key of keys) {
  20511. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  20512. if (targetType) {
  20513. targetType._ownerScope = resolved.props[key]._ownerScope;
  20514. types.push(targetType);
  20515. }
  20516. }
  20517. return types;
  20518. }
  20519. function resolveArrayElementType(ctx, node, scope) {
  20520. if (node.type === "TSArrayType") {
  20521. return [node.elementType];
  20522. }
  20523. if (node.type === "TSTupleType") {
  20524. return node.elementTypes.map(
  20525. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  20526. );
  20527. }
  20528. if (node.type === "TSTypeReference") {
  20529. if (getReferenceName(node) === "Array" && node.typeParameters) {
  20530. return node.typeParameters.params;
  20531. } else {
  20532. const resolved = resolveTypeReference(ctx, node, scope);
  20533. if (resolved) {
  20534. return resolveArrayElementType(ctx, resolved, scope);
  20535. }
  20536. }
  20537. }
  20538. return ctx.error(
  20539. "Failed to resolve element type from target type",
  20540. node,
  20541. scope
  20542. );
  20543. }
  20544. function resolveStringType(ctx, node, scope, typeParameters) {
  20545. switch (node.type) {
  20546. case "StringLiteral":
  20547. return [node.value];
  20548. case "TSLiteralType":
  20549. return resolveStringType(ctx, node.literal, scope, typeParameters);
  20550. case "TSUnionType":
  20551. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  20552. case "TemplateLiteral": {
  20553. return resolveTemplateKeys(ctx, node, scope);
  20554. }
  20555. case "TSTypeReference": {
  20556. const resolved = resolveTypeReference(ctx, node, scope);
  20557. if (resolved) {
  20558. return resolveStringType(ctx, resolved, scope, typeParameters);
  20559. }
  20560. if (node.typeName.type === "Identifier") {
  20561. const name = node.typeName.name;
  20562. if (typeParameters && typeParameters[name]) {
  20563. return resolveStringType(
  20564. ctx,
  20565. typeParameters[name],
  20566. scope,
  20567. typeParameters
  20568. );
  20569. }
  20570. const getParam = (index = 0) => resolveStringType(
  20571. ctx,
  20572. node.typeParameters.params[index],
  20573. scope,
  20574. typeParameters
  20575. );
  20576. switch (name) {
  20577. case "Extract":
  20578. return getParam(1);
  20579. case "Exclude": {
  20580. const excluded = getParam(1);
  20581. return getParam().filter((s) => !excluded.includes(s));
  20582. }
  20583. case "Uppercase":
  20584. return getParam().map((s) => s.toUpperCase());
  20585. case "Lowercase":
  20586. return getParam().map((s) => s.toLowerCase());
  20587. case "Capitalize":
  20588. return getParam().map(shared.capitalize);
  20589. case "Uncapitalize":
  20590. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  20591. default:
  20592. ctx.error(
  20593. "Unsupported type when resolving index type",
  20594. node.typeName,
  20595. scope
  20596. );
  20597. }
  20598. }
  20599. }
  20600. }
  20601. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  20602. }
  20603. function resolveTemplateKeys(ctx, node, scope) {
  20604. if (!node.expressions.length) {
  20605. return [node.quasis[0].value.raw];
  20606. }
  20607. const res = [];
  20608. const e = node.expressions[0];
  20609. const q = node.quasis[0];
  20610. const leading = q ? q.value.raw : ``;
  20611. const resolved = resolveStringType(ctx, e, scope);
  20612. const restResolved = resolveTemplateKeys(
  20613. ctx,
  20614. {
  20615. ...node,
  20616. expressions: node.expressions.slice(1),
  20617. quasis: q ? node.quasis.slice(1) : node.quasis
  20618. },
  20619. scope
  20620. );
  20621. for (const r of resolved) {
  20622. for (const rr of restResolved) {
  20623. res.push(leading + r + rr);
  20624. }
  20625. }
  20626. return res;
  20627. }
  20628. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  20629. "Partial",
  20630. "Required",
  20631. "Readonly",
  20632. "Pick",
  20633. "Omit"
  20634. ]);
  20635. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  20636. const t = resolveTypeElements(
  20637. ctx,
  20638. node.typeParameters.params[0],
  20639. scope,
  20640. typeParameters
  20641. );
  20642. switch (name) {
  20643. case "Partial": {
  20644. const res2 = { props: {}, calls: t.calls };
  20645. Object.keys(t.props).forEach((key) => {
  20646. res2.props[key] = { ...t.props[key], optional: true };
  20647. });
  20648. return res2;
  20649. }
  20650. case "Required": {
  20651. const res2 = { props: {}, calls: t.calls };
  20652. Object.keys(t.props).forEach((key) => {
  20653. res2.props[key] = { ...t.props[key], optional: false };
  20654. });
  20655. return res2;
  20656. }
  20657. case "Readonly":
  20658. return t;
  20659. case "Pick": {
  20660. const picked = resolveStringType(
  20661. ctx,
  20662. node.typeParameters.params[1],
  20663. scope,
  20664. typeParameters
  20665. );
  20666. const res2 = { props: {}, calls: t.calls };
  20667. for (const key of picked) {
  20668. res2.props[key] = t.props[key];
  20669. }
  20670. return res2;
  20671. }
  20672. case "Omit":
  20673. const omitted = resolveStringType(
  20674. ctx,
  20675. node.typeParameters.params[1],
  20676. scope,
  20677. typeParameters
  20678. );
  20679. const res = { props: {}, calls: t.calls };
  20680. for (const key in t.props) {
  20681. if (!omitted.includes(key)) {
  20682. res.props[key] = t.props[key];
  20683. }
  20684. }
  20685. return res;
  20686. }
  20687. }
  20688. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  20689. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  20690. if (canCache && node._resolvedReference) {
  20691. return node._resolvedReference;
  20692. }
  20693. const resolved = innerResolveTypeReference(
  20694. ctx,
  20695. scope || ctxToScope(ctx),
  20696. name || getReferenceName(node),
  20697. node,
  20698. onlyExported
  20699. );
  20700. return canCache ? node._resolvedReference = resolved : resolved;
  20701. }
  20702. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  20703. if (typeof name === "string") {
  20704. if (scope.imports[name]) {
  20705. return resolveTypeFromImport(ctx, node, name, scope);
  20706. } else {
  20707. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  20708. if (lookupSource[name]) {
  20709. return lookupSource[name];
  20710. } else {
  20711. const globalScopes = resolveGlobalScope(ctx);
  20712. if (globalScopes) {
  20713. for (const s of globalScopes) {
  20714. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  20715. if (src[name]) {
  20716. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  20717. return src[name];
  20718. }
  20719. }
  20720. }
  20721. }
  20722. }
  20723. } else {
  20724. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  20725. if (ns) {
  20726. if (ns.type !== "TSModuleDeclaration") {
  20727. ns = ns._ns;
  20728. }
  20729. if (ns) {
  20730. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  20731. return innerResolveTypeReference(
  20732. ctx,
  20733. childScope,
  20734. name.length > 2 ? name.slice(1) : name[name.length - 1],
  20735. node,
  20736. !ns.declare
  20737. );
  20738. }
  20739. }
  20740. }
  20741. }
  20742. function getReferenceName(node) {
  20743. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  20744. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  20745. return ref.name;
  20746. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  20747. return qualifiedNameToPath(ref);
  20748. } else {
  20749. return "default";
  20750. }
  20751. }
  20752. function qualifiedNameToPath(node) {
  20753. if (node.type === "Identifier") {
  20754. return [node.name];
  20755. } else {
  20756. return [...qualifiedNameToPath(node.left), node.right.name];
  20757. }
  20758. }
  20759. function resolveGlobalScope(ctx) {
  20760. if (ctx.options.globalTypeFiles) {
  20761. const fs = resolveFS(ctx);
  20762. if (!fs) {
  20763. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  20764. }
  20765. return ctx.options.globalTypeFiles.map(
  20766. (file) => fileToScope(ctx, normalizePath(file), true)
  20767. );
  20768. }
  20769. }
  20770. let ts;
  20771. let loadTS;
  20772. function registerTS(_loadTS) {
  20773. loadTS = () => {
  20774. try {
  20775. return _loadTS();
  20776. } catch (err) {
  20777. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  20778. throw new Error(
  20779. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  20780. );
  20781. } else {
  20782. throw new Error(
  20783. "Failed to load TypeScript for resolving imported types."
  20784. );
  20785. }
  20786. }
  20787. };
  20788. }
  20789. function resolveFS(ctx) {
  20790. if (ctx.fs) {
  20791. return ctx.fs;
  20792. }
  20793. if (!ts && loadTS) {
  20794. ts = loadTS();
  20795. }
  20796. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  20797. if (!fs) {
  20798. return;
  20799. }
  20800. return ctx.fs = {
  20801. fileExists(file) {
  20802. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  20803. file = file.replace(/\.ts$/, "");
  20804. }
  20805. return fs.fileExists(file);
  20806. },
  20807. readFile(file) {
  20808. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  20809. file = file.replace(/\.ts$/, "");
  20810. }
  20811. return fs.readFile(file);
  20812. },
  20813. realpath: fs.realpath
  20814. };
  20815. }
  20816. function resolveTypeFromImport(ctx, node, name, scope) {
  20817. const { source, imported } = scope.imports[name];
  20818. const sourceScope = importSourceToScope(ctx, node, scope, source);
  20819. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  20820. }
  20821. function importSourceToScope(ctx, node, scope, source) {
  20822. let fs;
  20823. try {
  20824. fs = resolveFS(ctx);
  20825. } catch (err) {
  20826. return ctx.error(err.message, node, scope);
  20827. }
  20828. if (!fs) {
  20829. return ctx.error(
  20830. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  20831. node,
  20832. scope
  20833. );
  20834. }
  20835. let resolved = scope.resolvedImportSources[source];
  20836. if (!resolved) {
  20837. if (source.startsWith("..")) {
  20838. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  20839. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  20840. resolved = resolveExt(filename, fs);
  20841. } else if (source[0] === ".") {
  20842. const filename = joinPaths(path$1.dirname(scope.filename), source);
  20843. resolved = resolveExt(filename, fs);
  20844. } else {
  20845. if (!ts) {
  20846. if (loadTS) ts = loadTS();
  20847. if (!ts) {
  20848. return ctx.error(
  20849. `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.`,
  20850. node,
  20851. scope
  20852. );
  20853. }
  20854. }
  20855. resolved = resolveWithTS(scope.filename, source, ts, fs);
  20856. }
  20857. if (resolved) {
  20858. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  20859. }
  20860. }
  20861. if (resolved) {
  20862. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  20863. return fileToScope(ctx, resolved);
  20864. } else {
  20865. return ctx.error(
  20866. `Failed to resolve import source ${JSON.stringify(source)}.`,
  20867. node,
  20868. scope
  20869. );
  20870. }
  20871. }
  20872. function resolveExt(filename, fs) {
  20873. filename = filename.replace(/\.js$/, "");
  20874. const tryResolve = (filename2) => {
  20875. if (fs.fileExists(filename2)) return filename2;
  20876. };
  20877. return tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  20878. }
  20879. const tsConfigCache = createCache();
  20880. const tsConfigRefMap = /* @__PURE__ */ new Map();
  20881. function resolveWithTS(containingFile, source, ts2, fs) {
  20882. var _a, _b;
  20883. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  20884. let tsCompilerOptions;
  20885. let tsResolveCache;
  20886. if (configPath) {
  20887. let configs;
  20888. const normalizedConfigPath = normalizePath(configPath);
  20889. const cached = tsConfigCache.get(normalizedConfigPath);
  20890. if (!cached) {
  20891. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  20892. tsConfigCache.set(normalizedConfigPath, configs);
  20893. } else {
  20894. configs = cached;
  20895. }
  20896. let matchedConfig;
  20897. if (configs.length === 1) {
  20898. matchedConfig = configs[0];
  20899. } else {
  20900. const [major, minor] = ts2.versionMajorMinor.split(".").map(Number);
  20901. const getPattern = (base, p) => {
  20902. const supportsConfigDir = major > 5 || major === 5 && minor >= 5;
  20903. return p.startsWith("${configDir}") && supportsConfigDir ? normalizePath(p.replace("${configDir}", path$1.dirname(configPath))) : joinPaths(base, p);
  20904. };
  20905. for (const c of configs) {
  20906. const base = normalizePath(
  20907. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  20908. );
  20909. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  20910. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  20911. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, getPattern(base, p))))) {
  20912. if (excluded && excluded.some((p) => minimatch(containingFile, getPattern(base, p)))) {
  20913. continue;
  20914. }
  20915. matchedConfig = c;
  20916. break;
  20917. }
  20918. }
  20919. if (!matchedConfig) {
  20920. matchedConfig = configs[configs.length - 1];
  20921. }
  20922. }
  20923. tsCompilerOptions = matchedConfig.config.options;
  20924. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  20925. process__namespace.cwd(),
  20926. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  20927. tsCompilerOptions
  20928. ));
  20929. } else {
  20930. tsCompilerOptions = {};
  20931. }
  20932. const res = ts2.resolveModuleName(
  20933. source,
  20934. containingFile,
  20935. tsCompilerOptions,
  20936. fs,
  20937. tsResolveCache
  20938. );
  20939. if (res.resolvedModule) {
  20940. let filename = res.resolvedModule.resolvedFileName;
  20941. if (filename.endsWith(".vue.ts") && !filename.endsWith(".d.vue.ts")) {
  20942. filename = filename.replace(/\.ts$/, "");
  20943. }
  20944. return fs.realpath ? fs.realpath(filename) : filename;
  20945. }
  20946. }
  20947. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  20948. const parseConfigHost = ts2.sys;
  20949. const config = ts2.parseJsonConfigFileContent(
  20950. ts2.readConfigFile(configPath, fs.readFile).config,
  20951. parseConfigHost,
  20952. path$1.dirname(configPath),
  20953. void 0,
  20954. configPath
  20955. );
  20956. const res = [config];
  20957. visited.add(configPath);
  20958. if (config.projectReferences) {
  20959. for (const ref of config.projectReferences) {
  20960. const refPath = ts2.resolveProjectReferencePath(ref);
  20961. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  20962. continue;
  20963. }
  20964. tsConfigRefMap.set(refPath, configPath);
  20965. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  20966. }
  20967. }
  20968. return res;
  20969. }
  20970. const fileToScopeCache = createCache();
  20971. function invalidateTypeCache(filename) {
  20972. filename = normalizePath(filename);
  20973. fileToScopeCache.delete(filename);
  20974. tsConfigCache.delete(filename);
  20975. const affectedConfig = tsConfigRefMap.get(filename);
  20976. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  20977. }
  20978. function fileToScope(ctx, filename, asGlobal = false) {
  20979. const cached = fileToScopeCache.get(filename);
  20980. if (cached) {
  20981. return cached;
  20982. }
  20983. const fs = resolveFS(ctx);
  20984. const source = fs.readFile(filename) || "";
  20985. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  20986. const scope = new TypeScope(filename, source, 0, recordImports(body));
  20987. recordTypes(ctx, body, scope, asGlobal);
  20988. fileToScopeCache.set(filename, scope);
  20989. return scope;
  20990. }
  20991. function parseFile(filename, content, fs, parserPlugins) {
  20992. const ext = path$1.extname(filename);
  20993. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".mtsx") {
  20994. return parser$2.parse(content, {
  20995. plugins: resolveParserPlugins(
  20996. ext.slice(1),
  20997. parserPlugins,
  20998. /\.d\.m?ts$/.test(filename)
  20999. ),
  21000. sourceType: "module"
  21001. }).program.body;
  21002. }
  21003. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  21004. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  21005. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  21006. if (hasArbitraryTypeDeclaration) {
  21007. return parser$2.parse(fs.readFile(arbitraryTypeSource), {
  21008. plugins: resolveParserPlugins("ts", parserPlugins, true),
  21009. sourceType: "module"
  21010. }).program.body;
  21011. }
  21012. if (ext === ".vue") {
  21013. const {
  21014. descriptor: { script, scriptSetup }
  21015. } = parse$1(content);
  21016. if (!script && !scriptSetup) {
  21017. return [];
  21018. }
  21019. const scriptOffset = script ? script.loc.start.offset : Infinity;
  21020. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  21021. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  21022. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  21023. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  21024. if (secondBlock) {
  21025. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  21026. }
  21027. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  21028. return parser$2.parse(scriptContent, {
  21029. plugins: resolveParserPlugins(lang, parserPlugins),
  21030. sourceType: "module"
  21031. }).program.body;
  21032. }
  21033. return [];
  21034. }
  21035. function ctxToScope(ctx) {
  21036. if (ctx.scope) {
  21037. return ctx.scope;
  21038. }
  21039. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  21040. const scope = new TypeScope(
  21041. ctx.filename,
  21042. ctx.source,
  21043. "startOffset" in ctx ? ctx.startOffset : 0,
  21044. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  21045. );
  21046. recordTypes(ctx, body, scope);
  21047. return ctx.scope = scope;
  21048. }
  21049. function moduleDeclToScope(ctx, node, parentScope) {
  21050. if (node._resolvedChildScope) {
  21051. return node._resolvedChildScope;
  21052. }
  21053. const scope = createChildScope(parentScope);
  21054. if (node.body.type === "TSModuleDeclaration") {
  21055. const decl = node.body;
  21056. decl._ownerScope = scope;
  21057. const id = getId(decl.id);
  21058. scope.types[id] = scope.exportedTypes[id] = decl;
  21059. } else {
  21060. recordTypes(ctx, node.body.body, scope);
  21061. }
  21062. return node._resolvedChildScope = scope;
  21063. }
  21064. function createChildScope(parentScope) {
  21065. return new TypeScope(
  21066. parentScope.filename,
  21067. parentScope.source,
  21068. parentScope.offset,
  21069. Object.create(parentScope.imports),
  21070. Object.create(parentScope.types),
  21071. Object.create(parentScope.declares)
  21072. );
  21073. }
  21074. const importExportRE = /^Import|^Export/;
  21075. function recordTypes(ctx, body, scope, asGlobal = false) {
  21076. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  21077. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  21078. for (const stmt of body) {
  21079. if (asGlobal) {
  21080. if (isAmbient) {
  21081. if (stmt.declare) {
  21082. recordType(stmt, types, declares);
  21083. }
  21084. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  21085. for (const s of stmt.body.body) {
  21086. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  21087. recordType(s.declaration, types, declares);
  21088. } else {
  21089. recordType(s, types, declares);
  21090. }
  21091. }
  21092. }
  21093. } else {
  21094. recordType(stmt, types, declares);
  21095. }
  21096. }
  21097. if (!asGlobal) {
  21098. for (const stmt of body) {
  21099. if (stmt.type === "ExportNamedDeclaration") {
  21100. if (stmt.declaration) {
  21101. recordType(stmt.declaration, types, declares);
  21102. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  21103. } else {
  21104. for (const spec of stmt.specifiers) {
  21105. if (spec.type === "ExportSpecifier") {
  21106. const local = spec.local.name;
  21107. const exported = getId(spec.exported);
  21108. if (stmt.source) {
  21109. imports[exported] = {
  21110. source: stmt.source.value,
  21111. imported: local
  21112. };
  21113. exportedTypes[exported] = {
  21114. type: "TSTypeReference",
  21115. typeName: {
  21116. type: "Identifier",
  21117. name: local
  21118. },
  21119. _ownerScope: scope
  21120. };
  21121. } else if (types[local]) {
  21122. exportedTypes[exported] = types[local];
  21123. }
  21124. }
  21125. }
  21126. }
  21127. } else if (stmt.type === "ExportAllDeclaration") {
  21128. const sourceScope = importSourceToScope(
  21129. ctx,
  21130. stmt.source,
  21131. scope,
  21132. stmt.source.value
  21133. );
  21134. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  21135. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  21136. if (stmt.declaration.type !== "Identifier") {
  21137. recordType(stmt.declaration, types, declares, "default");
  21138. recordType(
  21139. stmt.declaration,
  21140. exportedTypes,
  21141. exportedDeclares,
  21142. "default"
  21143. );
  21144. } else if (types[stmt.declaration.name]) {
  21145. exportedTypes["default"] = types[stmt.declaration.name];
  21146. }
  21147. }
  21148. }
  21149. }
  21150. for (const key of Object.keys(types)) {
  21151. const node = types[key];
  21152. node._ownerScope = scope;
  21153. if (node._ns) node._ns._ownerScope = scope;
  21154. }
  21155. for (const key of Object.keys(declares)) {
  21156. declares[key]._ownerScope = scope;
  21157. }
  21158. }
  21159. function recordType(node, types, declares, overwriteId) {
  21160. switch (node.type) {
  21161. case "TSInterfaceDeclaration":
  21162. case "TSEnumDeclaration":
  21163. case "TSModuleDeclaration": {
  21164. if (node.type === "TSModuleDeclaration" && node.global) {
  21165. const body = node.body;
  21166. for (const s of body.body) {
  21167. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  21168. recordType(s.declaration, types, declares);
  21169. } else {
  21170. recordType(s, types, declares);
  21171. }
  21172. }
  21173. break;
  21174. }
  21175. const id = overwriteId || getId(node.id);
  21176. let existing = types[id];
  21177. if (existing) {
  21178. if (node.type === "TSModuleDeclaration") {
  21179. if (existing.type === "TSModuleDeclaration") {
  21180. mergeNamespaces(existing, node);
  21181. } else {
  21182. attachNamespace(existing, node);
  21183. }
  21184. break;
  21185. }
  21186. if (existing.type === "TSModuleDeclaration") {
  21187. types[id] = node;
  21188. attachNamespace(node, existing);
  21189. break;
  21190. }
  21191. if (existing.type !== node.type) {
  21192. break;
  21193. }
  21194. if (node.type === "TSInterfaceDeclaration") {
  21195. existing.body.body.push(...node.body.body);
  21196. } else {
  21197. existing.members.push(...node.members);
  21198. }
  21199. } else {
  21200. types[id] = node;
  21201. }
  21202. break;
  21203. }
  21204. case "ClassDeclaration":
  21205. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  21206. break;
  21207. case "TSTypeAliasDeclaration":
  21208. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  21209. break;
  21210. case "TSDeclareFunction":
  21211. if (node.id) declares[node.id.name] = node;
  21212. break;
  21213. case "VariableDeclaration": {
  21214. if (node.declare) {
  21215. for (const decl of node.declarations) {
  21216. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  21217. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  21218. }
  21219. }
  21220. }
  21221. break;
  21222. }
  21223. }
  21224. }
  21225. function mergeNamespaces(to, from) {
  21226. const toBody = to.body;
  21227. const fromBody = from.body;
  21228. if (toBody.type === "TSModuleDeclaration") {
  21229. if (fromBody.type === "TSModuleDeclaration") {
  21230. mergeNamespaces(toBody, fromBody);
  21231. } else {
  21232. fromBody.body.push({
  21233. type: "ExportNamedDeclaration",
  21234. declaration: toBody,
  21235. exportKind: "type",
  21236. specifiers: []
  21237. });
  21238. }
  21239. } else if (fromBody.type === "TSModuleDeclaration") {
  21240. toBody.body.push({
  21241. type: "ExportNamedDeclaration",
  21242. declaration: fromBody,
  21243. exportKind: "type",
  21244. specifiers: []
  21245. });
  21246. } else {
  21247. toBody.body.push(...fromBody.body);
  21248. }
  21249. }
  21250. function attachNamespace(to, ns) {
  21251. if (!to._ns) {
  21252. to._ns = ns;
  21253. } else {
  21254. mergeNamespaces(to._ns, ns);
  21255. }
  21256. }
  21257. function recordImports(body) {
  21258. const imports = /* @__PURE__ */ Object.create(null);
  21259. for (const s of body) {
  21260. recordImport(s, imports);
  21261. }
  21262. return imports;
  21263. }
  21264. function recordImport(node, imports) {
  21265. if (node.type !== "ImportDeclaration") {
  21266. return;
  21267. }
  21268. for (const s of node.specifiers) {
  21269. imports[s.local.name] = {
  21270. imported: getImportedName(s),
  21271. source: node.source.value
  21272. };
  21273. }
  21274. }
  21275. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  21276. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  21277. return [UNKNOWN_TYPE];
  21278. }
  21279. const prevSilent = ctx.silentOnExtendsFailure;
  21280. ctx.silentOnExtendsFailure = true;
  21281. try {
  21282. switch (node.type) {
  21283. case "TSStringKeyword":
  21284. return ["String"];
  21285. case "TSNumberKeyword":
  21286. return ["Number"];
  21287. case "TSBooleanKeyword":
  21288. return ["Boolean"];
  21289. case "TSObjectKeyword":
  21290. return ["Object"];
  21291. case "TSNullKeyword":
  21292. return ["null"];
  21293. case "TSTypeLiteral":
  21294. case "TSInterfaceDeclaration": {
  21295. const types = /* @__PURE__ */ new Set();
  21296. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  21297. for (const m of members) {
  21298. if (isKeyOf) {
  21299. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  21300. types.add("Number");
  21301. } else if (m.type === "TSIndexSignature") {
  21302. const annotation = m.parameters[0].typeAnnotation;
  21303. if (annotation && annotation.type !== "Noop") {
  21304. const type = inferRuntimeType(
  21305. ctx,
  21306. annotation.typeAnnotation,
  21307. scope
  21308. )[0];
  21309. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  21310. types.add(type);
  21311. }
  21312. } else {
  21313. types.add("String");
  21314. }
  21315. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  21316. types.add("Function");
  21317. } else {
  21318. types.add("Object");
  21319. }
  21320. }
  21321. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  21322. }
  21323. case "TSPropertySignature":
  21324. if (node.typeAnnotation) {
  21325. return inferRuntimeType(
  21326. ctx,
  21327. node.typeAnnotation.typeAnnotation,
  21328. scope
  21329. );
  21330. }
  21331. break;
  21332. case "TSMethodSignature":
  21333. case "TSFunctionType":
  21334. return ["Function"];
  21335. case "TSArrayType":
  21336. case "TSTupleType":
  21337. return ["Array"];
  21338. case "TSLiteralType":
  21339. switch (node.literal.type) {
  21340. case "StringLiteral":
  21341. return ["String"];
  21342. case "BooleanLiteral":
  21343. return ["Boolean"];
  21344. case "NumericLiteral":
  21345. case "BigIntLiteral":
  21346. return ["Number"];
  21347. default:
  21348. return [UNKNOWN_TYPE];
  21349. }
  21350. case "TSTypeReference": {
  21351. const resolved = resolveTypeReference(ctx, node, scope);
  21352. if (resolved) {
  21353. if (resolved.type === "TSTypeAliasDeclaration") {
  21354. if (resolved.typeAnnotation.type === "TSFunctionType") {
  21355. return ["Function"];
  21356. }
  21357. if (node.typeParameters) {
  21358. const typeParams = /* @__PURE__ */ Object.create(null);
  21359. if (resolved.typeParameters) {
  21360. resolved.typeParameters.params.forEach((p, i) => {
  21361. typeParams[p.name] = node.typeParameters.params[i];
  21362. });
  21363. }
  21364. return inferRuntimeType(
  21365. ctx,
  21366. resolved.typeAnnotation,
  21367. resolved._ownerScope,
  21368. isKeyOf,
  21369. typeParams
  21370. );
  21371. }
  21372. }
  21373. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  21374. }
  21375. if (node.typeName.type === "Identifier") {
  21376. if (typeParameters && typeParameters[node.typeName.name]) {
  21377. return inferRuntimeType(
  21378. ctx,
  21379. typeParameters[node.typeName.name],
  21380. scope,
  21381. isKeyOf,
  21382. typeParameters
  21383. );
  21384. }
  21385. if (isKeyOf) {
  21386. switch (node.typeName.name) {
  21387. case "String":
  21388. case "Array":
  21389. case "ArrayLike":
  21390. case "Parameters":
  21391. case "ConstructorParameters":
  21392. case "ReadonlyArray":
  21393. return ["String", "Number"];
  21394. // TS built-in utility types
  21395. case "Record":
  21396. case "Partial":
  21397. case "Required":
  21398. case "Readonly":
  21399. if (node.typeParameters && node.typeParameters.params[0]) {
  21400. return inferRuntimeType(
  21401. ctx,
  21402. node.typeParameters.params[0],
  21403. scope,
  21404. true
  21405. );
  21406. }
  21407. break;
  21408. case "Pick":
  21409. case "Extract":
  21410. if (node.typeParameters && node.typeParameters.params[1]) {
  21411. return inferRuntimeType(
  21412. ctx,
  21413. node.typeParameters.params[1],
  21414. scope
  21415. );
  21416. }
  21417. break;
  21418. case "Function":
  21419. case "Object":
  21420. case "Set":
  21421. case "Map":
  21422. case "WeakSet":
  21423. case "WeakMap":
  21424. case "Date":
  21425. case "Promise":
  21426. case "Error":
  21427. case "Uppercase":
  21428. case "Lowercase":
  21429. case "Capitalize":
  21430. case "Uncapitalize":
  21431. case "ReadonlyMap":
  21432. case "ReadonlySet":
  21433. return ["String"];
  21434. }
  21435. } else {
  21436. switch (node.typeName.name) {
  21437. case "Array":
  21438. case "Function":
  21439. case "Object":
  21440. case "Set":
  21441. case "Map":
  21442. case "WeakSet":
  21443. case "WeakMap":
  21444. case "Date":
  21445. case "Promise":
  21446. case "Error":
  21447. return [node.typeName.name];
  21448. // TS built-in utility types
  21449. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  21450. case "Partial":
  21451. case "Required":
  21452. case "Readonly":
  21453. case "Record":
  21454. case "Pick":
  21455. case "Omit":
  21456. case "InstanceType":
  21457. return ["Object"];
  21458. case "Uppercase":
  21459. case "Lowercase":
  21460. case "Capitalize":
  21461. case "Uncapitalize":
  21462. return ["String"];
  21463. case "Parameters":
  21464. case "ConstructorParameters":
  21465. case "ReadonlyArray":
  21466. return ["Array"];
  21467. case "ReadonlyMap":
  21468. return ["Map"];
  21469. case "ReadonlySet":
  21470. return ["Set"];
  21471. case "NonNullable":
  21472. if (node.typeParameters && node.typeParameters.params[0]) {
  21473. return inferRuntimeType(
  21474. ctx,
  21475. node.typeParameters.params[0],
  21476. scope
  21477. ).filter((t) => t !== "null");
  21478. }
  21479. break;
  21480. case "Extract":
  21481. if (node.typeParameters && node.typeParameters.params[1]) {
  21482. return inferRuntimeType(
  21483. ctx,
  21484. node.typeParameters.params[1],
  21485. scope
  21486. );
  21487. }
  21488. break;
  21489. case "Exclude":
  21490. case "OmitThisParameter":
  21491. if (node.typeParameters && node.typeParameters.params[0]) {
  21492. return inferRuntimeType(
  21493. ctx,
  21494. node.typeParameters.params[0],
  21495. scope
  21496. );
  21497. }
  21498. break;
  21499. }
  21500. }
  21501. }
  21502. break;
  21503. }
  21504. case "TSParenthesizedType":
  21505. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  21506. case "TSUnionType":
  21507. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  21508. case "TSIntersectionType": {
  21509. return flattenTypes(
  21510. ctx,
  21511. node.types,
  21512. scope,
  21513. isKeyOf,
  21514. typeParameters
  21515. ).filter((t) => t !== UNKNOWN_TYPE);
  21516. }
  21517. case "TSMappedType": {
  21518. const { typeAnnotation, typeParameter } = node;
  21519. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  21520. const constraint = typeParameter.constraint;
  21521. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  21522. const typeName = constraint.typeAnnotation.typeName.name;
  21523. const index = typeAnnotation.indexType;
  21524. const obj = typeAnnotation.objectType;
  21525. 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) {
  21526. const targetType = typeParameters[typeName];
  21527. if (targetType) {
  21528. return inferRuntimeType(ctx, targetType, scope);
  21529. }
  21530. }
  21531. }
  21532. }
  21533. return [UNKNOWN_TYPE];
  21534. }
  21535. case "TSEnumDeclaration":
  21536. return inferEnumType(node);
  21537. case "TSSymbolKeyword":
  21538. return ["Symbol"];
  21539. case "TSIndexedAccessType": {
  21540. const types = resolveIndexType(ctx, node, scope);
  21541. return flattenTypes(ctx, types, scope, isKeyOf);
  21542. }
  21543. case "ClassDeclaration":
  21544. return ["Object"];
  21545. case "TSImportType": {
  21546. const sourceScope = importSourceToScope(
  21547. ctx,
  21548. node.argument,
  21549. scope,
  21550. node.argument.value
  21551. );
  21552. const resolved = resolveTypeReference(ctx, node, sourceScope);
  21553. if (resolved) {
  21554. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  21555. }
  21556. break;
  21557. }
  21558. case "TSTypeQuery": {
  21559. const id = node.exprName;
  21560. if (id.type === "Identifier") {
  21561. const matched = scope.declares[id.name];
  21562. if (matched) {
  21563. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  21564. }
  21565. }
  21566. break;
  21567. }
  21568. // e.g. readonly
  21569. case "TSTypeOperator": {
  21570. return inferRuntimeType(
  21571. ctx,
  21572. node.typeAnnotation,
  21573. scope,
  21574. node.operator === "keyof"
  21575. );
  21576. }
  21577. case "TSAnyKeyword": {
  21578. if (isKeyOf) {
  21579. return ["String", "Number", "Symbol"];
  21580. }
  21581. break;
  21582. }
  21583. }
  21584. } catch (e) {
  21585. } finally {
  21586. ctx.silentOnExtendsFailure = prevSilent;
  21587. }
  21588. return [UNKNOWN_TYPE];
  21589. }
  21590. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  21591. if (types.length === 1) {
  21592. return inferRuntimeType(
  21593. ctx,
  21594. types[0],
  21595. types[0]._ownerScope || scope,
  21596. isKeyOf,
  21597. typeParameters
  21598. );
  21599. }
  21600. return [
  21601. ...new Set(
  21602. [].concat(
  21603. ...types.map(
  21604. (t) => inferRuntimeType(
  21605. ctx,
  21606. t,
  21607. t._ownerScope || scope,
  21608. isKeyOf,
  21609. typeParameters
  21610. )
  21611. )
  21612. )
  21613. )
  21614. ];
  21615. }
  21616. function inferEnumType(node) {
  21617. const types = /* @__PURE__ */ new Set();
  21618. for (const m of node.members) {
  21619. if (m.initializer) {
  21620. switch (m.initializer.type) {
  21621. case "StringLiteral":
  21622. types.add("String");
  21623. break;
  21624. case "NumericLiteral":
  21625. types.add("Number");
  21626. break;
  21627. }
  21628. }
  21629. }
  21630. return types.size ? [...types] : ["Number"];
  21631. }
  21632. function resolveExtractPropTypes({ props }, scope) {
  21633. const res = { props: {} };
  21634. for (const key in props) {
  21635. const raw = props[key];
  21636. res.props[key] = reverseInferType(
  21637. raw.key,
  21638. raw.typeAnnotation.typeAnnotation,
  21639. scope
  21640. );
  21641. }
  21642. return res;
  21643. }
  21644. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  21645. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  21646. const typeType = findStaticPropertyType(node, "type");
  21647. if (typeType) {
  21648. const requiredType = findStaticPropertyType(node, "required");
  21649. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  21650. return reverseInferType(key, typeType, scope, optional2, false);
  21651. }
  21652. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  21653. if (node.typeName.name.endsWith("Constructor")) {
  21654. return createProperty(
  21655. key,
  21656. ctorToType(node.typeName.name),
  21657. scope,
  21658. optional
  21659. );
  21660. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  21661. return createProperty(key, node.typeParameters.params[0], scope, optional);
  21662. }
  21663. }
  21664. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  21665. for (const t of node.typeParameters.params) {
  21666. const inferred = reverseInferType(key, t, scope, optional);
  21667. if (inferred) return inferred;
  21668. }
  21669. }
  21670. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  21671. }
  21672. function ctorToType(ctorType) {
  21673. const ctor = ctorType.slice(0, -11);
  21674. switch (ctor) {
  21675. case "String":
  21676. case "Number":
  21677. case "Boolean":
  21678. return { type: `TS${ctor}Keyword` };
  21679. case "Array":
  21680. case "Function":
  21681. case "Object":
  21682. case "Set":
  21683. case "Map":
  21684. case "WeakSet":
  21685. case "WeakMap":
  21686. case "Date":
  21687. case "Promise":
  21688. return {
  21689. type: "TSTypeReference",
  21690. typeName: { type: "Identifier", name: ctor }
  21691. };
  21692. }
  21693. return { type: `TSNullKeyword` };
  21694. }
  21695. function findStaticPropertyType(node, key) {
  21696. const prop = node.members.find(
  21697. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  21698. );
  21699. return prop && prop.typeAnnotation.typeAnnotation;
  21700. }
  21701. function resolveReturnType(ctx, arg, scope) {
  21702. var _a;
  21703. let resolved = arg;
  21704. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  21705. resolved = resolveTypeReference(ctx, arg, scope);
  21706. }
  21707. if (!resolved) return;
  21708. if (resolved.type === "TSFunctionType") {
  21709. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  21710. }
  21711. if (resolved.type === "TSDeclareFunction") {
  21712. return resolved.returnType;
  21713. }
  21714. }
  21715. function resolveUnionType(ctx, node, scope) {
  21716. if (node.type === "TSTypeReference") {
  21717. const resolved = resolveTypeReference(ctx, node, scope);
  21718. if (resolved) node = resolved;
  21719. }
  21720. let types;
  21721. if (node.type === "TSUnionType") {
  21722. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  21723. } else {
  21724. types = [node];
  21725. }
  21726. return types;
  21727. }
  21728. const DEFINE_MODEL = "defineModel";
  21729. function processDefineModel(ctx, node, declId) {
  21730. if (!isCallOf(node, DEFINE_MODEL)) {
  21731. return false;
  21732. }
  21733. ctx.hasDefineModelCall = true;
  21734. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  21735. let modelName;
  21736. let options;
  21737. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  21738. const hasName = arg0 && arg0.type === "StringLiteral";
  21739. if (hasName) {
  21740. modelName = arg0.value;
  21741. options = node.arguments[1];
  21742. } else {
  21743. modelName = "modelValue";
  21744. options = arg0;
  21745. }
  21746. if (ctx.modelDecls[modelName]) {
  21747. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  21748. }
  21749. let optionsString = options && ctx.getString(options);
  21750. let optionsRemoved = !options;
  21751. const runtimeOptionNodes = [];
  21752. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  21753. let removed = 0;
  21754. for (let i = options.properties.length - 1; i >= 0; i--) {
  21755. const p = options.properties[i];
  21756. const next = options.properties[i + 1];
  21757. const start = p.start;
  21758. const end = next ? next.start : options.end - 1;
  21759. 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"))) {
  21760. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  21761. } else {
  21762. removed++;
  21763. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  21764. runtimeOptionNodes.push(p);
  21765. }
  21766. }
  21767. if (removed === options.properties.length) {
  21768. optionsRemoved = true;
  21769. ctx.s.remove(
  21770. ctx.startOffset + (hasName ? arg0.end : options.start),
  21771. ctx.startOffset + options.end
  21772. );
  21773. }
  21774. }
  21775. ctx.modelDecls[modelName] = {
  21776. type,
  21777. options: optionsString,
  21778. runtimeOptionNodes,
  21779. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  21780. };
  21781. ctx.bindingMetadata[modelName] = "props";
  21782. ctx.s.overwrite(
  21783. ctx.startOffset + node.callee.start,
  21784. ctx.startOffset + node.callee.end,
  21785. ctx.helper("useModel")
  21786. );
  21787. ctx.s.appendLeft(
  21788. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  21789. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  21790. );
  21791. return true;
  21792. }
  21793. function genModelProps(ctx) {
  21794. if (!ctx.hasDefineModelCall) return;
  21795. const isProd = !!ctx.options.isProd;
  21796. let modelPropsDecl = "";
  21797. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  21798. ctx.modelDecls
  21799. )) {
  21800. let skipCheck = false;
  21801. let codegenOptions = ``;
  21802. let runtimeTypes = type && inferRuntimeType(ctx, type);
  21803. if (runtimeTypes) {
  21804. const hasBoolean = runtimeTypes.includes("Boolean");
  21805. const hasFunction = runtimeTypes.includes("Function");
  21806. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  21807. if (hasUnknownType) {
  21808. if (hasBoolean || hasFunction) {
  21809. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  21810. skipCheck = true;
  21811. } else {
  21812. runtimeTypes = ["null"];
  21813. }
  21814. }
  21815. if (!isProd) {
  21816. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  21817. } else if (hasBoolean || runtimeOptions && hasFunction) {
  21818. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  21819. } else ;
  21820. }
  21821. let decl;
  21822. if (codegenOptions && runtimeOptions) {
  21823. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  21824. } else if (codegenOptions) {
  21825. decl = `{ ${codegenOptions} }`;
  21826. } else if (runtimeOptions) {
  21827. decl = runtimeOptions;
  21828. } else {
  21829. decl = `{}`;
  21830. }
  21831. modelPropsDecl += `
  21832. ${JSON.stringify(name)}: ${decl},`;
  21833. const modifierPropName = JSON.stringify(
  21834. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  21835. );
  21836. modelPropsDecl += `
  21837. ${modifierPropName}: {},`;
  21838. }
  21839. return `{${modelPropsDecl}
  21840. }`;
  21841. }
  21842. const DEFINE_PROPS = "defineProps";
  21843. const WITH_DEFAULTS = "withDefaults";
  21844. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  21845. if (!isCallOf(node, DEFINE_PROPS)) {
  21846. return processWithDefaults(ctx, node, declId);
  21847. }
  21848. if (ctx.hasDefinePropsCall) {
  21849. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  21850. }
  21851. ctx.hasDefinePropsCall = true;
  21852. ctx.propsRuntimeDecl = node.arguments[0];
  21853. if (ctx.propsRuntimeDecl) {
  21854. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  21855. if (!(key in ctx.bindingMetadata)) {
  21856. ctx.bindingMetadata[key] = "props";
  21857. }
  21858. }
  21859. }
  21860. if (node.typeParameters) {
  21861. if (ctx.propsRuntimeDecl) {
  21862. ctx.error(
  21863. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  21864. node
  21865. );
  21866. }
  21867. ctx.propsTypeDecl = node.typeParameters.params[0];
  21868. }
  21869. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  21870. processPropsDestructure(ctx, declId);
  21871. }
  21872. ctx.propsCall = node;
  21873. ctx.propsDecl = declId;
  21874. return true;
  21875. }
  21876. function processWithDefaults(ctx, node, declId) {
  21877. if (!isCallOf(node, WITH_DEFAULTS)) {
  21878. return false;
  21879. }
  21880. if (!processDefineProps(
  21881. ctx,
  21882. node.arguments[0],
  21883. declId,
  21884. true
  21885. )) {
  21886. ctx.error(
  21887. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  21888. node.arguments[0] || node
  21889. );
  21890. }
  21891. if (ctx.propsRuntimeDecl) {
  21892. ctx.error(
  21893. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  21894. node
  21895. );
  21896. }
  21897. if (declId && declId.type === "ObjectPattern") {
  21898. ctx.warn(
  21899. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  21900. Reactive destructure will be disabled when using withDefaults().
  21901. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  21902. node.callee
  21903. );
  21904. }
  21905. ctx.propsRuntimeDefaults = node.arguments[1];
  21906. if (!ctx.propsRuntimeDefaults) {
  21907. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  21908. }
  21909. ctx.propsCall = node;
  21910. return true;
  21911. }
  21912. function genRuntimeProps(ctx) {
  21913. let propsDecls;
  21914. if (ctx.propsRuntimeDecl) {
  21915. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  21916. if (ctx.propsDestructureDecl) {
  21917. const defaults = [];
  21918. for (const key in ctx.propsDestructuredBindings) {
  21919. const d = genDestructuredDefaultValue(ctx, key);
  21920. const finalKey = getEscapedPropName(key);
  21921. if (d)
  21922. defaults.push(
  21923. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  21924. );
  21925. }
  21926. if (defaults.length) {
  21927. propsDecls = `/*@__PURE__*/${ctx.helper(
  21928. `mergeDefaults`
  21929. )}(${propsDecls}, {
  21930. ${defaults.join(",\n ")}
  21931. })`;
  21932. }
  21933. }
  21934. } else if (ctx.propsTypeDecl) {
  21935. propsDecls = extractRuntimeProps(ctx);
  21936. }
  21937. const modelsDecls = genModelProps(ctx);
  21938. if (propsDecls && modelsDecls) {
  21939. return `/*@__PURE__*/${ctx.helper(
  21940. "mergeModels"
  21941. )}(${propsDecls}, ${modelsDecls})`;
  21942. } else {
  21943. return modelsDecls || propsDecls;
  21944. }
  21945. }
  21946. function extractRuntimeProps(ctx) {
  21947. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  21948. if (!props.length) {
  21949. return;
  21950. }
  21951. const propStrings = [];
  21952. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  21953. for (const prop of props) {
  21954. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  21955. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  21956. ctx.bindingMetadata[prop.key] = "props";
  21957. }
  21958. }
  21959. let propsDecls = `{
  21960. ${propStrings.join(",\n ")}
  21961. }`;
  21962. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  21963. propsDecls = `/*@__PURE__*/${ctx.helper(
  21964. "mergeDefaults"
  21965. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  21966. }
  21967. return propsDecls;
  21968. }
  21969. function resolveRuntimePropsFromType(ctx, node) {
  21970. const props = [];
  21971. const elements = resolveTypeElements(ctx, node);
  21972. for (const key in elements.props) {
  21973. const e = elements.props[key];
  21974. let type = inferRuntimeType(ctx, e);
  21975. let skipCheck = false;
  21976. if (type.includes(UNKNOWN_TYPE)) {
  21977. if (type.includes("Boolean") || type.includes("Function")) {
  21978. type = type.filter((t) => t !== UNKNOWN_TYPE);
  21979. skipCheck = true;
  21980. } else {
  21981. type = ["null"];
  21982. }
  21983. }
  21984. props.push({
  21985. key,
  21986. required: !e.optional,
  21987. type: type || [`null`],
  21988. skipCheck
  21989. });
  21990. }
  21991. return props;
  21992. }
  21993. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  21994. let defaultString;
  21995. const destructured = genDestructuredDefaultValue(ctx, key, type);
  21996. if (destructured) {
  21997. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  21998. } else if (hasStaticDefaults) {
  21999. const prop = ctx.propsRuntimeDefaults.properties.find(
  22000. (node) => {
  22001. if (node.type === "SpreadElement") return false;
  22002. return resolveObjectKey(node.key, node.computed) === key;
  22003. }
  22004. );
  22005. if (prop) {
  22006. if (prop.type === "ObjectProperty") {
  22007. defaultString = `default: ${ctx.getString(prop.value)}`;
  22008. } else {
  22009. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  22010. }
  22011. }
  22012. }
  22013. const finalKey = getEscapedPropName(key);
  22014. if (!ctx.options.isProd) {
  22015. return `${finalKey}: { ${concatStrings([
  22016. `type: ${toRuntimeTypeString(type)}`,
  22017. `required: ${required}`,
  22018. skipCheck && "skipCheck: true",
  22019. defaultString
  22020. ])} }`;
  22021. } else if (type.some(
  22022. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  22023. )) {
  22024. return `${finalKey}: { ${concatStrings([
  22025. `type: ${toRuntimeTypeString(type)}`,
  22026. defaultString
  22027. ])} }`;
  22028. } else {
  22029. if (ctx.isCE) {
  22030. if (defaultString) {
  22031. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  22032. type
  22033. )} }`}`;
  22034. } else {
  22035. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  22036. }
  22037. }
  22038. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  22039. }
  22040. }
  22041. function hasStaticWithDefaults(ctx) {
  22042. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  22043. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  22044. ));
  22045. }
  22046. function genDestructuredDefaultValue(ctx, key, inferredType) {
  22047. const destructured = ctx.propsDestructuredBindings[key];
  22048. const defaultVal = destructured && destructured.default;
  22049. if (defaultVal) {
  22050. const value = ctx.getString(defaultVal);
  22051. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  22052. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  22053. const valueType = inferValueType(unwrapped);
  22054. if (valueType && !inferredType.includes(valueType)) {
  22055. ctx.error(
  22056. `Default value of prop "${key}" does not match declared type.`,
  22057. unwrapped
  22058. );
  22059. }
  22060. }
  22061. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  22062. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  22063. return {
  22064. valueString: needFactoryWrap ? `() => (${value})` : value,
  22065. needSkipFactory
  22066. };
  22067. }
  22068. }
  22069. function inferValueType(node) {
  22070. switch (node.type) {
  22071. case "StringLiteral":
  22072. return "String";
  22073. case "NumericLiteral":
  22074. return "Number";
  22075. case "BooleanLiteral":
  22076. return "Boolean";
  22077. case "ObjectExpression":
  22078. return "Object";
  22079. case "ArrayExpression":
  22080. return "Array";
  22081. case "FunctionExpression":
  22082. case "ArrowFunctionExpression":
  22083. return "Function";
  22084. }
  22085. }
  22086. function processPropsDestructure(ctx, declId) {
  22087. if (ctx.options.propsDestructure === "error") {
  22088. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  22089. } else if (ctx.options.propsDestructure === false) {
  22090. return;
  22091. }
  22092. ctx.propsDestructureDecl = declId;
  22093. const registerBinding = (key, local, defaultValue) => {
  22094. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  22095. if (local !== key) {
  22096. ctx.bindingMetadata[local] = "props-aliased";
  22097. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  22098. }
  22099. };
  22100. for (const prop of declId.properties) {
  22101. if (prop.type === "ObjectProperty") {
  22102. const propKey = resolveObjectKey(prop.key, prop.computed);
  22103. if (!propKey) {
  22104. ctx.error(
  22105. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  22106. prop.key
  22107. );
  22108. }
  22109. if (prop.value.type === "AssignmentPattern") {
  22110. const { left, right } = prop.value;
  22111. if (left.type !== "Identifier") {
  22112. ctx.error(
  22113. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22114. left
  22115. );
  22116. }
  22117. registerBinding(propKey, left.name, right);
  22118. } else if (prop.value.type === "Identifier") {
  22119. registerBinding(propKey, prop.value.name);
  22120. } else {
  22121. ctx.error(
  22122. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22123. prop.value
  22124. );
  22125. }
  22126. } else {
  22127. ctx.propsDestructureRestId = prop.argument.name;
  22128. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  22129. }
  22130. }
  22131. }
  22132. function transformDestructuredProps(ctx, vueImportAliases) {
  22133. if (ctx.options.propsDestructure === false) {
  22134. return;
  22135. }
  22136. const rootScope = /* @__PURE__ */ Object.create(null);
  22137. const scopeStack = [rootScope];
  22138. let currentScope = rootScope;
  22139. const excludedIds = /* @__PURE__ */ new WeakSet();
  22140. const parentStack = [];
  22141. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  22142. for (const key in ctx.propsDestructuredBindings) {
  22143. const { local } = ctx.propsDestructuredBindings[key];
  22144. rootScope[local] = true;
  22145. propsLocalToPublicMap[local] = key;
  22146. }
  22147. function pushScope() {
  22148. scopeStack.push(currentScope = Object.create(currentScope));
  22149. }
  22150. function popScope() {
  22151. scopeStack.pop();
  22152. currentScope = scopeStack[scopeStack.length - 1] || null;
  22153. }
  22154. function registerLocalBinding(id) {
  22155. excludedIds.add(id);
  22156. if (currentScope) {
  22157. currentScope[id.name] = false;
  22158. } else {
  22159. ctx.error(
  22160. "registerBinding called without active scope, something is wrong.",
  22161. id
  22162. );
  22163. }
  22164. }
  22165. function walkScope(node, isRoot = false) {
  22166. for (const stmt of node.body) {
  22167. if (stmt.type === "VariableDeclaration") {
  22168. walkVariableDeclaration(stmt, isRoot);
  22169. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  22170. if (stmt.declare || !stmt.id) continue;
  22171. registerLocalBinding(stmt.id);
  22172. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  22173. walkVariableDeclaration(stmt.declaration, isRoot);
  22174. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  22175. walkVariableDeclaration(stmt.body, isRoot);
  22176. }
  22177. }
  22178. }
  22179. function walkVariableDeclaration(stmt, isRoot = false) {
  22180. if (stmt.declare) {
  22181. return;
  22182. }
  22183. for (const decl of stmt.declarations) {
  22184. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  22185. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  22186. if (isDefineProps) {
  22187. excludedIds.add(id);
  22188. } else {
  22189. registerLocalBinding(id);
  22190. }
  22191. }
  22192. }
  22193. }
  22194. function rewriteId(id, parent, parentStack2) {
  22195. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  22196. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  22197. }
  22198. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  22199. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  22200. ctx.s.appendLeft(
  22201. id.end + ctx.startOffset,
  22202. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  22203. );
  22204. }
  22205. } else {
  22206. ctx.s.overwrite(
  22207. id.start + ctx.startOffset,
  22208. id.end + ctx.startOffset,
  22209. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  22210. );
  22211. }
  22212. }
  22213. function checkUsage(node, method, alias = method) {
  22214. if (isCallOf(node, alias)) {
  22215. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22216. if (arg.type === "Identifier" && currentScope[arg.name]) {
  22217. ctx.error(
  22218. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  22219. arg
  22220. );
  22221. }
  22222. }
  22223. }
  22224. const ast = ctx.scriptSetupAst;
  22225. walkScope(ast, true);
  22226. estreeWalker.walk(ast, {
  22227. enter(node, parent) {
  22228. parent && parentStack.push(parent);
  22229. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22230. return this.skip();
  22231. }
  22232. checkUsage(node, "watch", vueImportAliases.watch);
  22233. checkUsage(node, "toRef", vueImportAliases.toRef);
  22234. if (CompilerDOM.isFunctionType(node)) {
  22235. pushScope();
  22236. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  22237. if (node.body.type === "BlockStatement") {
  22238. walkScope(node.body);
  22239. }
  22240. return;
  22241. }
  22242. if (node.type === "CatchClause") {
  22243. pushScope();
  22244. if (node.param && node.param.type === "Identifier") {
  22245. registerLocalBinding(node.param);
  22246. }
  22247. walkScope(node.body);
  22248. return;
  22249. }
  22250. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22251. pushScope();
  22252. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  22253. if (varDecl && varDecl.type === "VariableDeclaration") {
  22254. walkVariableDeclaration(varDecl);
  22255. }
  22256. if (node.body.type === "BlockStatement") {
  22257. walkScope(node.body);
  22258. }
  22259. return;
  22260. }
  22261. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22262. pushScope();
  22263. walkScope(node);
  22264. return;
  22265. }
  22266. if (node.type === "Identifier") {
  22267. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  22268. if (currentScope[node.name]) {
  22269. rewriteId(node, parent, parentStack);
  22270. }
  22271. }
  22272. }
  22273. },
  22274. leave(node, parent) {
  22275. parent && parentStack.pop();
  22276. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node) || node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22277. popScope();
  22278. }
  22279. }
  22280. });
  22281. }
  22282. const DEFINE_EMITS = "defineEmits";
  22283. function processDefineEmits(ctx, node, declId) {
  22284. if (!isCallOf(node, DEFINE_EMITS)) {
  22285. return false;
  22286. }
  22287. if (ctx.hasDefineEmitCall) {
  22288. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  22289. }
  22290. ctx.hasDefineEmitCall = true;
  22291. ctx.emitsRuntimeDecl = node.arguments[0];
  22292. if (node.typeParameters) {
  22293. if (ctx.emitsRuntimeDecl) {
  22294. ctx.error(
  22295. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22296. node
  22297. );
  22298. }
  22299. ctx.emitsTypeDecl = node.typeParameters.params[0];
  22300. }
  22301. ctx.emitDecl = declId;
  22302. return true;
  22303. }
  22304. function genRuntimeEmits(ctx) {
  22305. let emitsDecl = "";
  22306. if (ctx.emitsRuntimeDecl) {
  22307. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  22308. } else if (ctx.emitsTypeDecl) {
  22309. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  22310. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  22311. }
  22312. if (ctx.hasDefineModelCall) {
  22313. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  22314. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  22315. "mergeModels"
  22316. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  22317. }
  22318. return emitsDecl;
  22319. }
  22320. function extractRuntimeEmits(ctx) {
  22321. const emits = /* @__PURE__ */ new Set();
  22322. const node = ctx.emitsTypeDecl;
  22323. if (node.type === "TSFunctionType") {
  22324. extractEventNames(ctx, node.parameters[0], emits);
  22325. return emits;
  22326. }
  22327. const { props, calls } = resolveTypeElements(ctx, node);
  22328. let hasProperty = false;
  22329. for (const key in props) {
  22330. emits.add(key);
  22331. hasProperty = true;
  22332. }
  22333. if (calls) {
  22334. if (hasProperty) {
  22335. ctx.error(
  22336. `defineEmits() type cannot mixed call signature and property syntax.`,
  22337. node
  22338. );
  22339. }
  22340. for (const call of calls) {
  22341. extractEventNames(ctx, call.parameters[0], emits);
  22342. }
  22343. }
  22344. return emits;
  22345. }
  22346. function extractEventNames(ctx, eventName, emits) {
  22347. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  22348. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  22349. for (const type of types) {
  22350. if (type.type === "TSLiteralType") {
  22351. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  22352. emits.add(String(type.literal.value));
  22353. }
  22354. }
  22355. }
  22356. }
  22357. }
  22358. const DEFINE_EXPOSE = "defineExpose";
  22359. function processDefineExpose(ctx, node) {
  22360. if (isCallOf(node, DEFINE_EXPOSE)) {
  22361. if (ctx.hasDefineExposeCall) {
  22362. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  22363. }
  22364. ctx.hasDefineExposeCall = true;
  22365. return true;
  22366. }
  22367. return false;
  22368. }
  22369. const DEFINE_SLOTS = "defineSlots";
  22370. function processDefineSlots(ctx, node, declId) {
  22371. if (!isCallOf(node, DEFINE_SLOTS)) {
  22372. return false;
  22373. }
  22374. if (ctx.hasDefineSlotsCall) {
  22375. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  22376. }
  22377. ctx.hasDefineSlotsCall = true;
  22378. if (node.arguments.length > 0) {
  22379. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  22380. }
  22381. if (declId) {
  22382. ctx.s.overwrite(
  22383. ctx.startOffset + node.start,
  22384. ctx.startOffset + node.end,
  22385. `${ctx.helper("useSlots")}()`
  22386. );
  22387. }
  22388. return true;
  22389. }
  22390. const DEFINE_OPTIONS = "defineOptions";
  22391. function processDefineOptions(ctx, node) {
  22392. if (!isCallOf(node, DEFINE_OPTIONS)) {
  22393. return false;
  22394. }
  22395. if (ctx.hasDefineOptionsCall) {
  22396. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  22397. }
  22398. if (node.typeParameters) {
  22399. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  22400. }
  22401. if (!node.arguments[0]) return true;
  22402. ctx.hasDefineOptionsCall = true;
  22403. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22404. let propsOption = void 0;
  22405. let emitsOption = void 0;
  22406. let exposeOption = void 0;
  22407. let slotsOption = void 0;
  22408. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  22409. for (const prop of ctx.optionsRuntimeDecl.properties) {
  22410. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  22411. switch (prop.key.name) {
  22412. case "props":
  22413. propsOption = prop;
  22414. break;
  22415. case "emits":
  22416. emitsOption = prop;
  22417. break;
  22418. case "expose":
  22419. exposeOption = prop;
  22420. break;
  22421. case "slots":
  22422. slotsOption = prop;
  22423. break;
  22424. }
  22425. }
  22426. }
  22427. }
  22428. if (propsOption) {
  22429. ctx.error(
  22430. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  22431. propsOption
  22432. );
  22433. }
  22434. if (emitsOption) {
  22435. ctx.error(
  22436. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  22437. emitsOption
  22438. );
  22439. }
  22440. if (exposeOption) {
  22441. ctx.error(
  22442. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  22443. exposeOption
  22444. );
  22445. }
  22446. if (slotsOption) {
  22447. ctx.error(
  22448. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  22449. slotsOption
  22450. );
  22451. }
  22452. return true;
  22453. }
  22454. function processAwait(ctx, node, needSemi, isStatement) {
  22455. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  22456. const startOffset = ctx.startOffset;
  22457. const argumentStr = ctx.descriptor.source.slice(
  22458. argumentStart + startOffset,
  22459. node.argument.end + startOffset
  22460. );
  22461. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  22462. ctx.s.overwrite(
  22463. node.start + startOffset,
  22464. argumentStart + startOffset,
  22465. `${needSemi ? `;` : ``}(
  22466. ([__temp,__restore] = ${ctx.helper(
  22467. `withAsyncContext`
  22468. )}(${containsNestedAwait ? `async ` : ``}() => `
  22469. );
  22470. ctx.s.appendLeft(
  22471. node.end + startOffset,
  22472. `)),
  22473. ${isStatement ? `` : `__temp = `}await __temp,
  22474. __restore()${isStatement ? `` : `,
  22475. __temp`}
  22476. )`
  22477. );
  22478. }
  22479. const MACROS = [
  22480. DEFINE_PROPS,
  22481. DEFINE_EMITS,
  22482. DEFINE_EXPOSE,
  22483. DEFINE_OPTIONS,
  22484. DEFINE_SLOTS,
  22485. DEFINE_MODEL,
  22486. WITH_DEFAULTS
  22487. ];
  22488. function compileScript(sfc, options) {
  22489. var _a, _b, _c;
  22490. if (!options.id) {
  22491. warnOnce(
  22492. `compileScript now requires passing the \`id\` option.
  22493. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  22494. );
  22495. }
  22496. const { script, scriptSetup, source, filename } = sfc;
  22497. const hoistStatic = options.hoistStatic !== false && !script;
  22498. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  22499. const scriptLang = script && script.lang;
  22500. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  22501. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  22502. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  22503. throw new Error(
  22504. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  22505. );
  22506. }
  22507. if (!scriptSetup) {
  22508. if (!script) {
  22509. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  22510. }
  22511. if (script.lang && !isJSOrTS) {
  22512. return script;
  22513. }
  22514. const ctx2 = new ScriptCompileContext(sfc, options);
  22515. return processNormalScript(ctx2, scopeId);
  22516. }
  22517. if (scriptSetupLang && !isJSOrTS) {
  22518. return scriptSetup;
  22519. }
  22520. const ctx = new ScriptCompileContext(sfc, options);
  22521. const scriptBindings = /* @__PURE__ */ Object.create(null);
  22522. const setupBindings = /* @__PURE__ */ Object.create(null);
  22523. let defaultExport;
  22524. let hasAwait = false;
  22525. let hasInlinedSsrRenderFn = false;
  22526. const startOffset = ctx.startOffset;
  22527. const endOffset = ctx.endOffset;
  22528. const scriptStartOffset = script && script.loc.start.offset;
  22529. const scriptEndOffset = script && script.loc.end.offset;
  22530. function hoistNode(node) {
  22531. const start = node.start + startOffset;
  22532. let end = node.end + startOffset;
  22533. if (node.trailingComments && node.trailingComments.length > 0) {
  22534. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  22535. end = lastCommentNode.end + startOffset;
  22536. }
  22537. while (end <= source.length) {
  22538. if (!/\s/.test(source.charAt(end))) {
  22539. break;
  22540. }
  22541. end++;
  22542. }
  22543. ctx.s.move(start, end, 0);
  22544. }
  22545. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  22546. let isUsedInTemplate = needTemplateUsageCheck;
  22547. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  22548. isUsedInTemplate = isImportUsed(local, sfc);
  22549. }
  22550. ctx.userImports[local] = {
  22551. isType,
  22552. imported,
  22553. local,
  22554. source: source2,
  22555. isFromSetup,
  22556. isUsedInTemplate
  22557. };
  22558. }
  22559. function checkInvalidScopeReference(node, method) {
  22560. if (!node) return;
  22561. CompilerDOM.walkIdentifiers(node, (id) => {
  22562. const binding = setupBindings[id.name];
  22563. if (binding && binding !== "literal-const") {
  22564. ctx.error(
  22565. `\`${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.`,
  22566. id
  22567. );
  22568. }
  22569. });
  22570. }
  22571. const scriptAst = ctx.scriptAst;
  22572. const scriptSetupAst = ctx.scriptSetupAst;
  22573. if (scriptAst) {
  22574. for (const node of scriptAst.body) {
  22575. if (node.type === "ImportDeclaration") {
  22576. for (const specifier of node.specifiers) {
  22577. const imported = getImportedName(specifier);
  22578. registerUserImport(
  22579. node.source.value,
  22580. specifier.local.name,
  22581. imported,
  22582. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22583. false,
  22584. !options.inlineTemplate
  22585. );
  22586. }
  22587. }
  22588. }
  22589. }
  22590. for (const node of scriptSetupAst.body) {
  22591. if (node.type === "ImportDeclaration") {
  22592. hoistNode(node);
  22593. let removed = 0;
  22594. const removeSpecifier = (i) => {
  22595. const removeLeft = i > removed;
  22596. removed++;
  22597. const current = node.specifiers[i];
  22598. const next = node.specifiers[i + 1];
  22599. ctx.s.remove(
  22600. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  22601. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  22602. );
  22603. };
  22604. for (let i = 0; i < node.specifiers.length; i++) {
  22605. const specifier = node.specifiers[i];
  22606. const local = specifier.local.name;
  22607. const imported = getImportedName(specifier);
  22608. const source2 = node.source.value;
  22609. const existing = ctx.userImports[local];
  22610. if (source2 === "vue" && MACROS.includes(imported)) {
  22611. if (local === imported) {
  22612. warnOnce(
  22613. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  22614. );
  22615. } else {
  22616. ctx.error(
  22617. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  22618. specifier
  22619. );
  22620. }
  22621. removeSpecifier(i);
  22622. } else if (existing) {
  22623. if (existing.source === source2 && existing.imported === imported) {
  22624. removeSpecifier(i);
  22625. } else {
  22626. ctx.error(
  22627. `different imports aliased to same local name.`,
  22628. specifier
  22629. );
  22630. }
  22631. } else {
  22632. registerUserImport(
  22633. source2,
  22634. local,
  22635. imported,
  22636. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22637. true,
  22638. !options.inlineTemplate
  22639. );
  22640. }
  22641. }
  22642. if (node.specifiers.length && removed === node.specifiers.length) {
  22643. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22644. }
  22645. }
  22646. }
  22647. const vueImportAliases = {};
  22648. for (const key in ctx.userImports) {
  22649. const { source: source2, imported, local } = ctx.userImports[key];
  22650. if (source2 === "vue") vueImportAliases[imported] = local;
  22651. }
  22652. if (script && scriptAst) {
  22653. for (const node of scriptAst.body) {
  22654. if (node.type === "ExportDefaultDeclaration") {
  22655. defaultExport = node;
  22656. let optionProperties;
  22657. if (defaultExport.declaration.type === "ObjectExpression") {
  22658. optionProperties = defaultExport.declaration.properties;
  22659. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  22660. optionProperties = defaultExport.declaration.arguments[0].properties;
  22661. }
  22662. if (optionProperties) {
  22663. for (const p of optionProperties) {
  22664. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  22665. ctx.hasDefaultExportName = true;
  22666. }
  22667. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  22668. ctx.hasDefaultExportRender = true;
  22669. }
  22670. }
  22671. }
  22672. const start = node.start + scriptStartOffset;
  22673. const end = node.declaration.start + scriptStartOffset;
  22674. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  22675. } else if (node.type === "ExportNamedDeclaration") {
  22676. const defaultSpecifier = node.specifiers.find(
  22677. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  22678. );
  22679. if (defaultSpecifier) {
  22680. defaultExport = node;
  22681. if (node.specifiers.length > 1) {
  22682. ctx.s.remove(
  22683. defaultSpecifier.start + scriptStartOffset,
  22684. defaultSpecifier.end + scriptStartOffset
  22685. );
  22686. } else {
  22687. ctx.s.remove(
  22688. node.start + scriptStartOffset,
  22689. node.end + scriptStartOffset
  22690. );
  22691. }
  22692. if (node.source) {
  22693. ctx.s.prepend(
  22694. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  22695. `
  22696. );
  22697. } else {
  22698. ctx.s.appendLeft(
  22699. scriptEndOffset,
  22700. `
  22701. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  22702. `
  22703. );
  22704. }
  22705. }
  22706. if (node.declaration) {
  22707. walkDeclaration(
  22708. "script",
  22709. node.declaration,
  22710. scriptBindings,
  22711. vueImportAliases,
  22712. hoistStatic
  22713. );
  22714. }
  22715. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  22716. walkDeclaration(
  22717. "script",
  22718. node,
  22719. scriptBindings,
  22720. vueImportAliases,
  22721. hoistStatic
  22722. );
  22723. }
  22724. }
  22725. if (scriptStartOffset > startOffset) {
  22726. if (!/\n$/.test(script.content.trim())) {
  22727. ctx.s.appendLeft(scriptEndOffset, `
  22728. `);
  22729. }
  22730. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  22731. }
  22732. }
  22733. for (const node of scriptSetupAst.body) {
  22734. if (node.type === "ExpressionStatement") {
  22735. const expr = CompilerDOM.unwrapTSNode(node.expression);
  22736. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  22737. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22738. } else if (processDefineExpose(ctx, expr)) {
  22739. const callee = expr.callee;
  22740. ctx.s.overwrite(
  22741. callee.start + startOffset,
  22742. callee.end + startOffset,
  22743. "__expose"
  22744. );
  22745. } else {
  22746. processDefineModel(ctx, expr);
  22747. }
  22748. }
  22749. if (node.type === "VariableDeclaration" && !node.declare) {
  22750. const total = node.declarations.length;
  22751. let left = total;
  22752. let lastNonRemoved;
  22753. for (let i = 0; i < total; i++) {
  22754. const decl = node.declarations[i];
  22755. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  22756. if (init) {
  22757. if (processDefineOptions(ctx, init)) {
  22758. ctx.error(
  22759. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  22760. node
  22761. );
  22762. }
  22763. const isDefineProps = processDefineProps(ctx, init, decl.id);
  22764. if (ctx.propsDestructureRestId) {
  22765. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  22766. }
  22767. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  22768. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  22769. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  22770. if (left === 1) {
  22771. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22772. } else {
  22773. let start = decl.start + startOffset;
  22774. let end = decl.end + startOffset;
  22775. if (i === total - 1) {
  22776. start = node.declarations[lastNonRemoved].end + startOffset;
  22777. } else {
  22778. end = node.declarations[i + 1].start + startOffset;
  22779. }
  22780. ctx.s.remove(start, end);
  22781. left--;
  22782. }
  22783. } else if (isDefineEmits) {
  22784. ctx.s.overwrite(
  22785. startOffset + init.start,
  22786. startOffset + init.end,
  22787. "__emit"
  22788. );
  22789. } else {
  22790. lastNonRemoved = i;
  22791. }
  22792. }
  22793. }
  22794. }
  22795. let isAllLiteral = false;
  22796. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  22797. isAllLiteral = walkDeclaration(
  22798. "scriptSetup",
  22799. node,
  22800. setupBindings,
  22801. vueImportAliases,
  22802. hoistStatic,
  22803. !!ctx.propsDestructureDecl
  22804. );
  22805. }
  22806. if (hoistStatic && isAllLiteral) {
  22807. hoistNode(node);
  22808. }
  22809. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  22810. const scope = [scriptSetupAst.body];
  22811. estreeWalker.walk(node, {
  22812. enter(child, parent) {
  22813. if (CompilerDOM.isFunctionType(child)) {
  22814. this.skip();
  22815. }
  22816. if (child.type === "BlockStatement") {
  22817. scope.push(child.body);
  22818. }
  22819. if (child.type === "AwaitExpression") {
  22820. hasAwait = true;
  22821. const currentScope = scope[scope.length - 1];
  22822. const needsSemi = currentScope.some((n, i) => {
  22823. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  22824. });
  22825. processAwait(
  22826. ctx,
  22827. child,
  22828. needsSemi,
  22829. parent.type === "ExpressionStatement"
  22830. );
  22831. }
  22832. },
  22833. exit(node2) {
  22834. if (node2.type === "BlockStatement") scope.pop();
  22835. }
  22836. });
  22837. }
  22838. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  22839. ctx.error(
  22840. `<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.`,
  22841. node
  22842. );
  22843. }
  22844. if (ctx.isTS) {
  22845. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  22846. if (node.type !== "TSEnumDeclaration") {
  22847. hoistNode(node);
  22848. }
  22849. }
  22850. }
  22851. }
  22852. if (ctx.propsDestructureDecl) {
  22853. transformDestructuredProps(ctx, vueImportAliases);
  22854. }
  22855. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  22856. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  22857. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  22858. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  22859. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  22860. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  22861. for (const node of runtimeOptionNodes) {
  22862. checkInvalidScopeReference(node, DEFINE_MODEL);
  22863. }
  22864. }
  22865. if (script) {
  22866. if (startOffset < scriptStartOffset) {
  22867. ctx.s.remove(0, startOffset);
  22868. ctx.s.remove(endOffset, scriptStartOffset);
  22869. ctx.s.remove(scriptEndOffset, source.length);
  22870. } else {
  22871. ctx.s.remove(0, scriptStartOffset);
  22872. ctx.s.remove(scriptEndOffset, startOffset);
  22873. ctx.s.remove(endOffset, source.length);
  22874. }
  22875. } else {
  22876. ctx.s.remove(0, startOffset);
  22877. ctx.s.remove(endOffset, source.length);
  22878. }
  22879. if (scriptAst) {
  22880. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  22881. }
  22882. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  22883. ctx.userImports
  22884. )) {
  22885. if (isType) continue;
  22886. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  22887. }
  22888. for (const key in scriptBindings) {
  22889. ctx.bindingMetadata[key] = scriptBindings[key];
  22890. }
  22891. for (const key in setupBindings) {
  22892. ctx.bindingMetadata[key] = setupBindings[key];
  22893. }
  22894. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  22895. const vModelIds = resolveTemplateVModelIdentifiers(sfc);
  22896. if (vModelIds.size) {
  22897. const toDemote = /* @__PURE__ */ new Set();
  22898. for (const id of vModelIds) {
  22899. if (setupBindings[id] === "setup-reactive-const") {
  22900. toDemote.add(id);
  22901. }
  22902. }
  22903. if (toDemote.size) {
  22904. for (const node of scriptSetupAst.body) {
  22905. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  22906. const demotedInDecl = [];
  22907. for (const decl of node.declarations) {
  22908. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  22909. demotedInDecl.push(decl.id.name);
  22910. }
  22911. }
  22912. if (demotedInDecl.length) {
  22913. ctx.s.overwrite(
  22914. node.start + startOffset,
  22915. node.start + startOffset + "const".length,
  22916. "let"
  22917. );
  22918. for (const id of demotedInDecl) {
  22919. setupBindings[id] = "setup-let";
  22920. ctx.bindingMetadata[id] = "setup-let";
  22921. warnOnce(
  22922. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  22923. );
  22924. }
  22925. }
  22926. }
  22927. }
  22928. }
  22929. }
  22930. }
  22931. if (sfc.cssVars.length && // no need to do this when targeting SSR
  22932. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  22933. ctx.helperImports.add(CSS_VARS_HELPER);
  22934. ctx.helperImports.add("unref");
  22935. ctx.s.prependLeft(
  22936. startOffset,
  22937. `
  22938. ${genCssVarsCode(
  22939. sfc.cssVars,
  22940. ctx.bindingMetadata,
  22941. scopeId,
  22942. !!options.isProd
  22943. )}
  22944. `
  22945. );
  22946. }
  22947. let args = `__props`;
  22948. if (ctx.propsTypeDecl) {
  22949. args += `: any`;
  22950. }
  22951. if (ctx.propsDecl) {
  22952. if (ctx.propsDestructureRestId) {
  22953. ctx.s.overwrite(
  22954. startOffset + ctx.propsCall.start,
  22955. startOffset + ctx.propsCall.end,
  22956. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  22957. Object.keys(ctx.propsDestructuredBindings)
  22958. )})`
  22959. );
  22960. ctx.s.overwrite(
  22961. startOffset + ctx.propsDestructureDecl.start,
  22962. startOffset + ctx.propsDestructureDecl.end,
  22963. ctx.propsDestructureRestId
  22964. );
  22965. } else if (!ctx.propsDestructureDecl) {
  22966. ctx.s.overwrite(
  22967. startOffset + ctx.propsCall.start,
  22968. startOffset + ctx.propsCall.end,
  22969. "__props"
  22970. );
  22971. }
  22972. }
  22973. if (hasAwait) {
  22974. const any = ctx.isTS ? `: any` : ``;
  22975. ctx.s.prependLeft(startOffset, `
  22976. let __temp${any}, __restore${any}
  22977. `);
  22978. }
  22979. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  22980. if (ctx.emitDecl) {
  22981. destructureElements.push(`emit: __emit`);
  22982. }
  22983. if (destructureElements.length) {
  22984. args += `, { ${destructureElements.join(", ")} }`;
  22985. }
  22986. let templateMap;
  22987. let returned;
  22988. const propsDecl = genRuntimeProps(ctx);
  22989. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  22990. const allBindings = {
  22991. ...scriptBindings,
  22992. ...setupBindings
  22993. };
  22994. for (const key in ctx.userImports) {
  22995. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  22996. allBindings[key] = true;
  22997. }
  22998. }
  22999. returned = `{ `;
  23000. for (const key in allBindings) {
  23001. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  23002. returned += `get ${key}() { return ${key} }, `;
  23003. } else if (ctx.bindingMetadata[key] === "setup-let") {
  23004. const setArg = key === "v" ? `_v` : `v`;
  23005. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  23006. } else {
  23007. returned += `${key}, `;
  23008. }
  23009. }
  23010. returned = returned.replace(/, $/, "") + ` }`;
  23011. } else {
  23012. if (sfc.template && !sfc.template.src) {
  23013. if (options.templateOptions && options.templateOptions.ssr) {
  23014. hasInlinedSsrRenderFn = true;
  23015. }
  23016. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate({
  23017. filename,
  23018. ast: sfc.template.ast,
  23019. source: sfc.template.content,
  23020. inMap: sfc.template.map,
  23021. ...options.templateOptions,
  23022. id: scopeId,
  23023. scoped: sfc.styles.some((s) => s.scoped),
  23024. isProd: options.isProd,
  23025. ssrCssVars: sfc.cssVars,
  23026. compilerOptions: {
  23027. ...options.templateOptions && options.templateOptions.compilerOptions,
  23028. inline: true,
  23029. isTS: ctx.isTS,
  23030. bindingMetadata: ctx.bindingMetadata
  23031. }
  23032. });
  23033. templateMap = map2;
  23034. if (tips.length) {
  23035. tips.forEach(warnOnce);
  23036. }
  23037. const err = errors[0];
  23038. if (typeof err === "string") {
  23039. throw new Error(err);
  23040. } else if (err) {
  23041. if (err.loc) {
  23042. err.message += `
  23043. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  23044. source,
  23045. err.loc.start.offset,
  23046. err.loc.end.offset
  23047. ) + `
  23048. `;
  23049. }
  23050. throw err;
  23051. }
  23052. if (preamble) {
  23053. ctx.s.prepend(preamble);
  23054. }
  23055. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  23056. ctx.helperImports.delete("unref");
  23057. }
  23058. returned = code;
  23059. } else {
  23060. returned = `() => {}`;
  23061. }
  23062. }
  23063. if (!options.inlineTemplate && true) {
  23064. ctx.s.appendRight(
  23065. endOffset,
  23066. `
  23067. const __returned__ = ${returned}
  23068. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  23069. return __returned__
  23070. }
  23071. `
  23072. );
  23073. } else {
  23074. ctx.s.appendRight(endOffset, `
  23075. return ${returned}
  23076. }
  23077. `);
  23078. }
  23079. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  23080. let runtimeOptions = ``;
  23081. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  23082. const match = filename.match(/([^/\\]+)\.\w+$/);
  23083. if (match) {
  23084. runtimeOptions += `
  23085. __name: '${match[1]}',`;
  23086. }
  23087. }
  23088. if (hasInlinedSsrRenderFn) {
  23089. runtimeOptions += `
  23090. __ssrInlineRender: true,`;
  23091. }
  23092. if (propsDecl) runtimeOptions += `
  23093. props: ${propsDecl},`;
  23094. const emitsDecl = genRuntimeEmits(ctx);
  23095. if (emitsDecl) runtimeOptions += `
  23096. emits: ${emitsDecl},`;
  23097. let definedOptions = "";
  23098. if (ctx.optionsRuntimeDecl) {
  23099. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  23100. }
  23101. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  23102. `;
  23103. if (ctx.isTS) {
  23104. const def = (defaultExport ? `
  23105. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  23106. ...${definedOptions},` : "");
  23107. ctx.s.prependLeft(
  23108. startOffset,
  23109. `
  23110. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  23111. `defineComponent`
  23112. )}({${def}${runtimeOptions}
  23113. ${hasAwait ? `async ` : ``}setup(${args}) {
  23114. ${exposeCall}`
  23115. );
  23116. ctx.s.appendRight(endOffset, `})`);
  23117. } else {
  23118. if (defaultExport || definedOptions) {
  23119. ctx.s.prependLeft(
  23120. startOffset,
  23121. `
  23122. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  23123. ${hasAwait ? `async ` : ``}setup(${args}) {
  23124. ${exposeCall}`
  23125. );
  23126. ctx.s.appendRight(endOffset, `})`);
  23127. } else {
  23128. ctx.s.prependLeft(
  23129. startOffset,
  23130. `
  23131. ${genDefaultAs} {${runtimeOptions}
  23132. ${hasAwait ? `async ` : ``}setup(${args}) {
  23133. ${exposeCall}`
  23134. );
  23135. ctx.s.appendRight(endOffset, `}`);
  23136. }
  23137. }
  23138. if (ctx.helperImports.size > 0) {
  23139. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  23140. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  23141. ctx.s.prepend(
  23142. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  23143. `
  23144. );
  23145. }
  23146. const content = ctx.s.toString();
  23147. let map = options.sourceMap !== false ? ctx.s.generateMap({
  23148. source: filename,
  23149. hires: true,
  23150. includeContent: true
  23151. }) : void 0;
  23152. if (templateMap && map) {
  23153. const offset = content.indexOf(returned);
  23154. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  23155. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  23156. }
  23157. return {
  23158. ...scriptSetup,
  23159. bindings: ctx.bindingMetadata,
  23160. imports: ctx.userImports,
  23161. content,
  23162. map,
  23163. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  23164. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  23165. deps: ctx.deps ? [...ctx.deps] : void 0
  23166. };
  23167. }
  23168. function registerBinding(bindings, node, type) {
  23169. bindings[node.name] = type;
  23170. }
  23171. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  23172. let isAllLiteral = false;
  23173. if (node.type === "VariableDeclaration") {
  23174. const isConst = node.kind === "const";
  23175. isAllLiteral = isConst && node.declarations.every(
  23176. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  23177. );
  23178. for (const { id, init: _init } of node.declarations) {
  23179. const init = _init && CompilerDOM.unwrapTSNode(_init);
  23180. const isConstMacroCall = isConst && isCallOf(
  23181. init,
  23182. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  23183. );
  23184. if (id.type === "Identifier") {
  23185. let bindingType;
  23186. const userReactiveBinding = userImportAliases["reactive"];
  23187. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  23188. bindingType = "literal-const";
  23189. } else if (isCallOf(init, userReactiveBinding)) {
  23190. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  23191. } else if (
  23192. // if a declaration is a const literal, we can mark it so that
  23193. // the generated render fn code doesn't need to unref() it
  23194. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  23195. ) {
  23196. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  23197. } else if (isConst) {
  23198. if (isCallOf(
  23199. init,
  23200. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  23201. )) {
  23202. bindingType = "setup-ref";
  23203. } else {
  23204. bindingType = "setup-maybe-ref";
  23205. }
  23206. } else {
  23207. bindingType = "setup-let";
  23208. }
  23209. registerBinding(bindings, id, bindingType);
  23210. } else {
  23211. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  23212. continue;
  23213. }
  23214. if (id.type === "ObjectPattern") {
  23215. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  23216. } else if (id.type === "ArrayPattern") {
  23217. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  23218. }
  23219. }
  23220. }
  23221. } else if (node.type === "TSEnumDeclaration") {
  23222. isAllLiteral = node.members.every(
  23223. (member) => !member.initializer || isStaticNode(member.initializer)
  23224. );
  23225. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  23226. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  23227. bindings[node.id.name] = "setup-const";
  23228. }
  23229. return isAllLiteral;
  23230. }
  23231. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  23232. for (const p of node.properties) {
  23233. if (p.type === "ObjectProperty") {
  23234. if (p.key.type === "Identifier" && p.key === p.value) {
  23235. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23236. registerBinding(bindings, p.key, type);
  23237. } else {
  23238. walkPattern(p.value, bindings, isConst, isDefineCall);
  23239. }
  23240. } else {
  23241. const type = isConst ? "setup-const" : "setup-let";
  23242. registerBinding(bindings, p.argument, type);
  23243. }
  23244. }
  23245. }
  23246. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  23247. for (const e of node.elements) {
  23248. e && walkPattern(e, bindings, isConst, isDefineCall);
  23249. }
  23250. }
  23251. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  23252. if (node.type === "Identifier") {
  23253. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23254. registerBinding(bindings, node, type);
  23255. } else if (node.type === "RestElement") {
  23256. const type = isConst ? "setup-const" : "setup-let";
  23257. registerBinding(bindings, node.argument, type);
  23258. } else if (node.type === "ObjectPattern") {
  23259. walkObjectPattern(node, bindings, isConst);
  23260. } else if (node.type === "ArrayPattern") {
  23261. walkArrayPattern(node, bindings, isConst);
  23262. } else if (node.type === "AssignmentPattern") {
  23263. if (node.left.type === "Identifier") {
  23264. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23265. registerBinding(bindings, node.left, type);
  23266. } else {
  23267. walkPattern(node.left, bindings, isConst);
  23268. }
  23269. }
  23270. }
  23271. function canNeverBeRef(node, userReactiveImport) {
  23272. if (isCallOf(node, userReactiveImport)) {
  23273. return true;
  23274. }
  23275. switch (node.type) {
  23276. case "UnaryExpression":
  23277. case "BinaryExpression":
  23278. case "ArrayExpression":
  23279. case "ObjectExpression":
  23280. case "FunctionExpression":
  23281. case "ArrowFunctionExpression":
  23282. case "UpdateExpression":
  23283. case "ClassExpression":
  23284. case "TaggedTemplateExpression":
  23285. return true;
  23286. case "SequenceExpression":
  23287. return canNeverBeRef(
  23288. node.expressions[node.expressions.length - 1],
  23289. userReactiveImport
  23290. );
  23291. default:
  23292. if (isLiteralNode(node)) {
  23293. return true;
  23294. }
  23295. return false;
  23296. }
  23297. }
  23298. function isStaticNode(node) {
  23299. node = CompilerDOM.unwrapTSNode(node);
  23300. switch (node.type) {
  23301. case "UnaryExpression":
  23302. return isStaticNode(node.argument);
  23303. case "LogicalExpression":
  23304. // 1 > 2
  23305. case "BinaryExpression":
  23306. return isStaticNode(node.left) && isStaticNode(node.right);
  23307. case "ConditionalExpression": {
  23308. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  23309. }
  23310. case "SequenceExpression":
  23311. // (1, 2)
  23312. case "TemplateLiteral":
  23313. return node.expressions.every((expr) => isStaticNode(expr));
  23314. case "ParenthesizedExpression":
  23315. return isStaticNode(node.expression);
  23316. case "StringLiteral":
  23317. case "NumericLiteral":
  23318. case "BooleanLiteral":
  23319. case "NullLiteral":
  23320. case "BigIntLiteral":
  23321. return true;
  23322. }
  23323. return false;
  23324. }
  23325. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  23326. const generator = new sourceMapJs.SourceMapGenerator();
  23327. const addMapping = (map, lineOffset = 0) => {
  23328. const consumer = new sourceMapJs.SourceMapConsumer(map);
  23329. consumer.sources.forEach((sourceFile) => {
  23330. generator._sources.add(sourceFile);
  23331. const sourceContent = consumer.sourceContentFor(sourceFile);
  23332. if (sourceContent != null) {
  23333. generator.setSourceContent(sourceFile, sourceContent);
  23334. }
  23335. });
  23336. consumer.eachMapping((m) => {
  23337. if (m.originalLine == null) return;
  23338. generator.addMapping({
  23339. generated: {
  23340. line: m.generatedLine + lineOffset,
  23341. column: m.generatedColumn
  23342. },
  23343. original: {
  23344. line: m.originalLine,
  23345. column: m.originalColumn
  23346. },
  23347. source: m.source,
  23348. name: m.name
  23349. });
  23350. });
  23351. };
  23352. addMapping(scriptMap);
  23353. addMapping(templateMap, templateLineOffset);
  23354. generator._sourceRoot = scriptMap.sourceRoot;
  23355. generator._file = scriptMap.file;
  23356. return generator.toJSON();
  23357. }
  23358. const version = "3.5.27";
  23359. const parseCache = parseCache$1;
  23360. const errorMessages = {
  23361. ...CompilerDOM.errorMessages,
  23362. ...CompilerDOM.DOMErrorMessages
  23363. };
  23364. const walk = estreeWalker.walk;
  23365. const shouldTransformRef = () => false;
  23366. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  23367. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  23368. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  23369. exports.isStaticProperty = compilerCore.isStaticProperty;
  23370. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  23371. exports.MagicString = MagicString;
  23372. exports.babelParse = parser$2.parse;
  23373. exports.compileScript = compileScript;
  23374. exports.compileStyle = compileStyle;
  23375. exports.compileStyleAsync = compileStyleAsync;
  23376. exports.compileTemplate = compileTemplate;
  23377. exports.errorMessages = errorMessages;
  23378. exports.extractRuntimeEmits = extractRuntimeEmits;
  23379. exports.extractRuntimeProps = extractRuntimeProps;
  23380. exports.inferRuntimeType = inferRuntimeType;
  23381. exports.invalidateTypeCache = invalidateTypeCache;
  23382. exports.parse = parse$1;
  23383. exports.parseCache = parseCache;
  23384. exports.registerTS = registerTS;
  23385. exports.resolveTypeElements = resolveTypeElements;
  23386. exports.rewriteDefault = rewriteDefault;
  23387. exports.rewriteDefaultAST = rewriteDefaultAST;
  23388. exports.shouldTransformRef = shouldTransformRef;
  23389. exports.version = version;
  23390. exports.walk = walk;