compiler-sfc.cjs.js 815 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970
  1. /**
  2. * @vue/compiler-sfc v3.5.13
  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) => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  111. ).join(",\n ")}
  112. }`;
  113. }
  114. function genVarName(id, raw, isProd, isSSR = false) {
  115. if (isProd) {
  116. return hash(id + raw);
  117. } else {
  118. return `${id}-${shared.getEscapedCssVarName(raw, isSSR)}`;
  119. }
  120. }
  121. function normalizeExpression(exp) {
  122. exp = exp.trim();
  123. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  124. return exp.slice(1, -1);
  125. }
  126. return exp;
  127. }
  128. const vBindRE = /v-bind\s*\(/g;
  129. function parseCssVars(sfc) {
  130. const vars = [];
  131. sfc.styles.forEach((style) => {
  132. let match;
  133. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  134. while (match = vBindRE.exec(content)) {
  135. const start = match.index + match[0].length;
  136. const end = lexBinding(content, start);
  137. if (end !== null) {
  138. const variable = normalizeExpression(content.slice(start, end));
  139. if (!vars.includes(variable)) {
  140. vars.push(variable);
  141. }
  142. }
  143. }
  144. });
  145. return vars;
  146. }
  147. function lexBinding(content, start) {
  148. let state = 0 /* inParens */;
  149. let parenDepth = 0;
  150. for (let i = start; i < content.length; i++) {
  151. const char = content.charAt(i);
  152. switch (state) {
  153. case 0 /* inParens */:
  154. if (char === `'`) {
  155. state = 1 /* inSingleQuoteString */;
  156. } else if (char === `"`) {
  157. state = 2 /* inDoubleQuoteString */;
  158. } else if (char === `(`) {
  159. parenDepth++;
  160. } else if (char === `)`) {
  161. if (parenDepth > 0) {
  162. parenDepth--;
  163. } else {
  164. return i;
  165. }
  166. }
  167. break;
  168. case 1 /* inSingleQuoteString */:
  169. if (char === `'`) {
  170. state = 0 /* inParens */;
  171. }
  172. break;
  173. case 2 /* inDoubleQuoteString */:
  174. if (char === `"`) {
  175. state = 0 /* inParens */;
  176. }
  177. break;
  178. }
  179. }
  180. return null;
  181. }
  182. const cssVarsPlugin = (opts) => {
  183. const { id, isProd } = opts;
  184. return {
  185. postcssPlugin: "vue-sfc-vars",
  186. Declaration(decl) {
  187. const value = decl.value;
  188. if (vBindRE.test(value)) {
  189. vBindRE.lastIndex = 0;
  190. let transformed = "";
  191. let lastIndex = 0;
  192. let match;
  193. while (match = vBindRE.exec(value)) {
  194. const start = match.index + match[0].length;
  195. const end = lexBinding(value, start);
  196. if (end !== null) {
  197. const variable = normalizeExpression(value.slice(start, end));
  198. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  199. lastIndex = end + 1;
  200. }
  201. }
  202. decl.value = transformed + value.slice(lastIndex);
  203. }
  204. }
  205. };
  206. };
  207. cssVarsPlugin.postcss = true;
  208. function genCssVarsCode(vars, bindings, id, isProd) {
  209. const varsExp = genCssVarsFromList(vars, id, isProd);
  210. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  211. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  212. prefixIdentifiers: true,
  213. inline: true,
  214. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  215. });
  216. const transformed = CompilerDOM.processExpression(exp, context);
  217. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  218. return typeof c === "string" ? c : c.content;
  219. }).join("");
  220. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  221. }
  222. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  223. return `
  224. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  225. const __injectCSSVars__ = () => {
  226. ${genCssVarsCode(
  227. cssVars,
  228. bindings,
  229. id,
  230. isProd
  231. )}}
  232. const __setup__ = ${defaultVar}.setup
  233. ${defaultVar}.setup = __setup__
  234. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  235. : __injectCSSVars__
  236. `;
  237. }
  238. /**
  239. * @module LRUCache
  240. */
  241. const perf = typeof performance === 'object' &&
  242. performance &&
  243. typeof performance.now === 'function'
  244. ? performance
  245. : Date;
  246. const warned = new Set();
  247. /* c8 ignore start */
  248. const PROCESS = (typeof process === 'object' && !!process ? process : {});
  249. /* c8 ignore start */
  250. const emitWarning = (msg, type, code, fn) => {
  251. typeof PROCESS.emitWarning === 'function'
  252. ? PROCESS.emitWarning(msg, type, code, fn)
  253. : console.error(`[${code}] ${type}: ${msg}`);
  254. };
  255. let AC = globalThis.AbortController;
  256. let AS = globalThis.AbortSignal;
  257. /* c8 ignore start */
  258. if (typeof AC === 'undefined') {
  259. //@ts-ignore
  260. AS = class AbortSignal {
  261. onabort;
  262. _onabort = [];
  263. reason;
  264. aborted = false;
  265. addEventListener(_, fn) {
  266. this._onabort.push(fn);
  267. }
  268. };
  269. //@ts-ignore
  270. AC = class AbortController {
  271. constructor() {
  272. warnACPolyfill();
  273. }
  274. signal = new AS();
  275. abort(reason) {
  276. if (this.signal.aborted)
  277. return;
  278. //@ts-ignore
  279. this.signal.reason = reason;
  280. //@ts-ignore
  281. this.signal.aborted = true;
  282. //@ts-ignore
  283. for (const fn of this.signal._onabort) {
  284. fn(reason);
  285. }
  286. this.signal.onabort?.(reason);
  287. }
  288. };
  289. let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
  290. const warnACPolyfill = () => {
  291. if (!printACPolyfillWarning)
  292. return;
  293. printACPolyfillWarning = false;
  294. emitWarning('AbortController is not defined. If using lru-cache in ' +
  295. 'node 14, load an AbortController polyfill from the ' +
  296. '`node-abort-controller` package. A minimal polyfill is ' +
  297. 'provided for use by LRUCache.fetch(), but it should not be ' +
  298. 'relied upon in other contexts (eg, passing it to other APIs that ' +
  299. 'use AbortController/AbortSignal might have undesirable effects). ' +
  300. 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
  301. };
  302. }
  303. /* c8 ignore stop */
  304. const shouldWarn = (code) => !warned.has(code);
  305. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  306. /* c8 ignore start */
  307. // This is a little bit ridiculous, tbh.
  308. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  309. // And well before that point, you're caching the entire world, I mean,
  310. // that's ~32GB of just integers for the next/prev links, plus whatever
  311. // else to hold that many keys and values. Just filling the memory with
  312. // zeroes at init time is brutal when you get that big.
  313. // But why not be complete?
  314. // Maybe in the future, these limits will have expanded.
  315. const getUintArray = (max) => !isPosInt(max)
  316. ? null
  317. : max <= Math.pow(2, 8)
  318. ? Uint8Array
  319. : max <= Math.pow(2, 16)
  320. ? Uint16Array
  321. : max <= Math.pow(2, 32)
  322. ? Uint32Array
  323. : max <= Number.MAX_SAFE_INTEGER
  324. ? ZeroArray
  325. : null;
  326. /* c8 ignore stop */
  327. class ZeroArray extends Array {
  328. constructor(size) {
  329. super(size);
  330. this.fill(0);
  331. }
  332. }
  333. class Stack {
  334. heap;
  335. length;
  336. // private constructor
  337. static #constructing = false;
  338. static create(max) {
  339. const HeapCls = getUintArray(max);
  340. if (!HeapCls)
  341. return [];
  342. Stack.#constructing = true;
  343. const s = new Stack(max, HeapCls);
  344. Stack.#constructing = false;
  345. return s;
  346. }
  347. constructor(max, HeapCls) {
  348. /* c8 ignore start */
  349. if (!Stack.#constructing) {
  350. throw new TypeError('instantiate Stack using Stack.create(n)');
  351. }
  352. /* c8 ignore stop */
  353. this.heap = new HeapCls(max);
  354. this.length = 0;
  355. }
  356. push(n) {
  357. this.heap[this.length++] = n;
  358. }
  359. pop() {
  360. return this.heap[--this.length];
  361. }
  362. }
  363. /**
  364. * Default export, the thing you're using this module to get.
  365. *
  366. * All properties from the options object (with the exception of
  367. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  368. * normal public members. (`max` and `maxBase` are read-only getters.)
  369. * Changing any of these will alter the defaults for subsequent method calls,
  370. * but is otherwise safe.
  371. */
  372. class LRUCache {
  373. // properties coming in from the options of these, only max and maxSize
  374. // really *need* to be protected. The rest can be modified, as they just
  375. // set defaults for various methods.
  376. #max;
  377. #maxSize;
  378. #dispose;
  379. #disposeAfter;
  380. #fetchMethod;
  381. /**
  382. * {@link LRUCache.OptionsBase.ttl}
  383. */
  384. ttl;
  385. /**
  386. * {@link LRUCache.OptionsBase.ttlResolution}
  387. */
  388. ttlResolution;
  389. /**
  390. * {@link LRUCache.OptionsBase.ttlAutopurge}
  391. */
  392. ttlAutopurge;
  393. /**
  394. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  395. */
  396. updateAgeOnGet;
  397. /**
  398. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  399. */
  400. updateAgeOnHas;
  401. /**
  402. * {@link LRUCache.OptionsBase.allowStale}
  403. */
  404. allowStale;
  405. /**
  406. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  407. */
  408. noDisposeOnSet;
  409. /**
  410. * {@link LRUCache.OptionsBase.noUpdateTTL}
  411. */
  412. noUpdateTTL;
  413. /**
  414. * {@link LRUCache.OptionsBase.maxEntrySize}
  415. */
  416. maxEntrySize;
  417. /**
  418. * {@link LRUCache.OptionsBase.sizeCalculation}
  419. */
  420. sizeCalculation;
  421. /**
  422. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  423. */
  424. noDeleteOnFetchRejection;
  425. /**
  426. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  427. */
  428. noDeleteOnStaleGet;
  429. /**
  430. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  431. */
  432. allowStaleOnFetchAbort;
  433. /**
  434. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  435. */
  436. allowStaleOnFetchRejection;
  437. /**
  438. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  439. */
  440. ignoreFetchAbort;
  441. // computed properties
  442. #size;
  443. #calculatedSize;
  444. #keyMap;
  445. #keyList;
  446. #valList;
  447. #next;
  448. #prev;
  449. #head;
  450. #tail;
  451. #free;
  452. #disposed;
  453. #sizes;
  454. #starts;
  455. #ttls;
  456. #hasDispose;
  457. #hasFetchMethod;
  458. #hasDisposeAfter;
  459. /**
  460. * Do not call this method unless you need to inspect the
  461. * inner workings of the cache. If anything returned by this
  462. * object is modified in any way, strange breakage may occur.
  463. *
  464. * These fields are private for a reason!
  465. *
  466. * @internal
  467. */
  468. static unsafeExposeInternals(c) {
  469. return {
  470. // properties
  471. starts: c.#starts,
  472. ttls: c.#ttls,
  473. sizes: c.#sizes,
  474. keyMap: c.#keyMap,
  475. keyList: c.#keyList,
  476. valList: c.#valList,
  477. next: c.#next,
  478. prev: c.#prev,
  479. get head() {
  480. return c.#head;
  481. },
  482. get tail() {
  483. return c.#tail;
  484. },
  485. free: c.#free,
  486. // methods
  487. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  488. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  489. moveToTail: (index) => c.#moveToTail(index),
  490. indexes: (options) => c.#indexes(options),
  491. rindexes: (options) => c.#rindexes(options),
  492. isStale: (index) => c.#isStale(index),
  493. };
  494. }
  495. // Protected read-only members
  496. /**
  497. * {@link LRUCache.OptionsBase.max} (read-only)
  498. */
  499. get max() {
  500. return this.#max;
  501. }
  502. /**
  503. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  504. */
  505. get maxSize() {
  506. return this.#maxSize;
  507. }
  508. /**
  509. * The total computed size of items in the cache (read-only)
  510. */
  511. get calculatedSize() {
  512. return this.#calculatedSize;
  513. }
  514. /**
  515. * The number of items stored in the cache (read-only)
  516. */
  517. get size() {
  518. return this.#size;
  519. }
  520. /**
  521. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  522. */
  523. get fetchMethod() {
  524. return this.#fetchMethod;
  525. }
  526. /**
  527. * {@link LRUCache.OptionsBase.dispose} (read-only)
  528. */
  529. get dispose() {
  530. return this.#dispose;
  531. }
  532. /**
  533. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  534. */
  535. get disposeAfter() {
  536. return this.#disposeAfter;
  537. }
  538. constructor(options) {
  539. 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;
  540. if (max !== 0 && !isPosInt(max)) {
  541. throw new TypeError('max option must be a nonnegative integer');
  542. }
  543. const UintArray = max ? getUintArray(max) : Array;
  544. if (!UintArray) {
  545. throw new Error('invalid max value: ' + max);
  546. }
  547. this.#max = max;
  548. this.#maxSize = maxSize;
  549. this.maxEntrySize = maxEntrySize || this.#maxSize;
  550. this.sizeCalculation = sizeCalculation;
  551. if (this.sizeCalculation) {
  552. if (!this.#maxSize && !this.maxEntrySize) {
  553. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  554. }
  555. if (typeof this.sizeCalculation !== 'function') {
  556. throw new TypeError('sizeCalculation set to non-function');
  557. }
  558. }
  559. if (fetchMethod !== undefined &&
  560. typeof fetchMethod !== 'function') {
  561. throw new TypeError('fetchMethod must be a function if specified');
  562. }
  563. this.#fetchMethod = fetchMethod;
  564. this.#hasFetchMethod = !!fetchMethod;
  565. this.#keyMap = new Map();
  566. this.#keyList = new Array(max).fill(undefined);
  567. this.#valList = new Array(max).fill(undefined);
  568. this.#next = new UintArray(max);
  569. this.#prev = new UintArray(max);
  570. this.#head = 0;
  571. this.#tail = 0;
  572. this.#free = Stack.create(max);
  573. this.#size = 0;
  574. this.#calculatedSize = 0;
  575. if (typeof dispose === 'function') {
  576. this.#dispose = dispose;
  577. }
  578. if (typeof disposeAfter === 'function') {
  579. this.#disposeAfter = disposeAfter;
  580. this.#disposed = [];
  581. }
  582. else {
  583. this.#disposeAfter = undefined;
  584. this.#disposed = undefined;
  585. }
  586. this.#hasDispose = !!this.#dispose;
  587. this.#hasDisposeAfter = !!this.#disposeAfter;
  588. this.noDisposeOnSet = !!noDisposeOnSet;
  589. this.noUpdateTTL = !!noUpdateTTL;
  590. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  591. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  592. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  593. this.ignoreFetchAbort = !!ignoreFetchAbort;
  594. // NB: maxEntrySize is set to maxSize if it's set
  595. if (this.maxEntrySize !== 0) {
  596. if (this.#maxSize !== 0) {
  597. if (!isPosInt(this.#maxSize)) {
  598. throw new TypeError('maxSize must be a positive integer if specified');
  599. }
  600. }
  601. if (!isPosInt(this.maxEntrySize)) {
  602. throw new TypeError('maxEntrySize must be a positive integer if specified');
  603. }
  604. this.#initializeSizeTracking();
  605. }
  606. this.allowStale = !!allowStale;
  607. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  608. this.updateAgeOnGet = !!updateAgeOnGet;
  609. this.updateAgeOnHas = !!updateAgeOnHas;
  610. this.ttlResolution =
  611. isPosInt(ttlResolution) || ttlResolution === 0
  612. ? ttlResolution
  613. : 1;
  614. this.ttlAutopurge = !!ttlAutopurge;
  615. this.ttl = ttl || 0;
  616. if (this.ttl) {
  617. if (!isPosInt(this.ttl)) {
  618. throw new TypeError('ttl must be a positive integer if specified');
  619. }
  620. this.#initializeTTLTracking();
  621. }
  622. // do not allow completely unbounded caches
  623. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  624. throw new TypeError('At least one of max, maxSize, or ttl is required');
  625. }
  626. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  627. const code = 'LRU_CACHE_UNBOUNDED';
  628. if (shouldWarn(code)) {
  629. warned.add(code);
  630. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  631. 'result in unbounded memory consumption.';
  632. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  633. }
  634. }
  635. }
  636. /**
  637. * Return the remaining TTL time for a given entry key
  638. */
  639. getRemainingTTL(key) {
  640. return this.#keyMap.has(key) ? Infinity : 0;
  641. }
  642. #initializeTTLTracking() {
  643. const ttls = new ZeroArray(this.#max);
  644. const starts = new ZeroArray(this.#max);
  645. this.#ttls = ttls;
  646. this.#starts = starts;
  647. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  648. starts[index] = ttl !== 0 ? start : 0;
  649. ttls[index] = ttl;
  650. if (ttl !== 0 && this.ttlAutopurge) {
  651. const t = setTimeout(() => {
  652. if (this.#isStale(index)) {
  653. this.delete(this.#keyList[index]);
  654. }
  655. }, ttl + 1);
  656. // unref() not supported on all platforms
  657. /* c8 ignore start */
  658. if (t.unref) {
  659. t.unref();
  660. }
  661. /* c8 ignore stop */
  662. }
  663. };
  664. this.#updateItemAge = index => {
  665. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  666. };
  667. this.#statusTTL = (status, index) => {
  668. if (ttls[index]) {
  669. const ttl = ttls[index];
  670. const start = starts[index];
  671. /* c8 ignore next */
  672. if (!ttl || !start)
  673. return;
  674. status.ttl = ttl;
  675. status.start = start;
  676. status.now = cachedNow || getNow();
  677. const age = status.now - start;
  678. status.remainingTTL = ttl - age;
  679. }
  680. };
  681. // debounce calls to perf.now() to 1s so we're not hitting
  682. // that costly call repeatedly.
  683. let cachedNow = 0;
  684. const getNow = () => {
  685. const n = perf.now();
  686. if (this.ttlResolution > 0) {
  687. cachedNow = n;
  688. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  689. // not available on all platforms
  690. /* c8 ignore start */
  691. if (t.unref) {
  692. t.unref();
  693. }
  694. /* c8 ignore stop */
  695. }
  696. return n;
  697. };
  698. this.getRemainingTTL = key => {
  699. const index = this.#keyMap.get(key);
  700. if (index === undefined) {
  701. return 0;
  702. }
  703. const ttl = ttls[index];
  704. const start = starts[index];
  705. if (!ttl || !start) {
  706. return Infinity;
  707. }
  708. const age = (cachedNow || getNow()) - start;
  709. return ttl - age;
  710. };
  711. this.#isStale = index => {
  712. const s = starts[index];
  713. const t = ttls[index];
  714. return !!t && !!s && (cachedNow || getNow()) - s > t;
  715. };
  716. }
  717. // conditionally set private methods related to TTL
  718. #updateItemAge = () => { };
  719. #statusTTL = () => { };
  720. #setItemTTL = () => { };
  721. /* c8 ignore stop */
  722. #isStale = () => false;
  723. #initializeSizeTracking() {
  724. const sizes = new ZeroArray(this.#max);
  725. this.#calculatedSize = 0;
  726. this.#sizes = sizes;
  727. this.#removeItemSize = index => {
  728. this.#calculatedSize -= sizes[index];
  729. sizes[index] = 0;
  730. };
  731. this.#requireSize = (k, v, size, sizeCalculation) => {
  732. // provisionally accept background fetches.
  733. // actual value size will be checked when they return.
  734. if (this.#isBackgroundFetch(v)) {
  735. return 0;
  736. }
  737. if (!isPosInt(size)) {
  738. if (sizeCalculation) {
  739. if (typeof sizeCalculation !== 'function') {
  740. throw new TypeError('sizeCalculation must be a function');
  741. }
  742. size = sizeCalculation(v, k);
  743. if (!isPosInt(size)) {
  744. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  745. }
  746. }
  747. else {
  748. throw new TypeError('invalid size value (must be positive integer). ' +
  749. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  750. 'or size must be set.');
  751. }
  752. }
  753. return size;
  754. };
  755. this.#addItemSize = (index, size, status) => {
  756. sizes[index] = size;
  757. if (this.#maxSize) {
  758. const maxSize = this.#maxSize - sizes[index];
  759. while (this.#calculatedSize > maxSize) {
  760. this.#evict(true);
  761. }
  762. }
  763. this.#calculatedSize += sizes[index];
  764. if (status) {
  765. status.entrySize = size;
  766. status.totalCalculatedSize = this.#calculatedSize;
  767. }
  768. };
  769. }
  770. #removeItemSize = _i => { };
  771. #addItemSize = (_i, _s, _st) => { };
  772. #requireSize = (_k, _v, size, sizeCalculation) => {
  773. if (size || sizeCalculation) {
  774. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  775. }
  776. return 0;
  777. };
  778. *#indexes({ allowStale = this.allowStale } = {}) {
  779. if (this.#size) {
  780. for (let i = this.#tail; true;) {
  781. if (!this.#isValidIndex(i)) {
  782. break;
  783. }
  784. if (allowStale || !this.#isStale(i)) {
  785. yield i;
  786. }
  787. if (i === this.#head) {
  788. break;
  789. }
  790. else {
  791. i = this.#prev[i];
  792. }
  793. }
  794. }
  795. }
  796. *#rindexes({ allowStale = this.allowStale } = {}) {
  797. if (this.#size) {
  798. for (let i = this.#head; true;) {
  799. if (!this.#isValidIndex(i)) {
  800. break;
  801. }
  802. if (allowStale || !this.#isStale(i)) {
  803. yield i;
  804. }
  805. if (i === this.#tail) {
  806. break;
  807. }
  808. else {
  809. i = this.#next[i];
  810. }
  811. }
  812. }
  813. }
  814. #isValidIndex(index) {
  815. return (index !== undefined &&
  816. this.#keyMap.get(this.#keyList[index]) === index);
  817. }
  818. /**
  819. * Return a generator yielding `[key, value]` pairs,
  820. * in order from most recently used to least recently used.
  821. */
  822. *entries() {
  823. for (const i of this.#indexes()) {
  824. if (this.#valList[i] !== undefined &&
  825. this.#keyList[i] !== undefined &&
  826. !this.#isBackgroundFetch(this.#valList[i])) {
  827. yield [this.#keyList[i], this.#valList[i]];
  828. }
  829. }
  830. }
  831. /**
  832. * Inverse order version of {@link LRUCache.entries}
  833. *
  834. * Return a generator yielding `[key, value]` pairs,
  835. * in order from least recently used to most recently used.
  836. */
  837. *rentries() {
  838. for (const i of this.#rindexes()) {
  839. if (this.#valList[i] !== undefined &&
  840. this.#keyList[i] !== undefined &&
  841. !this.#isBackgroundFetch(this.#valList[i])) {
  842. yield [this.#keyList[i], this.#valList[i]];
  843. }
  844. }
  845. }
  846. /**
  847. * Return a generator yielding the keys in the cache,
  848. * in order from most recently used to least recently used.
  849. */
  850. *keys() {
  851. for (const i of this.#indexes()) {
  852. const k = this.#keyList[i];
  853. if (k !== undefined &&
  854. !this.#isBackgroundFetch(this.#valList[i])) {
  855. yield k;
  856. }
  857. }
  858. }
  859. /**
  860. * Inverse order version of {@link LRUCache.keys}
  861. *
  862. * Return a generator yielding the keys in the cache,
  863. * in order from least recently used to most recently used.
  864. */
  865. *rkeys() {
  866. for (const i of this.#rindexes()) {
  867. const k = this.#keyList[i];
  868. if (k !== undefined &&
  869. !this.#isBackgroundFetch(this.#valList[i])) {
  870. yield k;
  871. }
  872. }
  873. }
  874. /**
  875. * Return a generator yielding the values in the cache,
  876. * in order from most recently used to least recently used.
  877. */
  878. *values() {
  879. for (const i of this.#indexes()) {
  880. const v = this.#valList[i];
  881. if (v !== undefined &&
  882. !this.#isBackgroundFetch(this.#valList[i])) {
  883. yield this.#valList[i];
  884. }
  885. }
  886. }
  887. /**
  888. * Inverse order version of {@link LRUCache.values}
  889. *
  890. * Return a generator yielding the values in the cache,
  891. * in order from least recently used to most recently used.
  892. */
  893. *rvalues() {
  894. for (const i of this.#rindexes()) {
  895. const v = this.#valList[i];
  896. if (v !== undefined &&
  897. !this.#isBackgroundFetch(this.#valList[i])) {
  898. yield this.#valList[i];
  899. }
  900. }
  901. }
  902. /**
  903. * Iterating over the cache itself yields the same results as
  904. * {@link LRUCache.entries}
  905. */
  906. [Symbol.iterator]() {
  907. return this.entries();
  908. }
  909. /**
  910. * Find a value for which the supplied fn method returns a truthy value,
  911. * similar to Array.find(). fn is called as fn(value, key, cache).
  912. */
  913. find(fn, getOptions = {}) {
  914. for (const i of this.#indexes()) {
  915. const v = this.#valList[i];
  916. const value = this.#isBackgroundFetch(v)
  917. ? v.__staleWhileFetching
  918. : v;
  919. if (value === undefined)
  920. continue;
  921. if (fn(value, this.#keyList[i], this)) {
  922. return this.get(this.#keyList[i], getOptions);
  923. }
  924. }
  925. }
  926. /**
  927. * Call the supplied function on each item in the cache, in order from
  928. * most recently used to least recently used. fn is called as
  929. * fn(value, key, cache). Does not update age or recenty of use.
  930. * Does not iterate over stale values.
  931. */
  932. forEach(fn, thisp = this) {
  933. for (const i of this.#indexes()) {
  934. const v = this.#valList[i];
  935. const value = this.#isBackgroundFetch(v)
  936. ? v.__staleWhileFetching
  937. : v;
  938. if (value === undefined)
  939. continue;
  940. fn.call(thisp, value, this.#keyList[i], this);
  941. }
  942. }
  943. /**
  944. * The same as {@link LRUCache.forEach} but items are iterated over in
  945. * reverse order. (ie, less recently used items are iterated over first.)
  946. */
  947. rforEach(fn, thisp = this) {
  948. for (const i of this.#rindexes()) {
  949. const v = this.#valList[i];
  950. const value = this.#isBackgroundFetch(v)
  951. ? v.__staleWhileFetching
  952. : v;
  953. if (value === undefined)
  954. continue;
  955. fn.call(thisp, value, this.#keyList[i], this);
  956. }
  957. }
  958. /**
  959. * Delete any stale entries. Returns true if anything was removed,
  960. * false otherwise.
  961. */
  962. purgeStale() {
  963. let deleted = false;
  964. for (const i of this.#rindexes({ allowStale: true })) {
  965. if (this.#isStale(i)) {
  966. this.delete(this.#keyList[i]);
  967. deleted = true;
  968. }
  969. }
  970. return deleted;
  971. }
  972. /**
  973. * Get the extended info about a given entry, to get its value, size, and
  974. * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
  975. * single key. Always returns stale values, if their info is found in the
  976. * cache, so be sure to check for expired TTLs if relevant.
  977. */
  978. info(key) {
  979. const i = this.#keyMap.get(key);
  980. if (i === undefined)
  981. return undefined;
  982. const v = this.#valList[i];
  983. const value = this.#isBackgroundFetch(v)
  984. ? v.__staleWhileFetching
  985. : v;
  986. if (value === undefined)
  987. return undefined;
  988. const entry = { value };
  989. if (this.#ttls && this.#starts) {
  990. const ttl = this.#ttls[i];
  991. const start = this.#starts[i];
  992. if (ttl && start) {
  993. const remain = ttl - (perf.now() - start);
  994. entry.ttl = remain;
  995. entry.start = Date.now();
  996. }
  997. }
  998. if (this.#sizes) {
  999. entry.size = this.#sizes[i];
  1000. }
  1001. return entry;
  1002. }
  1003. /**
  1004. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1005. * passed to cache.load()
  1006. */
  1007. dump() {
  1008. const arr = [];
  1009. for (const i of this.#indexes({ allowStale: true })) {
  1010. const key = this.#keyList[i];
  1011. const v = this.#valList[i];
  1012. const value = this.#isBackgroundFetch(v)
  1013. ? v.__staleWhileFetching
  1014. : v;
  1015. if (value === undefined || key === undefined)
  1016. continue;
  1017. const entry = { value };
  1018. if (this.#ttls && this.#starts) {
  1019. entry.ttl = this.#ttls[i];
  1020. // always dump the start relative to a portable timestamp
  1021. // it's ok for this to be a bit slow, it's a rare operation.
  1022. const age = perf.now() - this.#starts[i];
  1023. entry.start = Math.floor(Date.now() - age);
  1024. }
  1025. if (this.#sizes) {
  1026. entry.size = this.#sizes[i];
  1027. }
  1028. arr.unshift([key, entry]);
  1029. }
  1030. return arr;
  1031. }
  1032. /**
  1033. * Reset the cache and load in the items in entries in the order listed.
  1034. * Note that the shape of the resulting cache may be different if the
  1035. * same options are not used in both caches.
  1036. */
  1037. load(arr) {
  1038. this.clear();
  1039. for (const [key, entry] of arr) {
  1040. if (entry.start) {
  1041. // entry.start is a portable timestamp, but we may be using
  1042. // node's performance.now(), so calculate the offset, so that
  1043. // we get the intended remaining TTL, no matter how long it's
  1044. // been on ice.
  1045. //
  1046. // it's ok for this to be a bit slow, it's a rare operation.
  1047. const age = Date.now() - entry.start;
  1048. entry.start = perf.now() - age;
  1049. }
  1050. this.set(key, entry.value, entry);
  1051. }
  1052. }
  1053. /**
  1054. * Add a value to the cache.
  1055. *
  1056. * Note: if `undefined` is specified as a value, this is an alias for
  1057. * {@link LRUCache#delete}
  1058. */
  1059. set(k, v, setOptions = {}) {
  1060. if (v === undefined) {
  1061. this.delete(k);
  1062. return this;
  1063. }
  1064. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  1065. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  1066. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  1067. // if the item doesn't fit, don't do anything
  1068. // NB: maxEntrySize set to maxSize by default
  1069. if (this.maxEntrySize && size > this.maxEntrySize) {
  1070. if (status) {
  1071. status.set = 'miss';
  1072. status.maxEntrySizeExceeded = true;
  1073. }
  1074. // have to delete, in case something is there already.
  1075. this.delete(k);
  1076. return this;
  1077. }
  1078. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  1079. if (index === undefined) {
  1080. // addition
  1081. index = (this.#size === 0
  1082. ? this.#tail
  1083. : this.#free.length !== 0
  1084. ? this.#free.pop()
  1085. : this.#size === this.#max
  1086. ? this.#evict(false)
  1087. : this.#size);
  1088. this.#keyList[index] = k;
  1089. this.#valList[index] = v;
  1090. this.#keyMap.set(k, index);
  1091. this.#next[this.#tail] = index;
  1092. this.#prev[index] = this.#tail;
  1093. this.#tail = index;
  1094. this.#size++;
  1095. this.#addItemSize(index, size, status);
  1096. if (status)
  1097. status.set = 'add';
  1098. noUpdateTTL = false;
  1099. }
  1100. else {
  1101. // update
  1102. this.#moveToTail(index);
  1103. const oldVal = this.#valList[index];
  1104. if (v !== oldVal) {
  1105. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  1106. oldVal.__abortController.abort(new Error('replaced'));
  1107. const { __staleWhileFetching: s } = oldVal;
  1108. if (s !== undefined && !noDisposeOnSet) {
  1109. if (this.#hasDispose) {
  1110. this.#dispose?.(s, k, 'set');
  1111. }
  1112. if (this.#hasDisposeAfter) {
  1113. this.#disposed?.push([s, k, 'set']);
  1114. }
  1115. }
  1116. }
  1117. else if (!noDisposeOnSet) {
  1118. if (this.#hasDispose) {
  1119. this.#dispose?.(oldVal, k, 'set');
  1120. }
  1121. if (this.#hasDisposeAfter) {
  1122. this.#disposed?.push([oldVal, k, 'set']);
  1123. }
  1124. }
  1125. this.#removeItemSize(index);
  1126. this.#addItemSize(index, size, status);
  1127. this.#valList[index] = v;
  1128. if (status) {
  1129. status.set = 'replace';
  1130. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  1131. ? oldVal.__staleWhileFetching
  1132. : oldVal;
  1133. if (oldValue !== undefined)
  1134. status.oldValue = oldValue;
  1135. }
  1136. }
  1137. else if (status) {
  1138. status.set = 'update';
  1139. }
  1140. }
  1141. if (ttl !== 0 && !this.#ttls) {
  1142. this.#initializeTTLTracking();
  1143. }
  1144. if (this.#ttls) {
  1145. if (!noUpdateTTL) {
  1146. this.#setItemTTL(index, ttl, start);
  1147. }
  1148. if (status)
  1149. this.#statusTTL(status, index);
  1150. }
  1151. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  1152. const dt = this.#disposed;
  1153. let task;
  1154. while ((task = dt?.shift())) {
  1155. this.#disposeAfter?.(...task);
  1156. }
  1157. }
  1158. return this;
  1159. }
  1160. /**
  1161. * Evict the least recently used item, returning its value or
  1162. * `undefined` if cache is empty.
  1163. */
  1164. pop() {
  1165. try {
  1166. while (this.#size) {
  1167. const val = this.#valList[this.#head];
  1168. this.#evict(true);
  1169. if (this.#isBackgroundFetch(val)) {
  1170. if (val.__staleWhileFetching) {
  1171. return val.__staleWhileFetching;
  1172. }
  1173. }
  1174. else if (val !== undefined) {
  1175. return val;
  1176. }
  1177. }
  1178. }
  1179. finally {
  1180. if (this.#hasDisposeAfter && this.#disposed) {
  1181. const dt = this.#disposed;
  1182. let task;
  1183. while ((task = dt?.shift())) {
  1184. this.#disposeAfter?.(...task);
  1185. }
  1186. }
  1187. }
  1188. }
  1189. #evict(free) {
  1190. const head = this.#head;
  1191. const k = this.#keyList[head];
  1192. const v = this.#valList[head];
  1193. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  1194. v.__abortController.abort(new Error('evicted'));
  1195. }
  1196. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1197. if (this.#hasDispose) {
  1198. this.#dispose?.(v, k, 'evict');
  1199. }
  1200. if (this.#hasDisposeAfter) {
  1201. this.#disposed?.push([v, k, 'evict']);
  1202. }
  1203. }
  1204. this.#removeItemSize(head);
  1205. // if we aren't about to use the index, then null these out
  1206. if (free) {
  1207. this.#keyList[head] = undefined;
  1208. this.#valList[head] = undefined;
  1209. this.#free.push(head);
  1210. }
  1211. if (this.#size === 1) {
  1212. this.#head = this.#tail = 0;
  1213. this.#free.length = 0;
  1214. }
  1215. else {
  1216. this.#head = this.#next[head];
  1217. }
  1218. this.#keyMap.delete(k);
  1219. this.#size--;
  1220. return head;
  1221. }
  1222. /**
  1223. * Check if a key is in the cache, without updating the recency of use.
  1224. * Will return false if the item is stale, even though it is technically
  1225. * in the cache.
  1226. *
  1227. * Will not update item age unless
  1228. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1229. */
  1230. has(k, hasOptions = {}) {
  1231. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  1232. const index = this.#keyMap.get(k);
  1233. if (index !== undefined) {
  1234. const v = this.#valList[index];
  1235. if (this.#isBackgroundFetch(v) &&
  1236. v.__staleWhileFetching === undefined) {
  1237. return false;
  1238. }
  1239. if (!this.#isStale(index)) {
  1240. if (updateAgeOnHas) {
  1241. this.#updateItemAge(index);
  1242. }
  1243. if (status) {
  1244. status.has = 'hit';
  1245. this.#statusTTL(status, index);
  1246. }
  1247. return true;
  1248. }
  1249. else if (status) {
  1250. status.has = 'stale';
  1251. this.#statusTTL(status, index);
  1252. }
  1253. }
  1254. else if (status) {
  1255. status.has = 'miss';
  1256. }
  1257. return false;
  1258. }
  1259. /**
  1260. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1261. * items.
  1262. *
  1263. * Returns `undefined` if the item is stale, unless
  1264. * {@link LRUCache.OptionsBase.allowStale} is set.
  1265. */
  1266. peek(k, peekOptions = {}) {
  1267. const { allowStale = this.allowStale } = peekOptions;
  1268. const index = this.#keyMap.get(k);
  1269. if (index === undefined ||
  1270. (!allowStale && this.#isStale(index))) {
  1271. return;
  1272. }
  1273. const v = this.#valList[index];
  1274. // either stale and allowed, or forcing a refresh of non-stale value
  1275. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  1276. }
  1277. #backgroundFetch(k, index, options, context) {
  1278. const v = index === undefined ? undefined : this.#valList[index];
  1279. if (this.#isBackgroundFetch(v)) {
  1280. return v;
  1281. }
  1282. const ac = new AC();
  1283. const { signal } = options;
  1284. // when/if our AC signals, then stop listening to theirs.
  1285. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  1286. signal: ac.signal,
  1287. });
  1288. const fetchOpts = {
  1289. signal: ac.signal,
  1290. options,
  1291. context,
  1292. };
  1293. const cb = (v, updateCache = false) => {
  1294. const { aborted } = ac.signal;
  1295. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  1296. if (options.status) {
  1297. if (aborted && !updateCache) {
  1298. options.status.fetchAborted = true;
  1299. options.status.fetchError = ac.signal.reason;
  1300. if (ignoreAbort)
  1301. options.status.fetchAbortIgnored = true;
  1302. }
  1303. else {
  1304. options.status.fetchResolved = true;
  1305. }
  1306. }
  1307. if (aborted && !ignoreAbort && !updateCache) {
  1308. return fetchFail(ac.signal.reason);
  1309. }
  1310. // either we didn't abort, and are still here, or we did, and ignored
  1311. const bf = p;
  1312. if (this.#valList[index] === p) {
  1313. if (v === undefined) {
  1314. if (bf.__staleWhileFetching) {
  1315. this.#valList[index] = bf.__staleWhileFetching;
  1316. }
  1317. else {
  1318. this.delete(k);
  1319. }
  1320. }
  1321. else {
  1322. if (options.status)
  1323. options.status.fetchUpdated = true;
  1324. this.set(k, v, fetchOpts.options);
  1325. }
  1326. }
  1327. return v;
  1328. };
  1329. const eb = (er) => {
  1330. if (options.status) {
  1331. options.status.fetchRejected = true;
  1332. options.status.fetchError = er;
  1333. }
  1334. return fetchFail(er);
  1335. };
  1336. const fetchFail = (er) => {
  1337. const { aborted } = ac.signal;
  1338. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1339. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1340. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1341. const bf = p;
  1342. if (this.#valList[index] === p) {
  1343. // if we allow stale on fetch rejections, then we need to ensure that
  1344. // the stale value is not removed from the cache when the fetch fails.
  1345. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1346. if (del) {
  1347. this.delete(k);
  1348. }
  1349. else if (!allowStaleAborted) {
  1350. // still replace the *promise* with the stale value,
  1351. // since we are done with the promise at this point.
  1352. // leave it untouched if we're still waiting for an
  1353. // aborted background fetch that hasn't yet returned.
  1354. this.#valList[index] = bf.__staleWhileFetching;
  1355. }
  1356. }
  1357. if (allowStale) {
  1358. if (options.status && bf.__staleWhileFetching !== undefined) {
  1359. options.status.returnedStale = true;
  1360. }
  1361. return bf.__staleWhileFetching;
  1362. }
  1363. else if (bf.__returned === bf) {
  1364. throw er;
  1365. }
  1366. };
  1367. const pcall = (res, rej) => {
  1368. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1369. if (fmp && fmp instanceof Promise) {
  1370. fmp.then(v => res(v === undefined ? undefined : v), rej);
  1371. }
  1372. // ignored, we go until we finish, regardless.
  1373. // defer check until we are actually aborting,
  1374. // so fetchMethod can override.
  1375. ac.signal.addEventListener('abort', () => {
  1376. if (!options.ignoreFetchAbort ||
  1377. options.allowStaleOnFetchAbort) {
  1378. res(undefined);
  1379. // when it eventually resolves, update the cache.
  1380. if (options.allowStaleOnFetchAbort) {
  1381. res = v => cb(v, true);
  1382. }
  1383. }
  1384. });
  1385. };
  1386. if (options.status)
  1387. options.status.fetchDispatched = true;
  1388. const p = new Promise(pcall).then(cb, eb);
  1389. const bf = Object.assign(p, {
  1390. __abortController: ac,
  1391. __staleWhileFetching: v,
  1392. __returned: undefined,
  1393. });
  1394. if (index === undefined) {
  1395. // internal, don't expose status.
  1396. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1397. index = this.#keyMap.get(k);
  1398. }
  1399. else {
  1400. this.#valList[index] = bf;
  1401. }
  1402. return bf;
  1403. }
  1404. #isBackgroundFetch(p) {
  1405. if (!this.#hasFetchMethod)
  1406. return false;
  1407. const b = p;
  1408. return (!!b &&
  1409. b instanceof Promise &&
  1410. b.hasOwnProperty('__staleWhileFetching') &&
  1411. b.__abortController instanceof AC);
  1412. }
  1413. async fetch(k, fetchOptions = {}) {
  1414. const {
  1415. // get options
  1416. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1417. // set options
  1418. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1419. // fetch exclusive options
  1420. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1421. if (!this.#hasFetchMethod) {
  1422. if (status)
  1423. status.fetch = 'get';
  1424. return this.get(k, {
  1425. allowStale,
  1426. updateAgeOnGet,
  1427. noDeleteOnStaleGet,
  1428. status,
  1429. });
  1430. }
  1431. const options = {
  1432. allowStale,
  1433. updateAgeOnGet,
  1434. noDeleteOnStaleGet,
  1435. ttl,
  1436. noDisposeOnSet,
  1437. size,
  1438. sizeCalculation,
  1439. noUpdateTTL,
  1440. noDeleteOnFetchRejection,
  1441. allowStaleOnFetchRejection,
  1442. allowStaleOnFetchAbort,
  1443. ignoreFetchAbort,
  1444. status,
  1445. signal,
  1446. };
  1447. let index = this.#keyMap.get(k);
  1448. if (index === undefined) {
  1449. if (status)
  1450. status.fetch = 'miss';
  1451. const p = this.#backgroundFetch(k, index, options, context);
  1452. return (p.__returned = p);
  1453. }
  1454. else {
  1455. // in cache, maybe already fetching
  1456. const v = this.#valList[index];
  1457. if (this.#isBackgroundFetch(v)) {
  1458. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1459. if (status) {
  1460. status.fetch = 'inflight';
  1461. if (stale)
  1462. status.returnedStale = true;
  1463. }
  1464. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1465. }
  1466. // if we force a refresh, that means do NOT serve the cached value,
  1467. // unless we are already in the process of refreshing the cache.
  1468. const isStale = this.#isStale(index);
  1469. if (!forceRefresh && !isStale) {
  1470. if (status)
  1471. status.fetch = 'hit';
  1472. this.#moveToTail(index);
  1473. if (updateAgeOnGet) {
  1474. this.#updateItemAge(index);
  1475. }
  1476. if (status)
  1477. this.#statusTTL(status, index);
  1478. return v;
  1479. }
  1480. // ok, it is stale or a forced refresh, and not already fetching.
  1481. // refresh the cache.
  1482. const p = this.#backgroundFetch(k, index, options, context);
  1483. const hasStale = p.__staleWhileFetching !== undefined;
  1484. const staleVal = hasStale && allowStale;
  1485. if (status) {
  1486. status.fetch = isStale ? 'stale' : 'refresh';
  1487. if (staleVal && isStale)
  1488. status.returnedStale = true;
  1489. }
  1490. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1491. }
  1492. }
  1493. /**
  1494. * Return a value from the cache. Will update the recency of the cache
  1495. * entry found.
  1496. *
  1497. * If the key is not found, get() will return `undefined`.
  1498. */
  1499. get(k, getOptions = {}) {
  1500. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1501. const index = this.#keyMap.get(k);
  1502. if (index !== undefined) {
  1503. const value = this.#valList[index];
  1504. const fetching = this.#isBackgroundFetch(value);
  1505. if (status)
  1506. this.#statusTTL(status, index);
  1507. if (this.#isStale(index)) {
  1508. if (status)
  1509. status.get = 'stale';
  1510. // delete only if not an in-flight background fetch
  1511. if (!fetching) {
  1512. if (!noDeleteOnStaleGet) {
  1513. this.delete(k);
  1514. }
  1515. if (status && allowStale)
  1516. status.returnedStale = true;
  1517. return allowStale ? value : undefined;
  1518. }
  1519. else {
  1520. if (status &&
  1521. allowStale &&
  1522. value.__staleWhileFetching !== undefined) {
  1523. status.returnedStale = true;
  1524. }
  1525. return allowStale ? value.__staleWhileFetching : undefined;
  1526. }
  1527. }
  1528. else {
  1529. if (status)
  1530. status.get = 'hit';
  1531. // if we're currently fetching it, we don't actually have it yet
  1532. // it's not stale, which means this isn't a staleWhileRefetching.
  1533. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1534. // value, then that means the user fetched with {forceRefresh:true},
  1535. // so it's safe to return that value.
  1536. if (fetching) {
  1537. return value.__staleWhileFetching;
  1538. }
  1539. this.#moveToTail(index);
  1540. if (updateAgeOnGet) {
  1541. this.#updateItemAge(index);
  1542. }
  1543. return value;
  1544. }
  1545. }
  1546. else if (status) {
  1547. status.get = 'miss';
  1548. }
  1549. }
  1550. #connect(p, n) {
  1551. this.#prev[n] = p;
  1552. this.#next[p] = n;
  1553. }
  1554. #moveToTail(index) {
  1555. // if tail already, nothing to do
  1556. // if head, move head to next[index]
  1557. // else
  1558. // move next[prev[index]] to next[index] (head has no prev)
  1559. // move prev[next[index]] to prev[index]
  1560. // prev[index] = tail
  1561. // next[tail] = index
  1562. // tail = index
  1563. if (index !== this.#tail) {
  1564. if (index === this.#head) {
  1565. this.#head = this.#next[index];
  1566. }
  1567. else {
  1568. this.#connect(this.#prev[index], this.#next[index]);
  1569. }
  1570. this.#connect(this.#tail, index);
  1571. this.#tail = index;
  1572. }
  1573. }
  1574. /**
  1575. * Deletes a key out of the cache.
  1576. * Returns true if the key was deleted, false otherwise.
  1577. */
  1578. delete(k) {
  1579. let deleted = false;
  1580. if (this.#size !== 0) {
  1581. const index = this.#keyMap.get(k);
  1582. if (index !== undefined) {
  1583. deleted = true;
  1584. if (this.#size === 1) {
  1585. this.clear();
  1586. }
  1587. else {
  1588. this.#removeItemSize(index);
  1589. const v = this.#valList[index];
  1590. if (this.#isBackgroundFetch(v)) {
  1591. v.__abortController.abort(new Error('deleted'));
  1592. }
  1593. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1594. if (this.#hasDispose) {
  1595. this.#dispose?.(v, k, 'delete');
  1596. }
  1597. if (this.#hasDisposeAfter) {
  1598. this.#disposed?.push([v, k, 'delete']);
  1599. }
  1600. }
  1601. this.#keyMap.delete(k);
  1602. this.#keyList[index] = undefined;
  1603. this.#valList[index] = undefined;
  1604. if (index === this.#tail) {
  1605. this.#tail = this.#prev[index];
  1606. }
  1607. else if (index === this.#head) {
  1608. this.#head = this.#next[index];
  1609. }
  1610. else {
  1611. const pi = this.#prev[index];
  1612. this.#next[pi] = this.#next[index];
  1613. const ni = this.#next[index];
  1614. this.#prev[ni] = this.#prev[index];
  1615. }
  1616. this.#size--;
  1617. this.#free.push(index);
  1618. }
  1619. }
  1620. }
  1621. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1622. const dt = this.#disposed;
  1623. let task;
  1624. while ((task = dt?.shift())) {
  1625. this.#disposeAfter?.(...task);
  1626. }
  1627. }
  1628. return deleted;
  1629. }
  1630. /**
  1631. * Clear the cache entirely, throwing away all values.
  1632. */
  1633. clear() {
  1634. for (const index of this.#rindexes({ allowStale: true })) {
  1635. const v = this.#valList[index];
  1636. if (this.#isBackgroundFetch(v)) {
  1637. v.__abortController.abort(new Error('deleted'));
  1638. }
  1639. else {
  1640. const k = this.#keyList[index];
  1641. if (this.#hasDispose) {
  1642. this.#dispose?.(v, k, 'delete');
  1643. }
  1644. if (this.#hasDisposeAfter) {
  1645. this.#disposed?.push([v, k, 'delete']);
  1646. }
  1647. }
  1648. }
  1649. this.#keyMap.clear();
  1650. this.#valList.fill(undefined);
  1651. this.#keyList.fill(undefined);
  1652. if (this.#ttls && this.#starts) {
  1653. this.#ttls.fill(0);
  1654. this.#starts.fill(0);
  1655. }
  1656. if (this.#sizes) {
  1657. this.#sizes.fill(0);
  1658. }
  1659. this.#head = 0;
  1660. this.#tail = 0;
  1661. this.#free.length = 0;
  1662. this.#calculatedSize = 0;
  1663. this.#size = 0;
  1664. if (this.#hasDisposeAfter && this.#disposed) {
  1665. const dt = this.#disposed;
  1666. let task;
  1667. while ((task = dt?.shift())) {
  1668. this.#disposeAfter?.(...task);
  1669. }
  1670. }
  1671. }
  1672. }
  1673. function createCache(max = 500) {
  1674. return new LRUCache({ max });
  1675. }
  1676. function isImportUsed(local, sfc) {
  1677. return resolveTemplateUsedIdentifiers(sfc).has(local);
  1678. }
  1679. const templateUsageCheckCache = createCache();
  1680. function resolveTemplateUsedIdentifiers(sfc) {
  1681. const { content, ast } = sfc.template;
  1682. const cached = templateUsageCheckCache.get(content);
  1683. if (cached) {
  1684. return cached;
  1685. }
  1686. const ids = /* @__PURE__ */ new Set();
  1687. ast.children.forEach(walk);
  1688. function walk(node) {
  1689. var _a;
  1690. switch (node.type) {
  1691. case 1:
  1692. let tag = node.tag;
  1693. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  1694. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1695. ids.add(shared.camelize(tag));
  1696. ids.add(shared.capitalize(shared.camelize(tag)));
  1697. }
  1698. for (let i = 0; i < node.props.length; i++) {
  1699. const prop = node.props[i];
  1700. if (prop.type === 7) {
  1701. if (!shared.isBuiltInDirective(prop.name)) {
  1702. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1703. }
  1704. if (prop.arg && !prop.arg.isStatic) {
  1705. extractIdentifiers(ids, prop.arg);
  1706. }
  1707. if (prop.name === "for") {
  1708. extractIdentifiers(ids, prop.forParseResult.source);
  1709. } else if (prop.exp) {
  1710. extractIdentifiers(ids, prop.exp);
  1711. } else if (prop.name === "bind" && !prop.exp) {
  1712. ids.add(shared.camelize(prop.arg.content));
  1713. }
  1714. }
  1715. if (prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1716. ids.add(prop.value.content);
  1717. }
  1718. }
  1719. node.children.forEach(walk);
  1720. break;
  1721. case 5:
  1722. extractIdentifiers(ids, node.content);
  1723. break;
  1724. }
  1725. }
  1726. templateUsageCheckCache.set(content, ids);
  1727. return ids;
  1728. }
  1729. function extractIdentifiers(ids, node) {
  1730. if (node.ast) {
  1731. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1732. } else if (node.ast === null) {
  1733. ids.add(node.content);
  1734. }
  1735. }
  1736. const DEFAULT_FILENAME = "anonymous.vue";
  1737. const parseCache$1 = createCache();
  1738. function parse$1(source, options = {}) {
  1739. var _a;
  1740. const sourceKey = shared.genCacheKey(source, {
  1741. ...options,
  1742. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1743. });
  1744. const cache = parseCache$1.get(sourceKey);
  1745. if (cache) {
  1746. return cache;
  1747. }
  1748. const {
  1749. sourceMap = true,
  1750. filename = DEFAULT_FILENAME,
  1751. sourceRoot = "",
  1752. pad = false,
  1753. ignoreEmpty = true,
  1754. compiler = CompilerDOM__namespace,
  1755. templateParseOptions = {}
  1756. } = options;
  1757. const descriptor = {
  1758. filename,
  1759. source,
  1760. template: null,
  1761. script: null,
  1762. scriptSetup: null,
  1763. styles: [],
  1764. customBlocks: [],
  1765. cssVars: [],
  1766. slotted: false,
  1767. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1768. };
  1769. const errors = [];
  1770. const ast = compiler.parse(source, {
  1771. parseMode: "sfc",
  1772. prefixIdentifiers: true,
  1773. ...templateParseOptions,
  1774. onError: (e) => {
  1775. errors.push(e);
  1776. }
  1777. });
  1778. ast.children.forEach((node) => {
  1779. if (node.type !== 1) {
  1780. return;
  1781. }
  1782. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1783. return;
  1784. }
  1785. switch (node.tag) {
  1786. case "template":
  1787. if (!descriptor.template) {
  1788. const templateBlock = descriptor.template = createBlock(
  1789. node,
  1790. source,
  1791. false
  1792. );
  1793. if (!templateBlock.attrs.src) {
  1794. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1795. }
  1796. if (templateBlock.attrs.functional) {
  1797. const err = new SyntaxError(
  1798. `<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.`
  1799. );
  1800. err.loc = node.props.find(
  1801. (p) => p.type === 6 && p.name === "functional"
  1802. ).loc;
  1803. errors.push(err);
  1804. }
  1805. } else {
  1806. errors.push(createDuplicateBlockError(node));
  1807. }
  1808. break;
  1809. case "script":
  1810. const scriptBlock = createBlock(node, source, pad);
  1811. const isSetup = !!scriptBlock.attrs.setup;
  1812. if (isSetup && !descriptor.scriptSetup) {
  1813. descriptor.scriptSetup = scriptBlock;
  1814. break;
  1815. }
  1816. if (!isSetup && !descriptor.script) {
  1817. descriptor.script = scriptBlock;
  1818. break;
  1819. }
  1820. errors.push(createDuplicateBlockError(node, isSetup));
  1821. break;
  1822. case "style":
  1823. const styleBlock = createBlock(node, source, pad);
  1824. if (styleBlock.attrs.vars) {
  1825. errors.push(
  1826. new SyntaxError(
  1827. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1828. )
  1829. );
  1830. }
  1831. descriptor.styles.push(styleBlock);
  1832. break;
  1833. default:
  1834. descriptor.customBlocks.push(createBlock(node, source, pad));
  1835. break;
  1836. }
  1837. });
  1838. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1839. errors.push(
  1840. new SyntaxError(
  1841. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  1842. )
  1843. );
  1844. }
  1845. if (descriptor.scriptSetup) {
  1846. if (descriptor.scriptSetup.src) {
  1847. errors.push(
  1848. new SyntaxError(
  1849. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1850. )
  1851. );
  1852. descriptor.scriptSetup = null;
  1853. }
  1854. if (descriptor.script && descriptor.script.src) {
  1855. errors.push(
  1856. new SyntaxError(
  1857. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1858. )
  1859. );
  1860. descriptor.script = null;
  1861. }
  1862. }
  1863. let templateColumnOffset = 0;
  1864. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1865. [descriptor.template.content, templateColumnOffset] = dedent(
  1866. descriptor.template.content
  1867. );
  1868. }
  1869. if (sourceMap) {
  1870. const genMap = (block, columnOffset = 0) => {
  1871. if (block && !block.src) {
  1872. block.map = generateSourceMap(
  1873. filename,
  1874. source,
  1875. block.content,
  1876. sourceRoot,
  1877. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1878. columnOffset
  1879. );
  1880. }
  1881. };
  1882. genMap(descriptor.template, templateColumnOffset);
  1883. genMap(descriptor.script);
  1884. descriptor.styles.forEach((s) => genMap(s));
  1885. descriptor.customBlocks.forEach((s) => genMap(s));
  1886. }
  1887. descriptor.cssVars = parseCssVars(descriptor);
  1888. const slottedRE = /(?:::v-|:)slotted\(/;
  1889. descriptor.slotted = descriptor.styles.some(
  1890. (s) => s.scoped && slottedRE.test(s.content)
  1891. );
  1892. const result = {
  1893. descriptor,
  1894. errors
  1895. };
  1896. parseCache$1.set(sourceKey, result);
  1897. return result;
  1898. }
  1899. function createDuplicateBlockError(node, isScriptSetup = false) {
  1900. const err = new SyntaxError(
  1901. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1902. );
  1903. err.loc = node.loc;
  1904. return err;
  1905. }
  1906. function createBlock(node, source, pad) {
  1907. const type = node.tag;
  1908. const loc = node.innerLoc;
  1909. const attrs = {};
  1910. const block = {
  1911. type,
  1912. content: source.slice(loc.start.offset, loc.end.offset),
  1913. loc,
  1914. attrs
  1915. };
  1916. if (pad) {
  1917. block.content = padContent(source, block, pad) + block.content;
  1918. }
  1919. node.props.forEach((p) => {
  1920. if (p.type === 6) {
  1921. const name = p.name;
  1922. attrs[name] = p.value ? p.value.content || true : true;
  1923. if (name === "lang") {
  1924. block.lang = p.value && p.value.content;
  1925. } else if (name === "src") {
  1926. block.src = p.value && p.value.content;
  1927. } else if (type === "style") {
  1928. if (name === "scoped") {
  1929. block.scoped = true;
  1930. } else if (name === "module") {
  1931. block.module = attrs[name];
  1932. }
  1933. } else if (type === "script" && name === "setup") {
  1934. block.setup = attrs.setup;
  1935. }
  1936. }
  1937. });
  1938. return block;
  1939. }
  1940. const splitRE = /\r?\n/g;
  1941. const emptyRE = /^(?:\/\/)?\s*$/;
  1942. const replaceRE = /./g;
  1943. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  1944. const map = new sourceMapJs.SourceMapGenerator({
  1945. file: filename.replace(/\\/g, "/"),
  1946. sourceRoot: sourceRoot.replace(/\\/g, "/")
  1947. });
  1948. map.setSourceContent(filename, source);
  1949. map._sources.add(filename);
  1950. generated.split(splitRE).forEach((line, index) => {
  1951. if (!emptyRE.test(line)) {
  1952. const originalLine = index + 1 + lineOffset;
  1953. const generatedLine = index + 1;
  1954. for (let i = 0; i < line.length; i++) {
  1955. if (!/\s/.test(line[i])) {
  1956. map._mappings.add({
  1957. originalLine,
  1958. originalColumn: i + columnOffset,
  1959. generatedLine,
  1960. generatedColumn: i,
  1961. source: filename,
  1962. name: null
  1963. });
  1964. }
  1965. }
  1966. }
  1967. });
  1968. return map.toJSON();
  1969. }
  1970. function padContent(content, block, pad) {
  1971. content = content.slice(0, block.loc.start.offset);
  1972. if (pad === "space") {
  1973. return content.replace(replaceRE, " ");
  1974. } else {
  1975. const offset = content.split(splitRE).length;
  1976. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  1977. return Array(offset).join(padChar);
  1978. }
  1979. }
  1980. function hasSrc(node) {
  1981. return node.props.some((p) => {
  1982. if (p.type !== 6) {
  1983. return false;
  1984. }
  1985. return p.name === "src";
  1986. });
  1987. }
  1988. function isEmpty(node) {
  1989. for (let i = 0; i < node.children.length; i++) {
  1990. const child = node.children[i];
  1991. if (child.type !== 2 || child.content.trim() !== "") {
  1992. return false;
  1993. }
  1994. }
  1995. return true;
  1996. }
  1997. function hmrShouldReload(prevImports, next) {
  1998. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  1999. return false;
  2000. }
  2001. for (const key in prevImports) {
  2002. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2003. return true;
  2004. }
  2005. }
  2006. return false;
  2007. }
  2008. function dedent(s) {
  2009. const lines = s.split("\n");
  2010. const minIndent = lines.reduce(function(minIndent2, line) {
  2011. var _a, _b;
  2012. if (line.trim() === "") {
  2013. return minIndent2;
  2014. }
  2015. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2016. return Math.min(indent, minIndent2);
  2017. }, Infinity);
  2018. if (minIndent === 0) {
  2019. return [s, minIndent];
  2020. }
  2021. return [
  2022. lines.map(function(line) {
  2023. return line.slice(minIndent);
  2024. }).join("\n"),
  2025. minIndent
  2026. ];
  2027. }
  2028. function isRelativeUrl(url) {
  2029. const firstChar = url.charAt(0);
  2030. return firstChar === "." || firstChar === "~" || firstChar === "@";
  2031. }
  2032. const externalRE = /^(https?:)?\/\//;
  2033. function isExternalUrl(url) {
  2034. return externalRE.test(url);
  2035. }
  2036. const dataUrlRE = /^\s*data:/i;
  2037. function isDataUrl(url) {
  2038. return dataUrlRE.test(url);
  2039. }
  2040. function parseUrl(url) {
  2041. const firstChar = url.charAt(0);
  2042. if (firstChar === "~") {
  2043. const secondChar = url.charAt(1);
  2044. url = url.slice(secondChar === "/" ? 2 : 1);
  2045. }
  2046. return parseUriParts(url);
  2047. }
  2048. function parseUriParts(urlString) {
  2049. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2050. }
  2051. const defaultAssetUrlOptions = {
  2052. base: null,
  2053. includeAbsolute: false,
  2054. tags: {
  2055. video: ["src", "poster"],
  2056. source: ["src"],
  2057. img: ["src"],
  2058. image: ["xlink:href", "href"],
  2059. use: ["xlink:href", "href"]
  2060. }
  2061. };
  2062. const normalizeOptions = (options) => {
  2063. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2064. return {
  2065. ...defaultAssetUrlOptions,
  2066. tags: options
  2067. };
  2068. }
  2069. return {
  2070. ...defaultAssetUrlOptions,
  2071. ...options
  2072. };
  2073. };
  2074. const createAssetUrlTransformWithOptions = (options) => {
  2075. return (node, context) => transformAssetUrl(node, context, options);
  2076. };
  2077. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2078. if (node.type === 1) {
  2079. if (!node.props.length) {
  2080. return;
  2081. }
  2082. const tags = options.tags || defaultAssetUrlOptions.tags;
  2083. const attrs = tags[node.tag];
  2084. const wildCardAttrs = tags["*"];
  2085. if (!attrs && !wildCardAttrs) {
  2086. return;
  2087. }
  2088. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2089. node.props.forEach((attr, index) => {
  2090. 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)) {
  2091. return;
  2092. }
  2093. const url = parseUrl(attr.value.content);
  2094. if (options.base && attr.value.content[0] === ".") {
  2095. const base = parseUrl(options.base);
  2096. const protocol = base.protocol || "";
  2097. const host = base.host ? protocol + "//" + base.host : "";
  2098. const basePath = base.path || "/";
  2099. attr.value.content = host + (path$1.posix || path$1).join(basePath, url.path + (url.hash || ""));
  2100. return;
  2101. }
  2102. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2103. node.props[index] = {
  2104. type: 7,
  2105. name: "bind",
  2106. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2107. exp,
  2108. modifiers: [],
  2109. loc: attr.loc
  2110. };
  2111. });
  2112. }
  2113. };
  2114. function getImportsExpressionExp(path2, hash, loc, context) {
  2115. if (path2) {
  2116. let name;
  2117. let exp;
  2118. const existingIndex = context.imports.findIndex((i) => i.path === path2);
  2119. if (existingIndex > -1) {
  2120. name = `_imports_${existingIndex}`;
  2121. exp = context.imports[existingIndex].exp;
  2122. } else {
  2123. name = `_imports_${context.imports.length}`;
  2124. exp = compilerCore.createSimpleExpression(
  2125. name,
  2126. false,
  2127. loc,
  2128. 3
  2129. );
  2130. context.imports.push({
  2131. exp,
  2132. path: decodeURIComponent(path2)
  2133. });
  2134. }
  2135. if (!hash) {
  2136. return exp;
  2137. }
  2138. const hashExp = `${name} + '${hash}'`;
  2139. const finalExp = compilerCore.createSimpleExpression(
  2140. hashExp,
  2141. false,
  2142. loc,
  2143. 3
  2144. );
  2145. if (!context.hoistStatic) {
  2146. return finalExp;
  2147. }
  2148. const existingHoistIndex = context.hoists.findIndex((h) => {
  2149. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2150. });
  2151. if (existingHoistIndex > -1) {
  2152. return compilerCore.createSimpleExpression(
  2153. `_hoisted_${existingHoistIndex + 1}`,
  2154. false,
  2155. loc,
  2156. 3
  2157. );
  2158. }
  2159. return context.hoist(finalExp);
  2160. } else {
  2161. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2162. }
  2163. }
  2164. const srcsetTags = ["img", "source"];
  2165. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2166. const createSrcsetTransformWithOptions = (options) => {
  2167. return (node, context) => transformSrcset(node, context, options);
  2168. };
  2169. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2170. if (node.type === 1) {
  2171. if (srcsetTags.includes(node.tag) && node.props.length) {
  2172. node.props.forEach((attr, index) => {
  2173. if (attr.name === "srcset" && attr.type === 6) {
  2174. if (!attr.value) return;
  2175. const value = attr.value.content;
  2176. if (!value) return;
  2177. const imageCandidates = value.split(",").map((s) => {
  2178. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2179. return { url, descriptor };
  2180. });
  2181. for (let i = 0; i < imageCandidates.length; i++) {
  2182. const { url } = imageCandidates[i];
  2183. if (isDataUrl(url)) {
  2184. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2185. imageCandidates.splice(i, 1);
  2186. }
  2187. }
  2188. const shouldProcessUrl = (url) => {
  2189. return !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2190. };
  2191. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2192. return;
  2193. }
  2194. if (options.base) {
  2195. const base = options.base;
  2196. const set = [];
  2197. let needImportTransform = false;
  2198. imageCandidates.forEach((candidate) => {
  2199. let { url, descriptor } = candidate;
  2200. descriptor = descriptor ? ` ${descriptor}` : ``;
  2201. if (url[0] === ".") {
  2202. candidate.url = (path$1.posix || path$1).join(base, url);
  2203. set.push(candidate.url + descriptor);
  2204. } else if (shouldProcessUrl(url)) {
  2205. needImportTransform = true;
  2206. } else {
  2207. set.push(url + descriptor);
  2208. }
  2209. });
  2210. if (!needImportTransform) {
  2211. attr.value.content = set.join(", ");
  2212. return;
  2213. }
  2214. }
  2215. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2216. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2217. if (shouldProcessUrl(url)) {
  2218. const { path: path2 } = parseUrl(url);
  2219. let exp2;
  2220. if (path2) {
  2221. const existingImportsIndex = context.imports.findIndex(
  2222. (i) => i.path === path2
  2223. );
  2224. if (existingImportsIndex > -1) {
  2225. exp2 = compilerCore.createSimpleExpression(
  2226. `_imports_${existingImportsIndex}`,
  2227. false,
  2228. attr.loc,
  2229. 3
  2230. );
  2231. } else {
  2232. exp2 = compilerCore.createSimpleExpression(
  2233. `_imports_${context.imports.length}`,
  2234. false,
  2235. attr.loc,
  2236. 3
  2237. );
  2238. context.imports.push({ exp: exp2, path: path2 });
  2239. }
  2240. compoundExpression.children.push(exp2);
  2241. }
  2242. } else {
  2243. const exp2 = compilerCore.createSimpleExpression(
  2244. `"${url}"`,
  2245. false,
  2246. attr.loc,
  2247. 3
  2248. );
  2249. compoundExpression.children.push(exp2);
  2250. }
  2251. const isNotLast = imageCandidates.length - 1 > index2;
  2252. if (descriptor && isNotLast) {
  2253. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2254. } else if (descriptor) {
  2255. compoundExpression.children.push(` + ' ${descriptor}'`);
  2256. } else if (isNotLast) {
  2257. compoundExpression.children.push(` + ', ' + `);
  2258. }
  2259. });
  2260. let exp = compoundExpression;
  2261. if (context.hoistStatic) {
  2262. exp = context.hoist(compoundExpression);
  2263. exp.constType = 3;
  2264. }
  2265. node.props[index] = {
  2266. type: 7,
  2267. name: "bind",
  2268. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2269. exp,
  2270. modifiers: [],
  2271. loc: attr.loc
  2272. };
  2273. }
  2274. });
  2275. }
  2276. }
  2277. };
  2278. function commonjsRequire(path) {
  2279. 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.');
  2280. }
  2281. var consolidate$2 = {exports: {}};
  2282. var hasRequiredConsolidate$1;
  2283. function requireConsolidate$1 () {
  2284. if (hasRequiredConsolidate$1) return consolidate$2.exports;
  2285. hasRequiredConsolidate$1 = 1;
  2286. (function (module, exports) {
  2287. /*
  2288. * Engines which do not support caching of their file contents
  2289. * should use the `read()` function defined in consolidate.js
  2290. * On top of this, when an engine compiles to a `Function`,
  2291. * these functions should either be cached within consolidate.js
  2292. * or the engine itself via `options.cache`. This will allow
  2293. * users and frameworks to pass `options.cache = true` for
  2294. * `NODE_ENV=production`, however edit the file(s) without
  2295. * re-loading the application in development.
  2296. */
  2297. /**
  2298. * Module dependencies.
  2299. */
  2300. var fs = require$$0;
  2301. var path = path$1;
  2302. var util = require$$2;
  2303. var join = path.join;
  2304. var resolve = path.resolve;
  2305. var extname = path.extname;
  2306. var dirname = path.dirname;
  2307. var isAbsolute = path.isAbsolute;
  2308. var readCache = {};
  2309. /**
  2310. * Require cache.
  2311. */
  2312. var cacheStore = {};
  2313. /**
  2314. * Require cache.
  2315. */
  2316. var requires = {};
  2317. /**
  2318. * Clear the cache.
  2319. *
  2320. * @api public
  2321. */
  2322. exports.clearCache = function() {
  2323. readCache = {};
  2324. cacheStore = {};
  2325. };
  2326. /**
  2327. * Conditionally cache `compiled` template based
  2328. * on the `options` filename and `.cache` boolean.
  2329. *
  2330. * @param {Object} options
  2331. * @param {Function} compiled
  2332. * @return {Function}
  2333. * @api private
  2334. */
  2335. function cache(options, compiled) {
  2336. // cachable
  2337. if (compiled && options.filename && options.cache) {
  2338. delete readCache[options.filename];
  2339. cacheStore[options.filename] = compiled;
  2340. return compiled;
  2341. }
  2342. // check cache
  2343. if (options.filename && options.cache) {
  2344. return cacheStore[options.filename];
  2345. }
  2346. return compiled;
  2347. }
  2348. /**
  2349. * Read `path` with `options` with
  2350. * callback `(err, str)`. When `options.cache`
  2351. * is true the template string will be cached.
  2352. *
  2353. * @param {String} options
  2354. * @param {Function} cb
  2355. * @api private
  2356. */
  2357. function read(path, options, cb) {
  2358. var str = readCache[path];
  2359. var cached = options.cache && str && typeof str === 'string';
  2360. // cached (only if cached is a string and not a compiled template function)
  2361. if (cached) return cb(null, str);
  2362. // read
  2363. fs.readFile(path, 'utf8', function(err, str) {
  2364. if (err) return cb(err);
  2365. // remove extraneous utf8 BOM marker
  2366. str = str.replace(/^\uFEFF/, '');
  2367. if (options.cache) readCache[path] = str;
  2368. cb(null, str);
  2369. });
  2370. }
  2371. /**
  2372. * Read `path` with `options` with
  2373. * callback `(err, str)`. When `options.cache`
  2374. * is true the partial string will be cached.
  2375. *
  2376. * @param {String} options
  2377. * @param {Function} fn
  2378. * @api private
  2379. */
  2380. function readPartials(path, options, cb) {
  2381. if (!options.partials) return cb();
  2382. var keys = Object.keys(options.partials);
  2383. var partials = {};
  2384. function next(index) {
  2385. if (index === keys.length) return cb(null, partials);
  2386. var key = keys[index];
  2387. var partialPath = options.partials[key];
  2388. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2389. return next(++index);
  2390. }
  2391. var file;
  2392. if (isAbsolute(partialPath)) {
  2393. if (extname(partialPath) !== '') {
  2394. file = partialPath;
  2395. } else {
  2396. file = join(partialPath + extname(path));
  2397. }
  2398. } else {
  2399. file = join(dirname(path), partialPath + extname(path));
  2400. }
  2401. read(file, options, function(err, str) {
  2402. if (err) return cb(err);
  2403. partials[key] = str;
  2404. next(++index);
  2405. });
  2406. }
  2407. next(0);
  2408. }
  2409. /**
  2410. * promisify
  2411. */
  2412. function promisify(cb, fn) {
  2413. return new Promise(function(resolve, reject) {
  2414. cb = cb || function(err, html) {
  2415. if (err) {
  2416. return reject(err);
  2417. }
  2418. resolve(html);
  2419. };
  2420. fn(cb);
  2421. });
  2422. }
  2423. /**
  2424. * fromStringRenderer
  2425. */
  2426. function fromStringRenderer(name) {
  2427. return function(path, options, cb) {
  2428. options.filename = path;
  2429. return promisify(cb, function(cb) {
  2430. readPartials(path, options, function(err, partials) {
  2431. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2432. var opts = extend({}, options);
  2433. opts.partials = partials;
  2434. if (err) return cb(err);
  2435. if (cache(opts)) {
  2436. exports[name].render('', opts, cb);
  2437. } else {
  2438. read(path, opts, function(err, str) {
  2439. if (err) return cb(err);
  2440. exports[name].render(str, opts, cb);
  2441. });
  2442. }
  2443. });
  2444. });
  2445. };
  2446. }
  2447. /**
  2448. * velocity support.
  2449. */
  2450. exports.velocityjs = fromStringRenderer('velocityjs');
  2451. /**
  2452. * velocity string support.
  2453. */
  2454. exports.velocityjs.render = function(str, options, cb) {
  2455. return promisify(cb, function(cb) {
  2456. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2457. try {
  2458. options.locals = options;
  2459. cb(null, engine.render(str, options).trimLeft());
  2460. } catch (err) {
  2461. cb(err);
  2462. }
  2463. });
  2464. };
  2465. /**
  2466. * Liquid support.
  2467. */
  2468. exports.liquid = fromStringRenderer('liquid');
  2469. /**
  2470. * Liquid string support.
  2471. */
  2472. /**
  2473. * Note that in order to get filters and custom tags we've had to push
  2474. * all user-defined locals down into @locals. However, just to make things
  2475. * backwards-compatible, any property of `options` that is left after
  2476. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2477. * `includeDir` will also become a local.
  2478. */
  2479. function _renderTinyliquid(engine, str, options, cb) {
  2480. var context = engine.newContext();
  2481. var k;
  2482. /**
  2483. * Note that there's a bug in the library that doesn't allow us to pass
  2484. * the locals to newContext(), hence looping through the keys:
  2485. */
  2486. if (options.locals) {
  2487. for (k in options.locals) {
  2488. context.setLocals(k, options.locals[k]);
  2489. }
  2490. delete options.locals;
  2491. }
  2492. if (options.meta) {
  2493. context.setLocals('page', options.meta);
  2494. delete options.meta;
  2495. }
  2496. /**
  2497. * Add any defined filters:
  2498. */
  2499. if (options.filters) {
  2500. for (k in options.filters) {
  2501. context.setFilter(k, options.filters[k]);
  2502. }
  2503. delete options.filters;
  2504. }
  2505. /**
  2506. * Set up a callback for the include directory:
  2507. */
  2508. var includeDir = options.includeDir || process.cwd();
  2509. context.onInclude(function(name, callback) {
  2510. var extname = path.extname(name) ? '' : '.liquid';
  2511. var filename = path.resolve(includeDir, name + extname);
  2512. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2513. if (err) return callback(err);
  2514. callback(null, engine.parse(data));
  2515. });
  2516. });
  2517. delete options.includeDir;
  2518. /**
  2519. * The custom tag functions need to have their results pushed back
  2520. * through the parser, so set up a shim before calling the provided
  2521. * callback:
  2522. */
  2523. var compileOptions = {
  2524. customTags: {}
  2525. };
  2526. if (options.customTags) {
  2527. var tagFunctions = options.customTags;
  2528. for (k in options.customTags) {
  2529. /*Tell jshint there's no problem with having this function in the loop */
  2530. /*jshint -W083 */
  2531. compileOptions.customTags[k] = function(context, name, body) {
  2532. var tpl = tagFunctions[name](body.trim());
  2533. context.astStack.push(engine.parse(tpl));
  2534. };
  2535. /*jshint +W083 */
  2536. }
  2537. delete options.customTags;
  2538. }
  2539. /**
  2540. * Now anything left in `options` becomes a local:
  2541. */
  2542. for (k in options) {
  2543. context.setLocals(k, options[k]);
  2544. }
  2545. /**
  2546. * Finally, execute the template:
  2547. */
  2548. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2549. tmpl(context, cb);
  2550. }
  2551. exports.liquid.render = function(str, options, cb) {
  2552. return promisify(cb, function(cb) {
  2553. var engine = requires.liquid;
  2554. var Liquid;
  2555. try {
  2556. // set up tinyliquid engine
  2557. engine = requires.liquid = require('tinyliquid');
  2558. // use tinyliquid engine
  2559. _renderTinyliquid(engine, str, options, cb);
  2560. return;
  2561. } catch (err) {
  2562. // set up liquid-node engine
  2563. try {
  2564. Liquid = requires.liquid = require('liquid-node');
  2565. engine = new Liquid.Engine();
  2566. } catch (err) {
  2567. throw err;
  2568. }
  2569. }
  2570. // use liquid-node engine
  2571. try {
  2572. var locals = options.locals || {};
  2573. if (options.meta) {
  2574. locals.pages = options.meta;
  2575. delete options.meta;
  2576. }
  2577. /**
  2578. * Add any defined filters:
  2579. */
  2580. if (options.filters) {
  2581. engine.registerFilters(options.filters);
  2582. delete options.filters;
  2583. }
  2584. /**
  2585. * Set up a callback for the include directory:
  2586. */
  2587. var includeDir = options.includeDir || process.cwd();
  2588. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2589. delete options.includeDir;
  2590. /**
  2591. * The custom tag functions need to have their results pushed back
  2592. * through the parser, so set up a shim before calling the provided
  2593. * callback:
  2594. */
  2595. if (options.customTags) {
  2596. var tagFunctions = options.customTags;
  2597. for (k in options.customTags) {
  2598. engine.registerTag(k, tagFunctions[k]);
  2599. }
  2600. delete options.customTags;
  2601. }
  2602. /**
  2603. * Now anything left in `options` becomes a local:
  2604. */
  2605. for (var k in options) {
  2606. locals[k] = options[k];
  2607. }
  2608. /**
  2609. * Finally, execute the template:
  2610. */
  2611. return engine
  2612. .parseAndRender(str, locals)
  2613. .nodeify(function(err, result) {
  2614. if (err) {
  2615. throw new Error(err);
  2616. } else {
  2617. return cb(null, result);
  2618. }
  2619. });
  2620. } catch (err) {
  2621. cb(err);
  2622. }
  2623. });
  2624. };
  2625. /**
  2626. * Jade support.
  2627. */
  2628. exports.jade = function(path, options, cb) {
  2629. return promisify(cb, function(cb) {
  2630. var engine = requires.jade;
  2631. if (!engine) {
  2632. try {
  2633. engine = requires.jade = require('jade');
  2634. } catch (err) {
  2635. try {
  2636. engine = requires.jade = require('then-jade');
  2637. } catch (otherError) {
  2638. throw err;
  2639. }
  2640. }
  2641. }
  2642. try {
  2643. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2644. cb(null, tmpl(options));
  2645. } catch (err) {
  2646. cb(err);
  2647. }
  2648. });
  2649. };
  2650. /**
  2651. * Jade string support.
  2652. */
  2653. exports.jade.render = function(str, options, cb) {
  2654. return promisify(cb, function(cb) {
  2655. var engine = requires.jade;
  2656. if (!engine) {
  2657. try {
  2658. engine = requires.jade = require('jade');
  2659. } catch (err) {
  2660. try {
  2661. engine = requires.jade = require('then-jade');
  2662. } catch (otherError) {
  2663. throw err;
  2664. }
  2665. }
  2666. }
  2667. try {
  2668. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2669. cb(null, tmpl(options));
  2670. } catch (err) {
  2671. cb(err);
  2672. }
  2673. });
  2674. };
  2675. /**
  2676. * Dust support.
  2677. */
  2678. exports.dust = fromStringRenderer('dust');
  2679. /**
  2680. * Dust string support.
  2681. */
  2682. exports.dust.render = function(str, options, cb) {
  2683. return promisify(cb, function(cb) {
  2684. var engine = requires.dust;
  2685. if (!engine) {
  2686. try {
  2687. engine = requires.dust = require('dust');
  2688. } catch (err) {
  2689. try {
  2690. engine = requires.dust = require('dustjs-helpers');
  2691. } catch (err) {
  2692. engine = requires.dust = require('dustjs-linkedin');
  2693. }
  2694. }
  2695. }
  2696. var ext = 'dust';
  2697. var views = '.';
  2698. if (options) {
  2699. if (options.ext) ext = options.ext;
  2700. if (options.views) views = options.views;
  2701. if (options.settings && options.settings.views) views = options.settings.views;
  2702. }
  2703. if (!options || (options && !options.cache)) engine.cache = {};
  2704. engine.onLoad = function(path, callback) {
  2705. if (extname(path) === '') path += '.' + ext;
  2706. if (path[0] !== '/') path = views + '/' + path;
  2707. read(path, options, callback);
  2708. };
  2709. try {
  2710. var templateName;
  2711. if (options.filename) {
  2712. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2713. }
  2714. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2715. tmpl(options, cb);
  2716. } catch (err) {
  2717. cb(err);
  2718. }
  2719. });
  2720. };
  2721. /**
  2722. * Swig support.
  2723. */
  2724. exports.swig = fromStringRenderer('swig');
  2725. /**
  2726. * Swig string support.
  2727. */
  2728. exports.swig.render = function(str, options, cb) {
  2729. return promisify(cb, function(cb) {
  2730. var engine = requires.swig;
  2731. if (!engine) {
  2732. try {
  2733. engine = requires.swig = require('swig');
  2734. } catch (err) {
  2735. try {
  2736. engine = requires.swig = require('swig-templates');
  2737. } catch (otherError) {
  2738. throw err;
  2739. }
  2740. }
  2741. }
  2742. try {
  2743. if (options.cache === true) options.cache = 'memory';
  2744. engine.setDefaults({ cache: options.cache });
  2745. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2746. cb(null, tmpl(options));
  2747. } catch (err) {
  2748. cb(err);
  2749. }
  2750. });
  2751. };
  2752. /**
  2753. * Razor support.
  2754. */
  2755. exports.razor = function(path, options, cb) {
  2756. return promisify(cb, function(cb) {
  2757. var engine = requires.razor;
  2758. if (!engine) {
  2759. try {
  2760. engine = requires.razor = require('razor-tmpl');
  2761. } catch (err) {
  2762. throw err;
  2763. }
  2764. }
  2765. try {
  2766. var tmpl = cache(options) || cache(options, (locals) => {
  2767. console.log('Rendering razor file', path);
  2768. return engine.renderFileSync(path, locals);
  2769. });
  2770. cb(null, tmpl(options));
  2771. } catch (err) {
  2772. cb(err);
  2773. }
  2774. });
  2775. };
  2776. /**
  2777. * razor string support.
  2778. */
  2779. exports.razor.render = function(str, options, cb) {
  2780. return promisify(cb, function(cb) {
  2781. try {
  2782. var engine = requires.razor = require('razor-tmpl');
  2783. } catch (err) {
  2784. throw err;
  2785. }
  2786. try {
  2787. var tf = engine.compile(str);
  2788. var tmpl = cache(options) || cache(options, tf);
  2789. cb(null, tmpl(options));
  2790. } catch (err) {
  2791. cb(err);
  2792. }
  2793. });
  2794. };
  2795. /**
  2796. * Atpl support.
  2797. */
  2798. exports.atpl = fromStringRenderer('atpl');
  2799. /**
  2800. * Atpl string support.
  2801. */
  2802. exports.atpl.render = function(str, options, cb) {
  2803. return promisify(cb, function(cb) {
  2804. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2805. try {
  2806. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2807. cb(null, tmpl(options));
  2808. } catch (err) {
  2809. cb(err);
  2810. }
  2811. });
  2812. };
  2813. /**
  2814. * Liquor support,
  2815. */
  2816. exports.liquor = fromStringRenderer('liquor');
  2817. /**
  2818. * Liquor string support.
  2819. */
  2820. exports.liquor.render = function(str, options, cb) {
  2821. return promisify(cb, function(cb) {
  2822. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2823. try {
  2824. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2825. cb(null, tmpl(options));
  2826. } catch (err) {
  2827. cb(err);
  2828. }
  2829. });
  2830. };
  2831. /**
  2832. * Twig support.
  2833. */
  2834. exports.twig = fromStringRenderer('twig');
  2835. /**
  2836. * Twig string support.
  2837. */
  2838. exports.twig.render = function(str, options, cb) {
  2839. return promisify(cb, function(cb) {
  2840. var engine = requires.twig || (requires.twig = require('twig').twig);
  2841. var templateData = {
  2842. data: str,
  2843. allowInlineIncludes: options.allowInlineIncludes,
  2844. namespaces: options.namespaces,
  2845. path: options.path
  2846. };
  2847. try {
  2848. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2849. cb(null, tmpl.render(options));
  2850. } catch (err) {
  2851. cb(err);
  2852. }
  2853. });
  2854. };
  2855. /**
  2856. * EJS support.
  2857. */
  2858. exports.ejs = fromStringRenderer('ejs');
  2859. /**
  2860. * EJS string support.
  2861. */
  2862. exports.ejs.render = function(str, options, cb) {
  2863. return promisify(cb, function(cb) {
  2864. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2865. try {
  2866. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2867. cb(null, tmpl(options));
  2868. } catch (err) {
  2869. cb(err);
  2870. }
  2871. });
  2872. };
  2873. /**
  2874. * Eco support.
  2875. */
  2876. exports.eco = fromStringRenderer('eco');
  2877. /**
  2878. * Eco string support.
  2879. */
  2880. exports.eco.render = function(str, options, cb) {
  2881. return promisify(cb, function(cb) {
  2882. var engine = requires.eco || (requires.eco = require('eco'));
  2883. try {
  2884. cb(null, engine.render(str, options));
  2885. } catch (err) {
  2886. cb(err);
  2887. }
  2888. });
  2889. };
  2890. /**
  2891. * Jazz support.
  2892. */
  2893. exports.jazz = fromStringRenderer('jazz');
  2894. /**
  2895. * Jazz string support.
  2896. */
  2897. exports.jazz.render = function(str, options, cb) {
  2898. return promisify(cb, function(cb) {
  2899. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2900. try {
  2901. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2902. tmpl.eval(options, function(str) {
  2903. cb(null, str);
  2904. });
  2905. } catch (err) {
  2906. cb(err);
  2907. }
  2908. });
  2909. };
  2910. /**
  2911. * JQTPL support.
  2912. */
  2913. exports.jqtpl = fromStringRenderer('jqtpl');
  2914. /**
  2915. * JQTPL string support.
  2916. */
  2917. exports.jqtpl.render = function(str, options, cb) {
  2918. return promisify(cb, function(cb) {
  2919. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2920. try {
  2921. engine.template(str, str);
  2922. cb(null, engine.tmpl(str, options));
  2923. } catch (err) {
  2924. cb(err);
  2925. }
  2926. });
  2927. };
  2928. /**
  2929. * Haml support.
  2930. */
  2931. exports.haml = fromStringRenderer('haml');
  2932. /**
  2933. * Haml string support.
  2934. */
  2935. exports.haml.render = function(str, options, cb) {
  2936. return promisify(cb, function(cb) {
  2937. var engine = requires.haml || (requires.haml = require('hamljs'));
  2938. try {
  2939. options.locals = options;
  2940. cb(null, engine.render(str, options).trimLeft());
  2941. } catch (err) {
  2942. cb(err);
  2943. }
  2944. });
  2945. };
  2946. /**
  2947. * Hamlet support.
  2948. */
  2949. exports.hamlet = fromStringRenderer('hamlet');
  2950. /**
  2951. * Hamlet string support.
  2952. */
  2953. exports.hamlet.render = function(str, options, cb) {
  2954. return promisify(cb, function(cb) {
  2955. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  2956. try {
  2957. options.locals = options;
  2958. cb(null, engine.render(str, options).trimLeft());
  2959. } catch (err) {
  2960. cb(err);
  2961. }
  2962. });
  2963. };
  2964. /**
  2965. * Whiskers support.
  2966. */
  2967. exports.whiskers = function(path, options, cb) {
  2968. return promisify(cb, function(cb) {
  2969. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  2970. engine.__express(path, options, cb);
  2971. });
  2972. };
  2973. /**
  2974. * Whiskers string support.
  2975. */
  2976. exports.whiskers.render = function(str, options, cb) {
  2977. return promisify(cb, function(cb) {
  2978. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  2979. try {
  2980. cb(null, engine.render(str, options));
  2981. } catch (err) {
  2982. cb(err);
  2983. }
  2984. });
  2985. };
  2986. /**
  2987. * Coffee-HAML support.
  2988. */
  2989. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  2990. /**
  2991. * Coffee-HAML string support.
  2992. */
  2993. exports['haml-coffee'].render = function(str, options, cb) {
  2994. return promisify(cb, function(cb) {
  2995. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  2996. try {
  2997. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2998. cb(null, tmpl(options));
  2999. } catch (err) {
  3000. cb(err);
  3001. }
  3002. });
  3003. };
  3004. /**
  3005. * Hogan support.
  3006. */
  3007. exports.hogan = fromStringRenderer('hogan');
  3008. /**
  3009. * Hogan string support.
  3010. */
  3011. exports.hogan.render = function(str, options, cb) {
  3012. return promisify(cb, function(cb) {
  3013. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3014. try {
  3015. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3016. cb(null, tmpl.render(options, options.partials));
  3017. } catch (err) {
  3018. cb(err);
  3019. }
  3020. });
  3021. };
  3022. /**
  3023. * templayed.js support.
  3024. */
  3025. exports.templayed = fromStringRenderer('templayed');
  3026. /**
  3027. * templayed.js string support.
  3028. */
  3029. exports.templayed.render = function(str, options, cb) {
  3030. return promisify(cb, function(cb) {
  3031. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3032. try {
  3033. var tmpl = cache(options) || cache(options, engine(str));
  3034. cb(null, tmpl(options));
  3035. } catch (err) {
  3036. cb(err);
  3037. }
  3038. });
  3039. };
  3040. /**
  3041. * Handlebars support.
  3042. */
  3043. exports.handlebars = fromStringRenderer('handlebars');
  3044. /**
  3045. * Handlebars string support.
  3046. */
  3047. exports.handlebars.render = function(str, options, cb) {
  3048. return promisify(cb, function(cb) {
  3049. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3050. try {
  3051. for (var partial in options.partials) {
  3052. engine.registerPartial(partial, options.partials[partial]);
  3053. }
  3054. for (var helper in options.helpers) {
  3055. engine.registerHelper(helper, options.helpers[helper]);
  3056. }
  3057. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3058. cb(null, tmpl(options));
  3059. } catch (err) {
  3060. cb(err);
  3061. }
  3062. });
  3063. };
  3064. /**
  3065. * Underscore support.
  3066. */
  3067. exports.underscore = fromStringRenderer('underscore');
  3068. /**
  3069. * Underscore string support.
  3070. */
  3071. exports.underscore.render = function(str, options, cb) {
  3072. return promisify(cb, function(cb) {
  3073. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3074. try {
  3075. const partials = {};
  3076. for (var partial in options.partials) {
  3077. partials[partial] = engine.template(options.partials[partial]);
  3078. }
  3079. options.partials = partials;
  3080. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3081. cb(null, tmpl(options).replace(/\n$/, ''));
  3082. } catch (err) {
  3083. cb(err);
  3084. }
  3085. });
  3086. };
  3087. /**
  3088. * Lodash support.
  3089. */
  3090. exports.lodash = fromStringRenderer('lodash');
  3091. /**
  3092. * Lodash string support.
  3093. */
  3094. exports.lodash.render = function(str, options, cb) {
  3095. return promisify(cb, function(cb) {
  3096. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3097. try {
  3098. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3099. cb(null, tmpl(options).replace(/\n$/, ''));
  3100. } catch (err) {
  3101. cb(err);
  3102. }
  3103. });
  3104. };
  3105. /**
  3106. * Pug support. (formerly Jade)
  3107. */
  3108. exports.pug = function(path, options, cb) {
  3109. return promisify(cb, function(cb) {
  3110. var engine = requires.pug;
  3111. if (!engine) {
  3112. try {
  3113. engine = requires.pug = require('pug');
  3114. } catch (err) {
  3115. try {
  3116. engine = requires.pug = require('then-pug');
  3117. } catch (otherError) {
  3118. throw err;
  3119. }
  3120. }
  3121. }
  3122. try {
  3123. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3124. cb(null, tmpl(options));
  3125. } catch (err) {
  3126. cb(err);
  3127. }
  3128. });
  3129. };
  3130. /**
  3131. * Pug string support.
  3132. */
  3133. exports.pug.render = function(str, options, cb) {
  3134. return promisify(cb, function(cb) {
  3135. var engine = requires.pug;
  3136. if (!engine) {
  3137. try {
  3138. engine = requires.pug = require('pug');
  3139. } catch (err) {
  3140. try {
  3141. engine = requires.pug = require('then-pug');
  3142. } catch (otherError) {
  3143. throw err;
  3144. }
  3145. }
  3146. }
  3147. try {
  3148. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3149. cb(null, tmpl(options));
  3150. } catch (err) {
  3151. cb(err);
  3152. }
  3153. });
  3154. };
  3155. /**
  3156. * QEJS support.
  3157. */
  3158. exports.qejs = fromStringRenderer('qejs');
  3159. /**
  3160. * QEJS string support.
  3161. */
  3162. exports.qejs.render = function(str, options, cb) {
  3163. return promisify(cb, function(cb) {
  3164. try {
  3165. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3166. engine.render(str, options).then(function(result) {
  3167. cb(null, result);
  3168. }, function(err) {
  3169. cb(err);
  3170. }).done();
  3171. } catch (err) {
  3172. cb(err);
  3173. }
  3174. });
  3175. };
  3176. /**
  3177. * Walrus support.
  3178. */
  3179. exports.walrus = fromStringRenderer('walrus');
  3180. /**
  3181. * Walrus string support.
  3182. */
  3183. exports.walrus.render = function(str, options, cb) {
  3184. return promisify(cb, function(cb) {
  3185. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3186. try {
  3187. var tmpl = cache(options) || cache(options, engine.parse(str));
  3188. cb(null, tmpl.compile(options));
  3189. } catch (err) {
  3190. cb(err);
  3191. }
  3192. });
  3193. };
  3194. /**
  3195. * Mustache support.
  3196. */
  3197. exports.mustache = fromStringRenderer('mustache');
  3198. /**
  3199. * Mustache string support.
  3200. */
  3201. exports.mustache.render = function(str, options, cb) {
  3202. return promisify(cb, function(cb) {
  3203. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3204. try {
  3205. cb(null, engine.render(str, options, options.partials));
  3206. } catch (err) {
  3207. cb(err);
  3208. }
  3209. });
  3210. };
  3211. /**
  3212. * Just support.
  3213. */
  3214. exports.just = function(path, options, cb) {
  3215. return promisify(cb, function(cb) {
  3216. var engine = requires.just;
  3217. if (!engine) {
  3218. var JUST = require('just');
  3219. engine = requires.just = new JUST();
  3220. }
  3221. engine.configure({ useCache: options.cache });
  3222. engine.render(path, options, cb);
  3223. });
  3224. };
  3225. /**
  3226. * Just string support.
  3227. */
  3228. exports.just.render = function(str, options, cb) {
  3229. return promisify(cb, function(cb) {
  3230. var JUST = require('just');
  3231. var engine = new JUST({ root: { page: str }});
  3232. engine.render('page', options, cb);
  3233. });
  3234. };
  3235. /**
  3236. * ECT support.
  3237. */
  3238. exports.ect = function(path, options, cb) {
  3239. return promisify(cb, function(cb) {
  3240. var engine = requires.ect;
  3241. if (!engine) {
  3242. var ECT = require('ect');
  3243. engine = requires.ect = new ECT(options);
  3244. }
  3245. engine.configure({ cache: options.cache });
  3246. engine.render(path, options, cb);
  3247. });
  3248. };
  3249. /**
  3250. * ECT string support.
  3251. */
  3252. exports.ect.render = function(str, options, cb) {
  3253. return promisify(cb, function(cb) {
  3254. var ECT = require('ect');
  3255. var engine = new ECT({ root: { page: str }});
  3256. engine.render('page', options, cb);
  3257. });
  3258. };
  3259. /**
  3260. * mote support.
  3261. */
  3262. exports.mote = fromStringRenderer('mote');
  3263. /**
  3264. * mote string support.
  3265. */
  3266. exports.mote.render = function(str, options, cb) {
  3267. return promisify(cb, function(cb) {
  3268. var engine = requires.mote || (requires.mote = require('mote'));
  3269. try {
  3270. var tmpl = cache(options) || cache(options, engine.compile(str));
  3271. cb(null, tmpl(options));
  3272. } catch (err) {
  3273. cb(err);
  3274. }
  3275. });
  3276. };
  3277. /**
  3278. * Toffee support.
  3279. */
  3280. exports.toffee = function(path, options, cb) {
  3281. return promisify(cb, function(cb) {
  3282. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3283. toffee.__consolidate_engine_render(path, options, cb);
  3284. });
  3285. };
  3286. /**
  3287. * Toffee string support.
  3288. */
  3289. exports.toffee.render = function(str, options, cb) {
  3290. return promisify(cb, function(cb) {
  3291. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3292. try {
  3293. engine.str_render(str, options, cb);
  3294. } catch (err) {
  3295. cb(err);
  3296. }
  3297. });
  3298. };
  3299. /**
  3300. * doT support.
  3301. */
  3302. exports.dot = fromStringRenderer('dot');
  3303. /**
  3304. * doT string support.
  3305. */
  3306. exports.dot.render = function(str, options, cb) {
  3307. return promisify(cb, function(cb) {
  3308. var engine = requires.dot || (requires.dot = require('dot'));
  3309. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3310. try {
  3311. var settings = {};
  3312. settings = extend(settings, engine.templateSettings);
  3313. settings = extend(settings, options ? options.dot : {});
  3314. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3315. cb(null, tmpl(options));
  3316. } catch (err) {
  3317. cb(err);
  3318. }
  3319. });
  3320. };
  3321. /**
  3322. * bracket support.
  3323. */
  3324. exports.bracket = fromStringRenderer('bracket');
  3325. /**
  3326. * bracket string support.
  3327. */
  3328. exports.bracket.render = function(str, options, cb) {
  3329. return promisify(cb, function(cb) {
  3330. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3331. try {
  3332. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3333. cb(null, tmpl(options));
  3334. } catch (err) {
  3335. cb(err);
  3336. }
  3337. });
  3338. };
  3339. /**
  3340. * Ractive support.
  3341. */
  3342. exports.ractive = fromStringRenderer('ractive');
  3343. /**
  3344. * Ractive string support.
  3345. */
  3346. exports.ractive.render = function(str, options, cb) {
  3347. return promisify(cb, function(cb) {
  3348. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3349. var template = cache(options) || cache(options, Engine.parse(str));
  3350. options.template = template;
  3351. if (options.data === null || options.data === undefined) {
  3352. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3353. // Shallow clone the options object
  3354. options.data = extend({}, options);
  3355. // Remove consolidate-specific properties from the clone
  3356. var i;
  3357. var length;
  3358. var properties = ['template', 'filename', 'cache', 'partials'];
  3359. for (i = 0, length = properties.length; i < length; i++) {
  3360. var property = properties[i];
  3361. delete options.data[property];
  3362. }
  3363. }
  3364. try {
  3365. cb(null, new Engine(options).toHTML());
  3366. } catch (err) {
  3367. cb(err);
  3368. }
  3369. });
  3370. };
  3371. /**
  3372. * Nunjucks support.
  3373. */
  3374. exports.nunjucks = fromStringRenderer('nunjucks');
  3375. /**
  3376. * Nunjucks string support.
  3377. */
  3378. exports.nunjucks.render = function(str, options, cb) {
  3379. return promisify(cb, function(cb) {
  3380. try {
  3381. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3382. var env = engine;
  3383. // deprecated fallback support for express
  3384. // <https://github.com/tj/consolidate.js/pull/152>
  3385. // <https://github.com/tj/consolidate.js/pull/224>
  3386. if (options.settings && options.settings.views) {
  3387. env = engine.configure(options.settings.views);
  3388. } else if (options.nunjucks && options.nunjucks.configure) {
  3389. env = engine.configure.apply(engine, options.nunjucks.configure);
  3390. }
  3391. //
  3392. // because `renderString` does not initiate loaders
  3393. // we must manually create a loader for it based off
  3394. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3395. //
  3396. // <https://github.com/mozilla/nunjucks/issues/730>
  3397. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3398. //
  3399. // so instead we simply check if we passed a custom loader
  3400. // otherwise we create a simple file based loader
  3401. if (options.loader) {
  3402. env = new engine.Environment(options.loader);
  3403. } else if (options.settings && options.settings.views) {
  3404. env = new engine.Environment(
  3405. new engine.FileSystemLoader(options.settings.views)
  3406. );
  3407. } else if (options.nunjucks && options.nunjucks.loader) {
  3408. if (typeof options.nunjucks.loader === 'string') {
  3409. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3410. } else {
  3411. env = new engine.Environment(
  3412. new engine.FileSystemLoader(
  3413. options.nunjucks.loader[0],
  3414. options.nunjucks.loader[1]
  3415. )
  3416. );
  3417. }
  3418. }
  3419. env.renderString(str, options, cb);
  3420. } catch (err) {
  3421. throw cb(err);
  3422. }
  3423. });
  3424. };
  3425. /**
  3426. * HTMLing support.
  3427. */
  3428. exports.htmling = fromStringRenderer('htmling');
  3429. /**
  3430. * HTMLing string support.
  3431. */
  3432. exports.htmling.render = function(str, options, cb) {
  3433. return promisify(cb, function(cb) {
  3434. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3435. try {
  3436. var tmpl = cache(options) || cache(options, engine.string(str));
  3437. cb(null, tmpl.render(options));
  3438. } catch (err) {
  3439. cb(err);
  3440. }
  3441. });
  3442. };
  3443. /**
  3444. * Rendering function
  3445. */
  3446. function requireReact(module, filename) {
  3447. var babel = requires.babel || (requires.babel = require('babel-core'));
  3448. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3449. return module._compile(compiled, filename);
  3450. }
  3451. exports.requireReact = requireReact;
  3452. /**
  3453. * Converting a string into a node module.
  3454. */
  3455. function requireReactString(src, filename) {
  3456. var babel = requires.babel || (requires.babel = require('babel-core'));
  3457. if (!filename) filename = '';
  3458. var m = new module.constructor();
  3459. filename = filename || '';
  3460. // Compile Using React
  3461. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3462. // Compile as a module
  3463. m.paths = module.paths;
  3464. m._compile(compiled, filename);
  3465. return m.exports;
  3466. }
  3467. /**
  3468. * A naive helper to replace {{tags}} with options.tags content
  3469. */
  3470. function reactBaseTmpl(data, options) {
  3471. var exp;
  3472. var regex;
  3473. // Iterates through the keys in file object
  3474. // and interpolate / replace {{key}} with it's value
  3475. for (var k in options) {
  3476. if (options.hasOwnProperty(k)) {
  3477. exp = '{{' + k + '}}';
  3478. regex = new RegExp(exp, 'g');
  3479. if (data.match(regex)) {
  3480. data = data.replace(regex, options[k]);
  3481. }
  3482. }
  3483. }
  3484. return data;
  3485. }
  3486. /**
  3487. * Plates Support.
  3488. */
  3489. exports.plates = fromStringRenderer('plates');
  3490. /**
  3491. * Plates string support.
  3492. */
  3493. exports.plates.render = function(str, options, cb) {
  3494. return promisify(cb, function(cb) {
  3495. var engine = requires.plates || (requires.plates = require('plates'));
  3496. var map = options.map || undefined;
  3497. try {
  3498. var tmpl = engine.bind(str, options, map);
  3499. cb(null, tmpl);
  3500. } catch (err) {
  3501. cb(err);
  3502. }
  3503. });
  3504. };
  3505. /**
  3506. * The main render parser for React bsaed templates
  3507. */
  3508. function reactRenderer(type) {
  3509. if (commonjsRequire.extensions) {
  3510. // Ensure JSX is transformed on require
  3511. if (!commonjsRequire.extensions['.jsx']) {
  3512. commonjsRequire.extensions['.jsx'] = requireReact;
  3513. }
  3514. // Supporting .react extension as well as test cases
  3515. // Using .react extension is not recommended.
  3516. if (!commonjsRequire.extensions['.react']) {
  3517. commonjsRequire.extensions['.react'] = requireReact;
  3518. }
  3519. }
  3520. // Return rendering fx
  3521. return function(str, options, cb) {
  3522. return promisify(cb, function(cb) {
  3523. // React Import
  3524. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3525. var react = requires.react || (requires.react = require('react'));
  3526. // Assign HTML Base
  3527. var base = options.base;
  3528. delete options.base;
  3529. var enableCache = options.cache;
  3530. delete options.cache;
  3531. var isNonStatic = options.isNonStatic;
  3532. delete options.isNonStatic;
  3533. // Start Conversion
  3534. try {
  3535. var Code;
  3536. var Factory;
  3537. var baseStr;
  3538. var content;
  3539. var parsed;
  3540. if (!cache(options)) {
  3541. // Parsing
  3542. if (type === 'path') {
  3543. var path = resolve(str);
  3544. delete require.cache[path];
  3545. Code = commonjsRequire(path);
  3546. } else {
  3547. Code = requireReactString(str);
  3548. }
  3549. Factory = cache(options, react.createFactory(Code));
  3550. } else {
  3551. Factory = cache(options);
  3552. }
  3553. parsed = new Factory(options);
  3554. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3555. if (base) {
  3556. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3557. if (enableCache) {
  3558. readCache[str] = baseStr;
  3559. }
  3560. options.content = content;
  3561. content = reactBaseTmpl(baseStr, options);
  3562. }
  3563. cb(null, content);
  3564. } catch (err) {
  3565. cb(err);
  3566. }
  3567. });
  3568. };
  3569. }
  3570. /**
  3571. * React JS Support
  3572. */
  3573. exports.react = reactRenderer('path');
  3574. /**
  3575. * React JS string support.
  3576. */
  3577. exports.react.render = reactRenderer('string');
  3578. /**
  3579. * ARC-templates support.
  3580. */
  3581. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3582. /**
  3583. * ARC-templates string support.
  3584. */
  3585. exports['arc-templates'].render = function(str, options, cb) {
  3586. var readFileWithOptions = util.promisify(read);
  3587. var consolidateFileSystem = {};
  3588. consolidateFileSystem.readFile = function(path) {
  3589. return readFileWithOptions(path, options);
  3590. };
  3591. return promisify(cb, function(cb) {
  3592. try {
  3593. var engine = requires['arc-templates'];
  3594. if (!engine) {
  3595. var Engine = require('arc-templates/dist/es5');
  3596. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3597. }
  3598. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3599. compiler.then(function(func) { return func(options); })
  3600. .then(function(result) { cb(null, result.content); })
  3601. .catch(cb);
  3602. } catch (err) {
  3603. cb(err);
  3604. }
  3605. });
  3606. };
  3607. /**
  3608. * Vash support
  3609. */
  3610. exports.vash = fromStringRenderer('vash');
  3611. /**
  3612. * Vash string support
  3613. */
  3614. exports.vash.render = function(str, options, cb) {
  3615. return promisify(cb, function(cb) {
  3616. var engine = requires.vash || (requires.vash = require('vash'));
  3617. try {
  3618. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3619. if (options.helpers) {
  3620. for (var key in options.helpers) {
  3621. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3622. continue;
  3623. }
  3624. engine.helpers[key] = options.helpers[key];
  3625. }
  3626. }
  3627. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3628. tmpl(options, function sealLayout(err, ctx) {
  3629. if (err) cb(err);
  3630. ctx.finishLayout();
  3631. cb(null, ctx.toString().replace(/\n$/, ''));
  3632. });
  3633. } catch (err) {
  3634. cb(err);
  3635. }
  3636. });
  3637. };
  3638. /**
  3639. * Slm support.
  3640. */
  3641. exports.slm = fromStringRenderer('slm');
  3642. /**
  3643. * Slm string support.
  3644. */
  3645. exports.slm.render = function(str, options, cb) {
  3646. return promisify(cb, function(cb) {
  3647. var engine = requires.slm || (requires.slm = require('slm'));
  3648. try {
  3649. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3650. cb(null, tmpl(options));
  3651. } catch (err) {
  3652. cb(err);
  3653. }
  3654. });
  3655. };
  3656. /**
  3657. * Marko support.
  3658. */
  3659. exports.marko = function(path, options, cb) {
  3660. return promisify(cb, function(cb) {
  3661. var engine = requires.marko || (requires.marko = require('marko'));
  3662. options.writeToDisk = !!options.cache;
  3663. try {
  3664. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3665. tmpl.renderToString(options, cb);
  3666. } catch (err) {
  3667. cb(err);
  3668. }
  3669. });
  3670. };
  3671. /**
  3672. * Marko string support.
  3673. */
  3674. exports.marko.render = function(str, options, cb) {
  3675. return promisify(cb, function(cb) {
  3676. var engine = requires.marko || (requires.marko = require('marko'));
  3677. options.writeToDisk = !!options.cache;
  3678. options.filename = options.filename || 'string.marko';
  3679. try {
  3680. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3681. tmpl.renderToString(options, cb);
  3682. } catch (err) {
  3683. cb(err);
  3684. }
  3685. });
  3686. };
  3687. /**
  3688. * Teacup support.
  3689. */
  3690. exports.teacup = function(path, options, cb) {
  3691. return promisify(cb, function(cb) {
  3692. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3693. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3694. if (path[0] !== '/') {
  3695. path = join(process.cwd(), path);
  3696. }
  3697. if (!options.cache) {
  3698. var callback = cb;
  3699. cb = function() {
  3700. delete require.cache[path];
  3701. callback.apply(this, arguments);
  3702. };
  3703. }
  3704. engine.renderFile(path, options, cb);
  3705. });
  3706. };
  3707. /**
  3708. * Teacup string support.
  3709. */
  3710. exports.teacup.render = function(str, options, cb) {
  3711. var coffee = require('coffee-script');
  3712. var vm = require('vm');
  3713. var sandbox = {
  3714. module: {exports: {}},
  3715. require: commonjsRequire
  3716. };
  3717. return promisify(cb, function(cb) {
  3718. vm.runInNewContext(coffee.compile(str), sandbox);
  3719. var tmpl = sandbox.module.exports;
  3720. cb(null, tmpl(options));
  3721. });
  3722. };
  3723. /**
  3724. * Squirrelly support.
  3725. */
  3726. exports.squirrelly = fromStringRenderer('squirrelly');
  3727. /**
  3728. * Squirrelly string support.
  3729. */
  3730. exports.squirrelly.render = function(str, options, cb) {
  3731. return promisify(cb, function(cb) {
  3732. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3733. try {
  3734. for (var partial in options.partials) {
  3735. engine.definePartial(partial, options.partials[partial]);
  3736. }
  3737. for (var helper in options.helpers) {
  3738. engine.defineHelper(helper, options.helpers[helper]);
  3739. }
  3740. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3741. cb(null, tmpl(options, engine));
  3742. } catch (err) {
  3743. cb(err);
  3744. }
  3745. });
  3746. };
  3747. /**
  3748. * Twing support.
  3749. */
  3750. exports.twing = fromStringRenderer('twing');
  3751. /**
  3752. * Twing string support.
  3753. */
  3754. exports.twing.render = function(str, options, cb) {
  3755. return promisify(cb, function(cb) {
  3756. var engine = requires.twing || (requires.twing = require('twing'));
  3757. try {
  3758. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3759. twingTemplate.render(options).then((rendTmpl) => {
  3760. var tmpl = cache(options) || cache(options, rendTmpl);
  3761. cb(null, tmpl);
  3762. });
  3763. });
  3764. } catch (err) {
  3765. cb(err);
  3766. }
  3767. });
  3768. };
  3769. /**
  3770. * expose the instance of the engine
  3771. */
  3772. exports.requires = requires;
  3773. } (consolidate$2, consolidate$2.exports));
  3774. return consolidate$2.exports;
  3775. }
  3776. var consolidate$1;
  3777. var hasRequiredConsolidate;
  3778. function requireConsolidate () {
  3779. if (hasRequiredConsolidate) return consolidate$1;
  3780. hasRequiredConsolidate = 1;
  3781. consolidate$1 = /*@__PURE__*/ requireConsolidate$1();
  3782. return consolidate$1;
  3783. }
  3784. var consolidateExports = /*@__PURE__*/ requireConsolidate();
  3785. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports);
  3786. const hasWarned = {};
  3787. function warnOnce(msg) {
  3788. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3789. if (!isNodeProd && true && !hasWarned[msg]) {
  3790. hasWarned[msg] = true;
  3791. warn(msg);
  3792. }
  3793. }
  3794. function warn(msg) {
  3795. console.warn(
  3796. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3797. `
  3798. );
  3799. }
  3800. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3801. let res = "";
  3802. let err = null;
  3803. preprocessor.render(
  3804. source,
  3805. { filename, ...preprocessOptions },
  3806. (_err, _res) => {
  3807. if (_err) err = _err;
  3808. res = _res;
  3809. }
  3810. );
  3811. if (err) throw err;
  3812. return res;
  3813. }
  3814. function compileTemplate(options) {
  3815. const { preprocessLang, preprocessCustomRequire } = options;
  3816. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3817. if (preprocessor) {
  3818. try {
  3819. return doCompileTemplate({
  3820. ...options,
  3821. source: preprocess$1(options, preprocessor),
  3822. ast: void 0
  3823. // invalidate AST if template goes through preprocessor
  3824. });
  3825. } catch (e) {
  3826. return {
  3827. code: `export default function render() {}`,
  3828. source: options.source,
  3829. tips: [],
  3830. errors: [e]
  3831. };
  3832. }
  3833. } else if (preprocessLang) {
  3834. return {
  3835. code: `export default function render() {}`,
  3836. source: options.source,
  3837. tips: [
  3838. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3839. ],
  3840. errors: [
  3841. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3842. ]
  3843. };
  3844. } else {
  3845. return doCompileTemplate(options);
  3846. }
  3847. }
  3848. function doCompileTemplate({
  3849. filename,
  3850. id,
  3851. scoped,
  3852. slotted,
  3853. inMap,
  3854. source,
  3855. ast: inAST,
  3856. ssr = false,
  3857. ssrCssVars,
  3858. isProd = false,
  3859. compiler,
  3860. compilerOptions = {},
  3861. transformAssetUrls
  3862. }) {
  3863. const errors = [];
  3864. const warnings = [];
  3865. let nodeTransforms = [];
  3866. if (shared.isObject(transformAssetUrls)) {
  3867. const assetOptions = normalizeOptions(transformAssetUrls);
  3868. nodeTransforms = [
  3869. createAssetUrlTransformWithOptions(assetOptions),
  3870. createSrcsetTransformWithOptions(assetOptions)
  3871. ];
  3872. } else if (transformAssetUrls !== false) {
  3873. nodeTransforms = [transformAssetUrl, transformSrcset];
  3874. }
  3875. if (ssr && !ssrCssVars) {
  3876. warnOnce(
  3877. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3878. );
  3879. }
  3880. if (!id) {
  3881. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3882. id = "";
  3883. }
  3884. const shortId = id.replace(/^data-v-/, "");
  3885. const longId = `data-v-${shortId}`;
  3886. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3887. compiler = compiler || defaultCompiler;
  3888. if (compiler !== defaultCompiler) {
  3889. inAST = void 0;
  3890. }
  3891. if (inAST == null ? void 0 : inAST.transformed) {
  3892. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3893. prefixIdentifiers: true,
  3894. ...compilerOptions,
  3895. parseMode: "sfc",
  3896. onError: (e) => errors.push(e)
  3897. });
  3898. const template = newAST.children.find(
  3899. (node) => node.type === 1 && node.tag === "template"
  3900. );
  3901. inAST = compilerCore.createRoot(template.children, inAST.source);
  3902. }
  3903. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3904. mode: "module",
  3905. prefixIdentifiers: true,
  3906. hoistStatic: true,
  3907. cacheHandlers: true,
  3908. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3909. scopeId: scoped ? longId : void 0,
  3910. slotted,
  3911. sourceMap: true,
  3912. ...compilerOptions,
  3913. hmr: !isProd,
  3914. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3915. filename,
  3916. onError: (e) => errors.push(e),
  3917. onWarn: (w) => warnings.push(w)
  3918. });
  3919. if (inMap && !inAST) {
  3920. if (map) {
  3921. map = mapLines(inMap, map);
  3922. }
  3923. if (errors.length) {
  3924. patchErrors(errors, source, inMap);
  3925. }
  3926. }
  3927. const tips = warnings.map((w) => {
  3928. let msg = w.message;
  3929. if (w.loc) {
  3930. msg += `
  3931. ${shared.generateCodeFrame(
  3932. (inAST == null ? void 0 : inAST.source) || source,
  3933. w.loc.start.offset,
  3934. w.loc.end.offset
  3935. )}`;
  3936. }
  3937. return msg;
  3938. });
  3939. return { code, ast, preamble, source, errors, tips, map };
  3940. }
  3941. function mapLines(oldMap, newMap) {
  3942. if (!oldMap) return newMap;
  3943. if (!newMap) return oldMap;
  3944. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  3945. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  3946. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  3947. newMapConsumer.eachMapping((m) => {
  3948. if (m.originalLine == null) {
  3949. return;
  3950. }
  3951. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  3952. line: m.originalLine,
  3953. column: m.originalColumn
  3954. });
  3955. if (origPosInOldMap.source == null) {
  3956. return;
  3957. }
  3958. mergedMapGenerator.addMapping({
  3959. generated: {
  3960. line: m.generatedLine,
  3961. column: m.generatedColumn
  3962. },
  3963. original: {
  3964. line: origPosInOldMap.line,
  3965. // map line
  3966. // use current column, since the oldMap produced by @vue/compiler-sfc
  3967. // does not
  3968. column: m.originalColumn
  3969. },
  3970. source: origPosInOldMap.source,
  3971. name: origPosInOldMap.name
  3972. });
  3973. });
  3974. const generator = mergedMapGenerator;
  3975. oldMapConsumer.sources.forEach((sourceFile) => {
  3976. generator._sources.add(sourceFile);
  3977. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  3978. if (sourceContent != null) {
  3979. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  3980. }
  3981. });
  3982. generator._sourceRoot = oldMap.sourceRoot;
  3983. generator._file = oldMap.file;
  3984. return generator.toJSON();
  3985. }
  3986. function patchErrors(errors, source, inMap) {
  3987. const originalSource = inMap.sourcesContent[0];
  3988. const offset = originalSource.indexOf(source);
  3989. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  3990. errors.forEach((err) => {
  3991. if (err.loc) {
  3992. err.loc.start.line += lineOffset;
  3993. err.loc.start.offset += offset;
  3994. if (err.loc.end !== err.loc.start) {
  3995. err.loc.end.line += lineOffset;
  3996. err.loc.end.offset += offset;
  3997. }
  3998. }
  3999. });
  4000. }
  4001. const trimPlugin = () => {
  4002. return {
  4003. postcssPlugin: "vue-sfc-trim",
  4004. Once(root) {
  4005. root.walk(({ type, raws }) => {
  4006. if (type === "rule" || type === "atrule") {
  4007. if (raws.before) raws.before = "\n";
  4008. if ("after" in raws && raws.after) raws.after = "\n";
  4009. }
  4010. });
  4011. }
  4012. };
  4013. };
  4014. trimPlugin.postcss = true;
  4015. var dist$1 = {exports: {}};
  4016. var processor$1 = {exports: {}};
  4017. var parser$1 = {exports: {}};
  4018. var root$1 = {exports: {}};
  4019. var container$1 = {exports: {}};
  4020. var node$2 = {exports: {}};
  4021. var util$2 = {};
  4022. var unesc$1 = {exports: {}};
  4023. var hasRequiredUnesc$1;
  4024. function requireUnesc$1 () {
  4025. if (hasRequiredUnesc$1) return unesc$1.exports;
  4026. hasRequiredUnesc$1 = 1;
  4027. (function (module, exports) {
  4028. exports.__esModule = true;
  4029. exports["default"] = unesc;
  4030. // Many thanks for this post which made this migration much easier.
  4031. // https://mathiasbynens.be/notes/css-escapes
  4032. /**
  4033. *
  4034. * @param {string} str
  4035. * @returns {[string, number]|undefined}
  4036. */
  4037. function gobbleHex(str) {
  4038. var lower = str.toLowerCase();
  4039. var hex = '';
  4040. var spaceTerminated = false;
  4041. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4042. var code = lower.charCodeAt(i);
  4043. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4044. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4045. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4046. spaceTerminated = code === 32;
  4047. if (!valid) {
  4048. break;
  4049. }
  4050. hex += lower[i];
  4051. }
  4052. if (hex.length === 0) {
  4053. return undefined;
  4054. }
  4055. var codePoint = parseInt(hex, 16);
  4056. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4057. // Add special case for
  4058. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4059. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4060. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4061. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4062. }
  4063. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4064. }
  4065. var CONTAINS_ESCAPE = /\\/;
  4066. function unesc(str) {
  4067. var needToProcess = CONTAINS_ESCAPE.test(str);
  4068. if (!needToProcess) {
  4069. return str;
  4070. }
  4071. var ret = "";
  4072. for (var i = 0; i < str.length; i++) {
  4073. if (str[i] === "\\") {
  4074. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4075. if (gobbled !== undefined) {
  4076. ret += gobbled[0];
  4077. i += gobbled[1];
  4078. continue;
  4079. }
  4080. // Retain a pair of \\ if double escaped `\\\\`
  4081. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4082. if (str[i + 1] === "\\") {
  4083. ret += "\\";
  4084. i++;
  4085. continue;
  4086. }
  4087. // if \\ is at the end of the string retain it
  4088. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4089. if (str.length === i + 1) {
  4090. ret += str[i];
  4091. }
  4092. continue;
  4093. }
  4094. ret += str[i];
  4095. }
  4096. return ret;
  4097. }
  4098. module.exports = exports.default;
  4099. } (unesc$1, unesc$1.exports));
  4100. return unesc$1.exports;
  4101. }
  4102. var getProp$1 = {exports: {}};
  4103. var hasRequiredGetProp$1;
  4104. function requireGetProp$1 () {
  4105. if (hasRequiredGetProp$1) return getProp$1.exports;
  4106. hasRequiredGetProp$1 = 1;
  4107. (function (module, exports) {
  4108. exports.__esModule = true;
  4109. exports["default"] = getProp;
  4110. function getProp(obj) {
  4111. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4112. props[_key - 1] = arguments[_key];
  4113. }
  4114. while (props.length > 0) {
  4115. var prop = props.shift();
  4116. if (!obj[prop]) {
  4117. return undefined;
  4118. }
  4119. obj = obj[prop];
  4120. }
  4121. return obj;
  4122. }
  4123. module.exports = exports.default;
  4124. } (getProp$1, getProp$1.exports));
  4125. return getProp$1.exports;
  4126. }
  4127. var ensureObject$1 = {exports: {}};
  4128. var hasRequiredEnsureObject$1;
  4129. function requireEnsureObject$1 () {
  4130. if (hasRequiredEnsureObject$1) return ensureObject$1.exports;
  4131. hasRequiredEnsureObject$1 = 1;
  4132. (function (module, exports) {
  4133. exports.__esModule = true;
  4134. exports["default"] = ensureObject;
  4135. function ensureObject(obj) {
  4136. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4137. props[_key - 1] = arguments[_key];
  4138. }
  4139. while (props.length > 0) {
  4140. var prop = props.shift();
  4141. if (!obj[prop]) {
  4142. obj[prop] = {};
  4143. }
  4144. obj = obj[prop];
  4145. }
  4146. }
  4147. module.exports = exports.default;
  4148. } (ensureObject$1, ensureObject$1.exports));
  4149. return ensureObject$1.exports;
  4150. }
  4151. var stripComments$1 = {exports: {}};
  4152. var hasRequiredStripComments$1;
  4153. function requireStripComments$1 () {
  4154. if (hasRequiredStripComments$1) return stripComments$1.exports;
  4155. hasRequiredStripComments$1 = 1;
  4156. (function (module, exports) {
  4157. exports.__esModule = true;
  4158. exports["default"] = stripComments;
  4159. function stripComments(str) {
  4160. var s = "";
  4161. var commentStart = str.indexOf("/*");
  4162. var lastEnd = 0;
  4163. while (commentStart >= 0) {
  4164. s = s + str.slice(lastEnd, commentStart);
  4165. var commentEnd = str.indexOf("*/", commentStart + 2);
  4166. if (commentEnd < 0) {
  4167. return s;
  4168. }
  4169. lastEnd = commentEnd + 2;
  4170. commentStart = str.indexOf("/*", lastEnd);
  4171. }
  4172. s = s + str.slice(lastEnd);
  4173. return s;
  4174. }
  4175. module.exports = exports.default;
  4176. } (stripComments$1, stripComments$1.exports));
  4177. return stripComments$1.exports;
  4178. }
  4179. var hasRequiredUtil$2;
  4180. function requireUtil$2 () {
  4181. if (hasRequiredUtil$2) return util$2;
  4182. hasRequiredUtil$2 = 1;
  4183. util$2.__esModule = true;
  4184. util$2.unesc = util$2.stripComments = util$2.getProp = util$2.ensureObject = void 0;
  4185. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  4186. util$2.unesc = _unesc["default"];
  4187. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp$1());
  4188. util$2.getProp = _getProp["default"];
  4189. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject$1());
  4190. util$2.ensureObject = _ensureObject["default"];
  4191. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments$1());
  4192. util$2.stripComments = _stripComments["default"];
  4193. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4194. return util$2;
  4195. }
  4196. var hasRequiredNode$2;
  4197. function requireNode$2 () {
  4198. if (hasRequiredNode$2) return node$2.exports;
  4199. hasRequiredNode$2 = 1;
  4200. (function (module, exports) {
  4201. exports.__esModule = true;
  4202. exports["default"] = void 0;
  4203. var _util = /*@__PURE__*/ requireUtil$2();
  4204. 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); } }
  4205. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4206. var cloneNode = function cloneNode(obj, parent) {
  4207. if (typeof obj !== 'object' || obj === null) {
  4208. return obj;
  4209. }
  4210. var cloned = new obj.constructor();
  4211. for (var i in obj) {
  4212. if (!obj.hasOwnProperty(i)) {
  4213. continue;
  4214. }
  4215. var value = obj[i];
  4216. var type = typeof value;
  4217. if (i === 'parent' && type === 'object') {
  4218. if (parent) {
  4219. cloned[i] = parent;
  4220. }
  4221. } else if (value instanceof Array) {
  4222. cloned[i] = value.map(function (j) {
  4223. return cloneNode(j, cloned);
  4224. });
  4225. } else {
  4226. cloned[i] = cloneNode(value, cloned);
  4227. }
  4228. }
  4229. return cloned;
  4230. };
  4231. var Node = /*#__PURE__*/function () {
  4232. function Node(opts) {
  4233. if (opts === void 0) {
  4234. opts = {};
  4235. }
  4236. Object.assign(this, opts);
  4237. this.spaces = this.spaces || {};
  4238. this.spaces.before = this.spaces.before || '';
  4239. this.spaces.after = this.spaces.after || '';
  4240. }
  4241. var _proto = Node.prototype;
  4242. _proto.remove = function remove() {
  4243. if (this.parent) {
  4244. this.parent.removeChild(this);
  4245. }
  4246. this.parent = undefined;
  4247. return this;
  4248. };
  4249. _proto.replaceWith = function replaceWith() {
  4250. if (this.parent) {
  4251. for (var index in arguments) {
  4252. this.parent.insertBefore(this, arguments[index]);
  4253. }
  4254. this.remove();
  4255. }
  4256. return this;
  4257. };
  4258. _proto.next = function next() {
  4259. return this.parent.at(this.parent.index(this) + 1);
  4260. };
  4261. _proto.prev = function prev() {
  4262. return this.parent.at(this.parent.index(this) - 1);
  4263. };
  4264. _proto.clone = function clone(overrides) {
  4265. if (overrides === void 0) {
  4266. overrides = {};
  4267. }
  4268. var cloned = cloneNode(this);
  4269. for (var name in overrides) {
  4270. cloned[name] = overrides[name];
  4271. }
  4272. return cloned;
  4273. }
  4274. /**
  4275. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4276. * This allows non standard syntax to be appended to an existing property
  4277. * by specifying the escaped value. By specifying the escaped value,
  4278. * illegal characters are allowed to be directly inserted into css output.
  4279. * @param {string} name the property to set
  4280. * @param {any} value the unescaped value of the property
  4281. * @param {string} valueEscaped optional. the escaped value of the property.
  4282. */;
  4283. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4284. if (!this.raws) {
  4285. this.raws = {};
  4286. }
  4287. var originalValue = this[name];
  4288. var originalEscaped = this.raws[name];
  4289. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4290. if (originalEscaped || valueEscaped !== value) {
  4291. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4292. } else {
  4293. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4294. }
  4295. }
  4296. /**
  4297. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4298. * This allows the escaped value to be specified directly, allowing illegal
  4299. * characters to be directly inserted into css output.
  4300. * @param {string} name the property to set
  4301. * @param {any} value the unescaped value of the property
  4302. * @param {string} valueEscaped the escaped value of the property.
  4303. */;
  4304. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4305. if (!this.raws) {
  4306. this.raws = {};
  4307. }
  4308. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4309. this.raws[name] = valueEscaped;
  4310. }
  4311. /**
  4312. * When you want a value to passed through to CSS directly. This method
  4313. * deletes the corresponding raw value causing the stringifier to fallback
  4314. * to the unescaped value.
  4315. * @param {string} name the property to set.
  4316. * @param {any} value The value that is both escaped and unescaped.
  4317. */;
  4318. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4319. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4320. if (this.raws) {
  4321. delete this.raws[name];
  4322. }
  4323. }
  4324. /**
  4325. *
  4326. * @param {number} line The number (starting with 1)
  4327. * @param {number} column The column number (starting with 1)
  4328. */;
  4329. _proto.isAtPosition = function isAtPosition(line, column) {
  4330. if (this.source && this.source.start && this.source.end) {
  4331. if (this.source.start.line > line) {
  4332. return false;
  4333. }
  4334. if (this.source.end.line < line) {
  4335. return false;
  4336. }
  4337. if (this.source.start.line === line && this.source.start.column > column) {
  4338. return false;
  4339. }
  4340. if (this.source.end.line === line && this.source.end.column < column) {
  4341. return false;
  4342. }
  4343. return true;
  4344. }
  4345. return undefined;
  4346. };
  4347. _proto.stringifyProperty = function stringifyProperty(name) {
  4348. return this.raws && this.raws[name] || this[name];
  4349. };
  4350. _proto.valueToString = function valueToString() {
  4351. return String(this.stringifyProperty("value"));
  4352. };
  4353. _proto.toString = function toString() {
  4354. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4355. };
  4356. _createClass(Node, [{
  4357. key: "rawSpaceBefore",
  4358. get: function get() {
  4359. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4360. if (rawSpace === undefined) {
  4361. rawSpace = this.spaces && this.spaces.before;
  4362. }
  4363. return rawSpace || "";
  4364. },
  4365. set: function set(raw) {
  4366. (0, _util.ensureObject)(this, "raws", "spaces");
  4367. this.raws.spaces.before = raw;
  4368. }
  4369. }, {
  4370. key: "rawSpaceAfter",
  4371. get: function get() {
  4372. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4373. if (rawSpace === undefined) {
  4374. rawSpace = this.spaces.after;
  4375. }
  4376. return rawSpace || "";
  4377. },
  4378. set: function set(raw) {
  4379. (0, _util.ensureObject)(this, "raws", "spaces");
  4380. this.raws.spaces.after = raw;
  4381. }
  4382. }]);
  4383. return Node;
  4384. }();
  4385. exports["default"] = Node;
  4386. module.exports = exports.default;
  4387. } (node$2, node$2.exports));
  4388. return node$2.exports;
  4389. }
  4390. var types$2 = {};
  4391. var hasRequiredTypes$1;
  4392. function requireTypes$1 () {
  4393. if (hasRequiredTypes$1) return types$2;
  4394. hasRequiredTypes$1 = 1;
  4395. types$2.__esModule = true;
  4396. 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;
  4397. var TAG = 'tag';
  4398. types$2.TAG = TAG;
  4399. var STRING = 'string';
  4400. types$2.STRING = STRING;
  4401. var SELECTOR = 'selector';
  4402. types$2.SELECTOR = SELECTOR;
  4403. var ROOT = 'root';
  4404. types$2.ROOT = ROOT;
  4405. var PSEUDO = 'pseudo';
  4406. types$2.PSEUDO = PSEUDO;
  4407. var NESTING = 'nesting';
  4408. types$2.NESTING = NESTING;
  4409. var ID = 'id';
  4410. types$2.ID = ID;
  4411. var COMMENT = 'comment';
  4412. types$2.COMMENT = COMMENT;
  4413. var COMBINATOR = 'combinator';
  4414. types$2.COMBINATOR = COMBINATOR;
  4415. var CLASS = 'class';
  4416. types$2.CLASS = CLASS;
  4417. var ATTRIBUTE = 'attribute';
  4418. types$2.ATTRIBUTE = ATTRIBUTE;
  4419. var UNIVERSAL = 'universal';
  4420. types$2.UNIVERSAL = UNIVERSAL;
  4421. return types$2;
  4422. }
  4423. var hasRequiredContainer$1;
  4424. function requireContainer$1 () {
  4425. if (hasRequiredContainer$1) return container$1.exports;
  4426. hasRequiredContainer$1 = 1;
  4427. (function (module, exports) {
  4428. exports.__esModule = true;
  4429. exports["default"] = void 0;
  4430. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4431. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  4432. 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); }
  4433. 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; }
  4434. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4435. 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."); }
  4436. 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); }
  4437. 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; }
  4438. 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); } }
  4439. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4440. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4441. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4442. var Container = /*#__PURE__*/function (_Node) {
  4443. _inheritsLoose(Container, _Node);
  4444. function Container(opts) {
  4445. var _this;
  4446. _this = _Node.call(this, opts) || this;
  4447. if (!_this.nodes) {
  4448. _this.nodes = [];
  4449. }
  4450. return _this;
  4451. }
  4452. var _proto = Container.prototype;
  4453. _proto.append = function append(selector) {
  4454. selector.parent = this;
  4455. this.nodes.push(selector);
  4456. return this;
  4457. };
  4458. _proto.prepend = function prepend(selector) {
  4459. selector.parent = this;
  4460. this.nodes.unshift(selector);
  4461. for (var id in this.indexes) {
  4462. this.indexes[id]++;
  4463. }
  4464. return this;
  4465. };
  4466. _proto.at = function at(index) {
  4467. return this.nodes[index];
  4468. };
  4469. _proto.index = function index(child) {
  4470. if (typeof child === 'number') {
  4471. return child;
  4472. }
  4473. return this.nodes.indexOf(child);
  4474. };
  4475. _proto.removeChild = function removeChild(child) {
  4476. child = this.index(child);
  4477. this.at(child).parent = undefined;
  4478. this.nodes.splice(child, 1);
  4479. var index;
  4480. for (var id in this.indexes) {
  4481. index = this.indexes[id];
  4482. if (index >= child) {
  4483. this.indexes[id] = index - 1;
  4484. }
  4485. }
  4486. return this;
  4487. };
  4488. _proto.removeAll = function removeAll() {
  4489. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4490. var node = _step.value;
  4491. node.parent = undefined;
  4492. }
  4493. this.nodes = [];
  4494. return this;
  4495. };
  4496. _proto.empty = function empty() {
  4497. return this.removeAll();
  4498. };
  4499. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4500. newNode.parent = this;
  4501. var oldIndex = this.index(oldNode);
  4502. this.nodes.splice(oldIndex + 1, 0, newNode);
  4503. newNode.parent = this;
  4504. var index;
  4505. for (var id in this.indexes) {
  4506. index = this.indexes[id];
  4507. if (oldIndex < index) {
  4508. this.indexes[id] = index + 1;
  4509. }
  4510. }
  4511. return this;
  4512. };
  4513. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4514. newNode.parent = this;
  4515. var oldIndex = this.index(oldNode);
  4516. this.nodes.splice(oldIndex, 0, newNode);
  4517. newNode.parent = this;
  4518. var index;
  4519. for (var id in this.indexes) {
  4520. index = this.indexes[id];
  4521. if (index >= oldIndex) {
  4522. this.indexes[id] = index + 1;
  4523. }
  4524. }
  4525. return this;
  4526. };
  4527. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4528. var found = undefined;
  4529. this.each(function (node) {
  4530. if (node.atPosition) {
  4531. var foundChild = node.atPosition(line, col);
  4532. if (foundChild) {
  4533. found = foundChild;
  4534. return false;
  4535. }
  4536. } else if (node.isAtPosition(line, col)) {
  4537. found = node;
  4538. return false;
  4539. }
  4540. });
  4541. return found;
  4542. }
  4543. /**
  4544. * Return the most specific node at the line and column number given.
  4545. * The source location is based on the original parsed location, locations aren't
  4546. * updated as selector nodes are mutated.
  4547. *
  4548. * Note that this location is relative to the location of the first character
  4549. * of the selector, and not the location of the selector in the overall document
  4550. * when used in conjunction with postcss.
  4551. *
  4552. * If not found, returns undefined.
  4553. * @param {number} line The line number of the node to find. (1-based index)
  4554. * @param {number} col The column number of the node to find. (1-based index)
  4555. */;
  4556. _proto.atPosition = function atPosition(line, col) {
  4557. if (this.isAtPosition(line, col)) {
  4558. return this._findChildAtPosition(line, col) || this;
  4559. } else {
  4560. return undefined;
  4561. }
  4562. };
  4563. _proto._inferEndPosition = function _inferEndPosition() {
  4564. if (this.last && this.last.source && this.last.source.end) {
  4565. this.source = this.source || {};
  4566. this.source.end = this.source.end || {};
  4567. Object.assign(this.source.end, this.last.source.end);
  4568. }
  4569. };
  4570. _proto.each = function each(callback) {
  4571. if (!this.lastEach) {
  4572. this.lastEach = 0;
  4573. }
  4574. if (!this.indexes) {
  4575. this.indexes = {};
  4576. }
  4577. this.lastEach++;
  4578. var id = this.lastEach;
  4579. this.indexes[id] = 0;
  4580. if (!this.length) {
  4581. return undefined;
  4582. }
  4583. var index, result;
  4584. while (this.indexes[id] < this.length) {
  4585. index = this.indexes[id];
  4586. result = callback(this.at(index), index);
  4587. if (result === false) {
  4588. break;
  4589. }
  4590. this.indexes[id] += 1;
  4591. }
  4592. delete this.indexes[id];
  4593. if (result === false) {
  4594. return false;
  4595. }
  4596. };
  4597. _proto.walk = function walk(callback) {
  4598. return this.each(function (node, i) {
  4599. var result = callback(node, i);
  4600. if (result !== false && node.length) {
  4601. result = node.walk(callback);
  4602. }
  4603. if (result === false) {
  4604. return false;
  4605. }
  4606. });
  4607. };
  4608. _proto.walkAttributes = function walkAttributes(callback) {
  4609. var _this2 = this;
  4610. return this.walk(function (selector) {
  4611. if (selector.type === types.ATTRIBUTE) {
  4612. return callback.call(_this2, selector);
  4613. }
  4614. });
  4615. };
  4616. _proto.walkClasses = function walkClasses(callback) {
  4617. var _this3 = this;
  4618. return this.walk(function (selector) {
  4619. if (selector.type === types.CLASS) {
  4620. return callback.call(_this3, selector);
  4621. }
  4622. });
  4623. };
  4624. _proto.walkCombinators = function walkCombinators(callback) {
  4625. var _this4 = this;
  4626. return this.walk(function (selector) {
  4627. if (selector.type === types.COMBINATOR) {
  4628. return callback.call(_this4, selector);
  4629. }
  4630. });
  4631. };
  4632. _proto.walkComments = function walkComments(callback) {
  4633. var _this5 = this;
  4634. return this.walk(function (selector) {
  4635. if (selector.type === types.COMMENT) {
  4636. return callback.call(_this5, selector);
  4637. }
  4638. });
  4639. };
  4640. _proto.walkIds = function walkIds(callback) {
  4641. var _this6 = this;
  4642. return this.walk(function (selector) {
  4643. if (selector.type === types.ID) {
  4644. return callback.call(_this6, selector);
  4645. }
  4646. });
  4647. };
  4648. _proto.walkNesting = function walkNesting(callback) {
  4649. var _this7 = this;
  4650. return this.walk(function (selector) {
  4651. if (selector.type === types.NESTING) {
  4652. return callback.call(_this7, selector);
  4653. }
  4654. });
  4655. };
  4656. _proto.walkPseudos = function walkPseudos(callback) {
  4657. var _this8 = this;
  4658. return this.walk(function (selector) {
  4659. if (selector.type === types.PSEUDO) {
  4660. return callback.call(_this8, selector);
  4661. }
  4662. });
  4663. };
  4664. _proto.walkTags = function walkTags(callback) {
  4665. var _this9 = this;
  4666. return this.walk(function (selector) {
  4667. if (selector.type === types.TAG) {
  4668. return callback.call(_this9, selector);
  4669. }
  4670. });
  4671. };
  4672. _proto.walkUniversals = function walkUniversals(callback) {
  4673. var _this10 = this;
  4674. return this.walk(function (selector) {
  4675. if (selector.type === types.UNIVERSAL) {
  4676. return callback.call(_this10, selector);
  4677. }
  4678. });
  4679. };
  4680. _proto.split = function split(callback) {
  4681. var _this11 = this;
  4682. var current = [];
  4683. return this.reduce(function (memo, node, index) {
  4684. var split = callback.call(_this11, node);
  4685. current.push(node);
  4686. if (split) {
  4687. memo.push(current);
  4688. current = [];
  4689. } else if (index === _this11.length - 1) {
  4690. memo.push(current);
  4691. }
  4692. return memo;
  4693. }, []);
  4694. };
  4695. _proto.map = function map(callback) {
  4696. return this.nodes.map(callback);
  4697. };
  4698. _proto.reduce = function reduce(callback, memo) {
  4699. return this.nodes.reduce(callback, memo);
  4700. };
  4701. _proto.every = function every(callback) {
  4702. return this.nodes.every(callback);
  4703. };
  4704. _proto.some = function some(callback) {
  4705. return this.nodes.some(callback);
  4706. };
  4707. _proto.filter = function filter(callback) {
  4708. return this.nodes.filter(callback);
  4709. };
  4710. _proto.sort = function sort(callback) {
  4711. return this.nodes.sort(callback);
  4712. };
  4713. _proto.toString = function toString() {
  4714. return this.map(String).join('');
  4715. };
  4716. _createClass(Container, [{
  4717. key: "first",
  4718. get: function get() {
  4719. return this.at(0);
  4720. }
  4721. }, {
  4722. key: "last",
  4723. get: function get() {
  4724. return this.at(this.length - 1);
  4725. }
  4726. }, {
  4727. key: "length",
  4728. get: function get() {
  4729. return this.nodes.length;
  4730. }
  4731. }]);
  4732. return Container;
  4733. }(_node["default"]);
  4734. exports["default"] = Container;
  4735. module.exports = exports.default;
  4736. } (container$1, container$1.exports));
  4737. return container$1.exports;
  4738. }
  4739. var hasRequiredRoot$1;
  4740. function requireRoot$1 () {
  4741. if (hasRequiredRoot$1) return root$1.exports;
  4742. hasRequiredRoot$1 = 1;
  4743. (function (module, exports) {
  4744. exports.__esModule = true;
  4745. exports["default"] = void 0;
  4746. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4747. var _types = /*@__PURE__*/ requireTypes$1();
  4748. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4749. 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); } }
  4750. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4751. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4752. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4753. var Root = /*#__PURE__*/function (_Container) {
  4754. _inheritsLoose(Root, _Container);
  4755. function Root(opts) {
  4756. var _this;
  4757. _this = _Container.call(this, opts) || this;
  4758. _this.type = _types.ROOT;
  4759. return _this;
  4760. }
  4761. var _proto = Root.prototype;
  4762. _proto.toString = function toString() {
  4763. var str = this.reduce(function (memo, selector) {
  4764. memo.push(String(selector));
  4765. return memo;
  4766. }, []).join(',');
  4767. return this.trailingComma ? str + ',' : str;
  4768. };
  4769. _proto.error = function error(message, options) {
  4770. if (this._error) {
  4771. return this._error(message, options);
  4772. } else {
  4773. return new Error(message);
  4774. }
  4775. };
  4776. _createClass(Root, [{
  4777. key: "errorGenerator",
  4778. set: function set(handler) {
  4779. this._error = handler;
  4780. }
  4781. }]);
  4782. return Root;
  4783. }(_container["default"]);
  4784. exports["default"] = Root;
  4785. module.exports = exports.default;
  4786. } (root$1, root$1.exports));
  4787. return root$1.exports;
  4788. }
  4789. var selector$1 = {exports: {}};
  4790. var hasRequiredSelector$1;
  4791. function requireSelector$1 () {
  4792. if (hasRequiredSelector$1) return selector$1.exports;
  4793. hasRequiredSelector$1 = 1;
  4794. (function (module, exports) {
  4795. exports.__esModule = true;
  4796. exports["default"] = void 0;
  4797. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4798. var _types = /*@__PURE__*/ requireTypes$1();
  4799. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4800. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4801. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4802. var Selector = /*#__PURE__*/function (_Container) {
  4803. _inheritsLoose(Selector, _Container);
  4804. function Selector(opts) {
  4805. var _this;
  4806. _this = _Container.call(this, opts) || this;
  4807. _this.type = _types.SELECTOR;
  4808. return _this;
  4809. }
  4810. return Selector;
  4811. }(_container["default"]);
  4812. exports["default"] = Selector;
  4813. module.exports = exports.default;
  4814. } (selector$1, selector$1.exports));
  4815. return selector$1.exports;
  4816. }
  4817. var className$1 = {exports: {}};
  4818. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4819. var cssesc_1;
  4820. var hasRequiredCssesc;
  4821. function requireCssesc () {
  4822. if (hasRequiredCssesc) return cssesc_1;
  4823. hasRequiredCssesc = 1;
  4824. var object = {};
  4825. var hasOwnProperty = object.hasOwnProperty;
  4826. var merge = function merge(options, defaults) {
  4827. if (!options) {
  4828. return defaults;
  4829. }
  4830. var result = {};
  4831. for (var key in defaults) {
  4832. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4833. // only recognized option names are used.
  4834. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  4835. }
  4836. return result;
  4837. };
  4838. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4839. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4840. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4841. // https://mathiasbynens.be/notes/css-escapes#css
  4842. var cssesc = function cssesc(string, options) {
  4843. options = merge(options, cssesc.options);
  4844. if (options.quotes != 'single' && options.quotes != 'double') {
  4845. options.quotes = 'single';
  4846. }
  4847. var quote = options.quotes == 'double' ? '"' : '\'';
  4848. var isIdentifier = options.isIdentifier;
  4849. var firstChar = string.charAt(0);
  4850. var output = '';
  4851. var counter = 0;
  4852. var length = string.length;
  4853. while (counter < length) {
  4854. var character = string.charAt(counter++);
  4855. var codePoint = character.charCodeAt();
  4856. var value = void 0;
  4857. // If it’s not a printable ASCII character…
  4858. if (codePoint < 0x20 || codePoint > 0x7E) {
  4859. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4860. // It’s a high surrogate, and there is a next character.
  4861. var extra = string.charCodeAt(counter++);
  4862. if ((extra & 0xFC00) == 0xDC00) {
  4863. // next character is low surrogate
  4864. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4865. } else {
  4866. // It’s an unmatched surrogate; only append this code unit, in case
  4867. // the next code unit is the high surrogate of a surrogate pair.
  4868. counter--;
  4869. }
  4870. }
  4871. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4872. } else {
  4873. if (options.escapeEverything) {
  4874. if (regexAnySingleEscape.test(character)) {
  4875. value = '\\' + character;
  4876. } else {
  4877. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4878. }
  4879. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4880. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4881. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4882. value = '\\' + character;
  4883. } else {
  4884. value = character;
  4885. }
  4886. }
  4887. output += value;
  4888. }
  4889. if (isIdentifier) {
  4890. if (/^-[-\d]/.test(output)) {
  4891. output = '\\-' + output.slice(1);
  4892. } else if (/\d/.test(firstChar)) {
  4893. output = '\\3' + firstChar + ' ' + output.slice(1);
  4894. }
  4895. }
  4896. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4897. // since they’re redundant. Note that this is only possible if the escape
  4898. // sequence isn’t preceded by an odd number of backslashes.
  4899. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4900. if ($1 && $1.length % 2) {
  4901. // It’s not safe to remove the space, so don’t.
  4902. return $0;
  4903. }
  4904. // Strip the space.
  4905. return ($1 || '') + $2;
  4906. });
  4907. if (!isIdentifier && options.wrap) {
  4908. return quote + output + quote;
  4909. }
  4910. return output;
  4911. };
  4912. // Expose default options (so they can be overridden globally).
  4913. cssesc.options = {
  4914. 'escapeEverything': false,
  4915. 'isIdentifier': false,
  4916. 'quotes': 'single',
  4917. 'wrap': false
  4918. };
  4919. cssesc.version = '3.0.0';
  4920. cssesc_1 = cssesc;
  4921. return cssesc_1;
  4922. }
  4923. var hasRequiredClassName$1;
  4924. function requireClassName$1 () {
  4925. if (hasRequiredClassName$1) return className$1.exports;
  4926. hasRequiredClassName$1 = 1;
  4927. (function (module, exports) {
  4928. exports.__esModule = true;
  4929. exports["default"] = void 0;
  4930. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  4931. var _util = /*@__PURE__*/ requireUtil$2();
  4932. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4933. var _types = /*@__PURE__*/ requireTypes$1();
  4934. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4935. 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); } }
  4936. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4937. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4938. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4939. var ClassName = /*#__PURE__*/function (_Node) {
  4940. _inheritsLoose(ClassName, _Node);
  4941. function ClassName(opts) {
  4942. var _this;
  4943. _this = _Node.call(this, opts) || this;
  4944. _this.type = _types.CLASS;
  4945. _this._constructed = true;
  4946. return _this;
  4947. }
  4948. var _proto = ClassName.prototype;
  4949. _proto.valueToString = function valueToString() {
  4950. return '.' + _Node.prototype.valueToString.call(this);
  4951. };
  4952. _createClass(ClassName, [{
  4953. key: "value",
  4954. get: function get() {
  4955. return this._value;
  4956. },
  4957. set: function set(v) {
  4958. if (this._constructed) {
  4959. var escaped = (0, _cssesc["default"])(v, {
  4960. isIdentifier: true
  4961. });
  4962. if (escaped !== v) {
  4963. (0, _util.ensureObject)(this, "raws");
  4964. this.raws.value = escaped;
  4965. } else if (this.raws) {
  4966. delete this.raws.value;
  4967. }
  4968. }
  4969. this._value = v;
  4970. }
  4971. }]);
  4972. return ClassName;
  4973. }(_node["default"]);
  4974. exports["default"] = ClassName;
  4975. module.exports = exports.default;
  4976. } (className$1, className$1.exports));
  4977. return className$1.exports;
  4978. }
  4979. var comment$1 = {exports: {}};
  4980. var hasRequiredComment$1;
  4981. function requireComment$1 () {
  4982. if (hasRequiredComment$1) return comment$1.exports;
  4983. hasRequiredComment$1 = 1;
  4984. (function (module, exports) {
  4985. exports.__esModule = true;
  4986. exports["default"] = void 0;
  4987. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4988. var _types = /*@__PURE__*/ requireTypes$1();
  4989. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4990. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4991. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4992. var Comment = /*#__PURE__*/function (_Node) {
  4993. _inheritsLoose(Comment, _Node);
  4994. function Comment(opts) {
  4995. var _this;
  4996. _this = _Node.call(this, opts) || this;
  4997. _this.type = _types.COMMENT;
  4998. return _this;
  4999. }
  5000. return Comment;
  5001. }(_node["default"]);
  5002. exports["default"] = Comment;
  5003. module.exports = exports.default;
  5004. } (comment$1, comment$1.exports));
  5005. return comment$1.exports;
  5006. }
  5007. var id$1 = {exports: {}};
  5008. var hasRequiredId$1;
  5009. function requireId$1 () {
  5010. if (hasRequiredId$1) return id$1.exports;
  5011. hasRequiredId$1 = 1;
  5012. (function (module, exports) {
  5013. exports.__esModule = true;
  5014. exports["default"] = void 0;
  5015. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5016. var _types = /*@__PURE__*/ requireTypes$1();
  5017. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5018. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5019. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5020. var ID = /*#__PURE__*/function (_Node) {
  5021. _inheritsLoose(ID, _Node);
  5022. function ID(opts) {
  5023. var _this;
  5024. _this = _Node.call(this, opts) || this;
  5025. _this.type = _types.ID;
  5026. return _this;
  5027. }
  5028. var _proto = ID.prototype;
  5029. _proto.valueToString = function valueToString() {
  5030. return '#' + _Node.prototype.valueToString.call(this);
  5031. };
  5032. return ID;
  5033. }(_node["default"]);
  5034. exports["default"] = ID;
  5035. module.exports = exports.default;
  5036. } (id$1, id$1.exports));
  5037. return id$1.exports;
  5038. }
  5039. var tag$1 = {exports: {}};
  5040. var namespace$1 = {exports: {}};
  5041. var hasRequiredNamespace$1;
  5042. function requireNamespace$1 () {
  5043. if (hasRequiredNamespace$1) return namespace$1.exports;
  5044. hasRequiredNamespace$1 = 1;
  5045. (function (module, exports) {
  5046. exports.__esModule = true;
  5047. exports["default"] = void 0;
  5048. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5049. var _util = /*@__PURE__*/ requireUtil$2();
  5050. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5051. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5052. 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); } }
  5053. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5054. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5055. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5056. var Namespace = /*#__PURE__*/function (_Node) {
  5057. _inheritsLoose(Namespace, _Node);
  5058. function Namespace() {
  5059. return _Node.apply(this, arguments) || this;
  5060. }
  5061. var _proto = Namespace.prototype;
  5062. _proto.qualifiedName = function qualifiedName(value) {
  5063. if (this.namespace) {
  5064. return this.namespaceString + "|" + value;
  5065. } else {
  5066. return value;
  5067. }
  5068. };
  5069. _proto.valueToString = function valueToString() {
  5070. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5071. };
  5072. _createClass(Namespace, [{
  5073. key: "namespace",
  5074. get: function get() {
  5075. return this._namespace;
  5076. },
  5077. set: function set(namespace) {
  5078. if (namespace === true || namespace === "*" || namespace === "&") {
  5079. this._namespace = namespace;
  5080. if (this.raws) {
  5081. delete this.raws.namespace;
  5082. }
  5083. return;
  5084. }
  5085. var escaped = (0, _cssesc["default"])(namespace, {
  5086. isIdentifier: true
  5087. });
  5088. this._namespace = namespace;
  5089. if (escaped !== namespace) {
  5090. (0, _util.ensureObject)(this, "raws");
  5091. this.raws.namespace = escaped;
  5092. } else if (this.raws) {
  5093. delete this.raws.namespace;
  5094. }
  5095. }
  5096. }, {
  5097. key: "ns",
  5098. get: function get() {
  5099. return this._namespace;
  5100. },
  5101. set: function set(namespace) {
  5102. this.namespace = namespace;
  5103. }
  5104. }, {
  5105. key: "namespaceString",
  5106. get: function get() {
  5107. if (this.namespace) {
  5108. var ns = this.stringifyProperty("namespace");
  5109. if (ns === true) {
  5110. return '';
  5111. } else {
  5112. return ns;
  5113. }
  5114. } else {
  5115. return '';
  5116. }
  5117. }
  5118. }]);
  5119. return Namespace;
  5120. }(_node["default"]);
  5121. exports["default"] = Namespace;
  5122. module.exports = exports.default;
  5123. } (namespace$1, namespace$1.exports));
  5124. return namespace$1.exports;
  5125. }
  5126. var hasRequiredTag$1;
  5127. function requireTag$1 () {
  5128. if (hasRequiredTag$1) return tag$1.exports;
  5129. hasRequiredTag$1 = 1;
  5130. (function (module, exports) {
  5131. exports.__esModule = true;
  5132. exports["default"] = void 0;
  5133. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5134. var _types = /*@__PURE__*/ requireTypes$1();
  5135. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5136. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5137. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5138. var Tag = /*#__PURE__*/function (_Namespace) {
  5139. _inheritsLoose(Tag, _Namespace);
  5140. function Tag(opts) {
  5141. var _this;
  5142. _this = _Namespace.call(this, opts) || this;
  5143. _this.type = _types.TAG;
  5144. return _this;
  5145. }
  5146. return Tag;
  5147. }(_namespace["default"]);
  5148. exports["default"] = Tag;
  5149. module.exports = exports.default;
  5150. } (tag$1, tag$1.exports));
  5151. return tag$1.exports;
  5152. }
  5153. var string$1 = {exports: {}};
  5154. var hasRequiredString$1;
  5155. function requireString$1 () {
  5156. if (hasRequiredString$1) return string$1.exports;
  5157. hasRequiredString$1 = 1;
  5158. (function (module, exports) {
  5159. exports.__esModule = true;
  5160. exports["default"] = void 0;
  5161. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5162. var _types = /*@__PURE__*/ requireTypes$1();
  5163. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5164. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5165. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5166. var String = /*#__PURE__*/function (_Node) {
  5167. _inheritsLoose(String, _Node);
  5168. function String(opts) {
  5169. var _this;
  5170. _this = _Node.call(this, opts) || this;
  5171. _this.type = _types.STRING;
  5172. return _this;
  5173. }
  5174. return String;
  5175. }(_node["default"]);
  5176. exports["default"] = String;
  5177. module.exports = exports.default;
  5178. } (string$1, string$1.exports));
  5179. return string$1.exports;
  5180. }
  5181. var pseudo$1 = {exports: {}};
  5182. var hasRequiredPseudo$1;
  5183. function requirePseudo$1 () {
  5184. if (hasRequiredPseudo$1) return pseudo$1.exports;
  5185. hasRequiredPseudo$1 = 1;
  5186. (function (module, exports) {
  5187. exports.__esModule = true;
  5188. exports["default"] = void 0;
  5189. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  5190. var _types = /*@__PURE__*/ requireTypes$1();
  5191. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5192. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5193. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5194. var Pseudo = /*#__PURE__*/function (_Container) {
  5195. _inheritsLoose(Pseudo, _Container);
  5196. function Pseudo(opts) {
  5197. var _this;
  5198. _this = _Container.call(this, opts) || this;
  5199. _this.type = _types.PSEUDO;
  5200. return _this;
  5201. }
  5202. var _proto = Pseudo.prototype;
  5203. _proto.toString = function toString() {
  5204. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5205. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5206. };
  5207. return Pseudo;
  5208. }(_container["default"]);
  5209. exports["default"] = Pseudo;
  5210. module.exports = exports.default;
  5211. } (pseudo$1, pseudo$1.exports));
  5212. return pseudo$1.exports;
  5213. }
  5214. var attribute$1 = {};
  5215. var node$1;
  5216. var hasRequiredNode$1;
  5217. function requireNode$1 () {
  5218. if (hasRequiredNode$1) return node$1;
  5219. hasRequiredNode$1 = 1;
  5220. /**
  5221. * For Node.js, simply re-export the core `util.deprecate` function.
  5222. */
  5223. node$1 = require$$2.deprecate;
  5224. return node$1;
  5225. }
  5226. var hasRequiredAttribute$1;
  5227. function requireAttribute$1 () {
  5228. if (hasRequiredAttribute$1) return attribute$1;
  5229. hasRequiredAttribute$1 = 1;
  5230. (function (exports) {
  5231. exports.__esModule = true;
  5232. exports["default"] = void 0;
  5233. exports.unescapeValue = unescapeValue;
  5234. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5235. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  5236. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5237. var _types = /*@__PURE__*/ requireTypes$1();
  5238. var _CSSESC_QUOTE_OPTIONS;
  5239. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5240. 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); } }
  5241. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5242. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5243. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5244. var deprecate = /*@__PURE__*/ requireNode$1();
  5245. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5246. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5247. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5248. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5249. function unescapeValue(value) {
  5250. var deprecatedUsage = false;
  5251. var quoteMark = null;
  5252. var unescaped = value;
  5253. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5254. if (m) {
  5255. quoteMark = m[1];
  5256. unescaped = m[2];
  5257. }
  5258. unescaped = (0, _unesc["default"])(unescaped);
  5259. if (unescaped !== value) {
  5260. deprecatedUsage = true;
  5261. }
  5262. return {
  5263. deprecatedUsage: deprecatedUsage,
  5264. unescaped: unescaped,
  5265. quoteMark: quoteMark
  5266. };
  5267. }
  5268. function handleDeprecatedContructorOpts(opts) {
  5269. if (opts.quoteMark !== undefined) {
  5270. return opts;
  5271. }
  5272. if (opts.value === undefined) {
  5273. return opts;
  5274. }
  5275. warnOfDeprecatedConstructor();
  5276. var _unescapeValue = unescapeValue(opts.value),
  5277. quoteMark = _unescapeValue.quoteMark,
  5278. unescaped = _unescapeValue.unescaped;
  5279. if (!opts.raws) {
  5280. opts.raws = {};
  5281. }
  5282. if (opts.raws.value === undefined) {
  5283. opts.raws.value = opts.value;
  5284. }
  5285. opts.value = unescaped;
  5286. opts.quoteMark = quoteMark;
  5287. return opts;
  5288. }
  5289. var Attribute = /*#__PURE__*/function (_Namespace) {
  5290. _inheritsLoose(Attribute, _Namespace);
  5291. function Attribute(opts) {
  5292. var _this;
  5293. if (opts === void 0) {
  5294. opts = {};
  5295. }
  5296. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5297. _this.type = _types.ATTRIBUTE;
  5298. _this.raws = _this.raws || {};
  5299. Object.defineProperty(_this.raws, 'unquoted', {
  5300. get: deprecate(function () {
  5301. return _this.value;
  5302. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5303. set: deprecate(function () {
  5304. return _this.value;
  5305. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5306. });
  5307. _this._constructed = true;
  5308. return _this;
  5309. }
  5310. /**
  5311. * Returns the Attribute's value quoted such that it would be legal to use
  5312. * in the value of a css file. The original value's quotation setting
  5313. * used for stringification is left unchanged. See `setValue(value, options)`
  5314. * if you want to control the quote settings of a new value for the attribute.
  5315. *
  5316. * You can also change the quotation used for the current value by setting quoteMark.
  5317. *
  5318. * Options:
  5319. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5320. * option is not set, the original value for quoteMark will be used. If
  5321. * indeterminate, a double quote is used. The legal values are:
  5322. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5323. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5324. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5325. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5326. * over the quoteMark option value.
  5327. * * smart {boolean} - if true, will select a quote mark based on the value
  5328. * and the other options specified here. See the `smartQuoteMark()`
  5329. * method.
  5330. **/
  5331. var _proto = Attribute.prototype;
  5332. _proto.getQuotedValue = function getQuotedValue(options) {
  5333. if (options === void 0) {
  5334. options = {};
  5335. }
  5336. var quoteMark = this._determineQuoteMark(options);
  5337. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5338. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5339. return escaped;
  5340. };
  5341. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5342. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5343. }
  5344. /**
  5345. * Set the unescaped value with the specified quotation options. The value
  5346. * provided must not include any wrapping quote marks -- those quotes will
  5347. * be interpreted as part of the value and escaped accordingly.
  5348. */;
  5349. _proto.setValue = function setValue(value, options) {
  5350. if (options === void 0) {
  5351. options = {};
  5352. }
  5353. this._value = value;
  5354. this._quoteMark = this._determineQuoteMark(options);
  5355. this._syncRawValue();
  5356. }
  5357. /**
  5358. * Intelligently select a quoteMark value based on the value's contents. If
  5359. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5360. * mark will be picked that minimizes the number of escapes.
  5361. *
  5362. * If there's no clear winner, the quote mark from these options is used,
  5363. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5364. * true). If the quoteMark is unspecified, a double quote is used.
  5365. *
  5366. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5367. * from the quoteValue method.
  5368. */;
  5369. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5370. var v = this.value;
  5371. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5372. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5373. if (numSingleQuotes + numDoubleQuotes === 0) {
  5374. var escaped = (0, _cssesc["default"])(v, {
  5375. isIdentifier: true
  5376. });
  5377. if (escaped === v) {
  5378. return Attribute.NO_QUOTE;
  5379. } else {
  5380. var pref = this.preferredQuoteMark(options);
  5381. if (pref === Attribute.NO_QUOTE) {
  5382. // pick a quote mark that isn't none and see if it's smaller
  5383. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5384. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5385. var quoteValue = (0, _cssesc["default"])(v, opts);
  5386. if (quoteValue.length < escaped.length) {
  5387. return quote;
  5388. }
  5389. }
  5390. return pref;
  5391. }
  5392. } else if (numDoubleQuotes === numSingleQuotes) {
  5393. return this.preferredQuoteMark(options);
  5394. } else if (numDoubleQuotes < numSingleQuotes) {
  5395. return Attribute.DOUBLE_QUOTE;
  5396. } else {
  5397. return Attribute.SINGLE_QUOTE;
  5398. }
  5399. }
  5400. /**
  5401. * Selects the preferred quote mark based on the options and the current quote mark value.
  5402. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5403. * instead.
  5404. */;
  5405. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5406. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5407. if (quoteMark === undefined) {
  5408. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5409. }
  5410. if (quoteMark === undefined) {
  5411. quoteMark = Attribute.DOUBLE_QUOTE;
  5412. }
  5413. return quoteMark;
  5414. };
  5415. _proto._syncRawValue = function _syncRawValue() {
  5416. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5417. if (rawValue === this._value) {
  5418. if (this.raws) {
  5419. delete this.raws.value;
  5420. }
  5421. } else {
  5422. this.raws.value = rawValue;
  5423. }
  5424. };
  5425. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5426. if (this._constructed) {
  5427. var escaped = (0, _cssesc["default"])(value, {
  5428. isIdentifier: true
  5429. });
  5430. if (escaped !== value) {
  5431. this.raws[prop] = escaped;
  5432. } else {
  5433. delete this.raws[prop];
  5434. }
  5435. }
  5436. };
  5437. _proto._spacesFor = function _spacesFor(name) {
  5438. var attrSpaces = {
  5439. before: '',
  5440. after: ''
  5441. };
  5442. var spaces = this.spaces[name] || {};
  5443. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5444. return Object.assign(attrSpaces, spaces, rawSpaces);
  5445. };
  5446. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5447. if (spaceName === void 0) {
  5448. spaceName = name;
  5449. }
  5450. if (concat === void 0) {
  5451. concat = defaultAttrConcat;
  5452. }
  5453. var attrSpaces = this._spacesFor(spaceName);
  5454. return concat(this.stringifyProperty(name), attrSpaces);
  5455. }
  5456. /**
  5457. * returns the offset of the attribute part specified relative to the
  5458. * start of the node of the output string.
  5459. *
  5460. * * "ns" - alias for "namespace"
  5461. * * "namespace" - the namespace if it exists.
  5462. * * "attribute" - the attribute name
  5463. * * "attributeNS" - the start of the attribute or its namespace
  5464. * * "operator" - the match operator of the attribute
  5465. * * "value" - The value (string or identifier)
  5466. * * "insensitive" - the case insensitivity flag;
  5467. * @param part One of the possible values inside an attribute.
  5468. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5469. */;
  5470. _proto.offsetOf = function offsetOf(name) {
  5471. var count = 1;
  5472. var attributeSpaces = this._spacesFor("attribute");
  5473. count += attributeSpaces.before.length;
  5474. if (name === "namespace" || name === "ns") {
  5475. return this.namespace ? count : -1;
  5476. }
  5477. if (name === "attributeNS") {
  5478. return count;
  5479. }
  5480. count += this.namespaceString.length;
  5481. if (this.namespace) {
  5482. count += 1;
  5483. }
  5484. if (name === "attribute") {
  5485. return count;
  5486. }
  5487. count += this.stringifyProperty("attribute").length;
  5488. count += attributeSpaces.after.length;
  5489. var operatorSpaces = this._spacesFor("operator");
  5490. count += operatorSpaces.before.length;
  5491. var operator = this.stringifyProperty("operator");
  5492. if (name === "operator") {
  5493. return operator ? count : -1;
  5494. }
  5495. count += operator.length;
  5496. count += operatorSpaces.after.length;
  5497. var valueSpaces = this._spacesFor("value");
  5498. count += valueSpaces.before.length;
  5499. var value = this.stringifyProperty("value");
  5500. if (name === "value") {
  5501. return value ? count : -1;
  5502. }
  5503. count += value.length;
  5504. count += valueSpaces.after.length;
  5505. var insensitiveSpaces = this._spacesFor("insensitive");
  5506. count += insensitiveSpaces.before.length;
  5507. if (name === "insensitive") {
  5508. return this.insensitive ? count : -1;
  5509. }
  5510. return -1;
  5511. };
  5512. _proto.toString = function toString() {
  5513. var _this2 = this;
  5514. var selector = [this.rawSpaceBefore, '['];
  5515. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5516. if (this.operator && (this.value || this.value === '')) {
  5517. selector.push(this._stringFor('operator'));
  5518. selector.push(this._stringFor('value'));
  5519. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5520. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5521. attrSpaces.before = " ";
  5522. }
  5523. return defaultAttrConcat(attrValue, attrSpaces);
  5524. }));
  5525. }
  5526. selector.push(']');
  5527. selector.push(this.rawSpaceAfter);
  5528. return selector.join('');
  5529. };
  5530. _createClass(Attribute, [{
  5531. key: "quoted",
  5532. get: function get() {
  5533. var qm = this.quoteMark;
  5534. return qm === "'" || qm === '"';
  5535. },
  5536. set: function set(value) {
  5537. warnOfDeprecatedQuotedAssignment();
  5538. }
  5539. /**
  5540. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5541. * returns `null` if the value is not quoted.
  5542. * returns `undefined` if the quotation state is unknown (this can happen when
  5543. * the attribute is constructed without specifying a quote mark.)
  5544. */
  5545. }, {
  5546. key: "quoteMark",
  5547. get: function get() {
  5548. return this._quoteMark;
  5549. }
  5550. /**
  5551. * Set the quote mark to be used by this attribute's value.
  5552. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5553. * value is updated accordingly.
  5554. *
  5555. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5556. */,
  5557. set: function set(quoteMark) {
  5558. if (!this._constructed) {
  5559. this._quoteMark = quoteMark;
  5560. return;
  5561. }
  5562. if (this._quoteMark !== quoteMark) {
  5563. this._quoteMark = quoteMark;
  5564. this._syncRawValue();
  5565. }
  5566. }
  5567. }, {
  5568. key: "qualifiedAttribute",
  5569. get: function get() {
  5570. return this.qualifiedName(this.raws.attribute || this.attribute);
  5571. }
  5572. }, {
  5573. key: "insensitiveFlag",
  5574. get: function get() {
  5575. return this.insensitive ? 'i' : '';
  5576. }
  5577. }, {
  5578. key: "value",
  5579. get: function get() {
  5580. return this._value;
  5581. },
  5582. set:
  5583. /**
  5584. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5585. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5586. * is unescaped during parsing and any quote marks are removed.
  5587. *
  5588. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5589. * a deprecation warning is raised when the new value contains any characters that would
  5590. * require escaping (including if it contains wrapped quotes).
  5591. *
  5592. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5593. * how the new value is quoted.
  5594. */
  5595. function set(v) {
  5596. if (this._constructed) {
  5597. var _unescapeValue2 = unescapeValue(v),
  5598. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5599. unescaped = _unescapeValue2.unescaped,
  5600. quoteMark = _unescapeValue2.quoteMark;
  5601. if (deprecatedUsage) {
  5602. warnOfDeprecatedValueAssignment();
  5603. }
  5604. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5605. return;
  5606. }
  5607. this._value = unescaped;
  5608. this._quoteMark = quoteMark;
  5609. this._syncRawValue();
  5610. } else {
  5611. this._value = v;
  5612. }
  5613. }
  5614. }, {
  5615. key: "insensitive",
  5616. get: function get() {
  5617. return this._insensitive;
  5618. }
  5619. /**
  5620. * Set the case insensitive flag.
  5621. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5622. * of the attribute is updated accordingly.
  5623. *
  5624. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5625. */,
  5626. set: function set(insensitive) {
  5627. if (!insensitive) {
  5628. this._insensitive = false;
  5629. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5630. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5631. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5632. this.raws.insensitiveFlag = undefined;
  5633. }
  5634. }
  5635. this._insensitive = insensitive;
  5636. }
  5637. }, {
  5638. key: "attribute",
  5639. get: function get() {
  5640. return this._attribute;
  5641. },
  5642. set: function set(name) {
  5643. this._handleEscapes("attribute", name);
  5644. this._attribute = name;
  5645. }
  5646. }]);
  5647. return Attribute;
  5648. }(_namespace["default"]);
  5649. exports["default"] = Attribute;
  5650. Attribute.NO_QUOTE = null;
  5651. Attribute.SINGLE_QUOTE = "'";
  5652. Attribute.DOUBLE_QUOTE = '"';
  5653. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5654. "'": {
  5655. quotes: 'single',
  5656. wrap: true
  5657. },
  5658. '"': {
  5659. quotes: 'double',
  5660. wrap: true
  5661. }
  5662. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5663. isIdentifier: true
  5664. }, _CSSESC_QUOTE_OPTIONS);
  5665. function defaultAttrConcat(attrValue, attrSpaces) {
  5666. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5667. }
  5668. } (attribute$1));
  5669. return attribute$1;
  5670. }
  5671. var universal$1 = {exports: {}};
  5672. var hasRequiredUniversal$1;
  5673. function requireUniversal$1 () {
  5674. if (hasRequiredUniversal$1) return universal$1.exports;
  5675. hasRequiredUniversal$1 = 1;
  5676. (function (module, exports) {
  5677. exports.__esModule = true;
  5678. exports["default"] = void 0;
  5679. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5680. var _types = /*@__PURE__*/ requireTypes$1();
  5681. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5682. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5683. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5684. var Universal = /*#__PURE__*/function (_Namespace) {
  5685. _inheritsLoose(Universal, _Namespace);
  5686. function Universal(opts) {
  5687. var _this;
  5688. _this = _Namespace.call(this, opts) || this;
  5689. _this.type = _types.UNIVERSAL;
  5690. _this.value = '*';
  5691. return _this;
  5692. }
  5693. return Universal;
  5694. }(_namespace["default"]);
  5695. exports["default"] = Universal;
  5696. module.exports = exports.default;
  5697. } (universal$1, universal$1.exports));
  5698. return universal$1.exports;
  5699. }
  5700. var combinator$1 = {exports: {}};
  5701. var hasRequiredCombinator$1;
  5702. function requireCombinator$1 () {
  5703. if (hasRequiredCombinator$1) return combinator$1.exports;
  5704. hasRequiredCombinator$1 = 1;
  5705. (function (module, exports) {
  5706. exports.__esModule = true;
  5707. exports["default"] = void 0;
  5708. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5709. var _types = /*@__PURE__*/ requireTypes$1();
  5710. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5711. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5712. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5713. var Combinator = /*#__PURE__*/function (_Node) {
  5714. _inheritsLoose(Combinator, _Node);
  5715. function Combinator(opts) {
  5716. var _this;
  5717. _this = _Node.call(this, opts) || this;
  5718. _this.type = _types.COMBINATOR;
  5719. return _this;
  5720. }
  5721. return Combinator;
  5722. }(_node["default"]);
  5723. exports["default"] = Combinator;
  5724. module.exports = exports.default;
  5725. } (combinator$1, combinator$1.exports));
  5726. return combinator$1.exports;
  5727. }
  5728. var nesting$1 = {exports: {}};
  5729. var hasRequiredNesting$1;
  5730. function requireNesting$1 () {
  5731. if (hasRequiredNesting$1) return nesting$1.exports;
  5732. hasRequiredNesting$1 = 1;
  5733. (function (module, exports) {
  5734. exports.__esModule = true;
  5735. exports["default"] = void 0;
  5736. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5737. var _types = /*@__PURE__*/ requireTypes$1();
  5738. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5739. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5740. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5741. var Nesting = /*#__PURE__*/function (_Node) {
  5742. _inheritsLoose(Nesting, _Node);
  5743. function Nesting(opts) {
  5744. var _this;
  5745. _this = _Node.call(this, opts) || this;
  5746. _this.type = _types.NESTING;
  5747. _this.value = '&';
  5748. return _this;
  5749. }
  5750. return Nesting;
  5751. }(_node["default"]);
  5752. exports["default"] = Nesting;
  5753. module.exports = exports.default;
  5754. } (nesting$1, nesting$1.exports));
  5755. return nesting$1.exports;
  5756. }
  5757. var sortAscending$1 = {exports: {}};
  5758. var hasRequiredSortAscending$1;
  5759. function requireSortAscending$1 () {
  5760. if (hasRequiredSortAscending$1) return sortAscending$1.exports;
  5761. hasRequiredSortAscending$1 = 1;
  5762. (function (module, exports) {
  5763. exports.__esModule = true;
  5764. exports["default"] = sortAscending;
  5765. function sortAscending(list) {
  5766. return list.sort(function (a, b) {
  5767. return a - b;
  5768. });
  5769. }
  5770. module.exports = exports.default;
  5771. } (sortAscending$1, sortAscending$1.exports));
  5772. return sortAscending$1.exports;
  5773. }
  5774. var tokenize$1 = {};
  5775. var tokenTypes$1 = {};
  5776. var hasRequiredTokenTypes$1;
  5777. function requireTokenTypes$1 () {
  5778. if (hasRequiredTokenTypes$1) return tokenTypes$1;
  5779. hasRequiredTokenTypes$1 = 1;
  5780. tokenTypes$1.__esModule = true;
  5781. 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;
  5782. var ampersand = 38; // `&`.charCodeAt(0);
  5783. tokenTypes$1.ampersand = ampersand;
  5784. var asterisk = 42; // `*`.charCodeAt(0);
  5785. tokenTypes$1.asterisk = asterisk;
  5786. var at = 64; // `@`.charCodeAt(0);
  5787. tokenTypes$1.at = at;
  5788. var comma = 44; // `,`.charCodeAt(0);
  5789. tokenTypes$1.comma = comma;
  5790. var colon = 58; // `:`.charCodeAt(0);
  5791. tokenTypes$1.colon = colon;
  5792. var semicolon = 59; // `;`.charCodeAt(0);
  5793. tokenTypes$1.semicolon = semicolon;
  5794. var openParenthesis = 40; // `(`.charCodeAt(0);
  5795. tokenTypes$1.openParenthesis = openParenthesis;
  5796. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5797. tokenTypes$1.closeParenthesis = closeParenthesis;
  5798. var openSquare = 91; // `[`.charCodeAt(0);
  5799. tokenTypes$1.openSquare = openSquare;
  5800. var closeSquare = 93; // `]`.charCodeAt(0);
  5801. tokenTypes$1.closeSquare = closeSquare;
  5802. var dollar = 36; // `$`.charCodeAt(0);
  5803. tokenTypes$1.dollar = dollar;
  5804. var tilde = 126; // `~`.charCodeAt(0);
  5805. tokenTypes$1.tilde = tilde;
  5806. var caret = 94; // `^`.charCodeAt(0);
  5807. tokenTypes$1.caret = caret;
  5808. var plus = 43; // `+`.charCodeAt(0);
  5809. tokenTypes$1.plus = plus;
  5810. var equals = 61; // `=`.charCodeAt(0);
  5811. tokenTypes$1.equals = equals;
  5812. var pipe = 124; // `|`.charCodeAt(0);
  5813. tokenTypes$1.pipe = pipe;
  5814. var greaterThan = 62; // `>`.charCodeAt(0);
  5815. tokenTypes$1.greaterThan = greaterThan;
  5816. var space = 32; // ` `.charCodeAt(0);
  5817. tokenTypes$1.space = space;
  5818. var singleQuote = 39; // `'`.charCodeAt(0);
  5819. tokenTypes$1.singleQuote = singleQuote;
  5820. var doubleQuote = 34; // `"`.charCodeAt(0);
  5821. tokenTypes$1.doubleQuote = doubleQuote;
  5822. var slash = 47; // `/`.charCodeAt(0);
  5823. tokenTypes$1.slash = slash;
  5824. var bang = 33; // `!`.charCodeAt(0);
  5825. tokenTypes$1.bang = bang;
  5826. var backslash = 92; // '\\'.charCodeAt(0);
  5827. tokenTypes$1.backslash = backslash;
  5828. var cr = 13; // '\r'.charCodeAt(0);
  5829. tokenTypes$1.cr = cr;
  5830. var feed = 12; // '\f'.charCodeAt(0);
  5831. tokenTypes$1.feed = feed;
  5832. var newline = 10; // '\n'.charCodeAt(0);
  5833. tokenTypes$1.newline = newline;
  5834. var tab = 9; // '\t'.charCodeAt(0);
  5835. // Expose aliases primarily for readability.
  5836. tokenTypes$1.tab = tab;
  5837. var str = singleQuote;
  5838. // No good single character representation!
  5839. tokenTypes$1.str = str;
  5840. var comment = -1;
  5841. tokenTypes$1.comment = comment;
  5842. var word = -2;
  5843. tokenTypes$1.word = word;
  5844. var combinator = -3;
  5845. tokenTypes$1.combinator = combinator;
  5846. return tokenTypes$1;
  5847. }
  5848. var hasRequiredTokenize$1;
  5849. function requireTokenize$1 () {
  5850. if (hasRequiredTokenize$1) return tokenize$1;
  5851. hasRequiredTokenize$1 = 1;
  5852. (function (exports) {
  5853. exports.__esModule = true;
  5854. exports.FIELDS = void 0;
  5855. exports["default"] = tokenize;
  5856. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  5857. var _unescapable, _wordDelimiters;
  5858. 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); }
  5859. 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; }
  5860. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5861. 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);
  5862. var hex = {};
  5863. var hexChars = "0123456789abcdefABCDEF";
  5864. for (var i = 0; i < hexChars.length; i++) {
  5865. hex[hexChars.charCodeAt(i)] = true;
  5866. }
  5867. /**
  5868. * Returns the last index of the bar css word
  5869. * @param {string} css The string in which the word begins
  5870. * @param {number} start The index into the string where word's first letter occurs
  5871. */
  5872. function consumeWord(css, start) {
  5873. var next = start;
  5874. var code;
  5875. do {
  5876. code = css.charCodeAt(next);
  5877. if (wordDelimiters[code]) {
  5878. return next - 1;
  5879. } else if (code === t.backslash) {
  5880. next = consumeEscape(css, next) + 1;
  5881. } else {
  5882. // All other characters are part of the word
  5883. next++;
  5884. }
  5885. } while (next < css.length);
  5886. return next - 1;
  5887. }
  5888. /**
  5889. * Returns the last index of the escape sequence
  5890. * @param {string} css The string in which the sequence begins
  5891. * @param {number} start The index into the string where escape character (`\`) occurs.
  5892. */
  5893. function consumeEscape(css, start) {
  5894. var next = start;
  5895. var code = css.charCodeAt(next + 1);
  5896. if (unescapable[code]) ; else if (hex[code]) {
  5897. var hexDigits = 0;
  5898. // consume up to 6 hex chars
  5899. do {
  5900. next++;
  5901. hexDigits++;
  5902. code = css.charCodeAt(next + 1);
  5903. } while (hex[code] && hexDigits < 6);
  5904. // if fewer than 6 hex chars, a trailing space ends the escape
  5905. if (hexDigits < 6 && code === t.space) {
  5906. next++;
  5907. }
  5908. } else {
  5909. // the next char is part of the current word
  5910. next++;
  5911. }
  5912. return next;
  5913. }
  5914. var FIELDS = {
  5915. TYPE: 0,
  5916. START_LINE: 1,
  5917. START_COL: 2,
  5918. END_LINE: 3,
  5919. END_COL: 4,
  5920. START_POS: 5,
  5921. END_POS: 6
  5922. };
  5923. exports.FIELDS = FIELDS;
  5924. function tokenize(input) {
  5925. var tokens = [];
  5926. var css = input.css.valueOf();
  5927. var _css = css,
  5928. length = _css.length;
  5929. var offset = -1;
  5930. var line = 1;
  5931. var start = 0;
  5932. var end = 0;
  5933. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5934. function unclosed(what, fix) {
  5935. if (input.safe) {
  5936. // fyi: this is never set to true.
  5937. css += fix;
  5938. next = css.length - 1;
  5939. } else {
  5940. throw input.error('Unclosed ' + what, line, start - offset, start);
  5941. }
  5942. }
  5943. while (start < length) {
  5944. code = css.charCodeAt(start);
  5945. if (code === t.newline) {
  5946. offset = start;
  5947. line += 1;
  5948. }
  5949. switch (code) {
  5950. case t.space:
  5951. case t.tab:
  5952. case t.newline:
  5953. case t.cr:
  5954. case t.feed:
  5955. next = start;
  5956. do {
  5957. next += 1;
  5958. code = css.charCodeAt(next);
  5959. if (code === t.newline) {
  5960. offset = next;
  5961. line += 1;
  5962. }
  5963. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  5964. tokenType = t.space;
  5965. endLine = line;
  5966. endColumn = next - offset - 1;
  5967. end = next;
  5968. break;
  5969. case t.plus:
  5970. case t.greaterThan:
  5971. case t.tilde:
  5972. case t.pipe:
  5973. next = start;
  5974. do {
  5975. next += 1;
  5976. code = css.charCodeAt(next);
  5977. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  5978. tokenType = t.combinator;
  5979. endLine = line;
  5980. endColumn = start - offset;
  5981. end = next;
  5982. break;
  5983. // Consume these characters as single tokens.
  5984. case t.asterisk:
  5985. case t.ampersand:
  5986. case t.bang:
  5987. case t.comma:
  5988. case t.equals:
  5989. case t.dollar:
  5990. case t.caret:
  5991. case t.openSquare:
  5992. case t.closeSquare:
  5993. case t.colon:
  5994. case t.semicolon:
  5995. case t.openParenthesis:
  5996. case t.closeParenthesis:
  5997. next = start;
  5998. tokenType = code;
  5999. endLine = line;
  6000. endColumn = start - offset;
  6001. end = next + 1;
  6002. break;
  6003. case t.singleQuote:
  6004. case t.doubleQuote:
  6005. quote = code === t.singleQuote ? "'" : '"';
  6006. next = start;
  6007. do {
  6008. escaped = false;
  6009. next = css.indexOf(quote, next + 1);
  6010. if (next === -1) {
  6011. unclosed('quote', quote);
  6012. }
  6013. escapePos = next;
  6014. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6015. escapePos -= 1;
  6016. escaped = !escaped;
  6017. }
  6018. } while (escaped);
  6019. tokenType = t.str;
  6020. endLine = line;
  6021. endColumn = start - offset;
  6022. end = next + 1;
  6023. break;
  6024. default:
  6025. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6026. next = css.indexOf('*/', start + 2) + 1;
  6027. if (next === 0) {
  6028. unclosed('comment', '*/');
  6029. }
  6030. content = css.slice(start, next + 1);
  6031. lines = content.split('\n');
  6032. last = lines.length - 1;
  6033. if (last > 0) {
  6034. nextLine = line + last;
  6035. nextOffset = next - lines[last].length;
  6036. } else {
  6037. nextLine = line;
  6038. nextOffset = offset;
  6039. }
  6040. tokenType = t.comment;
  6041. line = nextLine;
  6042. endLine = nextLine;
  6043. endColumn = next - nextOffset;
  6044. } else if (code === t.slash) {
  6045. next = start;
  6046. tokenType = code;
  6047. endLine = line;
  6048. endColumn = start - offset;
  6049. end = next + 1;
  6050. } else {
  6051. next = consumeWord(css, start);
  6052. tokenType = t.word;
  6053. endLine = line;
  6054. endColumn = next - offset;
  6055. }
  6056. end = next + 1;
  6057. break;
  6058. }
  6059. // Ensure that the token structure remains consistent
  6060. tokens.push([tokenType,
  6061. // [0] Token type
  6062. line,
  6063. // [1] Starting line
  6064. start - offset,
  6065. // [2] Starting column
  6066. endLine,
  6067. // [3] Ending line
  6068. endColumn,
  6069. // [4] Ending column
  6070. start,
  6071. // [5] Start position / Source index
  6072. end // [6] End position
  6073. ]);
  6074. // Reset offset for the next token
  6075. if (nextOffset) {
  6076. offset = nextOffset;
  6077. nextOffset = null;
  6078. }
  6079. start = end;
  6080. }
  6081. return tokens;
  6082. }
  6083. } (tokenize$1));
  6084. return tokenize$1;
  6085. }
  6086. var hasRequiredParser$2;
  6087. function requireParser$2 () {
  6088. if (hasRequiredParser$2) return parser$1.exports;
  6089. hasRequiredParser$2 = 1;
  6090. (function (module, exports) {
  6091. exports.__esModule = true;
  6092. exports["default"] = void 0;
  6093. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  6094. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  6095. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  6096. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  6097. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  6098. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  6099. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  6100. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  6101. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute$1());
  6102. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  6103. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  6104. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  6105. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending$1());
  6106. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize$1());
  6107. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  6108. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  6109. var _util = /*@__PURE__*/ requireUtil$2();
  6110. var _WHITESPACE_TOKENS, _Object$assign;
  6111. 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); }
  6112. 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; }
  6113. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6114. 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); } }
  6115. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6116. 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);
  6117. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6118. function tokenStart(token) {
  6119. return {
  6120. line: token[_tokenize.FIELDS.START_LINE],
  6121. column: token[_tokenize.FIELDS.START_COL]
  6122. };
  6123. }
  6124. function tokenEnd(token) {
  6125. return {
  6126. line: token[_tokenize.FIELDS.END_LINE],
  6127. column: token[_tokenize.FIELDS.END_COL]
  6128. };
  6129. }
  6130. function getSource(startLine, startColumn, endLine, endColumn) {
  6131. return {
  6132. start: {
  6133. line: startLine,
  6134. column: startColumn
  6135. },
  6136. end: {
  6137. line: endLine,
  6138. column: endColumn
  6139. }
  6140. };
  6141. }
  6142. function getTokenSource(token) {
  6143. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6144. }
  6145. function getTokenSourceSpan(startToken, endToken) {
  6146. if (!startToken) {
  6147. return undefined;
  6148. }
  6149. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6150. }
  6151. function unescapeProp(node, prop) {
  6152. var value = node[prop];
  6153. if (typeof value !== "string") {
  6154. return;
  6155. }
  6156. if (value.indexOf("\\") !== -1) {
  6157. (0, _util.ensureObject)(node, 'raws');
  6158. node[prop] = (0, _util.unesc)(value);
  6159. if (node.raws[prop] === undefined) {
  6160. node.raws[prop] = value;
  6161. }
  6162. }
  6163. return node;
  6164. }
  6165. function indexesOf(array, item) {
  6166. var i = -1;
  6167. var indexes = [];
  6168. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6169. indexes.push(i);
  6170. }
  6171. return indexes;
  6172. }
  6173. function uniqs() {
  6174. var list = Array.prototype.concat.apply([], arguments);
  6175. return list.filter(function (item, i) {
  6176. return i === list.indexOf(item);
  6177. });
  6178. }
  6179. var Parser = /*#__PURE__*/function () {
  6180. function Parser(rule, options) {
  6181. if (options === void 0) {
  6182. options = {};
  6183. }
  6184. this.rule = rule;
  6185. this.options = Object.assign({
  6186. lossy: false,
  6187. safe: false
  6188. }, options);
  6189. this.position = 0;
  6190. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6191. this.tokens = (0, _tokenize["default"])({
  6192. css: this.css,
  6193. error: this._errorGenerator(),
  6194. safe: this.options.safe
  6195. });
  6196. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6197. this.root = new _root["default"]({
  6198. source: rootSource
  6199. });
  6200. this.root.errorGenerator = this._errorGenerator();
  6201. var selector = new _selector["default"]({
  6202. source: {
  6203. start: {
  6204. line: 1,
  6205. column: 1
  6206. }
  6207. },
  6208. sourceIndex: 0
  6209. });
  6210. this.root.append(selector);
  6211. this.current = selector;
  6212. this.loop();
  6213. }
  6214. var _proto = Parser.prototype;
  6215. _proto._errorGenerator = function _errorGenerator() {
  6216. var _this = this;
  6217. return function (message, errorOptions) {
  6218. if (typeof _this.rule === 'string') {
  6219. return new Error(message);
  6220. }
  6221. return _this.rule.error(message, errorOptions);
  6222. };
  6223. };
  6224. _proto.attribute = function attribute() {
  6225. var attr = [];
  6226. var startingToken = this.currToken;
  6227. this.position++;
  6228. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6229. attr.push(this.currToken);
  6230. this.position++;
  6231. }
  6232. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6233. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6234. }
  6235. var len = attr.length;
  6236. var node = {
  6237. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6238. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6239. };
  6240. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6241. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6242. }
  6243. var pos = 0;
  6244. var spaceBefore = '';
  6245. var commentBefore = '';
  6246. var lastAdded = null;
  6247. var spaceAfterMeaningfulToken = false;
  6248. while (pos < len) {
  6249. var token = attr[pos];
  6250. var content = this.content(token);
  6251. var next = attr[pos + 1];
  6252. switch (token[_tokenize.FIELDS.TYPE]) {
  6253. case tokens.space:
  6254. // if (
  6255. // len === 1 ||
  6256. // pos === 0 && this.content(next) === '|'
  6257. // ) {
  6258. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6259. // }
  6260. spaceAfterMeaningfulToken = true;
  6261. if (this.options.lossy) {
  6262. break;
  6263. }
  6264. if (lastAdded) {
  6265. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6266. var prevContent = node.spaces[lastAdded].after || '';
  6267. node.spaces[lastAdded].after = prevContent + content;
  6268. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6269. if (existingComment) {
  6270. node.raws.spaces[lastAdded].after = existingComment + content;
  6271. }
  6272. } else {
  6273. spaceBefore = spaceBefore + content;
  6274. commentBefore = commentBefore + content;
  6275. }
  6276. break;
  6277. case tokens.asterisk:
  6278. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6279. node.operator = content;
  6280. lastAdded = 'operator';
  6281. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6282. if (spaceBefore) {
  6283. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6284. node.spaces.attribute.before = spaceBefore;
  6285. spaceBefore = '';
  6286. }
  6287. if (commentBefore) {
  6288. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6289. node.raws.spaces.attribute.before = spaceBefore;
  6290. commentBefore = '';
  6291. }
  6292. node.namespace = (node.namespace || "") + content;
  6293. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6294. if (rawValue) {
  6295. node.raws.namespace += content;
  6296. }
  6297. lastAdded = 'namespace';
  6298. }
  6299. spaceAfterMeaningfulToken = false;
  6300. break;
  6301. case tokens.dollar:
  6302. if (lastAdded === "value") {
  6303. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6304. node.value += "$";
  6305. if (oldRawValue) {
  6306. node.raws.value = oldRawValue + "$";
  6307. }
  6308. break;
  6309. }
  6310. // Falls through
  6311. case tokens.caret:
  6312. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6313. node.operator = content;
  6314. lastAdded = 'operator';
  6315. }
  6316. spaceAfterMeaningfulToken = false;
  6317. break;
  6318. case tokens.combinator:
  6319. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6320. node.operator = content;
  6321. lastAdded = 'operator';
  6322. }
  6323. if (content !== '|') {
  6324. spaceAfterMeaningfulToken = false;
  6325. break;
  6326. }
  6327. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6328. node.operator = content;
  6329. lastAdded = 'operator';
  6330. } else if (!node.namespace && !node.attribute) {
  6331. node.namespace = true;
  6332. }
  6333. spaceAfterMeaningfulToken = false;
  6334. break;
  6335. case tokens.word:
  6336. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6337. // this look-ahead probably fails with comment nodes involved.
  6338. !node.operator && !node.namespace) {
  6339. node.namespace = content;
  6340. lastAdded = 'namespace';
  6341. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6342. if (spaceBefore) {
  6343. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6344. node.spaces.attribute.before = spaceBefore;
  6345. spaceBefore = '';
  6346. }
  6347. if (commentBefore) {
  6348. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6349. node.raws.spaces.attribute.before = commentBefore;
  6350. commentBefore = '';
  6351. }
  6352. node.attribute = (node.attribute || "") + content;
  6353. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6354. if (_rawValue) {
  6355. node.raws.attribute += content;
  6356. }
  6357. lastAdded = 'attribute';
  6358. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6359. var _unescaped = (0, _util.unesc)(content);
  6360. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6361. var oldValue = node.value || '';
  6362. node.value = oldValue + _unescaped;
  6363. node.quoteMark = null;
  6364. if (_unescaped !== content || _oldRawValue) {
  6365. (0, _util.ensureObject)(node, 'raws');
  6366. node.raws.value = (_oldRawValue || oldValue) + content;
  6367. }
  6368. lastAdded = 'value';
  6369. } else {
  6370. var insensitive = content === 'i' || content === "I";
  6371. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6372. node.insensitive = insensitive;
  6373. if (!insensitive || content === "I") {
  6374. (0, _util.ensureObject)(node, 'raws');
  6375. node.raws.insensitiveFlag = content;
  6376. }
  6377. lastAdded = 'insensitive';
  6378. if (spaceBefore) {
  6379. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6380. node.spaces.insensitive.before = spaceBefore;
  6381. spaceBefore = '';
  6382. }
  6383. if (commentBefore) {
  6384. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6385. node.raws.spaces.insensitive.before = commentBefore;
  6386. commentBefore = '';
  6387. }
  6388. } else if (node.value || node.value === '') {
  6389. lastAdded = 'value';
  6390. node.value += content;
  6391. if (node.raws.value) {
  6392. node.raws.value += content;
  6393. }
  6394. }
  6395. }
  6396. spaceAfterMeaningfulToken = false;
  6397. break;
  6398. case tokens.str:
  6399. if (!node.attribute || !node.operator) {
  6400. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6401. index: token[_tokenize.FIELDS.START_POS]
  6402. });
  6403. }
  6404. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6405. unescaped = _unescapeValue.unescaped,
  6406. quoteMark = _unescapeValue.quoteMark;
  6407. node.value = unescaped;
  6408. node.quoteMark = quoteMark;
  6409. lastAdded = 'value';
  6410. (0, _util.ensureObject)(node, 'raws');
  6411. node.raws.value = content;
  6412. spaceAfterMeaningfulToken = false;
  6413. break;
  6414. case tokens.equals:
  6415. if (!node.attribute) {
  6416. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6417. }
  6418. if (node.value) {
  6419. return this.error('Unexpected "=" found; an operator was already defined.', {
  6420. index: token[_tokenize.FIELDS.START_POS]
  6421. });
  6422. }
  6423. node.operator = node.operator ? node.operator + content : content;
  6424. lastAdded = 'operator';
  6425. spaceAfterMeaningfulToken = false;
  6426. break;
  6427. case tokens.comment:
  6428. if (lastAdded) {
  6429. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6430. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6431. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6432. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6433. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6434. } else {
  6435. var lastValue = node[lastAdded] || '';
  6436. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6437. (0, _util.ensureObject)(node, 'raws');
  6438. node.raws[lastAdded] = rawLastValue + content;
  6439. }
  6440. } else {
  6441. commentBefore = commentBefore + content;
  6442. }
  6443. break;
  6444. default:
  6445. return this.error("Unexpected \"" + content + "\" found.", {
  6446. index: token[_tokenize.FIELDS.START_POS]
  6447. });
  6448. }
  6449. pos++;
  6450. }
  6451. unescapeProp(node, "attribute");
  6452. unescapeProp(node, "namespace");
  6453. this.newNode(new _attribute["default"](node));
  6454. this.position++;
  6455. }
  6456. /**
  6457. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6458. * if the token position is negative, all remaining tokens are consumed.
  6459. *
  6460. * This returns an array containing a single string node if all whitespace,
  6461. * otherwise an array of comment nodes with space before and after.
  6462. *
  6463. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6464. * a previous node's space metadata.
  6465. *
  6466. * In lossy mode, this returns only comments.
  6467. */;
  6468. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6469. if (stopPosition < 0) {
  6470. stopPosition = this.tokens.length;
  6471. }
  6472. var startPosition = this.position;
  6473. var nodes = [];
  6474. var space = "";
  6475. var lastComment = undefined;
  6476. do {
  6477. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6478. if (!this.options.lossy) {
  6479. space += this.content();
  6480. }
  6481. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6482. var spaces = {};
  6483. if (space) {
  6484. spaces.before = space;
  6485. space = "";
  6486. }
  6487. lastComment = new _comment["default"]({
  6488. value: this.content(),
  6489. source: getTokenSource(this.currToken),
  6490. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6491. spaces: spaces
  6492. });
  6493. nodes.push(lastComment);
  6494. }
  6495. } while (++this.position < stopPosition);
  6496. if (space) {
  6497. if (lastComment) {
  6498. lastComment.spaces.after = space;
  6499. } else if (!this.options.lossy) {
  6500. var firstToken = this.tokens[startPosition];
  6501. var lastToken = this.tokens[this.position - 1];
  6502. nodes.push(new _string["default"]({
  6503. value: '',
  6504. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6505. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6506. spaces: {
  6507. before: space,
  6508. after: ''
  6509. }
  6510. }));
  6511. }
  6512. }
  6513. return nodes;
  6514. }
  6515. /**
  6516. *
  6517. * @param {*} nodes
  6518. */;
  6519. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6520. var _this2 = this;
  6521. if (requiredSpace === void 0) {
  6522. requiredSpace = false;
  6523. }
  6524. var space = "";
  6525. var rawSpace = "";
  6526. nodes.forEach(function (n) {
  6527. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6528. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6529. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6530. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6531. });
  6532. if (rawSpace === space) {
  6533. rawSpace = undefined;
  6534. }
  6535. var result = {
  6536. space: space,
  6537. rawSpace: rawSpace
  6538. };
  6539. return result;
  6540. };
  6541. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6542. if (position === void 0) {
  6543. position = this.position;
  6544. }
  6545. 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;
  6546. };
  6547. _proto.namedCombinator = function namedCombinator() {
  6548. if (this.isNamedCombinator()) {
  6549. var nameRaw = this.content(this.tokens[this.position + 1]);
  6550. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6551. var raws = {};
  6552. if (name !== nameRaw) {
  6553. raws.value = "/" + nameRaw + "/";
  6554. }
  6555. var node = new _combinator["default"]({
  6556. value: "/" + name + "/",
  6557. 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]),
  6558. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6559. raws: raws
  6560. });
  6561. this.position = this.position + 3;
  6562. return node;
  6563. } else {
  6564. this.unexpected();
  6565. }
  6566. };
  6567. _proto.combinator = function combinator() {
  6568. var _this3 = this;
  6569. if (this.content() === '|') {
  6570. return this.namespace();
  6571. }
  6572. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6573. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6574. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6575. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6576. if (nodes.length > 0) {
  6577. var last = this.current.last;
  6578. if (last) {
  6579. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6580. space = _this$convertWhitespa.space,
  6581. rawSpace = _this$convertWhitespa.rawSpace;
  6582. if (rawSpace !== undefined) {
  6583. last.rawSpaceAfter += rawSpace;
  6584. }
  6585. last.spaces.after += space;
  6586. } else {
  6587. nodes.forEach(function (n) {
  6588. return _this3.newNode(n);
  6589. });
  6590. }
  6591. }
  6592. return;
  6593. }
  6594. var firstToken = this.currToken;
  6595. var spaceOrDescendantSelectorNodes = undefined;
  6596. if (nextSigTokenPos > this.position) {
  6597. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6598. }
  6599. var node;
  6600. if (this.isNamedCombinator()) {
  6601. node = this.namedCombinator();
  6602. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6603. node = new _combinator["default"]({
  6604. value: this.content(),
  6605. source: getTokenSource(this.currToken),
  6606. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6607. });
  6608. this.position++;
  6609. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6610. this.unexpected();
  6611. }
  6612. if (node) {
  6613. if (spaceOrDescendantSelectorNodes) {
  6614. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6615. _space = _this$convertWhitespa2.space,
  6616. _rawSpace = _this$convertWhitespa2.rawSpace;
  6617. node.spaces.before = _space;
  6618. node.rawSpaceBefore = _rawSpace;
  6619. }
  6620. } else {
  6621. // descendant combinator
  6622. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6623. _space2 = _this$convertWhitespa3.space,
  6624. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6625. if (!_rawSpace2) {
  6626. _rawSpace2 = _space2;
  6627. }
  6628. var spaces = {};
  6629. var raws = {
  6630. spaces: {}
  6631. };
  6632. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6633. spaces.before = _space2.slice(0, _space2.length - 1);
  6634. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6635. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  6636. spaces.after = _space2.slice(1);
  6637. raws.spaces.after = _rawSpace2.slice(1);
  6638. } else {
  6639. raws.value = _rawSpace2;
  6640. }
  6641. node = new _combinator["default"]({
  6642. value: ' ',
  6643. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6644. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6645. spaces: spaces,
  6646. raws: raws
  6647. });
  6648. }
  6649. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6650. node.spaces.after = this.optionalSpace(this.content());
  6651. this.position++;
  6652. }
  6653. return this.newNode(node);
  6654. };
  6655. _proto.comma = function comma() {
  6656. if (this.position === this.tokens.length - 1) {
  6657. this.root.trailingComma = true;
  6658. this.position++;
  6659. return;
  6660. }
  6661. this.current._inferEndPosition();
  6662. var selector = new _selector["default"]({
  6663. source: {
  6664. start: tokenStart(this.tokens[this.position + 1])
  6665. },
  6666. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6667. });
  6668. this.current.parent.append(selector);
  6669. this.current = selector;
  6670. this.position++;
  6671. };
  6672. _proto.comment = function comment() {
  6673. var current = this.currToken;
  6674. this.newNode(new _comment["default"]({
  6675. value: this.content(),
  6676. source: getTokenSource(current),
  6677. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6678. }));
  6679. this.position++;
  6680. };
  6681. _proto.error = function error(message, opts) {
  6682. throw this.root.error(message, opts);
  6683. };
  6684. _proto.missingBackslash = function missingBackslash() {
  6685. return this.error('Expected a backslash preceding the semicolon.', {
  6686. index: this.currToken[_tokenize.FIELDS.START_POS]
  6687. });
  6688. };
  6689. _proto.missingParenthesis = function missingParenthesis() {
  6690. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6691. };
  6692. _proto.missingSquareBracket = function missingSquareBracket() {
  6693. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6694. };
  6695. _proto.unexpected = function unexpected() {
  6696. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6697. };
  6698. _proto.unexpectedPipe = function unexpectedPipe() {
  6699. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6700. };
  6701. _proto.namespace = function namespace() {
  6702. var before = this.prevToken && this.content(this.prevToken) || true;
  6703. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6704. this.position++;
  6705. return this.word(before);
  6706. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6707. this.position++;
  6708. return this.universal(before);
  6709. }
  6710. this.unexpectedPipe();
  6711. };
  6712. _proto.nesting = function nesting() {
  6713. if (this.nextToken) {
  6714. var nextContent = this.content(this.nextToken);
  6715. if (nextContent === "|") {
  6716. this.position++;
  6717. return;
  6718. }
  6719. }
  6720. var current = this.currToken;
  6721. this.newNode(new _nesting["default"]({
  6722. value: this.content(),
  6723. source: getTokenSource(current),
  6724. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6725. }));
  6726. this.position++;
  6727. };
  6728. _proto.parentheses = function parentheses() {
  6729. var last = this.current.last;
  6730. var unbalanced = 1;
  6731. this.position++;
  6732. if (last && last.type === types.PSEUDO) {
  6733. var selector = new _selector["default"]({
  6734. source: {
  6735. start: tokenStart(this.tokens[this.position])
  6736. },
  6737. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6738. });
  6739. var cache = this.current;
  6740. last.append(selector);
  6741. this.current = selector;
  6742. while (this.position < this.tokens.length && unbalanced) {
  6743. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6744. unbalanced++;
  6745. }
  6746. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6747. unbalanced--;
  6748. }
  6749. if (unbalanced) {
  6750. this.parse();
  6751. } else {
  6752. this.current.source.end = tokenEnd(this.currToken);
  6753. this.current.parent.source.end = tokenEnd(this.currToken);
  6754. this.position++;
  6755. }
  6756. }
  6757. this.current = cache;
  6758. } else {
  6759. // I think this case should be an error. It's used to implement a basic parse of media queries
  6760. // but I don't think it's a good idea.
  6761. var parenStart = this.currToken;
  6762. var parenValue = "(";
  6763. var parenEnd;
  6764. while (this.position < this.tokens.length && unbalanced) {
  6765. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6766. unbalanced++;
  6767. }
  6768. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6769. unbalanced--;
  6770. }
  6771. parenEnd = this.currToken;
  6772. parenValue += this.parseParenthesisToken(this.currToken);
  6773. this.position++;
  6774. }
  6775. if (last) {
  6776. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6777. } else {
  6778. this.newNode(new _string["default"]({
  6779. value: parenValue,
  6780. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6781. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6782. }));
  6783. }
  6784. }
  6785. if (unbalanced) {
  6786. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6787. }
  6788. };
  6789. _proto.pseudo = function pseudo() {
  6790. var _this4 = this;
  6791. var pseudoStr = '';
  6792. var startingToken = this.currToken;
  6793. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6794. pseudoStr += this.content();
  6795. this.position++;
  6796. }
  6797. if (!this.currToken) {
  6798. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6799. }
  6800. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6801. this.splitWord(false, function (first, length) {
  6802. pseudoStr += first;
  6803. _this4.newNode(new _pseudo["default"]({
  6804. value: pseudoStr,
  6805. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6806. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6807. }));
  6808. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6809. _this4.error('Misplaced parenthesis.', {
  6810. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6811. });
  6812. }
  6813. });
  6814. } else {
  6815. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6816. }
  6817. };
  6818. _proto.space = function space() {
  6819. var content = this.content();
  6820. // Handle space before and after the selector
  6821. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6822. return node.type === 'comment';
  6823. })) {
  6824. this.spaces = this.optionalSpace(content);
  6825. this.position++;
  6826. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6827. this.current.last.spaces.after = this.optionalSpace(content);
  6828. this.position++;
  6829. } else {
  6830. this.combinator();
  6831. }
  6832. };
  6833. _proto.string = function string() {
  6834. var current = this.currToken;
  6835. this.newNode(new _string["default"]({
  6836. value: this.content(),
  6837. source: getTokenSource(current),
  6838. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6839. }));
  6840. this.position++;
  6841. };
  6842. _proto.universal = function universal(namespace) {
  6843. var nextToken = this.nextToken;
  6844. if (nextToken && this.content(nextToken) === '|') {
  6845. this.position++;
  6846. return this.namespace();
  6847. }
  6848. var current = this.currToken;
  6849. this.newNode(new _universal["default"]({
  6850. value: this.content(),
  6851. source: getTokenSource(current),
  6852. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6853. }), namespace);
  6854. this.position++;
  6855. };
  6856. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6857. var _this5 = this;
  6858. var nextToken = this.nextToken;
  6859. var word = this.content();
  6860. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6861. this.position++;
  6862. var current = this.content();
  6863. word += current;
  6864. if (current.lastIndexOf('\\') === current.length - 1) {
  6865. var next = this.nextToken;
  6866. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6867. word += this.requiredSpace(this.content(next));
  6868. this.position++;
  6869. }
  6870. }
  6871. nextToken = this.nextToken;
  6872. }
  6873. var hasClass = indexesOf(word, '.').filter(function (i) {
  6874. // Allow escaped dot within class name
  6875. var escapedDot = word[i - 1] === '\\';
  6876. // Allow decimal numbers percent in @keyframes
  6877. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6878. return !escapedDot && !isKeyframesPercent;
  6879. });
  6880. var hasId = indexesOf(word, '#').filter(function (i) {
  6881. return word[i - 1] !== '\\';
  6882. });
  6883. // Eliminate Sass interpolations from the list of id indexes
  6884. var interpolations = indexesOf(word, '#{');
  6885. if (interpolations.length) {
  6886. hasId = hasId.filter(function (hashIndex) {
  6887. return !~interpolations.indexOf(hashIndex);
  6888. });
  6889. }
  6890. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6891. indices.forEach(function (ind, i) {
  6892. var index = indices[i + 1] || word.length;
  6893. var value = word.slice(ind, index);
  6894. if (i === 0 && firstCallback) {
  6895. return firstCallback.call(_this5, value, indices.length);
  6896. }
  6897. var node;
  6898. var current = _this5.currToken;
  6899. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6900. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6901. if (~hasClass.indexOf(ind)) {
  6902. var classNameOpts = {
  6903. value: value.slice(1),
  6904. source: source,
  6905. sourceIndex: sourceIndex
  6906. };
  6907. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6908. } else if (~hasId.indexOf(ind)) {
  6909. var idOpts = {
  6910. value: value.slice(1),
  6911. source: source,
  6912. sourceIndex: sourceIndex
  6913. };
  6914. node = new _id["default"](unescapeProp(idOpts, "value"));
  6915. } else {
  6916. var tagOpts = {
  6917. value: value,
  6918. source: source,
  6919. sourceIndex: sourceIndex
  6920. };
  6921. unescapeProp(tagOpts, "value");
  6922. node = new _tag["default"](tagOpts);
  6923. }
  6924. _this5.newNode(node, namespace);
  6925. // Ensure that the namespace is used only once
  6926. namespace = null;
  6927. });
  6928. this.position++;
  6929. };
  6930. _proto.word = function word(namespace) {
  6931. var nextToken = this.nextToken;
  6932. if (nextToken && this.content(nextToken) === '|') {
  6933. this.position++;
  6934. return this.namespace();
  6935. }
  6936. return this.splitWord(namespace);
  6937. };
  6938. _proto.loop = function loop() {
  6939. while (this.position < this.tokens.length) {
  6940. this.parse(true);
  6941. }
  6942. this.current._inferEndPosition();
  6943. return this.root;
  6944. };
  6945. _proto.parse = function parse(throwOnParenthesis) {
  6946. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6947. case tokens.space:
  6948. this.space();
  6949. break;
  6950. case tokens.comment:
  6951. this.comment();
  6952. break;
  6953. case tokens.openParenthesis:
  6954. this.parentheses();
  6955. break;
  6956. case tokens.closeParenthesis:
  6957. if (throwOnParenthesis) {
  6958. this.missingParenthesis();
  6959. }
  6960. break;
  6961. case tokens.openSquare:
  6962. this.attribute();
  6963. break;
  6964. case tokens.dollar:
  6965. case tokens.caret:
  6966. case tokens.equals:
  6967. case tokens.word:
  6968. this.word();
  6969. break;
  6970. case tokens.colon:
  6971. this.pseudo();
  6972. break;
  6973. case tokens.comma:
  6974. this.comma();
  6975. break;
  6976. case tokens.asterisk:
  6977. this.universal();
  6978. break;
  6979. case tokens.ampersand:
  6980. this.nesting();
  6981. break;
  6982. case tokens.slash:
  6983. case tokens.combinator:
  6984. this.combinator();
  6985. break;
  6986. case tokens.str:
  6987. this.string();
  6988. break;
  6989. // These cases throw; no break needed.
  6990. case tokens.closeSquare:
  6991. this.missingSquareBracket();
  6992. case tokens.semicolon:
  6993. this.missingBackslash();
  6994. default:
  6995. this.unexpected();
  6996. }
  6997. }
  6998. /**
  6999. * Helpers
  7000. */;
  7001. _proto.expected = function expected(description, index, found) {
  7002. if (Array.isArray(description)) {
  7003. var last = description.pop();
  7004. description = description.join(', ') + " or " + last;
  7005. }
  7006. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  7007. if (!found) {
  7008. return this.error("Expected " + an + " " + description + ".", {
  7009. index: index
  7010. });
  7011. }
  7012. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  7013. index: index
  7014. });
  7015. };
  7016. _proto.requiredSpace = function requiredSpace(space) {
  7017. return this.options.lossy ? ' ' : space;
  7018. };
  7019. _proto.optionalSpace = function optionalSpace(space) {
  7020. return this.options.lossy ? '' : space;
  7021. };
  7022. _proto.lossySpace = function lossySpace(space, required) {
  7023. if (this.options.lossy) {
  7024. return required ? ' ' : '';
  7025. } else {
  7026. return space;
  7027. }
  7028. };
  7029. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  7030. var content = this.content(token);
  7031. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  7032. return this.requiredSpace(content);
  7033. } else {
  7034. return content;
  7035. }
  7036. };
  7037. _proto.newNode = function newNode(node, namespace) {
  7038. if (namespace) {
  7039. if (/^ +$/.test(namespace)) {
  7040. if (!this.options.lossy) {
  7041. this.spaces = (this.spaces || '') + namespace;
  7042. }
  7043. namespace = true;
  7044. }
  7045. node.namespace = namespace;
  7046. unescapeProp(node, "namespace");
  7047. }
  7048. if (this.spaces) {
  7049. node.spaces.before = this.spaces;
  7050. this.spaces = '';
  7051. }
  7052. return this.current.append(node);
  7053. };
  7054. _proto.content = function content(token) {
  7055. if (token === void 0) {
  7056. token = this.currToken;
  7057. }
  7058. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  7059. };
  7060. /**
  7061. * returns the index of the next non-whitespace, non-comment token.
  7062. * returns -1 if no meaningful token is found.
  7063. */
  7064. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  7065. if (startPosition === void 0) {
  7066. startPosition = this.position + 1;
  7067. }
  7068. var searchPosition = startPosition;
  7069. while (searchPosition < this.tokens.length) {
  7070. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  7071. searchPosition++;
  7072. continue;
  7073. } else {
  7074. return searchPosition;
  7075. }
  7076. }
  7077. return -1;
  7078. };
  7079. _createClass(Parser, [{
  7080. key: "currToken",
  7081. get: function get() {
  7082. return this.tokens[this.position];
  7083. }
  7084. }, {
  7085. key: "nextToken",
  7086. get: function get() {
  7087. return this.tokens[this.position + 1];
  7088. }
  7089. }, {
  7090. key: "prevToken",
  7091. get: function get() {
  7092. return this.tokens[this.position - 1];
  7093. }
  7094. }]);
  7095. return Parser;
  7096. }();
  7097. exports["default"] = Parser;
  7098. module.exports = exports.default;
  7099. } (parser$1, parser$1.exports));
  7100. return parser$1.exports;
  7101. }
  7102. var hasRequiredProcessor$1;
  7103. function requireProcessor$1 () {
  7104. if (hasRequiredProcessor$1) return processor$1.exports;
  7105. hasRequiredProcessor$1 = 1;
  7106. (function (module, exports) {
  7107. exports.__esModule = true;
  7108. exports["default"] = void 0;
  7109. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser$2());
  7110. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7111. var Processor = /*#__PURE__*/function () {
  7112. function Processor(func, options) {
  7113. this.func = func || function noop() {};
  7114. this.funcRes = null;
  7115. this.options = options;
  7116. }
  7117. var _proto = Processor.prototype;
  7118. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7119. if (options === void 0) {
  7120. options = {};
  7121. }
  7122. var merged = Object.assign({}, this.options, options);
  7123. if (merged.updateSelector === false) {
  7124. return false;
  7125. } else {
  7126. return typeof rule !== "string";
  7127. }
  7128. };
  7129. _proto._isLossy = function _isLossy(options) {
  7130. if (options === void 0) {
  7131. options = {};
  7132. }
  7133. var merged = Object.assign({}, this.options, options);
  7134. if (merged.lossless === false) {
  7135. return true;
  7136. } else {
  7137. return false;
  7138. }
  7139. };
  7140. _proto._root = function _root(rule, options) {
  7141. if (options === void 0) {
  7142. options = {};
  7143. }
  7144. var parser = new _parser["default"](rule, this._parseOptions(options));
  7145. return parser.root;
  7146. };
  7147. _proto._parseOptions = function _parseOptions(options) {
  7148. return {
  7149. lossy: this._isLossy(options)
  7150. };
  7151. };
  7152. _proto._run = function _run(rule, options) {
  7153. var _this = this;
  7154. if (options === void 0) {
  7155. options = {};
  7156. }
  7157. return new Promise(function (resolve, reject) {
  7158. try {
  7159. var root = _this._root(rule, options);
  7160. Promise.resolve(_this.func(root)).then(function (transform) {
  7161. var string = undefined;
  7162. if (_this._shouldUpdateSelector(rule, options)) {
  7163. string = root.toString();
  7164. rule.selector = string;
  7165. }
  7166. return {
  7167. transform: transform,
  7168. root: root,
  7169. string: string
  7170. };
  7171. }).then(resolve, reject);
  7172. } catch (e) {
  7173. reject(e);
  7174. return;
  7175. }
  7176. });
  7177. };
  7178. _proto._runSync = function _runSync(rule, options) {
  7179. if (options === void 0) {
  7180. options = {};
  7181. }
  7182. var root = this._root(rule, options);
  7183. var transform = this.func(root);
  7184. if (transform && typeof transform.then === "function") {
  7185. throw new Error("Selector processor returned a promise to a synchronous call.");
  7186. }
  7187. var string = undefined;
  7188. if (options.updateSelector && typeof rule !== "string") {
  7189. string = root.toString();
  7190. rule.selector = string;
  7191. }
  7192. return {
  7193. transform: transform,
  7194. root: root,
  7195. string: string
  7196. };
  7197. }
  7198. /**
  7199. * Process rule into a selector AST.
  7200. *
  7201. * @param rule {postcss.Rule | string} The css selector to be processed
  7202. * @param options The options for processing
  7203. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7204. */;
  7205. _proto.ast = function ast(rule, options) {
  7206. return this._run(rule, options).then(function (result) {
  7207. return result.root;
  7208. });
  7209. }
  7210. /**
  7211. * Process rule into a selector AST synchronously.
  7212. *
  7213. * @param rule {postcss.Rule | string} The css selector to be processed
  7214. * @param options The options for processing
  7215. * @returns {parser.Root} The AST of the selector after processing it.
  7216. */;
  7217. _proto.astSync = function astSync(rule, options) {
  7218. return this._runSync(rule, options).root;
  7219. }
  7220. /**
  7221. * Process a selector into a transformed value asynchronously
  7222. *
  7223. * @param rule {postcss.Rule | string} The css selector to be processed
  7224. * @param options The options for processing
  7225. * @returns {Promise<any>} The value returned by the processor.
  7226. */;
  7227. _proto.transform = function transform(rule, options) {
  7228. return this._run(rule, options).then(function (result) {
  7229. return result.transform;
  7230. });
  7231. }
  7232. /**
  7233. * Process a selector into a transformed value synchronously.
  7234. *
  7235. * @param rule {postcss.Rule | string} The css selector to be processed
  7236. * @param options The options for processing
  7237. * @returns {any} The value returned by the processor.
  7238. */;
  7239. _proto.transformSync = function transformSync(rule, options) {
  7240. return this._runSync(rule, options).transform;
  7241. }
  7242. /**
  7243. * Process a selector into a new selector string asynchronously.
  7244. *
  7245. * @param rule {postcss.Rule | string} The css selector to be processed
  7246. * @param options The options for processing
  7247. * @returns {string} the selector after processing.
  7248. */;
  7249. _proto.process = function process(rule, options) {
  7250. return this._run(rule, options).then(function (result) {
  7251. return result.string || result.root.toString();
  7252. });
  7253. }
  7254. /**
  7255. * Process a selector into a new selector string synchronously.
  7256. *
  7257. * @param rule {postcss.Rule | string} The css selector to be processed
  7258. * @param options The options for processing
  7259. * @returns {string} the selector after processing.
  7260. */;
  7261. _proto.processSync = function processSync(rule, options) {
  7262. var result = this._runSync(rule, options);
  7263. return result.string || result.root.toString();
  7264. };
  7265. return Processor;
  7266. }();
  7267. exports["default"] = Processor;
  7268. module.exports = exports.default;
  7269. } (processor$1, processor$1.exports));
  7270. return processor$1.exports;
  7271. }
  7272. var selectors$1 = {};
  7273. var constructors$1 = {};
  7274. var hasRequiredConstructors$1;
  7275. function requireConstructors$1 () {
  7276. if (hasRequiredConstructors$1) return constructors$1;
  7277. hasRequiredConstructors$1 = 1;
  7278. constructors$1.__esModule = true;
  7279. 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;
  7280. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute$1());
  7281. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  7282. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  7283. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  7284. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  7285. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  7286. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  7287. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  7288. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  7289. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  7290. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  7291. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  7292. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7293. var attribute = function attribute(opts) {
  7294. return new _attribute["default"](opts);
  7295. };
  7296. constructors$1.attribute = attribute;
  7297. var className = function className(opts) {
  7298. return new _className["default"](opts);
  7299. };
  7300. constructors$1.className = className;
  7301. var combinator = function combinator(opts) {
  7302. return new _combinator["default"](opts);
  7303. };
  7304. constructors$1.combinator = combinator;
  7305. var comment = function comment(opts) {
  7306. return new _comment["default"](opts);
  7307. };
  7308. constructors$1.comment = comment;
  7309. var id = function id(opts) {
  7310. return new _id["default"](opts);
  7311. };
  7312. constructors$1.id = id;
  7313. var nesting = function nesting(opts) {
  7314. return new _nesting["default"](opts);
  7315. };
  7316. constructors$1.nesting = nesting;
  7317. var pseudo = function pseudo(opts) {
  7318. return new _pseudo["default"](opts);
  7319. };
  7320. constructors$1.pseudo = pseudo;
  7321. var root = function root(opts) {
  7322. return new _root["default"](opts);
  7323. };
  7324. constructors$1.root = root;
  7325. var selector = function selector(opts) {
  7326. return new _selector["default"](opts);
  7327. };
  7328. constructors$1.selector = selector;
  7329. var string = function string(opts) {
  7330. return new _string["default"](opts);
  7331. };
  7332. constructors$1.string = string;
  7333. var tag = function tag(opts) {
  7334. return new _tag["default"](opts);
  7335. };
  7336. constructors$1.tag = tag;
  7337. var universal = function universal(opts) {
  7338. return new _universal["default"](opts);
  7339. };
  7340. constructors$1.universal = universal;
  7341. return constructors$1;
  7342. }
  7343. var guards$1 = {};
  7344. var hasRequiredGuards$1;
  7345. function requireGuards$1 () {
  7346. if (hasRequiredGuards$1) return guards$1;
  7347. hasRequiredGuards$1 = 1;
  7348. guards$1.__esModule = true;
  7349. guards$1.isComment = guards$1.isCombinator = guards$1.isClassName = guards$1.isAttribute = void 0;
  7350. guards$1.isContainer = isContainer;
  7351. guards$1.isIdentifier = void 0;
  7352. guards$1.isNamespace = isNamespace;
  7353. guards$1.isNesting = void 0;
  7354. guards$1.isNode = isNode;
  7355. guards$1.isPseudo = void 0;
  7356. guards$1.isPseudoClass = isPseudoClass;
  7357. guards$1.isPseudoElement = isPseudoElement;
  7358. guards$1.isUniversal = guards$1.isTag = guards$1.isString = guards$1.isSelector = guards$1.isRoot = void 0;
  7359. var _types = /*@__PURE__*/ requireTypes$1();
  7360. var _IS_TYPE;
  7361. 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);
  7362. function isNode(node) {
  7363. return typeof node === "object" && IS_TYPE[node.type];
  7364. }
  7365. function isNodeType(type, node) {
  7366. return isNode(node) && node.type === type;
  7367. }
  7368. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7369. guards$1.isAttribute = isAttribute;
  7370. var isClassName = isNodeType.bind(null, _types.CLASS);
  7371. guards$1.isClassName = isClassName;
  7372. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7373. guards$1.isCombinator = isCombinator;
  7374. var isComment = isNodeType.bind(null, _types.COMMENT);
  7375. guards$1.isComment = isComment;
  7376. var isIdentifier = isNodeType.bind(null, _types.ID);
  7377. guards$1.isIdentifier = isIdentifier;
  7378. var isNesting = isNodeType.bind(null, _types.NESTING);
  7379. guards$1.isNesting = isNesting;
  7380. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7381. guards$1.isPseudo = isPseudo;
  7382. var isRoot = isNodeType.bind(null, _types.ROOT);
  7383. guards$1.isRoot = isRoot;
  7384. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7385. guards$1.isSelector = isSelector;
  7386. var isString = isNodeType.bind(null, _types.STRING);
  7387. guards$1.isString = isString;
  7388. var isTag = isNodeType.bind(null, _types.TAG);
  7389. guards$1.isTag = isTag;
  7390. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7391. guards$1.isUniversal = isUniversal;
  7392. function isPseudoElement(node) {
  7393. 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");
  7394. }
  7395. function isPseudoClass(node) {
  7396. return isPseudo(node) && !isPseudoElement(node);
  7397. }
  7398. function isContainer(node) {
  7399. return !!(isNode(node) && node.walk);
  7400. }
  7401. function isNamespace(node) {
  7402. return isAttribute(node) || isTag(node);
  7403. }
  7404. return guards$1;
  7405. }
  7406. var hasRequiredSelectors$1;
  7407. function requireSelectors$1 () {
  7408. if (hasRequiredSelectors$1) return selectors$1;
  7409. hasRequiredSelectors$1 = 1;
  7410. (function (exports) {
  7411. exports.__esModule = true;
  7412. var _types = /*@__PURE__*/ requireTypes$1();
  7413. Object.keys(_types).forEach(function (key) {
  7414. if (key === "default" || key === "__esModule") return;
  7415. if (key in exports && exports[key] === _types[key]) return;
  7416. exports[key] = _types[key];
  7417. });
  7418. var _constructors = /*@__PURE__*/ requireConstructors$1();
  7419. Object.keys(_constructors).forEach(function (key) {
  7420. if (key === "default" || key === "__esModule") return;
  7421. if (key in exports && exports[key] === _constructors[key]) return;
  7422. exports[key] = _constructors[key];
  7423. });
  7424. var _guards = /*@__PURE__*/ requireGuards$1();
  7425. Object.keys(_guards).forEach(function (key) {
  7426. if (key === "default" || key === "__esModule") return;
  7427. if (key in exports && exports[key] === _guards[key]) return;
  7428. exports[key] = _guards[key];
  7429. });
  7430. } (selectors$1));
  7431. return selectors$1;
  7432. }
  7433. var hasRequiredDist$1;
  7434. function requireDist$1 () {
  7435. if (hasRequiredDist$1) return dist$1.exports;
  7436. hasRequiredDist$1 = 1;
  7437. (function (module, exports) {
  7438. exports.__esModule = true;
  7439. exports["default"] = void 0;
  7440. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor$1());
  7441. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors$1());
  7442. 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); }
  7443. 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; }
  7444. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7445. var parser = function parser(processor) {
  7446. return new _processor["default"](processor);
  7447. };
  7448. Object.assign(parser, selectors);
  7449. delete parser.__esModule;
  7450. var _default = parser;
  7451. exports["default"] = _default;
  7452. module.exports = exports.default;
  7453. } (dist$1, dist$1.exports));
  7454. return dist$1.exports;
  7455. }
  7456. var distExports = /*@__PURE__*/ requireDist$1();
  7457. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7458. const animationNameRE = /^(-\w+-)?animation-name$/;
  7459. const animationRE = /^(-\w+-)?animation$/;
  7460. const scopedPlugin = (id = "") => {
  7461. const keyframes = /* @__PURE__ */ Object.create(null);
  7462. const shortId = id.replace(/^data-v-/, "");
  7463. return {
  7464. postcssPlugin: "vue-sfc-scoped",
  7465. Rule(rule) {
  7466. processRule(id, rule);
  7467. },
  7468. AtRule(node) {
  7469. if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7470. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7471. }
  7472. },
  7473. OnceExit(root) {
  7474. if (Object.keys(keyframes).length) {
  7475. root.walkDecls((decl) => {
  7476. if (animationNameRE.test(decl.prop)) {
  7477. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7478. }
  7479. if (animationRE.test(decl.prop)) {
  7480. decl.value = decl.value.split(",").map((v) => {
  7481. const vals = v.trim().split(/\s+/);
  7482. const i = vals.findIndex((val) => keyframes[val]);
  7483. if (i !== -1) {
  7484. vals.splice(i, 1, keyframes[vals[i]]);
  7485. return vals.join(" ");
  7486. } else {
  7487. return v;
  7488. }
  7489. }).join(",");
  7490. }
  7491. });
  7492. }
  7493. }
  7494. };
  7495. };
  7496. const processedRules = /* @__PURE__ */ new WeakSet();
  7497. function processRule(id, rule) {
  7498. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) {
  7499. return;
  7500. }
  7501. processedRules.add(rule);
  7502. let deep = false;
  7503. let parent = rule.parent;
  7504. while (parent && parent.type !== "root") {
  7505. if (parent.__deep) {
  7506. deep = true;
  7507. break;
  7508. }
  7509. parent = parent.parent;
  7510. }
  7511. rule.selector = selectorParser((selectorRoot) => {
  7512. selectorRoot.each((selector) => {
  7513. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7514. });
  7515. }).processSync(rule.selector);
  7516. }
  7517. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7518. let node = null;
  7519. let shouldInject = !deep;
  7520. selector.each((n) => {
  7521. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7522. n.value = " ";
  7523. n.spaces.before = n.spaces.after = "";
  7524. warn(
  7525. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7526. );
  7527. return false;
  7528. }
  7529. if (n.type === "pseudo") {
  7530. const { value } = n;
  7531. if (value === ":deep" || value === "::v-deep") {
  7532. rule.__deep = true;
  7533. if (n.nodes.length) {
  7534. let last = n;
  7535. n.nodes[0].each((ss) => {
  7536. selector.insertAfter(last, ss);
  7537. last = ss;
  7538. });
  7539. const prev = selector.at(selector.index(n) - 1);
  7540. if (!prev || !isSpaceCombinator(prev)) {
  7541. selector.insertAfter(
  7542. n,
  7543. selectorParser.combinator({
  7544. value: " "
  7545. })
  7546. );
  7547. }
  7548. selector.removeChild(n);
  7549. } else {
  7550. warn(
  7551. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7552. );
  7553. const prev = selector.at(selector.index(n) - 1);
  7554. if (prev && isSpaceCombinator(prev)) {
  7555. selector.removeChild(prev);
  7556. }
  7557. selector.removeChild(n);
  7558. }
  7559. return false;
  7560. }
  7561. if (value === ":slotted" || value === "::v-slotted") {
  7562. rewriteSelector(
  7563. id,
  7564. rule,
  7565. n.nodes[0],
  7566. selectorRoot,
  7567. deep,
  7568. true
  7569. );
  7570. let last = n;
  7571. n.nodes[0].each((ss) => {
  7572. selector.insertAfter(last, ss);
  7573. last = ss;
  7574. });
  7575. selector.removeChild(n);
  7576. shouldInject = false;
  7577. return false;
  7578. }
  7579. if (value === ":global" || value === "::v-global") {
  7580. selector.replaceWith(n.nodes[0]);
  7581. return false;
  7582. }
  7583. }
  7584. if (n.type === "universal") {
  7585. const prev = selector.at(selector.index(n) - 1);
  7586. const next = selector.at(selector.index(n) + 1);
  7587. if (!prev) {
  7588. if (next) {
  7589. if (next.type === "combinator" && next.value === " ") {
  7590. selector.removeChild(next);
  7591. }
  7592. selector.removeChild(n);
  7593. return;
  7594. } else {
  7595. node = selectorParser.combinator({
  7596. value: ""
  7597. });
  7598. selector.insertBefore(n, node);
  7599. selector.removeChild(n);
  7600. return false;
  7601. }
  7602. }
  7603. if (node) return;
  7604. }
  7605. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node) {
  7606. node = n;
  7607. }
  7608. });
  7609. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7610. const deep2 = rule.__deep;
  7611. if (!deep2) {
  7612. extractAndWrapNodes(rule);
  7613. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7614. for (const atnode of atruleNodes) {
  7615. extractAndWrapNodes(atnode);
  7616. }
  7617. }
  7618. shouldInject = deep2;
  7619. }
  7620. if (node) {
  7621. const { type, value } = node;
  7622. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7623. node.nodes.forEach(
  7624. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7625. );
  7626. shouldInject = false;
  7627. }
  7628. }
  7629. if (node) {
  7630. node.spaces.after = "";
  7631. } else {
  7632. selector.first.spaces.before = "";
  7633. }
  7634. if (shouldInject) {
  7635. const idToAdd = slotted ? id + "-s" : id;
  7636. selector.insertAfter(
  7637. // If node is null it means we need to inject [id] at the start
  7638. // insertAfter can handle `null` here
  7639. node,
  7640. selectorParser.attribute({
  7641. attribute: idToAdd,
  7642. value: idToAdd,
  7643. raws: {},
  7644. quoteMark: `"`
  7645. })
  7646. );
  7647. }
  7648. }
  7649. function isSpaceCombinator(node) {
  7650. return node.type === "combinator" && /^\s+$/.test(node.value);
  7651. }
  7652. function extractAndWrapNodes(parentNode) {
  7653. if (!parentNode.nodes) return;
  7654. const nodes = parentNode.nodes.filter(
  7655. (node) => node.type === "decl" || node.type === "comment"
  7656. );
  7657. if (nodes.length) {
  7658. for (const node of nodes) {
  7659. parentNode.removeChild(node);
  7660. }
  7661. const wrappedRule = new require$$0$1.Rule({
  7662. nodes,
  7663. selector: "&"
  7664. });
  7665. parentNode.prepend(wrappedRule);
  7666. }
  7667. }
  7668. scopedPlugin.postcss = true;
  7669. var sourceMap = {};
  7670. var sourceMapGenerator = {};
  7671. var base64Vlq = {};
  7672. var base64 = {};
  7673. /* -*- Mode: js; js-indent-level: 2; -*- */
  7674. var hasRequiredBase64;
  7675. function requireBase64 () {
  7676. if (hasRequiredBase64) return base64;
  7677. hasRequiredBase64 = 1;
  7678. /*
  7679. * Copyright 2011 Mozilla Foundation and contributors
  7680. * Licensed under the New BSD license. See LICENSE or:
  7681. * http://opensource.org/licenses/BSD-3-Clause
  7682. */
  7683. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7684. /**
  7685. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7686. */
  7687. base64.encode = function (number) {
  7688. if (0 <= number && number < intToCharMap.length) {
  7689. return intToCharMap[number];
  7690. }
  7691. throw new TypeError("Must be between 0 and 63: " + number);
  7692. };
  7693. /**
  7694. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7695. * failure.
  7696. */
  7697. base64.decode = function (charCode) {
  7698. var bigA = 65; // 'A'
  7699. var bigZ = 90; // 'Z'
  7700. var littleA = 97; // 'a'
  7701. var littleZ = 122; // 'z'
  7702. var zero = 48; // '0'
  7703. var nine = 57; // '9'
  7704. var plus = 43; // '+'
  7705. var slash = 47; // '/'
  7706. var littleOffset = 26;
  7707. var numberOffset = 52;
  7708. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7709. if (bigA <= charCode && charCode <= bigZ) {
  7710. return (charCode - bigA);
  7711. }
  7712. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7713. if (littleA <= charCode && charCode <= littleZ) {
  7714. return (charCode - littleA + littleOffset);
  7715. }
  7716. // 52 - 61: 0123456789
  7717. if (zero <= charCode && charCode <= nine) {
  7718. return (charCode - zero + numberOffset);
  7719. }
  7720. // 62: +
  7721. if (charCode == plus) {
  7722. return 62;
  7723. }
  7724. // 63: /
  7725. if (charCode == slash) {
  7726. return 63;
  7727. }
  7728. // Invalid base64 digit.
  7729. return -1;
  7730. };
  7731. return base64;
  7732. }
  7733. /* -*- Mode: js; js-indent-level: 2; -*- */
  7734. var hasRequiredBase64Vlq;
  7735. function requireBase64Vlq () {
  7736. if (hasRequiredBase64Vlq) return base64Vlq;
  7737. hasRequiredBase64Vlq = 1;
  7738. /*
  7739. * Copyright 2011 Mozilla Foundation and contributors
  7740. * Licensed under the New BSD license. See LICENSE or:
  7741. * http://opensource.org/licenses/BSD-3-Clause
  7742. *
  7743. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7744. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7745. *
  7746. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7747. * Redistribution and use in source and binary forms, with or without
  7748. * modification, are permitted provided that the following conditions are
  7749. * met:
  7750. *
  7751. * * Redistributions of source code must retain the above copyright
  7752. * notice, this list of conditions and the following disclaimer.
  7753. * * Redistributions in binary form must reproduce the above
  7754. * copyright notice, this list of conditions and the following
  7755. * disclaimer in the documentation and/or other materials provided
  7756. * with the distribution.
  7757. * * Neither the name of Google Inc. nor the names of its
  7758. * contributors may be used to endorse or promote products derived
  7759. * from this software without specific prior written permission.
  7760. *
  7761. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7762. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7763. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7764. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7765. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7766. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7767. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7768. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7769. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7770. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7771. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7772. */
  7773. var base64 = /*@__PURE__*/ requireBase64();
  7774. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7775. // length quantities we use in the source map spec, the first bit is the sign,
  7776. // the next four bits are the actual value, and the 6th bit is the
  7777. // continuation bit. The continuation bit tells us whether there are more
  7778. // digits in this value following this digit.
  7779. //
  7780. // Continuation
  7781. // | Sign
  7782. // | |
  7783. // V V
  7784. // 101011
  7785. var VLQ_BASE_SHIFT = 5;
  7786. // binary: 100000
  7787. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7788. // binary: 011111
  7789. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7790. // binary: 100000
  7791. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7792. /**
  7793. * Converts from a two-complement value to a value where the sign bit is
  7794. * placed in the least significant bit. For example, as decimals:
  7795. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7796. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7797. */
  7798. function toVLQSigned(aValue) {
  7799. return aValue < 0
  7800. ? ((-aValue) << 1) + 1
  7801. : (aValue << 1) + 0;
  7802. }
  7803. /**
  7804. * Converts to a two-complement value from a value where the sign bit is
  7805. * placed in the least significant bit. For example, as decimals:
  7806. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7807. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7808. */
  7809. function fromVLQSigned(aValue) {
  7810. var isNegative = (aValue & 1) === 1;
  7811. var shifted = aValue >> 1;
  7812. return isNegative
  7813. ? -shifted
  7814. : shifted;
  7815. }
  7816. /**
  7817. * Returns the base 64 VLQ encoded value.
  7818. */
  7819. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7820. var encoded = "";
  7821. var digit;
  7822. var vlq = toVLQSigned(aValue);
  7823. do {
  7824. digit = vlq & VLQ_BASE_MASK;
  7825. vlq >>>= VLQ_BASE_SHIFT;
  7826. if (vlq > 0) {
  7827. // There are still more digits in this value, so we must make sure the
  7828. // continuation bit is marked.
  7829. digit |= VLQ_CONTINUATION_BIT;
  7830. }
  7831. encoded += base64.encode(digit);
  7832. } while (vlq > 0);
  7833. return encoded;
  7834. };
  7835. /**
  7836. * Decodes the next base 64 VLQ value from the given string and returns the
  7837. * value and the rest of the string via the out parameter.
  7838. */
  7839. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7840. var strLen = aStr.length;
  7841. var result = 0;
  7842. var shift = 0;
  7843. var continuation, digit;
  7844. do {
  7845. if (aIndex >= strLen) {
  7846. throw new Error("Expected more digits in base 64 VLQ value.");
  7847. }
  7848. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7849. if (digit === -1) {
  7850. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7851. }
  7852. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7853. digit &= VLQ_BASE_MASK;
  7854. result = result + (digit << shift);
  7855. shift += VLQ_BASE_SHIFT;
  7856. } while (continuation);
  7857. aOutParam.value = fromVLQSigned(result);
  7858. aOutParam.rest = aIndex;
  7859. };
  7860. return base64Vlq;
  7861. }
  7862. var util$1 = {};
  7863. /* -*- Mode: js; js-indent-level: 2; -*- */
  7864. var hasRequiredUtil$1;
  7865. function requireUtil$1 () {
  7866. if (hasRequiredUtil$1) return util$1;
  7867. hasRequiredUtil$1 = 1;
  7868. (function (exports) {
  7869. /*
  7870. * Copyright 2011 Mozilla Foundation and contributors
  7871. * Licensed under the New BSD license. See LICENSE or:
  7872. * http://opensource.org/licenses/BSD-3-Clause
  7873. */
  7874. /**
  7875. * This is a helper function for getting values from parameter/options
  7876. * objects.
  7877. *
  7878. * @param args The object we are extracting values from
  7879. * @param name The name of the property we are getting.
  7880. * @param defaultValue An optional value to return if the property is missing
  7881. * from the object. If this is not specified and the property is missing, an
  7882. * error will be thrown.
  7883. */
  7884. function getArg(aArgs, aName, aDefaultValue) {
  7885. if (aName in aArgs) {
  7886. return aArgs[aName];
  7887. } else if (arguments.length === 3) {
  7888. return aDefaultValue;
  7889. } else {
  7890. throw new Error('"' + aName + '" is a required argument.');
  7891. }
  7892. }
  7893. exports.getArg = getArg;
  7894. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7895. var dataUrlRegexp = /^data:.+\,.+$/;
  7896. function urlParse(aUrl) {
  7897. var match = aUrl.match(urlRegexp);
  7898. if (!match) {
  7899. return null;
  7900. }
  7901. return {
  7902. scheme: match[1],
  7903. auth: match[2],
  7904. host: match[3],
  7905. port: match[4],
  7906. path: match[5]
  7907. };
  7908. }
  7909. exports.urlParse = urlParse;
  7910. function urlGenerate(aParsedUrl) {
  7911. var url = '';
  7912. if (aParsedUrl.scheme) {
  7913. url += aParsedUrl.scheme + ':';
  7914. }
  7915. url += '//';
  7916. if (aParsedUrl.auth) {
  7917. url += aParsedUrl.auth + '@';
  7918. }
  7919. if (aParsedUrl.host) {
  7920. url += aParsedUrl.host;
  7921. }
  7922. if (aParsedUrl.port) {
  7923. url += ":" + aParsedUrl.port;
  7924. }
  7925. if (aParsedUrl.path) {
  7926. url += aParsedUrl.path;
  7927. }
  7928. return url;
  7929. }
  7930. exports.urlGenerate = urlGenerate;
  7931. /**
  7932. * Normalizes a path, or the path portion of a URL:
  7933. *
  7934. * - Replaces consecutive slashes with one slash.
  7935. * - Removes unnecessary '.' parts.
  7936. * - Removes unnecessary '<dir>/..' parts.
  7937. *
  7938. * Based on code in the Node.js 'path' core module.
  7939. *
  7940. * @param aPath The path or url to normalize.
  7941. */
  7942. function normalize(aPath) {
  7943. var path = aPath;
  7944. var url = urlParse(aPath);
  7945. if (url) {
  7946. if (!url.path) {
  7947. return aPath;
  7948. }
  7949. path = url.path;
  7950. }
  7951. var isAbsolute = exports.isAbsolute(path);
  7952. var parts = path.split(/\/+/);
  7953. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7954. part = parts[i];
  7955. if (part === '.') {
  7956. parts.splice(i, 1);
  7957. } else if (part === '..') {
  7958. up++;
  7959. } else if (up > 0) {
  7960. if (part === '') {
  7961. // The first part is blank if the path is absolute. Trying to go
  7962. // above the root is a no-op. Therefore we can remove all '..' parts
  7963. // directly after the root.
  7964. parts.splice(i + 1, up);
  7965. up = 0;
  7966. } else {
  7967. parts.splice(i, 2);
  7968. up--;
  7969. }
  7970. }
  7971. }
  7972. path = parts.join('/');
  7973. if (path === '') {
  7974. path = isAbsolute ? '/' : '.';
  7975. }
  7976. if (url) {
  7977. url.path = path;
  7978. return urlGenerate(url);
  7979. }
  7980. return path;
  7981. }
  7982. exports.normalize = normalize;
  7983. /**
  7984. * Joins two paths/URLs.
  7985. *
  7986. * @param aRoot The root path or URL.
  7987. * @param aPath The path or URL to be joined with the root.
  7988. *
  7989. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  7990. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  7991. * first.
  7992. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  7993. * is updated with the result and aRoot is returned. Otherwise the result
  7994. * is returned.
  7995. * - If aPath is absolute, the result is aPath.
  7996. * - Otherwise the two paths are joined with a slash.
  7997. * - Joining for example 'http://' and 'www.example.com' is also supported.
  7998. */
  7999. function join(aRoot, aPath) {
  8000. if (aRoot === "") {
  8001. aRoot = ".";
  8002. }
  8003. if (aPath === "") {
  8004. aPath = ".";
  8005. }
  8006. var aPathUrl = urlParse(aPath);
  8007. var aRootUrl = urlParse(aRoot);
  8008. if (aRootUrl) {
  8009. aRoot = aRootUrl.path || '/';
  8010. }
  8011. // `join(foo, '//www.example.org')`
  8012. if (aPathUrl && !aPathUrl.scheme) {
  8013. if (aRootUrl) {
  8014. aPathUrl.scheme = aRootUrl.scheme;
  8015. }
  8016. return urlGenerate(aPathUrl);
  8017. }
  8018. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8019. return aPath;
  8020. }
  8021. // `join('http://', 'www.example.com')`
  8022. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8023. aRootUrl.host = aPath;
  8024. return urlGenerate(aRootUrl);
  8025. }
  8026. var joined = aPath.charAt(0) === '/'
  8027. ? aPath
  8028. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8029. if (aRootUrl) {
  8030. aRootUrl.path = joined;
  8031. return urlGenerate(aRootUrl);
  8032. }
  8033. return joined;
  8034. }
  8035. exports.join = join;
  8036. exports.isAbsolute = function (aPath) {
  8037. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8038. };
  8039. /**
  8040. * Make a path relative to a URL or another path.
  8041. *
  8042. * @param aRoot The root path or URL.
  8043. * @param aPath The path or URL to be made relative to aRoot.
  8044. */
  8045. function relative(aRoot, aPath) {
  8046. if (aRoot === "") {
  8047. aRoot = ".";
  8048. }
  8049. aRoot = aRoot.replace(/\/$/, '');
  8050. // It is possible for the path to be above the root. In this case, simply
  8051. // checking whether the root is a prefix of the path won't work. Instead, we
  8052. // need to remove components from the root one by one, until either we find
  8053. // a prefix that fits, or we run out of components to remove.
  8054. var level = 0;
  8055. while (aPath.indexOf(aRoot + '/') !== 0) {
  8056. var index = aRoot.lastIndexOf("/");
  8057. if (index < 0) {
  8058. return aPath;
  8059. }
  8060. // If the only part of the root that is left is the scheme (i.e. http://,
  8061. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8062. // have exhausted all components, so the path is not relative to the root.
  8063. aRoot = aRoot.slice(0, index);
  8064. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8065. return aPath;
  8066. }
  8067. ++level;
  8068. }
  8069. // Make sure we add a "../" for each component we removed from the root.
  8070. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8071. }
  8072. exports.relative = relative;
  8073. var supportsNullProto = (function () {
  8074. var obj = Object.create(null);
  8075. return !('__proto__' in obj);
  8076. }());
  8077. function identity (s) {
  8078. return s;
  8079. }
  8080. /**
  8081. * Because behavior goes wacky when you set `__proto__` on objects, we
  8082. * have to prefix all the strings in our set with an arbitrary character.
  8083. *
  8084. * See https://github.com/mozilla/source-map/pull/31 and
  8085. * https://github.com/mozilla/source-map/issues/30
  8086. *
  8087. * @param String aStr
  8088. */
  8089. function toSetString(aStr) {
  8090. if (isProtoString(aStr)) {
  8091. return '$' + aStr;
  8092. }
  8093. return aStr;
  8094. }
  8095. exports.toSetString = supportsNullProto ? identity : toSetString;
  8096. function fromSetString(aStr) {
  8097. if (isProtoString(aStr)) {
  8098. return aStr.slice(1);
  8099. }
  8100. return aStr;
  8101. }
  8102. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  8103. function isProtoString(s) {
  8104. if (!s) {
  8105. return false;
  8106. }
  8107. var length = s.length;
  8108. if (length < 9 /* "__proto__".length */) {
  8109. return false;
  8110. }
  8111. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8112. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8113. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8114. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8115. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8116. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8117. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8118. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8119. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8120. return false;
  8121. }
  8122. for (var i = length - 10; i >= 0; i--) {
  8123. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8124. return false;
  8125. }
  8126. }
  8127. return true;
  8128. }
  8129. /**
  8130. * Comparator between two mappings where the original positions are compared.
  8131. *
  8132. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8133. * mappings with the same original source/line/column, but different generated
  8134. * line and column the same. Useful when searching for a mapping with a
  8135. * stubbed out mapping.
  8136. */
  8137. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8138. var cmp = strcmp(mappingA.source, mappingB.source);
  8139. if (cmp !== 0) {
  8140. return cmp;
  8141. }
  8142. cmp = mappingA.originalLine - mappingB.originalLine;
  8143. if (cmp !== 0) {
  8144. return cmp;
  8145. }
  8146. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8147. if (cmp !== 0 || onlyCompareOriginal) {
  8148. return cmp;
  8149. }
  8150. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8151. if (cmp !== 0) {
  8152. return cmp;
  8153. }
  8154. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8155. if (cmp !== 0) {
  8156. return cmp;
  8157. }
  8158. return strcmp(mappingA.name, mappingB.name);
  8159. }
  8160. exports.compareByOriginalPositions = compareByOriginalPositions;
  8161. /**
  8162. * Comparator between two mappings with deflated source and name indices where
  8163. * the generated positions are compared.
  8164. *
  8165. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8166. * mappings with the same generated line and column, but different
  8167. * source/name/original line and column the same. Useful when searching for a
  8168. * mapping with a stubbed out mapping.
  8169. */
  8170. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8171. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8172. if (cmp !== 0) {
  8173. return cmp;
  8174. }
  8175. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8176. if (cmp !== 0 || onlyCompareGenerated) {
  8177. return cmp;
  8178. }
  8179. 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) {
  8189. return cmp;
  8190. }
  8191. return strcmp(mappingA.name, mappingB.name);
  8192. }
  8193. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8194. function strcmp(aStr1, aStr2) {
  8195. if (aStr1 === aStr2) {
  8196. return 0;
  8197. }
  8198. if (aStr1 === null) {
  8199. return 1; // aStr2 !== null
  8200. }
  8201. if (aStr2 === null) {
  8202. return -1; // aStr1 !== null
  8203. }
  8204. if (aStr1 > aStr2) {
  8205. return 1;
  8206. }
  8207. return -1;
  8208. }
  8209. /**
  8210. * Comparator between two mappings with inflated source and name strings where
  8211. * the generated positions are compared.
  8212. */
  8213. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8214. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8215. if (cmp !== 0) {
  8216. return cmp;
  8217. }
  8218. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8219. if (cmp !== 0) {
  8220. return cmp;
  8221. }
  8222. cmp = strcmp(mappingA.source, mappingB.source);
  8223. if (cmp !== 0) {
  8224. return cmp;
  8225. }
  8226. cmp = mappingA.originalLine - mappingB.originalLine;
  8227. if (cmp !== 0) {
  8228. return cmp;
  8229. }
  8230. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8231. if (cmp !== 0) {
  8232. return cmp;
  8233. }
  8234. return strcmp(mappingA.name, mappingB.name);
  8235. }
  8236. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8237. /**
  8238. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8239. * in the source maps specification), and then parse the string as
  8240. * JSON.
  8241. */
  8242. function parseSourceMapInput(str) {
  8243. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8244. }
  8245. exports.parseSourceMapInput = parseSourceMapInput;
  8246. /**
  8247. * Compute the URL of a source given the the source root, the source's
  8248. * URL, and the source map's URL.
  8249. */
  8250. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8251. sourceURL = sourceURL || '';
  8252. if (sourceRoot) {
  8253. // This follows what Chrome does.
  8254. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8255. sourceRoot += '/';
  8256. }
  8257. // The spec says:
  8258. // Line 4: An optional source root, useful for relocating source
  8259. // files on a server or removing repeated values in the
  8260. // “sources” entry. This value is prepended to the individual
  8261. // entries in the “source” field.
  8262. sourceURL = sourceRoot + sourceURL;
  8263. }
  8264. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8265. // a parameter. This mode is still somewhat supported, which is why
  8266. // this code block is conditional. However, it's preferable to pass
  8267. // the source map URL to SourceMapConsumer, so that this function
  8268. // can implement the source URL resolution algorithm as outlined in
  8269. // the spec. This block is basically the equivalent of:
  8270. // new URL(sourceURL, sourceMapURL).toString()
  8271. // ... except it avoids using URL, which wasn't available in the
  8272. // older releases of node still supported by this library.
  8273. //
  8274. // The spec says:
  8275. // If the sources are not absolute URLs after prepending of the
  8276. // “sourceRoot”, the sources are resolved relative to the
  8277. // SourceMap (like resolving script src in a html document).
  8278. if (sourceMapURL) {
  8279. var parsed = urlParse(sourceMapURL);
  8280. if (!parsed) {
  8281. throw new Error("sourceMapURL could not be parsed");
  8282. }
  8283. if (parsed.path) {
  8284. // Strip the last path component, but keep the "/".
  8285. var index = parsed.path.lastIndexOf('/');
  8286. if (index >= 0) {
  8287. parsed.path = parsed.path.substring(0, index + 1);
  8288. }
  8289. }
  8290. sourceURL = join(urlGenerate(parsed), sourceURL);
  8291. }
  8292. return normalize(sourceURL);
  8293. }
  8294. exports.computeSourceURL = computeSourceURL;
  8295. } (util$1));
  8296. return util$1;
  8297. }
  8298. var arraySet = {};
  8299. /* -*- Mode: js; js-indent-level: 2; -*- */
  8300. var hasRequiredArraySet;
  8301. function requireArraySet () {
  8302. if (hasRequiredArraySet) return arraySet;
  8303. hasRequiredArraySet = 1;
  8304. /*
  8305. * Copyright 2011 Mozilla Foundation and contributors
  8306. * Licensed under the New BSD license. See LICENSE or:
  8307. * http://opensource.org/licenses/BSD-3-Clause
  8308. */
  8309. var util = /*@__PURE__*/ requireUtil$1();
  8310. var has = Object.prototype.hasOwnProperty;
  8311. var hasNativeMap = typeof Map !== "undefined";
  8312. /**
  8313. * A data structure which is a combination of an array and a set. Adding a new
  8314. * member is O(1), testing for membership is O(1), and finding the index of an
  8315. * element is O(1). Removing elements from the set is not supported. Only
  8316. * strings are supported for membership.
  8317. */
  8318. function ArraySet() {
  8319. this._array = [];
  8320. this._set = hasNativeMap ? new Map() : Object.create(null);
  8321. }
  8322. /**
  8323. * Static method for creating ArraySet instances from an existing array.
  8324. */
  8325. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8326. var set = new ArraySet();
  8327. for (var i = 0, len = aArray.length; i < len; i++) {
  8328. set.add(aArray[i], aAllowDuplicates);
  8329. }
  8330. return set;
  8331. };
  8332. /**
  8333. * Return how many unique items are in this ArraySet. If duplicates have been
  8334. * added, than those do not count towards the size.
  8335. *
  8336. * @returns Number
  8337. */
  8338. ArraySet.prototype.size = function ArraySet_size() {
  8339. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8340. };
  8341. /**
  8342. * Add the given string to this set.
  8343. *
  8344. * @param String aStr
  8345. */
  8346. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8347. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8348. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8349. var idx = this._array.length;
  8350. if (!isDuplicate || aAllowDuplicates) {
  8351. this._array.push(aStr);
  8352. }
  8353. if (!isDuplicate) {
  8354. if (hasNativeMap) {
  8355. this._set.set(aStr, idx);
  8356. } else {
  8357. this._set[sStr] = idx;
  8358. }
  8359. }
  8360. };
  8361. /**
  8362. * Is the given string a member of this set?
  8363. *
  8364. * @param String aStr
  8365. */
  8366. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8367. if (hasNativeMap) {
  8368. return this._set.has(aStr);
  8369. } else {
  8370. var sStr = util.toSetString(aStr);
  8371. return has.call(this._set, sStr);
  8372. }
  8373. };
  8374. /**
  8375. * What is the index of the given string in the array?
  8376. *
  8377. * @param String aStr
  8378. */
  8379. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8380. if (hasNativeMap) {
  8381. var idx = this._set.get(aStr);
  8382. if (idx >= 0) {
  8383. return idx;
  8384. }
  8385. } else {
  8386. var sStr = util.toSetString(aStr);
  8387. if (has.call(this._set, sStr)) {
  8388. return this._set[sStr];
  8389. }
  8390. }
  8391. throw new Error('"' + aStr + '" is not in the set.');
  8392. };
  8393. /**
  8394. * What is the element at the given index?
  8395. *
  8396. * @param Number aIdx
  8397. */
  8398. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8399. if (aIdx >= 0 && aIdx < this._array.length) {
  8400. return this._array[aIdx];
  8401. }
  8402. throw new Error('No element indexed by ' + aIdx);
  8403. };
  8404. /**
  8405. * Returns the array representation of this set (which has the proper indices
  8406. * indicated by indexOf). Note that this is a copy of the internal array used
  8407. * for storing the members so that no one can mess with internal state.
  8408. */
  8409. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8410. return this._array.slice();
  8411. };
  8412. arraySet.ArraySet = ArraySet;
  8413. return arraySet;
  8414. }
  8415. var mappingList = {};
  8416. /* -*- Mode: js; js-indent-level: 2; -*- */
  8417. var hasRequiredMappingList;
  8418. function requireMappingList () {
  8419. if (hasRequiredMappingList) return mappingList;
  8420. hasRequiredMappingList = 1;
  8421. /*
  8422. * Copyright 2014 Mozilla Foundation and contributors
  8423. * Licensed under the New BSD license. See LICENSE or:
  8424. * http://opensource.org/licenses/BSD-3-Clause
  8425. */
  8426. var util = /*@__PURE__*/ requireUtil$1();
  8427. /**
  8428. * Determine whether mappingB is after mappingA with respect to generated
  8429. * position.
  8430. */
  8431. function generatedPositionAfter(mappingA, mappingB) {
  8432. // Optimized for most common case
  8433. var lineA = mappingA.generatedLine;
  8434. var lineB = mappingB.generatedLine;
  8435. var columnA = mappingA.generatedColumn;
  8436. var columnB = mappingB.generatedColumn;
  8437. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8438. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8439. }
  8440. /**
  8441. * A data structure to provide a sorted view of accumulated mappings in a
  8442. * performance conscious manner. It trades a neglibable overhead in general
  8443. * case for a large speedup in case of mappings being added in order.
  8444. */
  8445. function MappingList() {
  8446. this._array = [];
  8447. this._sorted = true;
  8448. // Serves as infimum
  8449. this._last = {generatedLine: -1, generatedColumn: 0};
  8450. }
  8451. /**
  8452. * Iterate through internal items. This method takes the same arguments that
  8453. * `Array.prototype.forEach` takes.
  8454. *
  8455. * NOTE: The order of the mappings is NOT guaranteed.
  8456. */
  8457. MappingList.prototype.unsortedForEach =
  8458. function MappingList_forEach(aCallback, aThisArg) {
  8459. this._array.forEach(aCallback, aThisArg);
  8460. };
  8461. /**
  8462. * Add the given source mapping.
  8463. *
  8464. * @param Object aMapping
  8465. */
  8466. MappingList.prototype.add = function MappingList_add(aMapping) {
  8467. if (generatedPositionAfter(this._last, aMapping)) {
  8468. this._last = aMapping;
  8469. this._array.push(aMapping);
  8470. } else {
  8471. this._sorted = false;
  8472. this._array.push(aMapping);
  8473. }
  8474. };
  8475. /**
  8476. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8477. * generated position.
  8478. *
  8479. * WARNING: This method returns internal data without copying, for
  8480. * performance. The return value must NOT be mutated, and should be treated as
  8481. * an immutable borrow. If you want to take ownership, you must make your own
  8482. * copy.
  8483. */
  8484. MappingList.prototype.toArray = function MappingList_toArray() {
  8485. if (!this._sorted) {
  8486. this._array.sort(util.compareByGeneratedPositionsInflated);
  8487. this._sorted = true;
  8488. }
  8489. return this._array;
  8490. };
  8491. mappingList.MappingList = MappingList;
  8492. return mappingList;
  8493. }
  8494. /* -*- Mode: js; js-indent-level: 2; -*- */
  8495. var hasRequiredSourceMapGenerator;
  8496. function requireSourceMapGenerator () {
  8497. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8498. hasRequiredSourceMapGenerator = 1;
  8499. /*
  8500. * Copyright 2011 Mozilla Foundation and contributors
  8501. * Licensed under the New BSD license. See LICENSE or:
  8502. * http://opensource.org/licenses/BSD-3-Clause
  8503. */
  8504. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8505. var util = /*@__PURE__*/ requireUtil$1();
  8506. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8507. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8508. /**
  8509. * An instance of the SourceMapGenerator represents a source map which is
  8510. * being built incrementally. You may pass an object with the following
  8511. * properties:
  8512. *
  8513. * - file: The filename of the generated source.
  8514. * - sourceRoot: A root for all relative URLs in this source map.
  8515. */
  8516. function SourceMapGenerator(aArgs) {
  8517. if (!aArgs) {
  8518. aArgs = {};
  8519. }
  8520. this._file = util.getArg(aArgs, 'file', null);
  8521. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8522. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8523. this._sources = new ArraySet();
  8524. this._names = new ArraySet();
  8525. this._mappings = new MappingList();
  8526. this._sourcesContents = null;
  8527. }
  8528. SourceMapGenerator.prototype._version = 3;
  8529. /**
  8530. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8531. *
  8532. * @param aSourceMapConsumer The SourceMap.
  8533. */
  8534. SourceMapGenerator.fromSourceMap =
  8535. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8536. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8537. var generator = new SourceMapGenerator({
  8538. file: aSourceMapConsumer.file,
  8539. sourceRoot: sourceRoot
  8540. });
  8541. aSourceMapConsumer.eachMapping(function (mapping) {
  8542. var newMapping = {
  8543. generated: {
  8544. line: mapping.generatedLine,
  8545. column: mapping.generatedColumn
  8546. }
  8547. };
  8548. if (mapping.source != null) {
  8549. newMapping.source = mapping.source;
  8550. if (sourceRoot != null) {
  8551. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8552. }
  8553. newMapping.original = {
  8554. line: mapping.originalLine,
  8555. column: mapping.originalColumn
  8556. };
  8557. if (mapping.name != null) {
  8558. newMapping.name = mapping.name;
  8559. }
  8560. }
  8561. generator.addMapping(newMapping);
  8562. });
  8563. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8564. var sourceRelative = sourceFile;
  8565. if (sourceRoot !== null) {
  8566. sourceRelative = util.relative(sourceRoot, sourceFile);
  8567. }
  8568. if (!generator._sources.has(sourceRelative)) {
  8569. generator._sources.add(sourceRelative);
  8570. }
  8571. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8572. if (content != null) {
  8573. generator.setSourceContent(sourceFile, content);
  8574. }
  8575. });
  8576. return generator;
  8577. };
  8578. /**
  8579. * Add a single mapping from original source line and column to the generated
  8580. * source's line and column for this source map being created. The mapping
  8581. * object should have the following properties:
  8582. *
  8583. * - generated: An object with the generated line and column positions.
  8584. * - original: An object with the original line and column positions.
  8585. * - source: The original source file (relative to the sourceRoot).
  8586. * - name: An optional original token name for this mapping.
  8587. */
  8588. SourceMapGenerator.prototype.addMapping =
  8589. function SourceMapGenerator_addMapping(aArgs) {
  8590. var generated = util.getArg(aArgs, 'generated');
  8591. var original = util.getArg(aArgs, 'original', null);
  8592. var source = util.getArg(aArgs, 'source', null);
  8593. var name = util.getArg(aArgs, 'name', null);
  8594. if (!this._skipValidation) {
  8595. this._validateMapping(generated, original, source, name);
  8596. }
  8597. if (source != null) {
  8598. source = String(source);
  8599. if (!this._sources.has(source)) {
  8600. this._sources.add(source);
  8601. }
  8602. }
  8603. if (name != null) {
  8604. name = String(name);
  8605. if (!this._names.has(name)) {
  8606. this._names.add(name);
  8607. }
  8608. }
  8609. this._mappings.add({
  8610. generatedLine: generated.line,
  8611. generatedColumn: generated.column,
  8612. originalLine: original != null && original.line,
  8613. originalColumn: original != null && original.column,
  8614. source: source,
  8615. name: name
  8616. });
  8617. };
  8618. /**
  8619. * Set the source content for a source file.
  8620. */
  8621. SourceMapGenerator.prototype.setSourceContent =
  8622. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8623. var source = aSourceFile;
  8624. if (this._sourceRoot != null) {
  8625. source = util.relative(this._sourceRoot, source);
  8626. }
  8627. if (aSourceContent != null) {
  8628. // Add the source content to the _sourcesContents map.
  8629. // Create a new _sourcesContents map if the property is null.
  8630. if (!this._sourcesContents) {
  8631. this._sourcesContents = Object.create(null);
  8632. }
  8633. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8634. } else if (this._sourcesContents) {
  8635. // Remove the source file from the _sourcesContents map.
  8636. // If the _sourcesContents map is empty, set the property to null.
  8637. delete this._sourcesContents[util.toSetString(source)];
  8638. if (Object.keys(this._sourcesContents).length === 0) {
  8639. this._sourcesContents = null;
  8640. }
  8641. }
  8642. };
  8643. /**
  8644. * Applies the mappings of a sub-source-map for a specific source file to the
  8645. * source map being generated. Each mapping to the supplied source file is
  8646. * rewritten using the supplied source map. Note: The resolution for the
  8647. * resulting mappings is the minimium of this map and the supplied map.
  8648. *
  8649. * @param aSourceMapConsumer The source map to be applied.
  8650. * @param aSourceFile Optional. The filename of the source file.
  8651. * If omitted, SourceMapConsumer's file property will be used.
  8652. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8653. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8654. * This parameter is needed when the two source maps aren't in the same
  8655. * directory, and the source map to be applied contains relative source
  8656. * paths. If so, those relative source paths need to be rewritten
  8657. * relative to the SourceMapGenerator.
  8658. */
  8659. SourceMapGenerator.prototype.applySourceMap =
  8660. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8661. var sourceFile = aSourceFile;
  8662. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8663. if (aSourceFile == null) {
  8664. if (aSourceMapConsumer.file == null) {
  8665. throw new Error(
  8666. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8667. 'or the source map\'s "file" property. Both were omitted.'
  8668. );
  8669. }
  8670. sourceFile = aSourceMapConsumer.file;
  8671. }
  8672. var sourceRoot = this._sourceRoot;
  8673. // Make "sourceFile" relative if an absolute Url is passed.
  8674. if (sourceRoot != null) {
  8675. sourceFile = util.relative(sourceRoot, sourceFile);
  8676. }
  8677. // Applying the SourceMap can add and remove items from the sources and
  8678. // the names array.
  8679. var newSources = new ArraySet();
  8680. var newNames = new ArraySet();
  8681. // Find mappings for the "sourceFile"
  8682. this._mappings.unsortedForEach(function (mapping) {
  8683. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8684. // Check if it can be mapped by the source map, then update the mapping.
  8685. var original = aSourceMapConsumer.originalPositionFor({
  8686. line: mapping.originalLine,
  8687. column: mapping.originalColumn
  8688. });
  8689. if (original.source != null) {
  8690. // Copy mapping
  8691. mapping.source = original.source;
  8692. if (aSourceMapPath != null) {
  8693. mapping.source = util.join(aSourceMapPath, mapping.source);
  8694. }
  8695. if (sourceRoot != null) {
  8696. mapping.source = util.relative(sourceRoot, mapping.source);
  8697. }
  8698. mapping.originalLine = original.line;
  8699. mapping.originalColumn = original.column;
  8700. if (original.name != null) {
  8701. mapping.name = original.name;
  8702. }
  8703. }
  8704. }
  8705. var source = mapping.source;
  8706. if (source != null && !newSources.has(source)) {
  8707. newSources.add(source);
  8708. }
  8709. var name = mapping.name;
  8710. if (name != null && !newNames.has(name)) {
  8711. newNames.add(name);
  8712. }
  8713. }, this);
  8714. this._sources = newSources;
  8715. this._names = newNames;
  8716. // Copy sourcesContents of applied map.
  8717. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8718. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8719. if (content != null) {
  8720. if (aSourceMapPath != null) {
  8721. sourceFile = util.join(aSourceMapPath, sourceFile);
  8722. }
  8723. if (sourceRoot != null) {
  8724. sourceFile = util.relative(sourceRoot, sourceFile);
  8725. }
  8726. this.setSourceContent(sourceFile, content);
  8727. }
  8728. }, this);
  8729. };
  8730. /**
  8731. * A mapping can have one of the three levels of data:
  8732. *
  8733. * 1. Just the generated position.
  8734. * 2. The Generated position, original position, and original source.
  8735. * 3. Generated and original position, original source, as well as a name
  8736. * token.
  8737. *
  8738. * To maintain consistency, we validate that any new mapping being added falls
  8739. * in to one of these categories.
  8740. */
  8741. SourceMapGenerator.prototype._validateMapping =
  8742. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8743. aName) {
  8744. // When aOriginal is truthy but has empty values for .line and .column,
  8745. // it is most likely a programmer error. In this case we throw a very
  8746. // specific error message to try to guide them the right way.
  8747. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8748. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8749. throw new Error(
  8750. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8751. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8752. 'null for the original mapping instead of an object with empty or null values.'
  8753. );
  8754. }
  8755. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8756. && aGenerated.line > 0 && aGenerated.column >= 0
  8757. && !aOriginal && !aSource && !aName) {
  8758. // Case 1.
  8759. return;
  8760. }
  8761. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8762. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8763. && aGenerated.line > 0 && aGenerated.column >= 0
  8764. && aOriginal.line > 0 && aOriginal.column >= 0
  8765. && aSource) {
  8766. // Cases 2 and 3.
  8767. return;
  8768. }
  8769. else {
  8770. throw new Error('Invalid mapping: ' + JSON.stringify({
  8771. generated: aGenerated,
  8772. source: aSource,
  8773. original: aOriginal,
  8774. name: aName
  8775. }));
  8776. }
  8777. };
  8778. /**
  8779. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8780. * specified by the source map format.
  8781. */
  8782. SourceMapGenerator.prototype._serializeMappings =
  8783. function SourceMapGenerator_serializeMappings() {
  8784. var previousGeneratedColumn = 0;
  8785. var previousGeneratedLine = 1;
  8786. var previousOriginalColumn = 0;
  8787. var previousOriginalLine = 0;
  8788. var previousName = 0;
  8789. var previousSource = 0;
  8790. var result = '';
  8791. var next;
  8792. var mapping;
  8793. var nameIdx;
  8794. var sourceIdx;
  8795. var mappings = this._mappings.toArray();
  8796. for (var i = 0, len = mappings.length; i < len; i++) {
  8797. mapping = mappings[i];
  8798. next = '';
  8799. if (mapping.generatedLine !== previousGeneratedLine) {
  8800. previousGeneratedColumn = 0;
  8801. while (mapping.generatedLine !== previousGeneratedLine) {
  8802. next += ';';
  8803. previousGeneratedLine++;
  8804. }
  8805. }
  8806. else {
  8807. if (i > 0) {
  8808. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8809. continue;
  8810. }
  8811. next += ',';
  8812. }
  8813. }
  8814. next += base64VLQ.encode(mapping.generatedColumn
  8815. - previousGeneratedColumn);
  8816. previousGeneratedColumn = mapping.generatedColumn;
  8817. if (mapping.source != null) {
  8818. sourceIdx = this._sources.indexOf(mapping.source);
  8819. next += base64VLQ.encode(sourceIdx - previousSource);
  8820. previousSource = sourceIdx;
  8821. // lines are stored 0-based in SourceMap spec version 3
  8822. next += base64VLQ.encode(mapping.originalLine - 1
  8823. - previousOriginalLine);
  8824. previousOriginalLine = mapping.originalLine - 1;
  8825. next += base64VLQ.encode(mapping.originalColumn
  8826. - previousOriginalColumn);
  8827. previousOriginalColumn = mapping.originalColumn;
  8828. if (mapping.name != null) {
  8829. nameIdx = this._names.indexOf(mapping.name);
  8830. next += base64VLQ.encode(nameIdx - previousName);
  8831. previousName = nameIdx;
  8832. }
  8833. }
  8834. result += next;
  8835. }
  8836. return result;
  8837. };
  8838. SourceMapGenerator.prototype._generateSourcesContent =
  8839. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8840. return aSources.map(function (source) {
  8841. if (!this._sourcesContents) {
  8842. return null;
  8843. }
  8844. if (aSourceRoot != null) {
  8845. source = util.relative(aSourceRoot, source);
  8846. }
  8847. var key = util.toSetString(source);
  8848. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8849. ? this._sourcesContents[key]
  8850. : null;
  8851. }, this);
  8852. };
  8853. /**
  8854. * Externalize the source map.
  8855. */
  8856. SourceMapGenerator.prototype.toJSON =
  8857. function SourceMapGenerator_toJSON() {
  8858. var map = {
  8859. version: this._version,
  8860. sources: this._sources.toArray(),
  8861. names: this._names.toArray(),
  8862. mappings: this._serializeMappings()
  8863. };
  8864. if (this._file != null) {
  8865. map.file = this._file;
  8866. }
  8867. if (this._sourceRoot != null) {
  8868. map.sourceRoot = this._sourceRoot;
  8869. }
  8870. if (this._sourcesContents) {
  8871. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8872. }
  8873. return map;
  8874. };
  8875. /**
  8876. * Render the source map being generated to a string.
  8877. */
  8878. SourceMapGenerator.prototype.toString =
  8879. function SourceMapGenerator_toString() {
  8880. return JSON.stringify(this.toJSON());
  8881. };
  8882. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  8883. return sourceMapGenerator;
  8884. }
  8885. var sourceMapConsumer = {};
  8886. var binarySearch = {};
  8887. /* -*- Mode: js; js-indent-level: 2; -*- */
  8888. var hasRequiredBinarySearch;
  8889. function requireBinarySearch () {
  8890. if (hasRequiredBinarySearch) return binarySearch;
  8891. hasRequiredBinarySearch = 1;
  8892. (function (exports) {
  8893. /*
  8894. * Copyright 2011 Mozilla Foundation and contributors
  8895. * Licensed under the New BSD license. See LICENSE or:
  8896. * http://opensource.org/licenses/BSD-3-Clause
  8897. */
  8898. exports.GREATEST_LOWER_BOUND = 1;
  8899. exports.LEAST_UPPER_BOUND = 2;
  8900. /**
  8901. * Recursive implementation of binary search.
  8902. *
  8903. * @param aLow Indices here and lower do not contain the needle.
  8904. * @param aHigh Indices here and higher do not contain the needle.
  8905. * @param aNeedle The element being searched for.
  8906. * @param aHaystack The non-empty array being searched.
  8907. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8908. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8909. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8910. * closest element that is smaller than or greater than the one we are
  8911. * searching for, respectively, if the exact element cannot be found.
  8912. */
  8913. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8914. // This function terminates when one of the following is true:
  8915. //
  8916. // 1. We find the exact element we are looking for.
  8917. //
  8918. // 2. We did not find the exact element, but we can return the index of
  8919. // the next-closest element.
  8920. //
  8921. // 3. We did not find the exact element, and there is no next-closest
  8922. // element than the one we are searching for, so we return -1.
  8923. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  8924. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  8925. if (cmp === 0) {
  8926. // Found the element we are looking for.
  8927. return mid;
  8928. }
  8929. else if (cmp > 0) {
  8930. // Our needle is greater than aHaystack[mid].
  8931. if (aHigh - mid > 1) {
  8932. // The element is in the upper half.
  8933. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  8934. }
  8935. // The exact needle element was not found in this haystack. Determine if
  8936. // we are in termination case (3) or (2) and return the appropriate thing.
  8937. if (aBias == exports.LEAST_UPPER_BOUND) {
  8938. return aHigh < aHaystack.length ? aHigh : -1;
  8939. } else {
  8940. return mid;
  8941. }
  8942. }
  8943. else {
  8944. // Our needle is less than aHaystack[mid].
  8945. if (mid - aLow > 1) {
  8946. // The element is in the lower half.
  8947. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  8948. }
  8949. // we are in termination case (3) or (2) and return the appropriate thing.
  8950. if (aBias == exports.LEAST_UPPER_BOUND) {
  8951. return mid;
  8952. } else {
  8953. return aLow < 0 ? -1 : aLow;
  8954. }
  8955. }
  8956. }
  8957. /**
  8958. * This is an implementation of binary search which will always try and return
  8959. * the index of the closest element if there is no exact hit. This is because
  8960. * mappings between original and generated line/col pairs are single points,
  8961. * and there is an implicit region between each of them, so a miss just means
  8962. * that you aren't on the very start of a region.
  8963. *
  8964. * @param aNeedle The element you are looking for.
  8965. * @param aHaystack The array that is being searched.
  8966. * @param aCompare A function which takes the needle and an element in the
  8967. * array and returns -1, 0, or 1 depending on whether the needle is less
  8968. * than, equal to, or greater than the element, respectively.
  8969. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8970. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8971. * closest element that is smaller than or greater than the one we are
  8972. * searching for, respectively, if the exact element cannot be found.
  8973. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  8974. */
  8975. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  8976. if (aHaystack.length === 0) {
  8977. return -1;
  8978. }
  8979. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  8980. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  8981. if (index < 0) {
  8982. return -1;
  8983. }
  8984. // We have found either the exact element, or the next-closest element than
  8985. // the one we are searching for. However, there may be more than one such
  8986. // element. Make sure we always return the smallest of these.
  8987. while (index - 1 >= 0) {
  8988. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  8989. break;
  8990. }
  8991. --index;
  8992. }
  8993. return index;
  8994. };
  8995. } (binarySearch));
  8996. return binarySearch;
  8997. }
  8998. var quickSort = {};
  8999. /* -*- Mode: js; js-indent-level: 2; -*- */
  9000. var hasRequiredQuickSort;
  9001. function requireQuickSort () {
  9002. if (hasRequiredQuickSort) return quickSort;
  9003. hasRequiredQuickSort = 1;
  9004. /*
  9005. * Copyright 2011 Mozilla Foundation and contributors
  9006. * Licensed under the New BSD license. See LICENSE or:
  9007. * http://opensource.org/licenses/BSD-3-Clause
  9008. */
  9009. // It turns out that some (most?) JavaScript engines don't self-host
  9010. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9011. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9012. // custom comparator function, calling back and forth between the VM's C++ and
  9013. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9014. // worse generated code for the comparator function than would be optimal. In
  9015. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9016. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9017. // a ~3500ms mean speed-up in `bench/bench.html`.
  9018. /**
  9019. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9020. *
  9021. * @param {Array} ary
  9022. * The array.
  9023. * @param {Number} x
  9024. * The index of the first item.
  9025. * @param {Number} y
  9026. * The index of the second item.
  9027. */
  9028. function swap(ary, x, y) {
  9029. var temp = ary[x];
  9030. ary[x] = ary[y];
  9031. ary[y] = temp;
  9032. }
  9033. /**
  9034. * Returns a random integer within the range `low .. high` inclusive.
  9035. *
  9036. * @param {Number} low
  9037. * The lower bound on the range.
  9038. * @param {Number} high
  9039. * The upper bound on the range.
  9040. */
  9041. function randomIntInRange(low, high) {
  9042. return Math.round(low + (Math.random() * (high - low)));
  9043. }
  9044. /**
  9045. * The Quick Sort algorithm.
  9046. *
  9047. * @param {Array} ary
  9048. * An array to sort.
  9049. * @param {function} comparator
  9050. * Function to use to compare two items.
  9051. * @param {Number} p
  9052. * Start index of the array
  9053. * @param {Number} r
  9054. * End index of the array
  9055. */
  9056. function doQuickSort(ary, comparator, p, r) {
  9057. // If our lower bound is less than our upper bound, we (1) partition the
  9058. // array into two pieces and (2) recurse on each half. If it is not, this is
  9059. // the empty array and our base case.
  9060. if (p < r) {
  9061. // (1) Partitioning.
  9062. //
  9063. // The partitioning chooses a pivot between `p` and `r` and moves all
  9064. // elements that are less than or equal to the pivot to the before it, and
  9065. // all the elements that are greater than it after it. The effect is that
  9066. // once partition is done, the pivot is in the exact place it will be when
  9067. // the array is put in sorted order, and it will not need to be moved
  9068. // again. This runs in O(n) time.
  9069. // Always choose a random pivot so that an input array which is reverse
  9070. // sorted does not cause O(n^2) running time.
  9071. var pivotIndex = randomIntInRange(p, r);
  9072. var i = p - 1;
  9073. swap(ary, pivotIndex, r);
  9074. var pivot = ary[r];
  9075. // Immediately after `j` is incremented in this loop, the following hold
  9076. // true:
  9077. //
  9078. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9079. //
  9080. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9081. for (var j = p; j < r; j++) {
  9082. if (comparator(ary[j], pivot) <= 0) {
  9083. i += 1;
  9084. swap(ary, i, j);
  9085. }
  9086. }
  9087. swap(ary, i + 1, j);
  9088. var q = i + 1;
  9089. // (2) Recurse on each half.
  9090. doQuickSort(ary, comparator, p, q - 1);
  9091. doQuickSort(ary, comparator, q + 1, r);
  9092. }
  9093. }
  9094. /**
  9095. * Sort the given array in-place with the given comparator function.
  9096. *
  9097. * @param {Array} ary
  9098. * An array to sort.
  9099. * @param {function} comparator
  9100. * Function to use to compare two items.
  9101. */
  9102. quickSort.quickSort = function (ary, comparator) {
  9103. doQuickSort(ary, comparator, 0, ary.length - 1);
  9104. };
  9105. return quickSort;
  9106. }
  9107. /* -*- Mode: js; js-indent-level: 2; -*- */
  9108. var hasRequiredSourceMapConsumer;
  9109. function requireSourceMapConsumer () {
  9110. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9111. hasRequiredSourceMapConsumer = 1;
  9112. /*
  9113. * Copyright 2011 Mozilla Foundation and contributors
  9114. * Licensed under the New BSD license. See LICENSE or:
  9115. * http://opensource.org/licenses/BSD-3-Clause
  9116. */
  9117. var util = /*@__PURE__*/ requireUtil$1();
  9118. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9119. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9120. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9121. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9122. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9123. var sourceMap = aSourceMap;
  9124. if (typeof aSourceMap === 'string') {
  9125. sourceMap = util.parseSourceMapInput(aSourceMap);
  9126. }
  9127. return sourceMap.sections != null
  9128. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9129. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9130. }
  9131. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9132. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9133. };
  9134. /**
  9135. * The version of the source mapping spec that we are consuming.
  9136. */
  9137. SourceMapConsumer.prototype._version = 3;
  9138. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9139. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9140. // are lazily instantiated, accessed via the `_generatedMappings` and
  9141. // `_originalMappings` getters respectively, and we only parse the mappings
  9142. // and create these arrays once queried for a source location. We jump through
  9143. // these hoops because there can be many thousands of mappings, and parsing
  9144. // them is expensive, so we only want to do it if we must.
  9145. //
  9146. // Each object in the arrays is of the form:
  9147. //
  9148. // {
  9149. // generatedLine: The line number in the generated code,
  9150. // generatedColumn: The column number in the generated code,
  9151. // source: The path to the original source file that generated this
  9152. // chunk of code,
  9153. // originalLine: The line number in the original source that
  9154. // corresponds to this chunk of generated code,
  9155. // originalColumn: The column number in the original source that
  9156. // corresponds to this chunk of generated code,
  9157. // name: The name of the original symbol which generated this chunk of
  9158. // code.
  9159. // }
  9160. //
  9161. // All properties except for `generatedLine` and `generatedColumn` can be
  9162. // `null`.
  9163. //
  9164. // `_generatedMappings` is ordered by the generated positions.
  9165. //
  9166. // `_originalMappings` is ordered by the original positions.
  9167. SourceMapConsumer.prototype.__generatedMappings = null;
  9168. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9169. configurable: true,
  9170. enumerable: true,
  9171. get: function () {
  9172. if (!this.__generatedMappings) {
  9173. this._parseMappings(this._mappings, this.sourceRoot);
  9174. }
  9175. return this.__generatedMappings;
  9176. }
  9177. });
  9178. SourceMapConsumer.prototype.__originalMappings = null;
  9179. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9180. configurable: true,
  9181. enumerable: true,
  9182. get: function () {
  9183. if (!this.__originalMappings) {
  9184. this._parseMappings(this._mappings, this.sourceRoot);
  9185. }
  9186. return this.__originalMappings;
  9187. }
  9188. });
  9189. SourceMapConsumer.prototype._charIsMappingSeparator =
  9190. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9191. var c = aStr.charAt(index);
  9192. return c === ";" || c === ",";
  9193. };
  9194. /**
  9195. * Parse the mappings in a string in to a data structure which we can easily
  9196. * query (the ordered arrays in the `this.__generatedMappings` and
  9197. * `this.__originalMappings` properties).
  9198. */
  9199. SourceMapConsumer.prototype._parseMappings =
  9200. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9201. throw new Error("Subclasses must implement _parseMappings");
  9202. };
  9203. SourceMapConsumer.GENERATED_ORDER = 1;
  9204. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9205. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9206. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9207. /**
  9208. * Iterate over each mapping between an original source/line/column and a
  9209. * generated line/column in this source map.
  9210. *
  9211. * @param Function aCallback
  9212. * The function that is called with each mapping.
  9213. * @param Object aContext
  9214. * Optional. If specified, this object will be the value of `this` every
  9215. * time that `aCallback` is called.
  9216. * @param aOrder
  9217. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9218. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9219. * iterate over the mappings sorted by the generated file's line/column
  9220. * order or the original's source/line/column order, respectively. Defaults to
  9221. * `SourceMapConsumer.GENERATED_ORDER`.
  9222. */
  9223. SourceMapConsumer.prototype.eachMapping =
  9224. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9225. var context = aContext || null;
  9226. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9227. var mappings;
  9228. switch (order) {
  9229. case SourceMapConsumer.GENERATED_ORDER:
  9230. mappings = this._generatedMappings;
  9231. break;
  9232. case SourceMapConsumer.ORIGINAL_ORDER:
  9233. mappings = this._originalMappings;
  9234. break;
  9235. default:
  9236. throw new Error("Unknown order of iteration.");
  9237. }
  9238. var sourceRoot = this.sourceRoot;
  9239. mappings.map(function (mapping) {
  9240. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9241. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9242. return {
  9243. source: source,
  9244. generatedLine: mapping.generatedLine,
  9245. generatedColumn: mapping.generatedColumn,
  9246. originalLine: mapping.originalLine,
  9247. originalColumn: mapping.originalColumn,
  9248. name: mapping.name === null ? null : this._names.at(mapping.name)
  9249. };
  9250. }, this).forEach(aCallback, context);
  9251. };
  9252. /**
  9253. * Returns all generated line and column information for the original source,
  9254. * line, and column provided. If no column is provided, returns all mappings
  9255. * corresponding to a either the line we are searching for or the next
  9256. * closest line that has any mappings. Otherwise, returns all mappings
  9257. * corresponding to the given line and either the column we are searching for
  9258. * or the next closest column that has any offsets.
  9259. *
  9260. * The only argument is an object with the following properties:
  9261. *
  9262. * - source: The filename of the original source.
  9263. * - line: The line number in the original source. The line number is 1-based.
  9264. * - column: Optional. the column number in the original source.
  9265. * The column number is 0-based.
  9266. *
  9267. * and an array of objects is returned, each with the following properties:
  9268. *
  9269. * - line: The line number in the generated source, or null. The
  9270. * line number is 1-based.
  9271. * - column: The column number in the generated source, or null.
  9272. * The column number is 0-based.
  9273. */
  9274. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9275. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9276. var line = util.getArg(aArgs, 'line');
  9277. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9278. // returns the index of the closest mapping less than the needle. By
  9279. // setting needle.originalColumn to 0, we thus find the last mapping for
  9280. // the given line, provided such a mapping exists.
  9281. var needle = {
  9282. source: util.getArg(aArgs, 'source'),
  9283. originalLine: line,
  9284. originalColumn: util.getArg(aArgs, 'column', 0)
  9285. };
  9286. needle.source = this._findSourceIndex(needle.source);
  9287. if (needle.source < 0) {
  9288. return [];
  9289. }
  9290. var mappings = [];
  9291. var index = this._findMapping(needle,
  9292. this._originalMappings,
  9293. "originalLine",
  9294. "originalColumn",
  9295. util.compareByOriginalPositions,
  9296. binarySearch.LEAST_UPPER_BOUND);
  9297. if (index >= 0) {
  9298. var mapping = this._originalMappings[index];
  9299. if (aArgs.column === undefined) {
  9300. var originalLine = mapping.originalLine;
  9301. // Iterate until either we run out of mappings, or we run into
  9302. // a mapping for a different line than the one we found. Since
  9303. // mappings are sorted, this is guaranteed to find all mappings for
  9304. // the line we found.
  9305. while (mapping && mapping.originalLine === originalLine) {
  9306. mappings.push({
  9307. line: util.getArg(mapping, 'generatedLine', null),
  9308. column: util.getArg(mapping, 'generatedColumn', null),
  9309. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9310. });
  9311. mapping = this._originalMappings[++index];
  9312. }
  9313. } else {
  9314. var originalColumn = mapping.originalColumn;
  9315. // Iterate until either we run out of mappings, or we run into
  9316. // a mapping for a different line than the one we were searching for.
  9317. // Since mappings are sorted, this is guaranteed to find all mappings for
  9318. // the line we are searching for.
  9319. while (mapping &&
  9320. mapping.originalLine === line &&
  9321. mapping.originalColumn == originalColumn) {
  9322. mappings.push({
  9323. line: util.getArg(mapping, 'generatedLine', null),
  9324. column: util.getArg(mapping, 'generatedColumn', null),
  9325. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9326. });
  9327. mapping = this._originalMappings[++index];
  9328. }
  9329. }
  9330. }
  9331. return mappings;
  9332. };
  9333. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9334. /**
  9335. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9336. * query for information about the original file positions by giving it a file
  9337. * position in the generated source.
  9338. *
  9339. * The first parameter is the raw source map (either as a JSON string, or
  9340. * already parsed to an object). According to the spec, source maps have the
  9341. * following attributes:
  9342. *
  9343. * - version: Which version of the source map spec this map is following.
  9344. * - sources: An array of URLs to the original source files.
  9345. * - names: An array of identifiers which can be referrenced by individual mappings.
  9346. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9347. * - sourcesContent: Optional. An array of contents of the original source files.
  9348. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9349. * - file: Optional. The generated file this source map is associated with.
  9350. *
  9351. * Here is an example source map, taken from the source map spec[0]:
  9352. *
  9353. * {
  9354. * version : 3,
  9355. * file: "out.js",
  9356. * sourceRoot : "",
  9357. * sources: ["foo.js", "bar.js"],
  9358. * names: ["src", "maps", "are", "fun"],
  9359. * mappings: "AA,AB;;ABCDE;"
  9360. * }
  9361. *
  9362. * The second parameter, if given, is a string whose value is the URL
  9363. * at which the source map was found. This URL is used to compute the
  9364. * sources array.
  9365. *
  9366. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9367. */
  9368. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9369. var sourceMap = aSourceMap;
  9370. if (typeof aSourceMap === 'string') {
  9371. sourceMap = util.parseSourceMapInput(aSourceMap);
  9372. }
  9373. var version = util.getArg(sourceMap, 'version');
  9374. var sources = util.getArg(sourceMap, 'sources');
  9375. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9376. // requires the array) to play nice here.
  9377. var names = util.getArg(sourceMap, 'names', []);
  9378. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9379. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9380. var mappings = util.getArg(sourceMap, 'mappings');
  9381. var file = util.getArg(sourceMap, 'file', null);
  9382. // Once again, Sass deviates from the spec and supplies the version as a
  9383. // string rather than a number, so we use loose equality checking here.
  9384. if (version != this._version) {
  9385. throw new Error('Unsupported version: ' + version);
  9386. }
  9387. if (sourceRoot) {
  9388. sourceRoot = util.normalize(sourceRoot);
  9389. }
  9390. sources = sources
  9391. .map(String)
  9392. // Some source maps produce relative source paths like "./foo.js" instead of
  9393. // "foo.js". Normalize these first so that future comparisons will succeed.
  9394. // See bugzil.la/1090768.
  9395. .map(util.normalize)
  9396. // Always ensure that absolute sources are internally stored relative to
  9397. // the source root, if the source root is absolute. Not doing this would
  9398. // be particularly problematic when the source root is a prefix of the
  9399. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9400. .map(function (source) {
  9401. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9402. ? util.relative(sourceRoot, source)
  9403. : source;
  9404. });
  9405. // Pass `true` below to allow duplicate names and sources. While source maps
  9406. // are intended to be compressed and deduplicated, the TypeScript compiler
  9407. // sometimes generates source maps with duplicates in them. See Github issue
  9408. // #72 and bugzil.la/889492.
  9409. this._names = ArraySet.fromArray(names.map(String), true);
  9410. this._sources = ArraySet.fromArray(sources, true);
  9411. this._absoluteSources = this._sources.toArray().map(function (s) {
  9412. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9413. });
  9414. this.sourceRoot = sourceRoot;
  9415. this.sourcesContent = sourcesContent;
  9416. this._mappings = mappings;
  9417. this._sourceMapURL = aSourceMapURL;
  9418. this.file = file;
  9419. }
  9420. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9421. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9422. /**
  9423. * Utility function to find the index of a source. Returns -1 if not
  9424. * found.
  9425. */
  9426. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9427. var relativeSource = aSource;
  9428. if (this.sourceRoot != null) {
  9429. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9430. }
  9431. if (this._sources.has(relativeSource)) {
  9432. return this._sources.indexOf(relativeSource);
  9433. }
  9434. // Maybe aSource is an absolute URL as returned by |sources|. In
  9435. // this case we can't simply undo the transform.
  9436. var i;
  9437. for (i = 0; i < this._absoluteSources.length; ++i) {
  9438. if (this._absoluteSources[i] == aSource) {
  9439. return i;
  9440. }
  9441. }
  9442. return -1;
  9443. };
  9444. /**
  9445. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9446. *
  9447. * @param SourceMapGenerator aSourceMap
  9448. * The source map that will be consumed.
  9449. * @param String aSourceMapURL
  9450. * The URL at which the source map can be found (optional)
  9451. * @returns BasicSourceMapConsumer
  9452. */
  9453. BasicSourceMapConsumer.fromSourceMap =
  9454. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9455. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9456. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9457. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9458. smc.sourceRoot = aSourceMap._sourceRoot;
  9459. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9460. smc.sourceRoot);
  9461. smc.file = aSourceMap._file;
  9462. smc._sourceMapURL = aSourceMapURL;
  9463. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9464. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9465. });
  9466. // Because we are modifying the entries (by converting string sources and
  9467. // names to indices into the sources and names ArraySets), we have to make
  9468. // a copy of the entry or else bad things happen. Shared mutable state
  9469. // strikes again! See github issue #191.
  9470. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9471. var destGeneratedMappings = smc.__generatedMappings = [];
  9472. var destOriginalMappings = smc.__originalMappings = [];
  9473. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9474. var srcMapping = generatedMappings[i];
  9475. var destMapping = new Mapping;
  9476. destMapping.generatedLine = srcMapping.generatedLine;
  9477. destMapping.generatedColumn = srcMapping.generatedColumn;
  9478. if (srcMapping.source) {
  9479. destMapping.source = sources.indexOf(srcMapping.source);
  9480. destMapping.originalLine = srcMapping.originalLine;
  9481. destMapping.originalColumn = srcMapping.originalColumn;
  9482. if (srcMapping.name) {
  9483. destMapping.name = names.indexOf(srcMapping.name);
  9484. }
  9485. destOriginalMappings.push(destMapping);
  9486. }
  9487. destGeneratedMappings.push(destMapping);
  9488. }
  9489. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9490. return smc;
  9491. };
  9492. /**
  9493. * The version of the source mapping spec that we are consuming.
  9494. */
  9495. BasicSourceMapConsumer.prototype._version = 3;
  9496. /**
  9497. * The list of original sources.
  9498. */
  9499. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9500. get: function () {
  9501. return this._absoluteSources.slice();
  9502. }
  9503. });
  9504. /**
  9505. * Provide the JIT with a nice shape / hidden class.
  9506. */
  9507. function Mapping() {
  9508. this.generatedLine = 0;
  9509. this.generatedColumn = 0;
  9510. this.source = null;
  9511. this.originalLine = null;
  9512. this.originalColumn = null;
  9513. this.name = null;
  9514. }
  9515. /**
  9516. * Parse the mappings in a string in to a data structure which we can easily
  9517. * query (the ordered arrays in the `this.__generatedMappings` and
  9518. * `this.__originalMappings` properties).
  9519. */
  9520. BasicSourceMapConsumer.prototype._parseMappings =
  9521. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9522. var generatedLine = 1;
  9523. var previousGeneratedColumn = 0;
  9524. var previousOriginalLine = 0;
  9525. var previousOriginalColumn = 0;
  9526. var previousSource = 0;
  9527. var previousName = 0;
  9528. var length = aStr.length;
  9529. var index = 0;
  9530. var cachedSegments = {};
  9531. var temp = {};
  9532. var originalMappings = [];
  9533. var generatedMappings = [];
  9534. var mapping, str, segment, end, value;
  9535. while (index < length) {
  9536. if (aStr.charAt(index) === ';') {
  9537. generatedLine++;
  9538. index++;
  9539. previousGeneratedColumn = 0;
  9540. }
  9541. else if (aStr.charAt(index) === ',') {
  9542. index++;
  9543. }
  9544. else {
  9545. mapping = new Mapping();
  9546. mapping.generatedLine = generatedLine;
  9547. // Because each offset is encoded relative to the previous one,
  9548. // many segments often have the same encoding. We can exploit this
  9549. // fact by caching the parsed variable length fields of each segment,
  9550. // allowing us to avoid a second parse if we encounter the same
  9551. // segment again.
  9552. for (end = index; end < length; end++) {
  9553. if (this._charIsMappingSeparator(aStr, end)) {
  9554. break;
  9555. }
  9556. }
  9557. str = aStr.slice(index, end);
  9558. segment = cachedSegments[str];
  9559. if (segment) {
  9560. index += str.length;
  9561. } else {
  9562. segment = [];
  9563. while (index < end) {
  9564. base64VLQ.decode(aStr, index, temp);
  9565. value = temp.value;
  9566. index = temp.rest;
  9567. segment.push(value);
  9568. }
  9569. if (segment.length === 2) {
  9570. throw new Error('Found a source, but no line and column');
  9571. }
  9572. if (segment.length === 3) {
  9573. throw new Error('Found a source and line, but no column');
  9574. }
  9575. cachedSegments[str] = segment;
  9576. }
  9577. // Generated column.
  9578. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9579. previousGeneratedColumn = mapping.generatedColumn;
  9580. if (segment.length > 1) {
  9581. // Original source.
  9582. mapping.source = previousSource + segment[1];
  9583. previousSource += segment[1];
  9584. // Original line.
  9585. mapping.originalLine = previousOriginalLine + segment[2];
  9586. previousOriginalLine = mapping.originalLine;
  9587. // Lines are stored 0-based
  9588. mapping.originalLine += 1;
  9589. // Original column.
  9590. mapping.originalColumn = previousOriginalColumn + segment[3];
  9591. previousOriginalColumn = mapping.originalColumn;
  9592. if (segment.length > 4) {
  9593. // Original name.
  9594. mapping.name = previousName + segment[4];
  9595. previousName += segment[4];
  9596. }
  9597. }
  9598. generatedMappings.push(mapping);
  9599. if (typeof mapping.originalLine === 'number') {
  9600. originalMappings.push(mapping);
  9601. }
  9602. }
  9603. }
  9604. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9605. this.__generatedMappings = generatedMappings;
  9606. quickSort(originalMappings, util.compareByOriginalPositions);
  9607. this.__originalMappings = originalMappings;
  9608. };
  9609. /**
  9610. * Find the mapping that best matches the hypothetical "needle" mapping that
  9611. * we are searching for in the given "haystack" of mappings.
  9612. */
  9613. BasicSourceMapConsumer.prototype._findMapping =
  9614. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9615. aColumnName, aComparator, aBias) {
  9616. // To return the position we are searching for, we must first find the
  9617. // mapping for the given position and then return the opposite position it
  9618. // points to. Because the mappings are sorted, we can use binary search to
  9619. // find the best mapping.
  9620. if (aNeedle[aLineName] <= 0) {
  9621. throw new TypeError('Line must be greater than or equal to 1, got '
  9622. + aNeedle[aLineName]);
  9623. }
  9624. if (aNeedle[aColumnName] < 0) {
  9625. throw new TypeError('Column must be greater than or equal to 0, got '
  9626. + aNeedle[aColumnName]);
  9627. }
  9628. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9629. };
  9630. /**
  9631. * Compute the last column for each generated mapping. The last column is
  9632. * inclusive.
  9633. */
  9634. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9635. function SourceMapConsumer_computeColumnSpans() {
  9636. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9637. var mapping = this._generatedMappings[index];
  9638. // Mappings do not contain a field for the last generated columnt. We
  9639. // can come up with an optimistic estimate, however, by assuming that
  9640. // mappings are contiguous (i.e. given two consecutive mappings, the
  9641. // first mapping ends where the second one starts).
  9642. if (index + 1 < this._generatedMappings.length) {
  9643. var nextMapping = this._generatedMappings[index + 1];
  9644. if (mapping.generatedLine === nextMapping.generatedLine) {
  9645. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9646. continue;
  9647. }
  9648. }
  9649. // The last mapping for each line spans the entire line.
  9650. mapping.lastGeneratedColumn = Infinity;
  9651. }
  9652. };
  9653. /**
  9654. * Returns the original source, line, and column information for the generated
  9655. * source's line and column positions provided. The only argument is an object
  9656. * with the following properties:
  9657. *
  9658. * - line: The line number in the generated source. The line number
  9659. * is 1-based.
  9660. * - column: The column number in the generated source. The column
  9661. * number is 0-based.
  9662. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9663. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9664. * closest element that is smaller than or greater than the one we are
  9665. * searching for, respectively, if the exact element cannot be found.
  9666. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9667. *
  9668. * and an object is returned with the following properties:
  9669. *
  9670. * - source: The original source file, or null.
  9671. * - line: The line number in the original source, or null. The
  9672. * line number is 1-based.
  9673. * - column: The column number in the original source, or null. The
  9674. * column number is 0-based.
  9675. * - name: The original identifier, or null.
  9676. */
  9677. BasicSourceMapConsumer.prototype.originalPositionFor =
  9678. function SourceMapConsumer_originalPositionFor(aArgs) {
  9679. var needle = {
  9680. generatedLine: util.getArg(aArgs, 'line'),
  9681. generatedColumn: util.getArg(aArgs, 'column')
  9682. };
  9683. var index = this._findMapping(
  9684. needle,
  9685. this._generatedMappings,
  9686. "generatedLine",
  9687. "generatedColumn",
  9688. util.compareByGeneratedPositionsDeflated,
  9689. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9690. );
  9691. if (index >= 0) {
  9692. var mapping = this._generatedMappings[index];
  9693. if (mapping.generatedLine === needle.generatedLine) {
  9694. var source = util.getArg(mapping, 'source', null);
  9695. if (source !== null) {
  9696. source = this._sources.at(source);
  9697. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9698. }
  9699. var name = util.getArg(mapping, 'name', null);
  9700. if (name !== null) {
  9701. name = this._names.at(name);
  9702. }
  9703. return {
  9704. source: source,
  9705. line: util.getArg(mapping, 'originalLine', null),
  9706. column: util.getArg(mapping, 'originalColumn', null),
  9707. name: name
  9708. };
  9709. }
  9710. }
  9711. return {
  9712. source: null,
  9713. line: null,
  9714. column: null,
  9715. name: null
  9716. };
  9717. };
  9718. /**
  9719. * Return true if we have the source content for every source in the source
  9720. * map, false otherwise.
  9721. */
  9722. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9723. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9724. if (!this.sourcesContent) {
  9725. return false;
  9726. }
  9727. return this.sourcesContent.length >= this._sources.size() &&
  9728. !this.sourcesContent.some(function (sc) { return sc == null; });
  9729. };
  9730. /**
  9731. * Returns the original source content. The only argument is the url of the
  9732. * original source file. Returns null if no original source content is
  9733. * available.
  9734. */
  9735. BasicSourceMapConsumer.prototype.sourceContentFor =
  9736. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9737. if (!this.sourcesContent) {
  9738. return null;
  9739. }
  9740. var index = this._findSourceIndex(aSource);
  9741. if (index >= 0) {
  9742. return this.sourcesContent[index];
  9743. }
  9744. var relativeSource = aSource;
  9745. if (this.sourceRoot != null) {
  9746. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9747. }
  9748. var url;
  9749. if (this.sourceRoot != null
  9750. && (url = util.urlParse(this.sourceRoot))) {
  9751. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9752. // many users. We can help them out when they expect file:// URIs to
  9753. // behave like it would if they were running a local HTTP server. See
  9754. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9755. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9756. if (url.scheme == "file"
  9757. && this._sources.has(fileUriAbsPath)) {
  9758. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9759. }
  9760. if ((!url.path || url.path == "/")
  9761. && this._sources.has("/" + relativeSource)) {
  9762. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9763. }
  9764. }
  9765. // This function is used recursively from
  9766. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9767. // don't want to throw if we can't find the source - we just want to
  9768. // return null, so we provide a flag to exit gracefully.
  9769. if (nullOnMissing) {
  9770. return null;
  9771. }
  9772. else {
  9773. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9774. }
  9775. };
  9776. /**
  9777. * Returns the generated line and column information for the original source,
  9778. * line, and column positions provided. The only argument is an object with
  9779. * the following properties:
  9780. *
  9781. * - source: The filename of the original source.
  9782. * - line: The line number in the original source. The line number
  9783. * is 1-based.
  9784. * - column: The column number in the original source. The column
  9785. * number is 0-based.
  9786. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9787. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9788. * closest element that is smaller than or greater than the one we are
  9789. * searching for, respectively, if the exact element cannot be found.
  9790. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9791. *
  9792. * and an object is returned with the following properties:
  9793. *
  9794. * - line: The line number in the generated source, or null. The
  9795. * line number is 1-based.
  9796. * - column: The column number in the generated source, or null.
  9797. * The column number is 0-based.
  9798. */
  9799. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9800. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9801. var source = util.getArg(aArgs, 'source');
  9802. source = this._findSourceIndex(source);
  9803. if (source < 0) {
  9804. return {
  9805. line: null,
  9806. column: null,
  9807. lastColumn: null
  9808. };
  9809. }
  9810. var needle = {
  9811. source: source,
  9812. originalLine: util.getArg(aArgs, 'line'),
  9813. originalColumn: util.getArg(aArgs, 'column')
  9814. };
  9815. var index = this._findMapping(
  9816. needle,
  9817. this._originalMappings,
  9818. "originalLine",
  9819. "originalColumn",
  9820. util.compareByOriginalPositions,
  9821. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9822. );
  9823. if (index >= 0) {
  9824. var mapping = this._originalMappings[index];
  9825. if (mapping.source === needle.source) {
  9826. return {
  9827. line: util.getArg(mapping, 'generatedLine', null),
  9828. column: util.getArg(mapping, 'generatedColumn', null),
  9829. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9830. };
  9831. }
  9832. }
  9833. return {
  9834. line: null,
  9835. column: null,
  9836. lastColumn: null
  9837. };
  9838. };
  9839. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9840. /**
  9841. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9842. * we can query for information. It differs from BasicSourceMapConsumer in
  9843. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9844. * input.
  9845. *
  9846. * The first parameter is a raw source map (either as a JSON string, or already
  9847. * parsed to an object). According to the spec for indexed source maps, they
  9848. * have the following attributes:
  9849. *
  9850. * - version: Which version of the source map spec this map is following.
  9851. * - file: Optional. The generated file this source map is associated with.
  9852. * - sections: A list of section definitions.
  9853. *
  9854. * Each value under the "sections" field has two fields:
  9855. * - offset: The offset into the original specified at which this section
  9856. * begins to apply, defined as an object with a "line" and "column"
  9857. * field.
  9858. * - map: A source map definition. This source map could also be indexed,
  9859. * but doesn't have to be.
  9860. *
  9861. * Instead of the "map" field, it's also possible to have a "url" field
  9862. * specifying a URL to retrieve a source map from, but that's currently
  9863. * unsupported.
  9864. *
  9865. * Here's an example source map, taken from the source map spec[0], but
  9866. * modified to omit a section which uses the "url" field.
  9867. *
  9868. * {
  9869. * version : 3,
  9870. * file: "app.js",
  9871. * sections: [{
  9872. * offset: {line:100, column:10},
  9873. * map: {
  9874. * version : 3,
  9875. * file: "section.js",
  9876. * sources: ["foo.js", "bar.js"],
  9877. * names: ["src", "maps", "are", "fun"],
  9878. * mappings: "AAAA,E;;ABCDE;"
  9879. * }
  9880. * }],
  9881. * }
  9882. *
  9883. * The second parameter, if given, is a string whose value is the URL
  9884. * at which the source map was found. This URL is used to compute the
  9885. * sources array.
  9886. *
  9887. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9888. */
  9889. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9890. var sourceMap = aSourceMap;
  9891. if (typeof aSourceMap === 'string') {
  9892. sourceMap = util.parseSourceMapInput(aSourceMap);
  9893. }
  9894. var version = util.getArg(sourceMap, 'version');
  9895. var sections = util.getArg(sourceMap, 'sections');
  9896. if (version != this._version) {
  9897. throw new Error('Unsupported version: ' + version);
  9898. }
  9899. this._sources = new ArraySet();
  9900. this._names = new ArraySet();
  9901. var lastOffset = {
  9902. line: -1,
  9903. column: 0
  9904. };
  9905. this._sections = sections.map(function (s) {
  9906. if (s.url) {
  9907. // The url field will require support for asynchronicity.
  9908. // See https://github.com/mozilla/source-map/issues/16
  9909. throw new Error('Support for url field in sections not implemented.');
  9910. }
  9911. var offset = util.getArg(s, 'offset');
  9912. var offsetLine = util.getArg(offset, 'line');
  9913. var offsetColumn = util.getArg(offset, 'column');
  9914. if (offsetLine < lastOffset.line ||
  9915. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9916. throw new Error('Section offsets must be ordered and non-overlapping.');
  9917. }
  9918. lastOffset = offset;
  9919. return {
  9920. generatedOffset: {
  9921. // The offset fields are 0-based, but we use 1-based indices when
  9922. // encoding/decoding from VLQ.
  9923. generatedLine: offsetLine + 1,
  9924. generatedColumn: offsetColumn + 1
  9925. },
  9926. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  9927. }
  9928. });
  9929. }
  9930. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9931. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  9932. /**
  9933. * The version of the source mapping spec that we are consuming.
  9934. */
  9935. IndexedSourceMapConsumer.prototype._version = 3;
  9936. /**
  9937. * The list of original sources.
  9938. */
  9939. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  9940. get: function () {
  9941. var sources = [];
  9942. for (var i = 0; i < this._sections.length; i++) {
  9943. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  9944. sources.push(this._sections[i].consumer.sources[j]);
  9945. }
  9946. }
  9947. return sources;
  9948. }
  9949. });
  9950. /**
  9951. * Returns the original source, line, and column information for the generated
  9952. * source's line and column positions provided. The only argument is an object
  9953. * with the following properties:
  9954. *
  9955. * - line: The line number in the generated source. The line number
  9956. * is 1-based.
  9957. * - column: The column number in the generated source. The column
  9958. * number is 0-based.
  9959. *
  9960. * and an object is returned with the following properties:
  9961. *
  9962. * - source: The original source file, or null.
  9963. * - line: The line number in the original source, or null. The
  9964. * line number is 1-based.
  9965. * - column: The column number in the original source, or null. The
  9966. * column number is 0-based.
  9967. * - name: The original identifier, or null.
  9968. */
  9969. IndexedSourceMapConsumer.prototype.originalPositionFor =
  9970. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  9971. var needle = {
  9972. generatedLine: util.getArg(aArgs, 'line'),
  9973. generatedColumn: util.getArg(aArgs, 'column')
  9974. };
  9975. // Find the section containing the generated position we're trying to map
  9976. // to an original position.
  9977. var sectionIndex = binarySearch.search(needle, this._sections,
  9978. function(needle, section) {
  9979. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  9980. if (cmp) {
  9981. return cmp;
  9982. }
  9983. return (needle.generatedColumn -
  9984. section.generatedOffset.generatedColumn);
  9985. });
  9986. var section = this._sections[sectionIndex];
  9987. if (!section) {
  9988. return {
  9989. source: null,
  9990. line: null,
  9991. column: null,
  9992. name: null
  9993. };
  9994. }
  9995. return section.consumer.originalPositionFor({
  9996. line: needle.generatedLine -
  9997. (section.generatedOffset.generatedLine - 1),
  9998. column: needle.generatedColumn -
  9999. (section.generatedOffset.generatedLine === needle.generatedLine
  10000. ? section.generatedOffset.generatedColumn - 1
  10001. : 0),
  10002. bias: aArgs.bias
  10003. });
  10004. };
  10005. /**
  10006. * Return true if we have the source content for every source in the source
  10007. * map, false otherwise.
  10008. */
  10009. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10010. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10011. return this._sections.every(function (s) {
  10012. return s.consumer.hasContentsOfAllSources();
  10013. });
  10014. };
  10015. /**
  10016. * Returns the original source content. The only argument is the url of the
  10017. * original source file. Returns null if no original source content is
  10018. * available.
  10019. */
  10020. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10021. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10022. for (var i = 0; i < this._sections.length; i++) {
  10023. var section = this._sections[i];
  10024. var content = section.consumer.sourceContentFor(aSource, true);
  10025. if (content) {
  10026. return content;
  10027. }
  10028. }
  10029. if (nullOnMissing) {
  10030. return null;
  10031. }
  10032. else {
  10033. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10034. }
  10035. };
  10036. /**
  10037. * Returns the generated line and column information for the original source,
  10038. * line, and column positions provided. The only argument is an object with
  10039. * the following properties:
  10040. *
  10041. * - source: The filename of the original source.
  10042. * - line: The line number in the original source. The line number
  10043. * is 1-based.
  10044. * - column: The column number in the original source. The column
  10045. * number is 0-based.
  10046. *
  10047. * and an object is returned with the following properties:
  10048. *
  10049. * - line: The line number in the generated source, or null. The
  10050. * line number is 1-based.
  10051. * - column: The column number in the generated source, or null.
  10052. * The column number is 0-based.
  10053. */
  10054. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10055. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10056. for (var i = 0; i < this._sections.length; i++) {
  10057. var section = this._sections[i];
  10058. // Only consider this section if the requested source is in the list of
  10059. // sources of the consumer.
  10060. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10061. continue;
  10062. }
  10063. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10064. if (generatedPosition) {
  10065. var ret = {
  10066. line: generatedPosition.line +
  10067. (section.generatedOffset.generatedLine - 1),
  10068. column: generatedPosition.column +
  10069. (section.generatedOffset.generatedLine === generatedPosition.line
  10070. ? section.generatedOffset.generatedColumn - 1
  10071. : 0)
  10072. };
  10073. return ret;
  10074. }
  10075. }
  10076. return {
  10077. line: null,
  10078. column: null
  10079. };
  10080. };
  10081. /**
  10082. * Parse the mappings in a string in to a data structure which we can easily
  10083. * query (the ordered arrays in the `this.__generatedMappings` and
  10084. * `this.__originalMappings` properties).
  10085. */
  10086. IndexedSourceMapConsumer.prototype._parseMappings =
  10087. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10088. this.__generatedMappings = [];
  10089. this.__originalMappings = [];
  10090. for (var i = 0; i < this._sections.length; i++) {
  10091. var section = this._sections[i];
  10092. var sectionMappings = section.consumer._generatedMappings;
  10093. for (var j = 0; j < sectionMappings.length; j++) {
  10094. var mapping = sectionMappings[j];
  10095. var source = section.consumer._sources.at(mapping.source);
  10096. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10097. this._sources.add(source);
  10098. source = this._sources.indexOf(source);
  10099. var name = null;
  10100. if (mapping.name) {
  10101. name = section.consumer._names.at(mapping.name);
  10102. this._names.add(name);
  10103. name = this._names.indexOf(name);
  10104. }
  10105. // The mappings coming from the consumer for the section have
  10106. // generated positions relative to the start of the section, so we
  10107. // need to offset them to be relative to the start of the concatenated
  10108. // generated file.
  10109. var adjustedMapping = {
  10110. source: source,
  10111. generatedLine: mapping.generatedLine +
  10112. (section.generatedOffset.generatedLine - 1),
  10113. generatedColumn: mapping.generatedColumn +
  10114. (section.generatedOffset.generatedLine === mapping.generatedLine
  10115. ? section.generatedOffset.generatedColumn - 1
  10116. : 0),
  10117. originalLine: mapping.originalLine,
  10118. originalColumn: mapping.originalColumn,
  10119. name: name
  10120. };
  10121. this.__generatedMappings.push(adjustedMapping);
  10122. if (typeof adjustedMapping.originalLine === 'number') {
  10123. this.__originalMappings.push(adjustedMapping);
  10124. }
  10125. }
  10126. }
  10127. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10128. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10129. };
  10130. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10131. return sourceMapConsumer;
  10132. }
  10133. var sourceNode = {};
  10134. /* -*- Mode: js; js-indent-level: 2; -*- */
  10135. var hasRequiredSourceNode;
  10136. function requireSourceNode () {
  10137. if (hasRequiredSourceNode) return sourceNode;
  10138. hasRequiredSourceNode = 1;
  10139. /*
  10140. * Copyright 2011 Mozilla Foundation and contributors
  10141. * Licensed under the New BSD license. See LICENSE or:
  10142. * http://opensource.org/licenses/BSD-3-Clause
  10143. */
  10144. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10145. var util = /*@__PURE__*/ requireUtil$1();
  10146. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10147. // operating systems these days (capturing the result).
  10148. var REGEX_NEWLINE = /(\r?\n)/;
  10149. // Newline character code for charCodeAt() comparisons
  10150. var NEWLINE_CODE = 10;
  10151. // Private symbol for identifying `SourceNode`s when multiple versions of
  10152. // the source-map library are loaded. This MUST NOT CHANGE across
  10153. // versions!
  10154. var isSourceNode = "$$$isSourceNode$$$";
  10155. /**
  10156. * SourceNodes provide a way to abstract over interpolating/concatenating
  10157. * snippets of generated JavaScript source code while maintaining the line and
  10158. * column information associated with the original source code.
  10159. *
  10160. * @param aLine The original line number.
  10161. * @param aColumn The original column number.
  10162. * @param aSource The original source's filename.
  10163. * @param aChunks Optional. An array of strings which are snippets of
  10164. * generated JS, or other SourceNodes.
  10165. * @param aName The original identifier.
  10166. */
  10167. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10168. this.children = [];
  10169. this.sourceContents = {};
  10170. this.line = aLine == null ? null : aLine;
  10171. this.column = aColumn == null ? null : aColumn;
  10172. this.source = aSource == null ? null : aSource;
  10173. this.name = aName == null ? null : aName;
  10174. this[isSourceNode] = true;
  10175. if (aChunks != null) this.add(aChunks);
  10176. }
  10177. /**
  10178. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10179. *
  10180. * @param aGeneratedCode The generated code
  10181. * @param aSourceMapConsumer The SourceMap for the generated code
  10182. * @param aRelativePath Optional. The path that relative sources in the
  10183. * SourceMapConsumer should be relative to.
  10184. */
  10185. SourceNode.fromStringWithSourceMap =
  10186. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10187. // The SourceNode we want to fill with the generated code
  10188. // and the SourceMap
  10189. var node = new SourceNode();
  10190. // All even indices of this array are one line of the generated code,
  10191. // while all odd indices are the newlines between two adjacent lines
  10192. // (since `REGEX_NEWLINE` captures its match).
  10193. // Processed fragments are accessed by calling `shiftNextLine`.
  10194. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10195. var remainingLinesIndex = 0;
  10196. var shiftNextLine = function() {
  10197. var lineContents = getNextLine();
  10198. // The last line of a file might not have a newline.
  10199. var newLine = getNextLine() || "";
  10200. return lineContents + newLine;
  10201. function getNextLine() {
  10202. return remainingLinesIndex < remainingLines.length ?
  10203. remainingLines[remainingLinesIndex++] : undefined;
  10204. }
  10205. };
  10206. // We need to remember the position of "remainingLines"
  10207. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10208. // The generate SourceNodes we need a code range.
  10209. // To extract it current and last mapping is used.
  10210. // Here we store the last mapping.
  10211. var lastMapping = null;
  10212. aSourceMapConsumer.eachMapping(function (mapping) {
  10213. if (lastMapping !== null) {
  10214. // We add the code from "lastMapping" to "mapping":
  10215. // First check if there is a new line in between.
  10216. if (lastGeneratedLine < mapping.generatedLine) {
  10217. // Associate first line with "lastMapping"
  10218. addMappingWithCode(lastMapping, shiftNextLine());
  10219. lastGeneratedLine++;
  10220. lastGeneratedColumn = 0;
  10221. // The remaining code is added without mapping
  10222. } else {
  10223. // There is no new line in between.
  10224. // Associate the code between "lastGeneratedColumn" and
  10225. // "mapping.generatedColumn" with "lastMapping"
  10226. var nextLine = remainingLines[remainingLinesIndex] || '';
  10227. var code = nextLine.substr(0, mapping.generatedColumn -
  10228. lastGeneratedColumn);
  10229. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10230. lastGeneratedColumn);
  10231. lastGeneratedColumn = mapping.generatedColumn;
  10232. addMappingWithCode(lastMapping, code);
  10233. // No more remaining code, continue
  10234. lastMapping = mapping;
  10235. return;
  10236. }
  10237. }
  10238. // We add the generated code until the first mapping
  10239. // to the SourceNode without any mapping.
  10240. // Each line is added as separate string.
  10241. while (lastGeneratedLine < mapping.generatedLine) {
  10242. node.add(shiftNextLine());
  10243. lastGeneratedLine++;
  10244. }
  10245. if (lastGeneratedColumn < mapping.generatedColumn) {
  10246. var nextLine = remainingLines[remainingLinesIndex] || '';
  10247. node.add(nextLine.substr(0, mapping.generatedColumn));
  10248. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10249. lastGeneratedColumn = mapping.generatedColumn;
  10250. }
  10251. lastMapping = mapping;
  10252. }, this);
  10253. // We have processed all mappings.
  10254. if (remainingLinesIndex < remainingLines.length) {
  10255. if (lastMapping) {
  10256. // Associate the remaining code in the current line with "lastMapping"
  10257. addMappingWithCode(lastMapping, shiftNextLine());
  10258. }
  10259. // and add the remaining lines without any mapping
  10260. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10261. }
  10262. // Copy sourcesContent into SourceNode
  10263. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10264. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10265. if (content != null) {
  10266. if (aRelativePath != null) {
  10267. sourceFile = util.join(aRelativePath, sourceFile);
  10268. }
  10269. node.setSourceContent(sourceFile, content);
  10270. }
  10271. });
  10272. return node;
  10273. function addMappingWithCode(mapping, code) {
  10274. if (mapping === null || mapping.source === undefined) {
  10275. node.add(code);
  10276. } else {
  10277. var source = aRelativePath
  10278. ? util.join(aRelativePath, mapping.source)
  10279. : mapping.source;
  10280. node.add(new SourceNode(mapping.originalLine,
  10281. mapping.originalColumn,
  10282. source,
  10283. code,
  10284. mapping.name));
  10285. }
  10286. }
  10287. };
  10288. /**
  10289. * Add a chunk of generated JS to this source node.
  10290. *
  10291. * @param aChunk A string snippet of generated JS code, another instance of
  10292. * SourceNode, or an array where each member is one of those things.
  10293. */
  10294. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10295. if (Array.isArray(aChunk)) {
  10296. aChunk.forEach(function (chunk) {
  10297. this.add(chunk);
  10298. }, this);
  10299. }
  10300. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10301. if (aChunk) {
  10302. this.children.push(aChunk);
  10303. }
  10304. }
  10305. else {
  10306. throw new TypeError(
  10307. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10308. );
  10309. }
  10310. return this;
  10311. };
  10312. /**
  10313. * Add a chunk of generated JS to the beginning of this source node.
  10314. *
  10315. * @param aChunk A string snippet of generated JS code, another instance of
  10316. * SourceNode, or an array where each member is one of those things.
  10317. */
  10318. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10319. if (Array.isArray(aChunk)) {
  10320. for (var i = aChunk.length-1; i >= 0; i--) {
  10321. this.prepend(aChunk[i]);
  10322. }
  10323. }
  10324. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10325. this.children.unshift(aChunk);
  10326. }
  10327. else {
  10328. throw new TypeError(
  10329. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10330. );
  10331. }
  10332. return this;
  10333. };
  10334. /**
  10335. * Walk over the tree of JS snippets in this node and its children. The
  10336. * walking function is called once for each snippet of JS and is passed that
  10337. * snippet and the its original associated source's line/column location.
  10338. *
  10339. * @param aFn The traversal function.
  10340. */
  10341. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10342. var chunk;
  10343. for (var i = 0, len = this.children.length; i < len; i++) {
  10344. chunk = this.children[i];
  10345. if (chunk[isSourceNode]) {
  10346. chunk.walk(aFn);
  10347. }
  10348. else {
  10349. if (chunk !== '') {
  10350. aFn(chunk, { source: this.source,
  10351. line: this.line,
  10352. column: this.column,
  10353. name: this.name });
  10354. }
  10355. }
  10356. }
  10357. };
  10358. /**
  10359. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10360. * each of `this.children`.
  10361. *
  10362. * @param aSep The separator.
  10363. */
  10364. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10365. var newChildren;
  10366. var i;
  10367. var len = this.children.length;
  10368. if (len > 0) {
  10369. newChildren = [];
  10370. for (i = 0; i < len-1; i++) {
  10371. newChildren.push(this.children[i]);
  10372. newChildren.push(aSep);
  10373. }
  10374. newChildren.push(this.children[i]);
  10375. this.children = newChildren;
  10376. }
  10377. return this;
  10378. };
  10379. /**
  10380. * Call String.prototype.replace on the very right-most source snippet. Useful
  10381. * for trimming whitespace from the end of a source node, etc.
  10382. *
  10383. * @param aPattern The pattern to replace.
  10384. * @param aReplacement The thing to replace the pattern with.
  10385. */
  10386. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10387. var lastChild = this.children[this.children.length - 1];
  10388. if (lastChild[isSourceNode]) {
  10389. lastChild.replaceRight(aPattern, aReplacement);
  10390. }
  10391. else if (typeof lastChild === 'string') {
  10392. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10393. }
  10394. else {
  10395. this.children.push(''.replace(aPattern, aReplacement));
  10396. }
  10397. return this;
  10398. };
  10399. /**
  10400. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10401. * in the sourcesContent field.
  10402. *
  10403. * @param aSourceFile The filename of the source file
  10404. * @param aSourceContent The content of the source file
  10405. */
  10406. SourceNode.prototype.setSourceContent =
  10407. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10408. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10409. };
  10410. /**
  10411. * Walk over the tree of SourceNodes. The walking function is called for each
  10412. * source file content and is passed the filename and source content.
  10413. *
  10414. * @param aFn The traversal function.
  10415. */
  10416. SourceNode.prototype.walkSourceContents =
  10417. function SourceNode_walkSourceContents(aFn) {
  10418. for (var i = 0, len = this.children.length; i < len; i++) {
  10419. if (this.children[i][isSourceNode]) {
  10420. this.children[i].walkSourceContents(aFn);
  10421. }
  10422. }
  10423. var sources = Object.keys(this.sourceContents);
  10424. for (var i = 0, len = sources.length; i < len; i++) {
  10425. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10426. }
  10427. };
  10428. /**
  10429. * Return the string representation of this source node. Walks over the tree
  10430. * and concatenates all the various snippets together to one string.
  10431. */
  10432. SourceNode.prototype.toString = function SourceNode_toString() {
  10433. var str = "";
  10434. this.walk(function (chunk) {
  10435. str += chunk;
  10436. });
  10437. return str;
  10438. };
  10439. /**
  10440. * Returns the string representation of this source node along with a source
  10441. * map.
  10442. */
  10443. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10444. var generated = {
  10445. code: "",
  10446. line: 1,
  10447. column: 0
  10448. };
  10449. var map = new SourceMapGenerator(aArgs);
  10450. var sourceMappingActive = false;
  10451. var lastOriginalSource = null;
  10452. var lastOriginalLine = null;
  10453. var lastOriginalColumn = null;
  10454. var lastOriginalName = null;
  10455. this.walk(function (chunk, original) {
  10456. generated.code += chunk;
  10457. if (original.source !== null
  10458. && original.line !== null
  10459. && original.column !== null) {
  10460. if(lastOriginalSource !== original.source
  10461. || lastOriginalLine !== original.line
  10462. || lastOriginalColumn !== original.column
  10463. || lastOriginalName !== original.name) {
  10464. map.addMapping({
  10465. source: original.source,
  10466. original: {
  10467. line: original.line,
  10468. column: original.column
  10469. },
  10470. generated: {
  10471. line: generated.line,
  10472. column: generated.column
  10473. },
  10474. name: original.name
  10475. });
  10476. }
  10477. lastOriginalSource = original.source;
  10478. lastOriginalLine = original.line;
  10479. lastOriginalColumn = original.column;
  10480. lastOriginalName = original.name;
  10481. sourceMappingActive = true;
  10482. } else if (sourceMappingActive) {
  10483. map.addMapping({
  10484. generated: {
  10485. line: generated.line,
  10486. column: generated.column
  10487. }
  10488. });
  10489. lastOriginalSource = null;
  10490. sourceMappingActive = false;
  10491. }
  10492. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10493. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10494. generated.line++;
  10495. generated.column = 0;
  10496. // Mappings end at eol
  10497. if (idx + 1 === length) {
  10498. lastOriginalSource = null;
  10499. sourceMappingActive = false;
  10500. } else if (sourceMappingActive) {
  10501. map.addMapping({
  10502. source: original.source,
  10503. original: {
  10504. line: original.line,
  10505. column: original.column
  10506. },
  10507. generated: {
  10508. line: generated.line,
  10509. column: generated.column
  10510. },
  10511. name: original.name
  10512. });
  10513. }
  10514. } else {
  10515. generated.column++;
  10516. }
  10517. }
  10518. });
  10519. this.walkSourceContents(function (sourceFile, sourceContent) {
  10520. map.setSourceContent(sourceFile, sourceContent);
  10521. });
  10522. return { code: generated.code, map: map };
  10523. };
  10524. sourceNode.SourceNode = SourceNode;
  10525. return sourceNode;
  10526. }
  10527. /*
  10528. * Copyright 2009-2011 Mozilla Foundation and contributors
  10529. * Licensed under the New BSD license. See LICENSE.txt or:
  10530. * http://opensource.org/licenses/BSD-3-Clause
  10531. */
  10532. var hasRequiredSourceMap;
  10533. function requireSourceMap () {
  10534. if (hasRequiredSourceMap) return sourceMap;
  10535. hasRequiredSourceMap = 1;
  10536. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10537. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10538. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10539. return sourceMap;
  10540. }
  10541. var mergeSourceMap;
  10542. var hasRequiredMergeSourceMap;
  10543. function requireMergeSourceMap () {
  10544. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10545. hasRequiredMergeSourceMap = 1;
  10546. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10547. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10548. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10549. mergeSourceMap = merge;
  10550. /**
  10551. * Merge old source map and new source map and return merged.
  10552. * If old or new source map value is falsy, return another one as it is.
  10553. *
  10554. * @param {object|string} [oldMap] old source map object
  10555. * @param {object|string} [newmap] new source map object
  10556. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10557. */
  10558. function merge(oldMap, newMap) {
  10559. if (!oldMap) return newMap
  10560. if (!newMap) return oldMap
  10561. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10562. var newMapConsumer = new SourceMapConsumer(newMap);
  10563. var mergedMapGenerator = new SourceMapGenerator();
  10564. // iterate on new map and overwrite original position of new map with one of old map
  10565. newMapConsumer.eachMapping(function(m) {
  10566. // pass when `originalLine` is null.
  10567. // It occurs in case that the node does not have origin in original code.
  10568. if (m.originalLine == null) return
  10569. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10570. line: m.originalLine,
  10571. column: m.originalColumn
  10572. });
  10573. if (origPosInOldMap.source == null) return
  10574. mergedMapGenerator.addMapping({
  10575. original: {
  10576. line: origPosInOldMap.line,
  10577. column: origPosInOldMap.column
  10578. },
  10579. generated: {
  10580. line: m.generatedLine,
  10581. column: m.generatedColumn
  10582. },
  10583. source: origPosInOldMap.source,
  10584. name: origPosInOldMap.name
  10585. });
  10586. });
  10587. var consumers = [oldMapConsumer, newMapConsumer];
  10588. consumers.forEach(function(consumer) {
  10589. consumer.sources.forEach(function(sourceFile) {
  10590. mergedMapGenerator._sources.add(sourceFile);
  10591. var sourceContent = consumer.sourceContentFor(sourceFile);
  10592. if (sourceContent != null) {
  10593. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10594. }
  10595. });
  10596. });
  10597. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10598. mergedMapGenerator._file = oldMap.file;
  10599. return JSON.parse(mergedMapGenerator.toString())
  10600. }
  10601. return mergeSourceMap;
  10602. }
  10603. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10604. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10605. const scss = (source, map, options, load = require) => {
  10606. const nodeSass = load("sass");
  10607. const { compileString, renderSync } = nodeSass;
  10608. const data = getSource(source, options.filename, options.additionalData);
  10609. let css;
  10610. let dependencies;
  10611. let sourceMap;
  10612. try {
  10613. if (compileString) {
  10614. const { pathToFileURL, fileURLToPath } = load("url");
  10615. const result = compileString(data, {
  10616. ...options,
  10617. url: pathToFileURL(options.filename),
  10618. sourceMap: !!map
  10619. });
  10620. css = result.css;
  10621. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10622. sourceMap = map ? result.sourceMap : void 0;
  10623. } else {
  10624. const result = renderSync({
  10625. ...options,
  10626. data,
  10627. file: options.filename,
  10628. outFile: options.filename,
  10629. sourceMap: !!map
  10630. });
  10631. css = result.css.toString();
  10632. dependencies = result.stats.includedFiles;
  10633. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10634. }
  10635. if (map) {
  10636. return {
  10637. code: css,
  10638. errors: [],
  10639. dependencies,
  10640. map: merge(map, sourceMap)
  10641. };
  10642. }
  10643. return { code: css, errors: [], dependencies };
  10644. } catch (e) {
  10645. return { code: "", errors: [e], dependencies: [] };
  10646. }
  10647. };
  10648. const sass = (source, map, options, load) => scss(
  10649. source,
  10650. map,
  10651. {
  10652. ...options,
  10653. indentedSyntax: true
  10654. },
  10655. load
  10656. );
  10657. const less = (source, map, options, load = require) => {
  10658. const nodeLess = load("less");
  10659. let result;
  10660. let error = null;
  10661. nodeLess.render(
  10662. getSource(source, options.filename, options.additionalData),
  10663. { ...options, syncImport: true },
  10664. (err, output) => {
  10665. error = err;
  10666. result = output;
  10667. }
  10668. );
  10669. if (error) return { code: "", errors: [error], dependencies: [] };
  10670. const dependencies = result.imports;
  10671. if (map) {
  10672. return {
  10673. code: result.css.toString(),
  10674. map: merge(map, result.map),
  10675. errors: [],
  10676. dependencies
  10677. };
  10678. }
  10679. return {
  10680. code: result.css.toString(),
  10681. errors: [],
  10682. dependencies
  10683. };
  10684. };
  10685. const styl = (source, map, options, load = require) => {
  10686. const nodeStylus = load("stylus");
  10687. try {
  10688. const ref = nodeStylus(source, options);
  10689. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10690. const result = ref.render();
  10691. const dependencies = ref.deps();
  10692. if (map) {
  10693. return {
  10694. code: result,
  10695. map: merge(map, ref.sourcemap),
  10696. errors: [],
  10697. dependencies
  10698. };
  10699. }
  10700. return { code: result, errors: [], dependencies };
  10701. } catch (e) {
  10702. return { code: "", errors: [e], dependencies: [] };
  10703. }
  10704. };
  10705. function getSource(source, filename, additionalData) {
  10706. if (!additionalData) return source;
  10707. if (shared.isFunction(additionalData)) {
  10708. return additionalData(source, filename);
  10709. }
  10710. return additionalData + source;
  10711. }
  10712. const processors = {
  10713. less,
  10714. sass,
  10715. scss,
  10716. styl,
  10717. stylus: styl
  10718. };
  10719. var build = {exports: {}};
  10720. var fs = {};
  10721. var hasRequiredFs;
  10722. function requireFs () {
  10723. if (hasRequiredFs) return fs;
  10724. hasRequiredFs = 1;
  10725. Object.defineProperty(fs, "__esModule", {
  10726. value: true
  10727. });
  10728. fs.getFileSystem = getFileSystem;
  10729. fs.setFileSystem = setFileSystem;
  10730. let fileSystem = {
  10731. readFile: () => {
  10732. throw Error("readFile not implemented");
  10733. },
  10734. writeFile: () => {
  10735. throw Error("writeFile not implemented");
  10736. }
  10737. };
  10738. function setFileSystem(fs) {
  10739. fileSystem.readFile = fs.readFile;
  10740. fileSystem.writeFile = fs.writeFile;
  10741. }
  10742. function getFileSystem() {
  10743. return fileSystem;
  10744. }
  10745. return fs;
  10746. }
  10747. var pluginFactory = {};
  10748. var unquote = {};
  10749. var hasRequiredUnquote;
  10750. function requireUnquote () {
  10751. if (hasRequiredUnquote) return unquote;
  10752. hasRequiredUnquote = 1;
  10753. Object.defineProperty(unquote, "__esModule", {
  10754. value: true
  10755. });
  10756. unquote.default = unquote$1;
  10757. // copied from https://github.com/lakenen/node-unquote
  10758. const reg = /['"]/;
  10759. function unquote$1(str) {
  10760. if (!str) {
  10761. return "";
  10762. }
  10763. if (reg.test(str.charAt(0))) {
  10764. str = str.substr(1);
  10765. }
  10766. if (reg.test(str.charAt(str.length - 1))) {
  10767. str = str.substr(0, str.length - 1);
  10768. }
  10769. return str;
  10770. }
  10771. return unquote;
  10772. }
  10773. var Parser = {};
  10774. var replaceValueSymbols_1;
  10775. var hasRequiredReplaceValueSymbols;
  10776. function requireReplaceValueSymbols () {
  10777. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10778. hasRequiredReplaceValueSymbols = 1;
  10779. const matchValueName = /[$]?[\w-]+/g;
  10780. const replaceValueSymbols = (value, replacements) => {
  10781. let matches;
  10782. while ((matches = matchValueName.exec(value))) {
  10783. const replacement = replacements[matches[0]];
  10784. if (replacement) {
  10785. value =
  10786. value.slice(0, matches.index) +
  10787. replacement +
  10788. value.slice(matchValueName.lastIndex);
  10789. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10790. }
  10791. }
  10792. return value;
  10793. };
  10794. replaceValueSymbols_1 = replaceValueSymbols;
  10795. return replaceValueSymbols_1;
  10796. }
  10797. var replaceSymbols_1;
  10798. var hasRequiredReplaceSymbols;
  10799. function requireReplaceSymbols () {
  10800. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10801. hasRequiredReplaceSymbols = 1;
  10802. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10803. const replaceSymbols = (css, replacements) => {
  10804. css.walk((node) => {
  10805. if (node.type === "decl" && node.value) {
  10806. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10807. } else if (node.type === "rule" && node.selector) {
  10808. node.selector = replaceValueSymbols(
  10809. node.selector.toString(),
  10810. replacements
  10811. );
  10812. } else if (node.type === "atrule" && node.params) {
  10813. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10814. }
  10815. });
  10816. };
  10817. replaceSymbols_1 = replaceSymbols;
  10818. return replaceSymbols_1;
  10819. }
  10820. var extractICSS_1;
  10821. var hasRequiredExtractICSS;
  10822. function requireExtractICSS () {
  10823. if (hasRequiredExtractICSS) return extractICSS_1;
  10824. hasRequiredExtractICSS = 1;
  10825. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10826. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10827. const getDeclsObject = (rule) => {
  10828. const object = {};
  10829. rule.walkDecls((decl) => {
  10830. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10831. object[before + decl.prop] = decl.value;
  10832. });
  10833. return object;
  10834. };
  10835. /**
  10836. *
  10837. * @param {string} css
  10838. * @param {boolean} removeRules
  10839. * @param {'auto' | 'rule' | 'at-rule'} mode
  10840. */
  10841. const extractICSS = (css, removeRules = true, mode = "auto") => {
  10842. const icssImports = {};
  10843. const icssExports = {};
  10844. function addImports(node, path) {
  10845. const unquoted = path.replace(/'|"/g, "");
  10846. icssImports[unquoted] = Object.assign(
  10847. icssImports[unquoted] || {},
  10848. getDeclsObject(node)
  10849. );
  10850. if (removeRules) {
  10851. node.remove();
  10852. }
  10853. }
  10854. function addExports(node) {
  10855. Object.assign(icssExports, getDeclsObject(node));
  10856. if (removeRules) {
  10857. node.remove();
  10858. }
  10859. }
  10860. css.each((node) => {
  10861. if (node.type === "rule" && mode !== "at-rule") {
  10862. if (node.selector.slice(0, 7) === ":import") {
  10863. const matches = importPattern.exec(node.selector);
  10864. if (matches) {
  10865. addImports(node, matches[1]);
  10866. }
  10867. }
  10868. if (node.selector === ":export") {
  10869. addExports(node);
  10870. }
  10871. }
  10872. if (node.type === "atrule" && mode !== "rule") {
  10873. if (node.name === "icss-import") {
  10874. const matches = balancedQuotes.exec(node.params);
  10875. if (matches) {
  10876. addImports(node, matches[1]);
  10877. }
  10878. }
  10879. if (node.name === "icss-export") {
  10880. addExports(node);
  10881. }
  10882. }
  10883. });
  10884. return { icssImports, icssExports };
  10885. };
  10886. extractICSS_1 = extractICSS;
  10887. return extractICSS_1;
  10888. }
  10889. var createICSSRules_1;
  10890. var hasRequiredCreateICSSRules;
  10891. function requireCreateICSSRules () {
  10892. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  10893. hasRequiredCreateICSSRules = 1;
  10894. const createImports = (imports, postcss, mode = "rule") => {
  10895. return Object.keys(imports).map((path) => {
  10896. const aliases = imports[path];
  10897. const declarations = Object.keys(aliases).map((key) =>
  10898. postcss.decl({
  10899. prop: key,
  10900. value: aliases[key],
  10901. raws: { before: "\n " },
  10902. })
  10903. );
  10904. const hasDeclarations = declarations.length > 0;
  10905. const rule =
  10906. mode === "rule"
  10907. ? postcss.rule({
  10908. selector: `:import('${path}')`,
  10909. raws: { after: hasDeclarations ? "\n" : "" },
  10910. })
  10911. : postcss.atRule({
  10912. name: "icss-import",
  10913. params: `'${path}'`,
  10914. raws: { after: hasDeclarations ? "\n" : "" },
  10915. });
  10916. if (hasDeclarations) {
  10917. rule.append(declarations);
  10918. }
  10919. return rule;
  10920. });
  10921. };
  10922. const createExports = (exports, postcss, mode = "rule") => {
  10923. const declarations = Object.keys(exports).map((key) =>
  10924. postcss.decl({
  10925. prop: key,
  10926. value: exports[key],
  10927. raws: { before: "\n " },
  10928. })
  10929. );
  10930. if (declarations.length === 0) {
  10931. return [];
  10932. }
  10933. const rule =
  10934. mode === "rule"
  10935. ? postcss.rule({
  10936. selector: `:export`,
  10937. raws: { after: "\n" },
  10938. })
  10939. : postcss.atRule({
  10940. name: "icss-export",
  10941. raws: { after: "\n" },
  10942. });
  10943. rule.append(declarations);
  10944. return [rule];
  10945. };
  10946. const createICSSRules = (imports, exports, postcss, mode) => [
  10947. ...createImports(imports, postcss, mode),
  10948. ...createExports(exports, postcss, mode),
  10949. ];
  10950. createICSSRules_1 = createICSSRules;
  10951. return createICSSRules_1;
  10952. }
  10953. var src$4;
  10954. var hasRequiredSrc$4;
  10955. function requireSrc$4 () {
  10956. if (hasRequiredSrc$4) return src$4;
  10957. hasRequiredSrc$4 = 1;
  10958. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10959. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  10960. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  10961. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  10962. src$4 = {
  10963. replaceValueSymbols,
  10964. replaceSymbols,
  10965. extractICSS,
  10966. createICSSRules,
  10967. };
  10968. return src$4;
  10969. }
  10970. var hasRequiredParser$1;
  10971. function requireParser$1 () {
  10972. if (hasRequiredParser$1) return Parser;
  10973. hasRequiredParser$1 = 1;
  10974. Object.defineProperty(Parser, "__esModule", {
  10975. value: true
  10976. });
  10977. Parser.default = void 0;
  10978. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  10979. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  10980. const importRegexp = /^:import\((.+)\)$/;
  10981. let Parser$1 = class Parser {
  10982. constructor(pathFetcher, trace) {
  10983. this.pathFetcher = pathFetcher;
  10984. this.plugin = this.plugin.bind(this);
  10985. this.exportTokens = {};
  10986. this.translations = {};
  10987. this.trace = trace;
  10988. }
  10989. plugin() {
  10990. const parser = this;
  10991. return {
  10992. postcssPlugin: "css-modules-parser",
  10993. async OnceExit(css) {
  10994. await Promise.all(parser.fetchAllImports(css));
  10995. parser.linkImportedSymbols(css);
  10996. return parser.extractExports(css);
  10997. }
  10998. };
  10999. }
  11000. fetchAllImports(css) {
  11001. let imports = [];
  11002. css.each(node => {
  11003. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11004. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11005. }
  11006. });
  11007. return imports;
  11008. }
  11009. linkImportedSymbols(css) {
  11010. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11011. }
  11012. extractExports(css) {
  11013. css.each(node => {
  11014. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11015. });
  11016. }
  11017. handleExport(exportNode) {
  11018. exportNode.each(decl => {
  11019. if (decl.type == "decl") {
  11020. Object.keys(this.translations).forEach(translation => {
  11021. decl.value = decl.value.replace(translation, this.translations[translation]);
  11022. });
  11023. this.exportTokens[decl.prop] = decl.value;
  11024. }
  11025. });
  11026. exportNode.remove();
  11027. }
  11028. async fetchImport(importNode, relativeTo, depNr) {
  11029. const file = importNode.selector.match(importRegexp)[1];
  11030. const depTrace = this.trace + String.fromCharCode(depNr);
  11031. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  11032. try {
  11033. importNode.each(decl => {
  11034. if (decl.type == "decl") {
  11035. this.translations[decl.prop] = exports[decl.value];
  11036. }
  11037. });
  11038. importNode.remove();
  11039. } catch (err) {
  11040. console.log(err);
  11041. }
  11042. }
  11043. };
  11044. Parser.default = Parser$1;
  11045. return Parser;
  11046. }
  11047. var saveJSON = {};
  11048. var hasRequiredSaveJSON;
  11049. function requireSaveJSON () {
  11050. if (hasRequiredSaveJSON) return saveJSON;
  11051. hasRequiredSaveJSON = 1;
  11052. Object.defineProperty(saveJSON, "__esModule", {
  11053. value: true
  11054. });
  11055. saveJSON.default = saveJSON$1;
  11056. var _fs = /*@__PURE__*/ requireFs();
  11057. function saveJSON$1(cssFile, json) {
  11058. return new Promise((resolve, reject) => {
  11059. const {
  11060. writeFile
  11061. } = (0, _fs.getFileSystem)();
  11062. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11063. });
  11064. }
  11065. return saveJSON;
  11066. }
  11067. var localsConvention = {};
  11068. /**
  11069. * lodash (Custom Build) <https://lodash.com/>
  11070. * Build: `lodash modularize exports="npm" -o ./`
  11071. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11072. * Released under MIT license <https://lodash.com/license>
  11073. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11074. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11075. */
  11076. var lodash_camelcase;
  11077. var hasRequiredLodash_camelcase;
  11078. function requireLodash_camelcase () {
  11079. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11080. hasRequiredLodash_camelcase = 1;
  11081. /** Used as references for various `Number` constants. */
  11082. var INFINITY = 1 / 0;
  11083. /** `Object#toString` result references. */
  11084. var symbolTag = '[object Symbol]';
  11085. /** Used to match words composed of alphanumeric characters. */
  11086. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11087. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11088. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11089. /** Used to compose unicode character classes. */
  11090. var rsAstralRange = '\\ud800-\\udfff',
  11091. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11092. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11093. rsDingbatRange = '\\u2700-\\u27bf',
  11094. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11095. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11096. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11097. rsPunctuationRange = '\\u2000-\\u206f',
  11098. 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',
  11099. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11100. rsVarRange = '\\ufe0e\\ufe0f',
  11101. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11102. /** Used to compose unicode capture groups. */
  11103. var rsApos = "['\u2019]",
  11104. rsAstral = '[' + rsAstralRange + ']',
  11105. rsBreak = '[' + rsBreakRange + ']',
  11106. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11107. rsDigits = '\\d+',
  11108. rsDingbat = '[' + rsDingbatRange + ']',
  11109. rsLower = '[' + rsLowerRange + ']',
  11110. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11111. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11112. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11113. rsNonAstral = '[^' + rsAstralRange + ']',
  11114. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11115. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11116. rsUpper = '[' + rsUpperRange + ']',
  11117. rsZWJ = '\\u200d';
  11118. /** Used to compose unicode regexes. */
  11119. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11120. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11121. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11122. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11123. reOptMod = rsModifier + '?',
  11124. rsOptVar = '[' + rsVarRange + ']?',
  11125. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11126. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11127. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11128. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11129. /** Used to match apostrophes. */
  11130. var reApos = RegExp(rsApos, 'g');
  11131. /**
  11132. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11133. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11134. */
  11135. var reComboMark = RegExp(rsCombo, 'g');
  11136. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11137. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11138. /** Used to match complex or compound words. */
  11139. var reUnicodeWord = RegExp([
  11140. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11141. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11142. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11143. rsUpper + '+' + rsOptUpperContr,
  11144. rsDigits,
  11145. rsEmoji
  11146. ].join('|'), 'g');
  11147. /** 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/). */
  11148. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11149. /** Used to detect strings that need a more robust regexp to match words. */
  11150. 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 ]/;
  11151. /** Used to map Latin Unicode letters to basic Latin letters. */
  11152. var deburredLetters = {
  11153. // Latin-1 Supplement block.
  11154. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11155. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11156. '\xc7': 'C', '\xe7': 'c',
  11157. '\xd0': 'D', '\xf0': 'd',
  11158. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11159. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11160. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11161. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11162. '\xd1': 'N', '\xf1': 'n',
  11163. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11164. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11165. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11166. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11167. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11168. '\xc6': 'Ae', '\xe6': 'ae',
  11169. '\xde': 'Th', '\xfe': 'th',
  11170. '\xdf': 'ss',
  11171. // Latin Extended-A block.
  11172. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11173. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11174. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11175. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11176. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11177. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11178. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11179. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11180. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11181. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11182. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11183. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11184. '\u0134': 'J', '\u0135': 'j',
  11185. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11186. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11187. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11188. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11189. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11190. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11191. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11192. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11193. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11194. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11195. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11196. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11197. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11198. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11199. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11200. '\u0174': 'W', '\u0175': 'w',
  11201. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11202. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11203. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11204. '\u0132': 'IJ', '\u0133': 'ij',
  11205. '\u0152': 'Oe', '\u0153': 'oe',
  11206. '\u0149': "'n", '\u017f': 'ss'
  11207. };
  11208. /** Detect free variable `global` from Node.js. */
  11209. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11210. /** Detect free variable `self`. */
  11211. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11212. /** Used as a reference to the global object. */
  11213. var root = freeGlobal || freeSelf || Function('return this')();
  11214. /**
  11215. * A specialized version of `_.reduce` for arrays without support for
  11216. * iteratee shorthands.
  11217. *
  11218. * @private
  11219. * @param {Array} [array] The array to iterate over.
  11220. * @param {Function} iteratee The function invoked per iteration.
  11221. * @param {*} [accumulator] The initial value.
  11222. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11223. * the initial value.
  11224. * @returns {*} Returns the accumulated value.
  11225. */
  11226. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11227. var index = -1,
  11228. length = array ? array.length : 0;
  11229. while (++index < length) {
  11230. accumulator = iteratee(accumulator, array[index], index, array);
  11231. }
  11232. return accumulator;
  11233. }
  11234. /**
  11235. * Converts an ASCII `string` to an array.
  11236. *
  11237. * @private
  11238. * @param {string} string The string to convert.
  11239. * @returns {Array} Returns the converted array.
  11240. */
  11241. function asciiToArray(string) {
  11242. return string.split('');
  11243. }
  11244. /**
  11245. * Splits an ASCII `string` into an array of its words.
  11246. *
  11247. * @private
  11248. * @param {string} The string to inspect.
  11249. * @returns {Array} Returns the words of `string`.
  11250. */
  11251. function asciiWords(string) {
  11252. return string.match(reAsciiWord) || [];
  11253. }
  11254. /**
  11255. * The base implementation of `_.propertyOf` without support for deep paths.
  11256. *
  11257. * @private
  11258. * @param {Object} object The object to query.
  11259. * @returns {Function} Returns the new accessor function.
  11260. */
  11261. function basePropertyOf(object) {
  11262. return function(key) {
  11263. return object == null ? undefined : object[key];
  11264. };
  11265. }
  11266. /**
  11267. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11268. * letters to basic Latin letters.
  11269. *
  11270. * @private
  11271. * @param {string} letter The matched letter to deburr.
  11272. * @returns {string} Returns the deburred letter.
  11273. */
  11274. var deburrLetter = basePropertyOf(deburredLetters);
  11275. /**
  11276. * Checks if `string` contains Unicode symbols.
  11277. *
  11278. * @private
  11279. * @param {string} string The string to inspect.
  11280. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11281. */
  11282. function hasUnicode(string) {
  11283. return reHasUnicode.test(string);
  11284. }
  11285. /**
  11286. * Checks if `string` contains a word composed of Unicode symbols.
  11287. *
  11288. * @private
  11289. * @param {string} string The string to inspect.
  11290. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11291. */
  11292. function hasUnicodeWord(string) {
  11293. return reHasUnicodeWord.test(string);
  11294. }
  11295. /**
  11296. * Converts `string` to an array.
  11297. *
  11298. * @private
  11299. * @param {string} string The string to convert.
  11300. * @returns {Array} Returns the converted array.
  11301. */
  11302. function stringToArray(string) {
  11303. return hasUnicode(string)
  11304. ? unicodeToArray(string)
  11305. : asciiToArray(string);
  11306. }
  11307. /**
  11308. * Converts a Unicode `string` to an array.
  11309. *
  11310. * @private
  11311. * @param {string} string The string to convert.
  11312. * @returns {Array} Returns the converted array.
  11313. */
  11314. function unicodeToArray(string) {
  11315. return string.match(reUnicode) || [];
  11316. }
  11317. /**
  11318. * Splits a Unicode `string` into an array of its words.
  11319. *
  11320. * @private
  11321. * @param {string} The string to inspect.
  11322. * @returns {Array} Returns the words of `string`.
  11323. */
  11324. function unicodeWords(string) {
  11325. return string.match(reUnicodeWord) || [];
  11326. }
  11327. /** Used for built-in method references. */
  11328. var objectProto = Object.prototype;
  11329. /**
  11330. * Used to resolve the
  11331. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11332. * of values.
  11333. */
  11334. var objectToString = objectProto.toString;
  11335. /** Built-in value references. */
  11336. var Symbol = root.Symbol;
  11337. /** Used to convert symbols to primitives and strings. */
  11338. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11339. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11340. /**
  11341. * The base implementation of `_.slice` without an iteratee call guard.
  11342. *
  11343. * @private
  11344. * @param {Array} array The array to slice.
  11345. * @param {number} [start=0] The start position.
  11346. * @param {number} [end=array.length] The end position.
  11347. * @returns {Array} Returns the slice of `array`.
  11348. */
  11349. function baseSlice(array, start, end) {
  11350. var index = -1,
  11351. length = array.length;
  11352. if (start < 0) {
  11353. start = -start > length ? 0 : (length + start);
  11354. }
  11355. end = end > length ? length : end;
  11356. if (end < 0) {
  11357. end += length;
  11358. }
  11359. length = start > end ? 0 : ((end - start) >>> 0);
  11360. start >>>= 0;
  11361. var result = Array(length);
  11362. while (++index < length) {
  11363. result[index] = array[index + start];
  11364. }
  11365. return result;
  11366. }
  11367. /**
  11368. * The base implementation of `_.toString` which doesn't convert nullish
  11369. * values to empty strings.
  11370. *
  11371. * @private
  11372. * @param {*} value The value to process.
  11373. * @returns {string} Returns the string.
  11374. */
  11375. function baseToString(value) {
  11376. // Exit early for strings to avoid a performance hit in some environments.
  11377. if (typeof value == 'string') {
  11378. return value;
  11379. }
  11380. if (isSymbol(value)) {
  11381. return symbolToString ? symbolToString.call(value) : '';
  11382. }
  11383. var result = (value + '');
  11384. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  11385. }
  11386. /**
  11387. * Casts `array` to a slice if it's needed.
  11388. *
  11389. * @private
  11390. * @param {Array} array The array to inspect.
  11391. * @param {number} start The start position.
  11392. * @param {number} [end=array.length] The end position.
  11393. * @returns {Array} Returns the cast slice.
  11394. */
  11395. function castSlice(array, start, end) {
  11396. var length = array.length;
  11397. end = end === undefined ? length : end;
  11398. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11399. }
  11400. /**
  11401. * Creates a function like `_.lowerFirst`.
  11402. *
  11403. * @private
  11404. * @param {string} methodName The name of the `String` case method to use.
  11405. * @returns {Function} Returns the new case function.
  11406. */
  11407. function createCaseFirst(methodName) {
  11408. return function(string) {
  11409. string = toString(string);
  11410. var strSymbols = hasUnicode(string)
  11411. ? stringToArray(string)
  11412. : undefined;
  11413. var chr = strSymbols
  11414. ? strSymbols[0]
  11415. : string.charAt(0);
  11416. var trailing = strSymbols
  11417. ? castSlice(strSymbols, 1).join('')
  11418. : string.slice(1);
  11419. return chr[methodName]() + trailing;
  11420. };
  11421. }
  11422. /**
  11423. * Creates a function like `_.camelCase`.
  11424. *
  11425. * @private
  11426. * @param {Function} callback The function to combine each word.
  11427. * @returns {Function} Returns the new compounder function.
  11428. */
  11429. function createCompounder(callback) {
  11430. return function(string) {
  11431. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11432. };
  11433. }
  11434. /**
  11435. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11436. * and has a `typeof` result of "object".
  11437. *
  11438. * @static
  11439. * @memberOf _
  11440. * @since 4.0.0
  11441. * @category Lang
  11442. * @param {*} value The value to check.
  11443. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11444. * @example
  11445. *
  11446. * _.isObjectLike({});
  11447. * // => true
  11448. *
  11449. * _.isObjectLike([1, 2, 3]);
  11450. * // => true
  11451. *
  11452. * _.isObjectLike(_.noop);
  11453. * // => false
  11454. *
  11455. * _.isObjectLike(null);
  11456. * // => false
  11457. */
  11458. function isObjectLike(value) {
  11459. return !!value && typeof value == 'object';
  11460. }
  11461. /**
  11462. * Checks if `value` is classified as a `Symbol` primitive or object.
  11463. *
  11464. * @static
  11465. * @memberOf _
  11466. * @since 4.0.0
  11467. * @category Lang
  11468. * @param {*} value The value to check.
  11469. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11470. * @example
  11471. *
  11472. * _.isSymbol(Symbol.iterator);
  11473. * // => true
  11474. *
  11475. * _.isSymbol('abc');
  11476. * // => false
  11477. */
  11478. function isSymbol(value) {
  11479. return typeof value == 'symbol' ||
  11480. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11481. }
  11482. /**
  11483. * Converts `value` to a string. An empty string is returned for `null`
  11484. * and `undefined` values. The sign of `-0` is preserved.
  11485. *
  11486. * @static
  11487. * @memberOf _
  11488. * @since 4.0.0
  11489. * @category Lang
  11490. * @param {*} value The value to process.
  11491. * @returns {string} Returns the string.
  11492. * @example
  11493. *
  11494. * _.toString(null);
  11495. * // => ''
  11496. *
  11497. * _.toString(-0);
  11498. * // => '-0'
  11499. *
  11500. * _.toString([1, 2, 3]);
  11501. * // => '1,2,3'
  11502. */
  11503. function toString(value) {
  11504. return value == null ? '' : baseToString(value);
  11505. }
  11506. /**
  11507. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11508. *
  11509. * @static
  11510. * @memberOf _
  11511. * @since 3.0.0
  11512. * @category String
  11513. * @param {string} [string=''] The string to convert.
  11514. * @returns {string} Returns the camel cased string.
  11515. * @example
  11516. *
  11517. * _.camelCase('Foo Bar');
  11518. * // => 'fooBar'
  11519. *
  11520. * _.camelCase('--foo-bar--');
  11521. * // => 'fooBar'
  11522. *
  11523. * _.camelCase('__FOO_BAR__');
  11524. * // => 'fooBar'
  11525. */
  11526. var camelCase = createCompounder(function(result, word, index) {
  11527. word = word.toLowerCase();
  11528. return result + (index ? capitalize(word) : word);
  11529. });
  11530. /**
  11531. * Converts the first character of `string` to upper case and the remaining
  11532. * to lower case.
  11533. *
  11534. * @static
  11535. * @memberOf _
  11536. * @since 3.0.0
  11537. * @category String
  11538. * @param {string} [string=''] The string to capitalize.
  11539. * @returns {string} Returns the capitalized string.
  11540. * @example
  11541. *
  11542. * _.capitalize('FRED');
  11543. * // => 'Fred'
  11544. */
  11545. function capitalize(string) {
  11546. return upperFirst(toString(string).toLowerCase());
  11547. }
  11548. /**
  11549. * Deburrs `string` by converting
  11550. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11551. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11552. * letters to basic Latin letters and removing
  11553. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11554. *
  11555. * @static
  11556. * @memberOf _
  11557. * @since 3.0.0
  11558. * @category String
  11559. * @param {string} [string=''] The string to deburr.
  11560. * @returns {string} Returns the deburred string.
  11561. * @example
  11562. *
  11563. * _.deburr('déjà vu');
  11564. * // => 'deja vu'
  11565. */
  11566. function deburr(string) {
  11567. string = toString(string);
  11568. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11569. }
  11570. /**
  11571. * Converts the first character of `string` to upper case.
  11572. *
  11573. * @static
  11574. * @memberOf _
  11575. * @since 4.0.0
  11576. * @category String
  11577. * @param {string} [string=''] The string to convert.
  11578. * @returns {string} Returns the converted string.
  11579. * @example
  11580. *
  11581. * _.upperFirst('fred');
  11582. * // => 'Fred'
  11583. *
  11584. * _.upperFirst('FRED');
  11585. * // => 'FRED'
  11586. */
  11587. var upperFirst = createCaseFirst('toUpperCase');
  11588. /**
  11589. * Splits `string` into an array of its words.
  11590. *
  11591. * @static
  11592. * @memberOf _
  11593. * @since 3.0.0
  11594. * @category String
  11595. * @param {string} [string=''] The string to inspect.
  11596. * @param {RegExp|string} [pattern] The pattern to match words.
  11597. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11598. * @returns {Array} Returns the words of `string`.
  11599. * @example
  11600. *
  11601. * _.words('fred, barney, & pebbles');
  11602. * // => ['fred', 'barney', 'pebbles']
  11603. *
  11604. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11605. * // => ['fred', 'barney', '&', 'pebbles']
  11606. */
  11607. function words(string, pattern, guard) {
  11608. string = toString(string);
  11609. pattern = pattern;
  11610. if (pattern === undefined) {
  11611. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11612. }
  11613. return string.match(pattern) || [];
  11614. }
  11615. lodash_camelcase = camelCase;
  11616. return lodash_camelcase;
  11617. }
  11618. var hasRequiredLocalsConvention;
  11619. function requireLocalsConvention () {
  11620. if (hasRequiredLocalsConvention) return localsConvention;
  11621. hasRequiredLocalsConvention = 1;
  11622. Object.defineProperty(localsConvention, "__esModule", {
  11623. value: true
  11624. });
  11625. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11626. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11627. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11628. function dashesCamelCase(string) {
  11629. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11630. }
  11631. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11632. const isFunc = typeof localsConvention === "function";
  11633. return (tokens, [className, value]) => {
  11634. if (isFunc) {
  11635. const convention = localsConvention(className, value, inputFile);
  11636. tokens[convention] = value;
  11637. return tokens;
  11638. }
  11639. switch (localsConvention) {
  11640. case "camelCase":
  11641. tokens[className] = value;
  11642. tokens[(0, _lodash.default)(className)] = value;
  11643. break;
  11644. case "camelCaseOnly":
  11645. tokens[(0, _lodash.default)(className)] = value;
  11646. break;
  11647. case "dashes":
  11648. tokens[className] = value;
  11649. tokens[dashesCamelCase(className)] = value;
  11650. break;
  11651. case "dashesOnly":
  11652. tokens[dashesCamelCase(className)] = value;
  11653. break;
  11654. }
  11655. return tokens;
  11656. };
  11657. }
  11658. return localsConvention;
  11659. }
  11660. var FileSystemLoader = {};
  11661. var hasRequiredFileSystemLoader;
  11662. function requireFileSystemLoader () {
  11663. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11664. hasRequiredFileSystemLoader = 1;
  11665. Object.defineProperty(FileSystemLoader, "__esModule", {
  11666. value: true
  11667. });
  11668. FileSystemLoader.default = void 0;
  11669. var _postcss = _interopRequireDefault(require$$0$1);
  11670. var _path = _interopRequireDefault(path$1);
  11671. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  11672. var _fs = /*@__PURE__*/ requireFs();
  11673. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11674. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11675. class Core {
  11676. constructor(plugins) {
  11677. this.plugins = plugins || Core.defaultPlugins;
  11678. }
  11679. async load(sourceString, sourcePath, trace, pathFetcher) {
  11680. const parser = new _Parser.default(pathFetcher, trace);
  11681. const plugins = this.plugins.concat([parser.plugin()]);
  11682. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11683. from: sourcePath
  11684. });
  11685. return {
  11686. injectableSource: result.css,
  11687. exportTokens: parser.exportTokens
  11688. };
  11689. }
  11690. } // Sorts dependencies in the following way:
  11691. // AAA comes before AA and A
  11692. // AB comes after AA and before A
  11693. // All Bs come after all As
  11694. // This ensures that the files are always returned in the following order:
  11695. // - In the order they were required, except
  11696. // - After all their dependencies
  11697. const traceKeySorter = (a, b) => {
  11698. if (a.length < b.length) {
  11699. return a < b.substring(0, a.length) ? -1 : 1;
  11700. }
  11701. if (a.length > b.length) {
  11702. return a.substring(0, b.length) <= b ? -1 : 1;
  11703. }
  11704. return a < b ? -1 : 1;
  11705. };
  11706. let FileSystemLoader$1 = class FileSystemLoader {
  11707. constructor(root, plugins, fileResolve) {
  11708. if (root === "/" && process.platform === "win32") {
  11709. const cwdDrive = process.cwd().slice(0, 3);
  11710. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11711. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11712. }
  11713. root = cwdDrive;
  11714. }
  11715. this.root = root;
  11716. this.fileResolve = fileResolve;
  11717. this.sources = {};
  11718. this.traces = {};
  11719. this.importNr = 0;
  11720. this.core = new Core(plugins);
  11721. this.tokensByFile = {};
  11722. this.fs = (0, _fs.getFileSystem)();
  11723. }
  11724. async fetch(_newPath, relativeTo, _trace) {
  11725. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11726. const trace = _trace || String.fromCharCode(this.importNr++);
  11727. const useFileResolve = typeof this.fileResolve === "function";
  11728. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11729. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11730. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11731. }
  11732. const relativeDir = _path.default.dirname(relativeTo);
  11733. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11734. 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
  11735. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11736. try {
  11737. fileRelativePath = require.resolve(newPath);
  11738. } catch (e) {// noop
  11739. }
  11740. }
  11741. const tokens = this.tokensByFile[fileRelativePath];
  11742. if (tokens) return tokens;
  11743. return new Promise((resolve, reject) => {
  11744. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11745. if (err) reject(err);
  11746. const {
  11747. injectableSource,
  11748. exportTokens
  11749. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11750. this.sources[fileRelativePath] = injectableSource;
  11751. this.traces[trace] = fileRelativePath;
  11752. this.tokensByFile[fileRelativePath] = exportTokens;
  11753. resolve(exportTokens);
  11754. });
  11755. });
  11756. }
  11757. get finalSource() {
  11758. const traces = this.traces;
  11759. const sources = this.sources;
  11760. let written = new Set();
  11761. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11762. const filename = traces[key];
  11763. if (written.has(filename)) {
  11764. return null;
  11765. }
  11766. written.add(filename);
  11767. return sources[filename];
  11768. }).join("");
  11769. }
  11770. };
  11771. FileSystemLoader.default = FileSystemLoader$1;
  11772. return FileSystemLoader;
  11773. }
  11774. var scoping = {};
  11775. var src$3 = {exports: {}};
  11776. var topologicalSort_1;
  11777. var hasRequiredTopologicalSort;
  11778. function requireTopologicalSort () {
  11779. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11780. hasRequiredTopologicalSort = 1;
  11781. const PERMANENT_MARKER = 2;
  11782. const TEMPORARY_MARKER = 1;
  11783. function createError(node, graph) {
  11784. const er = new Error("Nondeterministic import's order");
  11785. const related = graph[node];
  11786. const relatedNode = related.find(
  11787. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11788. );
  11789. er.nodes = [node, relatedNode];
  11790. return er;
  11791. }
  11792. function walkGraph(node, graph, state, result, strict) {
  11793. if (state[node] === PERMANENT_MARKER) {
  11794. return;
  11795. }
  11796. if (state[node] === TEMPORARY_MARKER) {
  11797. if (strict) {
  11798. return createError(node, graph);
  11799. }
  11800. return;
  11801. }
  11802. state[node] = TEMPORARY_MARKER;
  11803. const children = graph[node];
  11804. const length = children.length;
  11805. for (let i = 0; i < length; ++i) {
  11806. const error = walkGraph(children[i], graph, state, result, strict);
  11807. if (error instanceof Error) {
  11808. return error;
  11809. }
  11810. }
  11811. state[node] = PERMANENT_MARKER;
  11812. result.push(node);
  11813. }
  11814. function topologicalSort(graph, strict) {
  11815. const result = [];
  11816. const state = {};
  11817. const nodes = Object.keys(graph);
  11818. const length = nodes.length;
  11819. for (let i = 0; i < length; ++i) {
  11820. const er = walkGraph(nodes[i], graph, state, result, strict);
  11821. if (er instanceof Error) {
  11822. return er;
  11823. }
  11824. }
  11825. return result;
  11826. }
  11827. topologicalSort_1 = topologicalSort;
  11828. return topologicalSort_1;
  11829. }
  11830. var hasRequiredSrc$3;
  11831. function requireSrc$3 () {
  11832. if (hasRequiredSrc$3) return src$3.exports;
  11833. hasRequiredSrc$3 = 1;
  11834. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  11835. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11836. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11837. const VISITED_MARKER = 1;
  11838. /**
  11839. * :import('G') {}
  11840. *
  11841. * Rule
  11842. * composes: ... from 'A'
  11843. * composes: ... from 'B'
  11844. * Rule
  11845. * composes: ... from 'A'
  11846. * composes: ... from 'A'
  11847. * composes: ... from 'C'
  11848. *
  11849. * Results in:
  11850. *
  11851. * graph: {
  11852. * G: [],
  11853. * A: [],
  11854. * B: ['A'],
  11855. * C: ['A'],
  11856. * }
  11857. */
  11858. function addImportToGraph(importId, parentId, graph, visited) {
  11859. const siblingsId = parentId + "_" + "siblings";
  11860. const visitedId = parentId + "_" + importId;
  11861. if (visited[visitedId] !== VISITED_MARKER) {
  11862. if (!Array.isArray(visited[siblingsId])) {
  11863. visited[siblingsId] = [];
  11864. }
  11865. const siblings = visited[siblingsId];
  11866. if (Array.isArray(graph[importId])) {
  11867. graph[importId] = graph[importId].concat(siblings);
  11868. } else {
  11869. graph[importId] = siblings.slice();
  11870. }
  11871. visited[visitedId] = VISITED_MARKER;
  11872. siblings.push(importId);
  11873. }
  11874. }
  11875. src$3.exports = (options = {}) => {
  11876. let importIndex = 0;
  11877. const createImportedName =
  11878. typeof options.createImportedName !== "function"
  11879. ? (importName /*, path*/) =>
  11880. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11881. : options.createImportedName;
  11882. const failOnWrongOrder = options.failOnWrongOrder;
  11883. return {
  11884. postcssPlugin: "postcss-modules-extract-imports",
  11885. prepare() {
  11886. const graph = {};
  11887. const visited = {};
  11888. const existingImports = {};
  11889. const importDecls = {};
  11890. const imports = {};
  11891. return {
  11892. Once(root, postcss) {
  11893. // Check the existing imports order and save refs
  11894. root.walkRules((rule) => {
  11895. const matches = icssImport.exec(rule.selector);
  11896. if (matches) {
  11897. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11898. const importPath = doubleQuotePath || singleQuotePath;
  11899. addImportToGraph(importPath, "root", graph, visited);
  11900. existingImports[importPath] = rule;
  11901. }
  11902. });
  11903. root.walkDecls(/^composes$/, (declaration) => {
  11904. const multiple = declaration.value.split(",");
  11905. const values = [];
  11906. multiple.forEach((value) => {
  11907. const matches = value.trim().match(matchImports);
  11908. if (!matches) {
  11909. values.push(value);
  11910. return;
  11911. }
  11912. let tmpSymbols;
  11913. let [
  11914. ,
  11915. /*match*/ symbols,
  11916. doubleQuotePath,
  11917. singleQuotePath,
  11918. global,
  11919. ] = matches;
  11920. if (global) {
  11921. // Composing globals simply means changing these classes to wrap them in global(name)
  11922. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  11923. } else {
  11924. const importPath = doubleQuotePath || singleQuotePath;
  11925. let parent = declaration.parent;
  11926. let parentIndexes = "";
  11927. while (parent.type !== "root") {
  11928. parentIndexes =
  11929. parent.parent.index(parent) + "_" + parentIndexes;
  11930. parent = parent.parent;
  11931. }
  11932. const { selector } = declaration.parent;
  11933. const parentRule = `_${parentIndexes}${selector}`;
  11934. addImportToGraph(importPath, parentRule, graph, visited);
  11935. importDecls[importPath] = declaration;
  11936. imports[importPath] = imports[importPath] || {};
  11937. tmpSymbols = symbols.split(/\s+/).map((s) => {
  11938. if (!imports[importPath][s]) {
  11939. imports[importPath][s] = createImportedName(s, importPath);
  11940. }
  11941. return imports[importPath][s];
  11942. });
  11943. }
  11944. values.push(tmpSymbols.join(" "));
  11945. });
  11946. declaration.value = values.join(", ");
  11947. });
  11948. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  11949. if (importsOrder instanceof Error) {
  11950. const importPath = importsOrder.nodes.find((importPath) =>
  11951. // eslint-disable-next-line no-prototype-builtins
  11952. importDecls.hasOwnProperty(importPath)
  11953. );
  11954. const decl = importDecls[importPath];
  11955. throw decl.error(
  11956. "Failed to resolve order of composed modules " +
  11957. importsOrder.nodes
  11958. .map((importPath) => "`" + importPath + "`")
  11959. .join(", ") +
  11960. ".",
  11961. {
  11962. plugin: "postcss-modules-extract-imports",
  11963. word: "composes",
  11964. }
  11965. );
  11966. }
  11967. let lastImportRule;
  11968. importsOrder.forEach((path) => {
  11969. const importedSymbols = imports[path];
  11970. let rule = existingImports[path];
  11971. if (!rule && importedSymbols) {
  11972. rule = postcss.rule({
  11973. selector: `:import("${path}")`,
  11974. raws: { after: "\n" },
  11975. });
  11976. if (lastImportRule) {
  11977. root.insertAfter(lastImportRule, rule);
  11978. } else {
  11979. root.prepend(rule);
  11980. }
  11981. }
  11982. lastImportRule = rule;
  11983. if (!importedSymbols) {
  11984. return;
  11985. }
  11986. Object.keys(importedSymbols).forEach((importedSymbol) => {
  11987. rule.append(
  11988. postcss.decl({
  11989. value: importedSymbol,
  11990. prop: importedSymbols[importedSymbol],
  11991. raws: { before: "\n " },
  11992. })
  11993. );
  11994. });
  11995. });
  11996. },
  11997. };
  11998. },
  11999. };
  12000. };
  12001. src$3.exports.postcss = true;
  12002. return src$3.exports;
  12003. }
  12004. var wasmHash = {exports: {}};
  12005. /*
  12006. MIT License http://www.opensource.org/licenses/mit-license.php
  12007. Author Tobias Koppers @sokra
  12008. */
  12009. var hasRequiredWasmHash;
  12010. function requireWasmHash () {
  12011. if (hasRequiredWasmHash) return wasmHash.exports;
  12012. hasRequiredWasmHash = 1;
  12013. // 65536 is the size of a wasm memory page
  12014. // 64 is the maximum chunk size for every possible wasm hash implementation
  12015. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12016. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12017. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
  12018. class WasmHash {
  12019. /**
  12020. * @param {WebAssembly.Instance} instance wasm instance
  12021. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12022. * @param {number} chunkSize size of data chunks passed to wasm
  12023. * @param {number} digestSize size of digest returned by wasm
  12024. */
  12025. constructor(instance, instancesPool, chunkSize, digestSize) {
  12026. const exports = /** @type {any} */ (instance.exports);
  12027. exports.init();
  12028. this.exports = exports;
  12029. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  12030. this.buffered = 0;
  12031. this.instancesPool = instancesPool;
  12032. this.chunkSize = chunkSize;
  12033. this.digestSize = digestSize;
  12034. }
  12035. reset() {
  12036. this.buffered = 0;
  12037. this.exports.init();
  12038. }
  12039. /**
  12040. * @param {Buffer | string} data data
  12041. * @param {BufferEncoding=} encoding encoding
  12042. * @returns {this} itself
  12043. */
  12044. update(data, encoding) {
  12045. if (typeof data === "string") {
  12046. while (data.length > MAX_SHORT_STRING) {
  12047. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12048. data = data.slice(MAX_SHORT_STRING);
  12049. }
  12050. this._updateWithShortString(data, encoding);
  12051. return this;
  12052. }
  12053. this._updateWithBuffer(data);
  12054. return this;
  12055. }
  12056. /**
  12057. * @param {string} data data
  12058. * @param {BufferEncoding=} encoding encoding
  12059. * @returns {void}
  12060. */
  12061. _updateWithShortString(data, encoding) {
  12062. const { exports, buffered, mem, chunkSize } = this;
  12063. let endPos;
  12064. if (data.length < 70) {
  12065. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12066. endPos = buffered;
  12067. for (let i = 0; i < data.length; i++) {
  12068. const cc = data.charCodeAt(i);
  12069. if (cc < 0x80) {
  12070. mem[endPos++] = cc;
  12071. } else if (cc < 0x800) {
  12072. mem[endPos] = (cc >> 6) | 0xc0;
  12073. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12074. endPos += 2;
  12075. } else {
  12076. // bail-out for weird chars
  12077. endPos += mem.write(data.slice(i), endPos, encoding);
  12078. break;
  12079. }
  12080. }
  12081. } else if (encoding === "latin1") {
  12082. endPos = buffered;
  12083. for (let i = 0; i < data.length; i++) {
  12084. const cc = data.charCodeAt(i);
  12085. mem[endPos++] = cc;
  12086. }
  12087. } else {
  12088. endPos = buffered + mem.write(data, buffered, encoding);
  12089. }
  12090. } else {
  12091. endPos = buffered + mem.write(data, buffered, encoding);
  12092. }
  12093. if (endPos < chunkSize) {
  12094. this.buffered = endPos;
  12095. } else {
  12096. const l = endPos & ~(this.chunkSize - 1);
  12097. exports.update(l);
  12098. const newBuffered = endPos - l;
  12099. this.buffered = newBuffered;
  12100. if (newBuffered > 0) {
  12101. mem.copyWithin(0, l, endPos);
  12102. }
  12103. }
  12104. }
  12105. /**
  12106. * @param {Buffer} data data
  12107. * @returns {void}
  12108. */
  12109. _updateWithBuffer(data) {
  12110. const { exports, buffered, mem } = this;
  12111. const length = data.length;
  12112. if (buffered + length < this.chunkSize) {
  12113. data.copy(mem, buffered, 0, length);
  12114. this.buffered += length;
  12115. } else {
  12116. const l = (buffered + length) & ~(this.chunkSize - 1);
  12117. if (l > 65536) {
  12118. let i = 65536 - buffered;
  12119. data.copy(mem, buffered, 0, i);
  12120. exports.update(65536);
  12121. const stop = l - buffered - 65536;
  12122. while (i < stop) {
  12123. data.copy(mem, 0, i, i + 65536);
  12124. exports.update(65536);
  12125. i += 65536;
  12126. }
  12127. data.copy(mem, 0, i, l - buffered);
  12128. exports.update(l - buffered - i);
  12129. } else {
  12130. data.copy(mem, buffered, 0, l - buffered);
  12131. exports.update(l);
  12132. }
  12133. const newBuffered = length + buffered - l;
  12134. this.buffered = newBuffered;
  12135. if (newBuffered > 0) {
  12136. data.copy(mem, 0, length - newBuffered, length);
  12137. }
  12138. }
  12139. }
  12140. digest(type) {
  12141. const { exports, buffered, mem, digestSize } = this;
  12142. exports.final(buffered);
  12143. this.instancesPool.push(this);
  12144. const hex = mem.toString("latin1", 0, digestSize);
  12145. if (type === "hex") {
  12146. return hex;
  12147. }
  12148. if (type === "binary" || !type) {
  12149. return Buffer.from(hex, "hex");
  12150. }
  12151. return Buffer.from(hex, "hex").toString(type);
  12152. }
  12153. }
  12154. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12155. if (instancesPool.length > 0) {
  12156. const old = instancesPool.pop();
  12157. old.reset();
  12158. return old;
  12159. } else {
  12160. return new WasmHash(
  12161. new WebAssembly.Instance(wasmModule),
  12162. instancesPool,
  12163. chunkSize,
  12164. digestSize
  12165. );
  12166. }
  12167. };
  12168. wasmHash.exports = create;
  12169. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12170. return wasmHash.exports;
  12171. }
  12172. /*
  12173. MIT License http://www.opensource.org/licenses/mit-license.php
  12174. Author Tobias Koppers @sokra
  12175. */
  12176. var xxhash64_1;
  12177. var hasRequiredXxhash64;
  12178. function requireXxhash64 () {
  12179. if (hasRequiredXxhash64) return xxhash64_1;
  12180. hasRequiredXxhash64 = 1;
  12181. const create = /*@__PURE__*/ requireWasmHash();
  12182. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12183. const xxhash64 = new WebAssembly.Module(
  12184. Buffer.from(
  12185. // 1173 bytes
  12186. "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",
  12187. "base64"
  12188. )
  12189. );
  12190. //#endregion
  12191. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12192. return xxhash64_1;
  12193. }
  12194. var BatchedHash_1;
  12195. var hasRequiredBatchedHash;
  12196. function requireBatchedHash () {
  12197. if (hasRequiredBatchedHash) return BatchedHash_1;
  12198. hasRequiredBatchedHash = 1;
  12199. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12200. class BatchedHash {
  12201. constructor(hash) {
  12202. this.string = undefined;
  12203. this.encoding = undefined;
  12204. this.hash = hash;
  12205. }
  12206. /**
  12207. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12208. * @param {string|Buffer} data data
  12209. * @param {string=} inputEncoding data encoding
  12210. * @returns {this} updated hash
  12211. */
  12212. update(data, inputEncoding) {
  12213. if (this.string !== undefined) {
  12214. if (
  12215. typeof data === "string" &&
  12216. inputEncoding === this.encoding &&
  12217. this.string.length + data.length < MAX_SHORT_STRING
  12218. ) {
  12219. this.string += data;
  12220. return this;
  12221. }
  12222. this.hash.update(this.string, this.encoding);
  12223. this.string = undefined;
  12224. }
  12225. if (typeof data === "string") {
  12226. if (
  12227. data.length < MAX_SHORT_STRING &&
  12228. // base64 encoding is not valid since it may contain padding chars
  12229. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12230. ) {
  12231. this.string = data;
  12232. this.encoding = inputEncoding;
  12233. } else {
  12234. this.hash.update(data, inputEncoding);
  12235. }
  12236. } else {
  12237. this.hash.update(data);
  12238. }
  12239. return this;
  12240. }
  12241. /**
  12242. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12243. * @param {string=} encoding encoding of the return value
  12244. * @returns {string|Buffer} digest
  12245. */
  12246. digest(encoding) {
  12247. if (this.string !== undefined) {
  12248. this.hash.update(this.string, this.encoding);
  12249. }
  12250. return this.hash.digest(encoding);
  12251. }
  12252. }
  12253. BatchedHash_1 = BatchedHash;
  12254. return BatchedHash_1;
  12255. }
  12256. /*
  12257. MIT License http://www.opensource.org/licenses/mit-license.php
  12258. Author Tobias Koppers @sokra
  12259. */
  12260. var md4_1;
  12261. var hasRequiredMd4;
  12262. function requireMd4 () {
  12263. if (hasRequiredMd4) return md4_1;
  12264. hasRequiredMd4 = 1;
  12265. const create = /*@__PURE__*/ requireWasmHash();
  12266. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12267. const md4 = new WebAssembly.Module(
  12268. Buffer.from(
  12269. // 2150 bytes
  12270. "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=",
  12271. "base64"
  12272. )
  12273. );
  12274. //#endregion
  12275. md4_1 = create.bind(null, md4, [], 64, 32);
  12276. return md4_1;
  12277. }
  12278. var BulkUpdateDecorator_1;
  12279. var hasRequiredBulkUpdateDecorator;
  12280. function requireBulkUpdateDecorator () {
  12281. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12282. hasRequiredBulkUpdateDecorator = 1;
  12283. const BULK_SIZE = 2000;
  12284. // We are using an object instead of a Map as this will stay static during the runtime
  12285. // so access to it can be optimized by v8
  12286. const digestCaches = {};
  12287. class BulkUpdateDecorator {
  12288. /**
  12289. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12290. * @param {string=} hashKey key for caching
  12291. */
  12292. constructor(hashOrFactory, hashKey) {
  12293. this.hashKey = hashKey;
  12294. if (typeof hashOrFactory === "function") {
  12295. this.hashFactory = hashOrFactory;
  12296. this.hash = undefined;
  12297. } else {
  12298. this.hashFactory = undefined;
  12299. this.hash = hashOrFactory;
  12300. }
  12301. this.buffer = "";
  12302. }
  12303. /**
  12304. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12305. * @param {string|Buffer} data data
  12306. * @param {string=} inputEncoding data encoding
  12307. * @returns {this} updated hash
  12308. */
  12309. update(data, inputEncoding) {
  12310. if (
  12311. inputEncoding !== undefined ||
  12312. typeof data !== "string" ||
  12313. data.length > BULK_SIZE
  12314. ) {
  12315. if (this.hash === undefined) {
  12316. this.hash = this.hashFactory();
  12317. }
  12318. if (this.buffer.length > 0) {
  12319. this.hash.update(this.buffer);
  12320. this.buffer = "";
  12321. }
  12322. this.hash.update(data, inputEncoding);
  12323. } else {
  12324. this.buffer += data;
  12325. if (this.buffer.length > BULK_SIZE) {
  12326. if (this.hash === undefined) {
  12327. this.hash = this.hashFactory();
  12328. }
  12329. this.hash.update(this.buffer);
  12330. this.buffer = "";
  12331. }
  12332. }
  12333. return this;
  12334. }
  12335. /**
  12336. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12337. * @param {string=} encoding encoding of the return value
  12338. * @returns {string|Buffer} digest
  12339. */
  12340. digest(encoding) {
  12341. let digestCache;
  12342. const buffer = this.buffer;
  12343. if (this.hash === undefined) {
  12344. // short data for hash, we can use caching
  12345. const cacheKey = `${this.hashKey}-${encoding}`;
  12346. digestCache = digestCaches[cacheKey];
  12347. if (digestCache === undefined) {
  12348. digestCache = digestCaches[cacheKey] = new Map();
  12349. }
  12350. const cacheEntry = digestCache.get(buffer);
  12351. if (cacheEntry !== undefined) {
  12352. return cacheEntry;
  12353. }
  12354. this.hash = this.hashFactory();
  12355. }
  12356. if (buffer.length > 0) {
  12357. this.hash.update(buffer);
  12358. }
  12359. const digestResult = this.hash.digest(encoding);
  12360. if (digestCache !== undefined) {
  12361. digestCache.set(buffer, digestResult);
  12362. }
  12363. return digestResult;
  12364. }
  12365. }
  12366. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12367. return BulkUpdateDecorator_1;
  12368. }
  12369. var getHashDigest_1;
  12370. var hasRequiredGetHashDigest;
  12371. function requireGetHashDigest () {
  12372. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12373. hasRequiredGetHashDigest = 1;
  12374. const baseEncodeTables = {
  12375. 26: "abcdefghijklmnopqrstuvwxyz",
  12376. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12377. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12378. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12379. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12380. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12381. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12382. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12383. };
  12384. /**
  12385. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12386. * @param {number} divisor The divisor
  12387. * @return {number} Modulo (remainder) of the division
  12388. */
  12389. function divmod32(uint32Array, divisor) {
  12390. let carry = 0;
  12391. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12392. const value = carry * 0x100000000 + uint32Array[i];
  12393. carry = value % divisor;
  12394. uint32Array[i] = Math.floor(value / divisor);
  12395. }
  12396. return carry;
  12397. }
  12398. function encodeBufferToBase(buffer, base, length) {
  12399. const encodeTable = baseEncodeTables[base];
  12400. if (!encodeTable) {
  12401. throw new Error("Unknown encoding base" + base);
  12402. }
  12403. // Input bits are only enough to generate this many characters
  12404. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12405. length = Math.min(length, limit);
  12406. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12407. // Fewer numbers in the array means faster math.
  12408. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12409. // Make sure the input buffer data is copied and is not mutated by reference.
  12410. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12411. buffer.copy(Buffer.from(uint32Array.buffer));
  12412. let output = "";
  12413. for (let i = 0; i < length; i++) {
  12414. output = encodeTable[divmod32(uint32Array, base)] + output;
  12415. }
  12416. return output;
  12417. }
  12418. let crypto = undefined;
  12419. let createXXHash64 = undefined;
  12420. let createMd4 = undefined;
  12421. let BatchedHash = undefined;
  12422. let BulkUpdateDecorator = undefined;
  12423. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12424. algorithm = algorithm || "xxhash64";
  12425. maxLength = maxLength || 9999;
  12426. let hash;
  12427. if (algorithm === "xxhash64") {
  12428. if (createXXHash64 === undefined) {
  12429. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12430. if (BatchedHash === undefined) {
  12431. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12432. }
  12433. }
  12434. hash = new BatchedHash(createXXHash64());
  12435. } else if (algorithm === "md4") {
  12436. if (createMd4 === undefined) {
  12437. createMd4 = /*@__PURE__*/ requireMd4();
  12438. if (BatchedHash === undefined) {
  12439. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12440. }
  12441. }
  12442. hash = new BatchedHash(createMd4());
  12443. } else if (algorithm === "native-md4") {
  12444. if (typeof crypto === "undefined") {
  12445. crypto = require("crypto");
  12446. if (BulkUpdateDecorator === undefined) {
  12447. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12448. }
  12449. }
  12450. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12451. } else {
  12452. if (typeof crypto === "undefined") {
  12453. crypto = require("crypto");
  12454. if (BulkUpdateDecorator === undefined) {
  12455. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12456. }
  12457. }
  12458. hash = new BulkUpdateDecorator(
  12459. () => crypto.createHash(algorithm),
  12460. algorithm
  12461. );
  12462. }
  12463. hash.update(buffer);
  12464. if (
  12465. digestType === "base26" ||
  12466. digestType === "base32" ||
  12467. digestType === "base36" ||
  12468. digestType === "base49" ||
  12469. digestType === "base52" ||
  12470. digestType === "base58" ||
  12471. digestType === "base62" ||
  12472. digestType === "base64safe"
  12473. ) {
  12474. return encodeBufferToBase(
  12475. hash.digest(),
  12476. digestType === "base64safe" ? 64 : digestType.substr(4),
  12477. maxLength
  12478. );
  12479. }
  12480. return hash.digest(digestType || "hex").substr(0, maxLength);
  12481. }
  12482. getHashDigest_1 = getHashDigest;
  12483. return getHashDigest_1;
  12484. }
  12485. var interpolateName_1;
  12486. var hasRequiredInterpolateName;
  12487. function requireInterpolateName () {
  12488. if (hasRequiredInterpolateName) return interpolateName_1;
  12489. hasRequiredInterpolateName = 1;
  12490. const path = path$1;
  12491. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12492. function interpolateName(loaderContext, name, options = {}) {
  12493. let filename;
  12494. const hasQuery =
  12495. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12496. if (typeof name === "function") {
  12497. filename = name(
  12498. loaderContext.resourcePath,
  12499. hasQuery ? loaderContext.resourceQuery : undefined
  12500. );
  12501. } else {
  12502. filename = name || "[hash].[ext]";
  12503. }
  12504. const context = options.context;
  12505. const content = options.content;
  12506. const regExp = options.regExp;
  12507. let ext = "bin";
  12508. let basename = "file";
  12509. let directory = "";
  12510. let folder = "";
  12511. let query = "";
  12512. if (loaderContext.resourcePath) {
  12513. const parsed = path.parse(loaderContext.resourcePath);
  12514. let resourcePath = loaderContext.resourcePath;
  12515. if (parsed.ext) {
  12516. ext = parsed.ext.substr(1);
  12517. }
  12518. if (parsed.dir) {
  12519. basename = parsed.name;
  12520. resourcePath = parsed.dir + path.sep;
  12521. }
  12522. if (typeof context !== "undefined") {
  12523. directory = path
  12524. .relative(context, resourcePath + "_")
  12525. .replace(/\\/g, "/")
  12526. .replace(/\.\.(\/)?/g, "_$1");
  12527. directory = directory.substr(0, directory.length - 1);
  12528. } else {
  12529. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12530. }
  12531. if (directory.length <= 1) {
  12532. directory = "";
  12533. } else {
  12534. // directory.length > 1
  12535. folder = path.basename(directory);
  12536. }
  12537. }
  12538. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12539. query = loaderContext.resourceQuery;
  12540. const hashIdx = query.indexOf("#");
  12541. if (hashIdx >= 0) {
  12542. query = query.substr(0, hashIdx);
  12543. }
  12544. }
  12545. let url = filename;
  12546. if (content) {
  12547. // Match hash template
  12548. url = url
  12549. // `hash` and `contenthash` are same in `loader-utils` context
  12550. // let's keep `hash` for backward compatibility
  12551. .replace(
  12552. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12553. (all, hashType, digestType, maxLength) =>
  12554. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12555. );
  12556. }
  12557. url = url
  12558. .replace(/\[ext\]/gi, () => ext)
  12559. .replace(/\[name\]/gi, () => basename)
  12560. .replace(/\[path\]/gi, () => directory)
  12561. .replace(/\[folder\]/gi, () => folder)
  12562. .replace(/\[query\]/gi, () => query);
  12563. if (regExp && loaderContext.resourcePath) {
  12564. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12565. match &&
  12566. match.forEach((matched, i) => {
  12567. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12568. });
  12569. }
  12570. if (
  12571. typeof loaderContext.options === "object" &&
  12572. typeof loaderContext.options.customInterpolateName === "function"
  12573. ) {
  12574. url = loaderContext.options.customInterpolateName.call(
  12575. loaderContext,
  12576. url,
  12577. name,
  12578. options
  12579. );
  12580. }
  12581. return url;
  12582. }
  12583. interpolateName_1 = interpolateName;
  12584. return interpolateName_1;
  12585. }
  12586. var genericNames;
  12587. var hasRequiredGenericNames;
  12588. function requireGenericNames () {
  12589. if (hasRequiredGenericNames) return genericNames;
  12590. hasRequiredGenericNames = 1;
  12591. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12592. var path = path$1;
  12593. /**
  12594. * @param {string} pattern
  12595. * @param {object} options
  12596. * @param {string} options.context
  12597. * @param {string} options.hashPrefix
  12598. * @return {function}
  12599. */
  12600. genericNames = function createGenerator(pattern, options) {
  12601. options = options || {};
  12602. var context =
  12603. options && typeof options.context === "string"
  12604. ? options.context
  12605. : process.cwd();
  12606. var hashPrefix =
  12607. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12608. /**
  12609. * @param {string} localName Usually a class name
  12610. * @param {string} filepath Absolute path
  12611. * @return {string}
  12612. */
  12613. return function generate(localName, filepath) {
  12614. var name = pattern.replace(/\[local\]/gi, localName);
  12615. var loaderContext = {
  12616. resourcePath: filepath,
  12617. };
  12618. var loaderOptions = {
  12619. content:
  12620. hashPrefix +
  12621. path.relative(context, filepath).replace(/\\/g, "/") +
  12622. "\x00" +
  12623. localName,
  12624. context: context,
  12625. };
  12626. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12627. return genericName
  12628. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12629. .replace(/^((-?[0-9])|--)/, "_$1");
  12630. };
  12631. };
  12632. return genericNames;
  12633. }
  12634. var src$2 = {exports: {}};
  12635. var dist = {exports: {}};
  12636. var processor = {exports: {}};
  12637. var parser = {exports: {}};
  12638. var root = {exports: {}};
  12639. var container = {exports: {}};
  12640. var node = {exports: {}};
  12641. var util = {};
  12642. var unesc = {exports: {}};
  12643. var hasRequiredUnesc;
  12644. function requireUnesc () {
  12645. if (hasRequiredUnesc) return unesc.exports;
  12646. hasRequiredUnesc = 1;
  12647. (function (module, exports) {
  12648. exports.__esModule = true;
  12649. exports["default"] = unesc;
  12650. // Many thanks for this post which made this migration much easier.
  12651. // https://mathiasbynens.be/notes/css-escapes
  12652. /**
  12653. *
  12654. * @param {string} str
  12655. * @returns {[string, number]|undefined}
  12656. */
  12657. function gobbleHex(str) {
  12658. var lower = str.toLowerCase();
  12659. var hex = '';
  12660. var spaceTerminated = false;
  12661. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  12662. var code = lower.charCodeAt(i);
  12663. // check to see if we are dealing with a valid hex char [a-f|0-9]
  12664. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  12665. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  12666. spaceTerminated = code === 32;
  12667. if (!valid) {
  12668. break;
  12669. }
  12670. hex += lower[i];
  12671. }
  12672. if (hex.length === 0) {
  12673. return undefined;
  12674. }
  12675. var codePoint = parseInt(hex, 16);
  12676. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  12677. // Add special case for
  12678. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  12679. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  12680. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  12681. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  12682. }
  12683. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  12684. }
  12685. var CONTAINS_ESCAPE = /\\/;
  12686. function unesc(str) {
  12687. var needToProcess = CONTAINS_ESCAPE.test(str);
  12688. if (!needToProcess) {
  12689. return str;
  12690. }
  12691. var ret = "";
  12692. for (var i = 0; i < str.length; i++) {
  12693. if (str[i] === "\\") {
  12694. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  12695. if (gobbled !== undefined) {
  12696. ret += gobbled[0];
  12697. i += gobbled[1];
  12698. continue;
  12699. }
  12700. // Retain a pair of \\ if double escaped `\\\\`
  12701. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  12702. if (str[i + 1] === "\\") {
  12703. ret += "\\";
  12704. i++;
  12705. continue;
  12706. }
  12707. // if \\ is at the end of the string retain it
  12708. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  12709. if (str.length === i + 1) {
  12710. ret += str[i];
  12711. }
  12712. continue;
  12713. }
  12714. ret += str[i];
  12715. }
  12716. return ret;
  12717. }
  12718. module.exports = exports.default;
  12719. } (unesc, unesc.exports));
  12720. return unesc.exports;
  12721. }
  12722. var getProp = {exports: {}};
  12723. var hasRequiredGetProp;
  12724. function requireGetProp () {
  12725. if (hasRequiredGetProp) return getProp.exports;
  12726. hasRequiredGetProp = 1;
  12727. (function (module, exports) {
  12728. exports.__esModule = true;
  12729. exports["default"] = getProp;
  12730. function getProp(obj) {
  12731. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12732. props[_key - 1] = arguments[_key];
  12733. }
  12734. while (props.length > 0) {
  12735. var prop = props.shift();
  12736. if (!obj[prop]) {
  12737. return undefined;
  12738. }
  12739. obj = obj[prop];
  12740. }
  12741. return obj;
  12742. }
  12743. module.exports = exports.default;
  12744. } (getProp, getProp.exports));
  12745. return getProp.exports;
  12746. }
  12747. var ensureObject = {exports: {}};
  12748. var hasRequiredEnsureObject;
  12749. function requireEnsureObject () {
  12750. if (hasRequiredEnsureObject) return ensureObject.exports;
  12751. hasRequiredEnsureObject = 1;
  12752. (function (module, exports) {
  12753. exports.__esModule = true;
  12754. exports["default"] = ensureObject;
  12755. function ensureObject(obj) {
  12756. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12757. props[_key - 1] = arguments[_key];
  12758. }
  12759. while (props.length > 0) {
  12760. var prop = props.shift();
  12761. if (!obj[prop]) {
  12762. obj[prop] = {};
  12763. }
  12764. obj = obj[prop];
  12765. }
  12766. }
  12767. module.exports = exports.default;
  12768. } (ensureObject, ensureObject.exports));
  12769. return ensureObject.exports;
  12770. }
  12771. var stripComments = {exports: {}};
  12772. var hasRequiredStripComments;
  12773. function requireStripComments () {
  12774. if (hasRequiredStripComments) return stripComments.exports;
  12775. hasRequiredStripComments = 1;
  12776. (function (module, exports) {
  12777. exports.__esModule = true;
  12778. exports["default"] = stripComments;
  12779. function stripComments(str) {
  12780. var s = "";
  12781. var commentStart = str.indexOf("/*");
  12782. var lastEnd = 0;
  12783. while (commentStart >= 0) {
  12784. s = s + str.slice(lastEnd, commentStart);
  12785. var commentEnd = str.indexOf("*/", commentStart + 2);
  12786. if (commentEnd < 0) {
  12787. return s;
  12788. }
  12789. lastEnd = commentEnd + 2;
  12790. commentStart = str.indexOf("/*", lastEnd);
  12791. }
  12792. s = s + str.slice(lastEnd);
  12793. return s;
  12794. }
  12795. module.exports = exports.default;
  12796. } (stripComments, stripComments.exports));
  12797. return stripComments.exports;
  12798. }
  12799. var hasRequiredUtil;
  12800. function requireUtil () {
  12801. if (hasRequiredUtil) return util;
  12802. hasRequiredUtil = 1;
  12803. util.__esModule = true;
  12804. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  12805. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  12806. util.unesc = _unesc["default"];
  12807. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  12808. util.getProp = _getProp["default"];
  12809. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  12810. util.ensureObject = _ensureObject["default"];
  12811. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  12812. util.stripComments = _stripComments["default"];
  12813. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  12814. return util;
  12815. }
  12816. var hasRequiredNode;
  12817. function requireNode () {
  12818. if (hasRequiredNode) return node.exports;
  12819. hasRequiredNode = 1;
  12820. (function (module, exports) {
  12821. exports.__esModule = true;
  12822. exports["default"] = void 0;
  12823. var _util = /*@__PURE__*/ requireUtil();
  12824. 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); } }
  12825. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12826. var cloneNode = function cloneNode(obj, parent) {
  12827. if (typeof obj !== 'object' || obj === null) {
  12828. return obj;
  12829. }
  12830. var cloned = new obj.constructor();
  12831. for (var i in obj) {
  12832. if (!obj.hasOwnProperty(i)) {
  12833. continue;
  12834. }
  12835. var value = obj[i];
  12836. var type = typeof value;
  12837. if (i === 'parent' && type === 'object') {
  12838. if (parent) {
  12839. cloned[i] = parent;
  12840. }
  12841. } else if (value instanceof Array) {
  12842. cloned[i] = value.map(function (j) {
  12843. return cloneNode(j, cloned);
  12844. });
  12845. } else {
  12846. cloned[i] = cloneNode(value, cloned);
  12847. }
  12848. }
  12849. return cloned;
  12850. };
  12851. var Node = /*#__PURE__*/function () {
  12852. function Node(opts) {
  12853. if (opts === void 0) {
  12854. opts = {};
  12855. }
  12856. Object.assign(this, opts);
  12857. this.spaces = this.spaces || {};
  12858. this.spaces.before = this.spaces.before || '';
  12859. this.spaces.after = this.spaces.after || '';
  12860. }
  12861. var _proto = Node.prototype;
  12862. _proto.remove = function remove() {
  12863. if (this.parent) {
  12864. this.parent.removeChild(this);
  12865. }
  12866. this.parent = undefined;
  12867. return this;
  12868. };
  12869. _proto.replaceWith = function replaceWith() {
  12870. if (this.parent) {
  12871. for (var index in arguments) {
  12872. this.parent.insertBefore(this, arguments[index]);
  12873. }
  12874. this.remove();
  12875. }
  12876. return this;
  12877. };
  12878. _proto.next = function next() {
  12879. return this.parent.at(this.parent.index(this) + 1);
  12880. };
  12881. _proto.prev = function prev() {
  12882. return this.parent.at(this.parent.index(this) - 1);
  12883. };
  12884. _proto.clone = function clone(overrides) {
  12885. if (overrides === void 0) {
  12886. overrides = {};
  12887. }
  12888. var cloned = cloneNode(this);
  12889. for (var name in overrides) {
  12890. cloned[name] = overrides[name];
  12891. }
  12892. return cloned;
  12893. }
  12894. /**
  12895. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12896. * This allows non standard syntax to be appended to an existing property
  12897. * by specifying the escaped value. By specifying the escaped value,
  12898. * illegal characters are allowed to be directly inserted into css output.
  12899. * @param {string} name the property to set
  12900. * @param {any} value the unescaped value of the property
  12901. * @param {string} valueEscaped optional. the escaped value of the property.
  12902. */;
  12903. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  12904. if (!this.raws) {
  12905. this.raws = {};
  12906. }
  12907. var originalValue = this[name];
  12908. var originalEscaped = this.raws[name];
  12909. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  12910. if (originalEscaped || valueEscaped !== value) {
  12911. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  12912. } else {
  12913. delete this.raws[name]; // delete any escaped value that was created by the setter.
  12914. }
  12915. }
  12916. /**
  12917. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12918. * This allows the escaped value to be specified directly, allowing illegal
  12919. * characters to be directly inserted into css output.
  12920. * @param {string} name the property to set
  12921. * @param {any} value the unescaped value of the property
  12922. * @param {string} valueEscaped the escaped value of the property.
  12923. */;
  12924. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  12925. if (!this.raws) {
  12926. this.raws = {};
  12927. }
  12928. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  12929. this.raws[name] = valueEscaped;
  12930. }
  12931. /**
  12932. * When you want a value to passed through to CSS directly. This method
  12933. * deletes the corresponding raw value causing the stringifier to fallback
  12934. * to the unescaped value.
  12935. * @param {string} name the property to set.
  12936. * @param {any} value The value that is both escaped and unescaped.
  12937. */;
  12938. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  12939. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  12940. if (this.raws) {
  12941. delete this.raws[name];
  12942. }
  12943. }
  12944. /**
  12945. *
  12946. * @param {number} line The number (starting with 1)
  12947. * @param {number} column The column number (starting with 1)
  12948. */;
  12949. _proto.isAtPosition = function isAtPosition(line, column) {
  12950. if (this.source && this.source.start && this.source.end) {
  12951. if (this.source.start.line > line) {
  12952. return false;
  12953. }
  12954. if (this.source.end.line < line) {
  12955. return false;
  12956. }
  12957. if (this.source.start.line === line && this.source.start.column > column) {
  12958. return false;
  12959. }
  12960. if (this.source.end.line === line && this.source.end.column < column) {
  12961. return false;
  12962. }
  12963. return true;
  12964. }
  12965. return undefined;
  12966. };
  12967. _proto.stringifyProperty = function stringifyProperty(name) {
  12968. return this.raws && this.raws[name] || this[name];
  12969. };
  12970. _proto.valueToString = function valueToString() {
  12971. return String(this.stringifyProperty("value"));
  12972. };
  12973. _proto.toString = function toString() {
  12974. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  12975. };
  12976. _createClass(Node, [{
  12977. key: "rawSpaceBefore",
  12978. get: function get() {
  12979. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  12980. if (rawSpace === undefined) {
  12981. rawSpace = this.spaces && this.spaces.before;
  12982. }
  12983. return rawSpace || "";
  12984. },
  12985. set: function set(raw) {
  12986. (0, _util.ensureObject)(this, "raws", "spaces");
  12987. this.raws.spaces.before = raw;
  12988. }
  12989. }, {
  12990. key: "rawSpaceAfter",
  12991. get: function get() {
  12992. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  12993. if (rawSpace === undefined) {
  12994. rawSpace = this.spaces.after;
  12995. }
  12996. return rawSpace || "";
  12997. },
  12998. set: function set(raw) {
  12999. (0, _util.ensureObject)(this, "raws", "spaces");
  13000. this.raws.spaces.after = raw;
  13001. }
  13002. }]);
  13003. return Node;
  13004. }();
  13005. exports["default"] = Node;
  13006. module.exports = exports.default;
  13007. } (node, node.exports));
  13008. return node.exports;
  13009. }
  13010. var types$1 = {};
  13011. var hasRequiredTypes;
  13012. function requireTypes () {
  13013. if (hasRequiredTypes) return types$1;
  13014. hasRequiredTypes = 1;
  13015. types$1.__esModule = true;
  13016. 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;
  13017. var TAG = 'tag';
  13018. types$1.TAG = TAG;
  13019. var STRING = 'string';
  13020. types$1.STRING = STRING;
  13021. var SELECTOR = 'selector';
  13022. types$1.SELECTOR = SELECTOR;
  13023. var ROOT = 'root';
  13024. types$1.ROOT = ROOT;
  13025. var PSEUDO = 'pseudo';
  13026. types$1.PSEUDO = PSEUDO;
  13027. var NESTING = 'nesting';
  13028. types$1.NESTING = NESTING;
  13029. var ID = 'id';
  13030. types$1.ID = ID;
  13031. var COMMENT = 'comment';
  13032. types$1.COMMENT = COMMENT;
  13033. var COMBINATOR = 'combinator';
  13034. types$1.COMBINATOR = COMBINATOR;
  13035. var CLASS = 'class';
  13036. types$1.CLASS = CLASS;
  13037. var ATTRIBUTE = 'attribute';
  13038. types$1.ATTRIBUTE = ATTRIBUTE;
  13039. var UNIVERSAL = 'universal';
  13040. types$1.UNIVERSAL = UNIVERSAL;
  13041. return types$1;
  13042. }
  13043. var hasRequiredContainer;
  13044. function requireContainer () {
  13045. if (hasRequiredContainer) return container.exports;
  13046. hasRequiredContainer = 1;
  13047. (function (module, exports) {
  13048. exports.__esModule = true;
  13049. exports["default"] = void 0;
  13050. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13051. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13052. 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); }
  13053. 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; }
  13054. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13055. 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."); }
  13056. 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); }
  13057. 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; }
  13058. 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); } }
  13059. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13060. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13061. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13062. var Container = /*#__PURE__*/function (_Node) {
  13063. _inheritsLoose(Container, _Node);
  13064. function Container(opts) {
  13065. var _this;
  13066. _this = _Node.call(this, opts) || this;
  13067. if (!_this.nodes) {
  13068. _this.nodes = [];
  13069. }
  13070. return _this;
  13071. }
  13072. var _proto = Container.prototype;
  13073. _proto.append = function append(selector) {
  13074. selector.parent = this;
  13075. this.nodes.push(selector);
  13076. return this;
  13077. };
  13078. _proto.prepend = function prepend(selector) {
  13079. selector.parent = this;
  13080. this.nodes.unshift(selector);
  13081. return this;
  13082. };
  13083. _proto.at = function at(index) {
  13084. return this.nodes[index];
  13085. };
  13086. _proto.index = function index(child) {
  13087. if (typeof child === 'number') {
  13088. return child;
  13089. }
  13090. return this.nodes.indexOf(child);
  13091. };
  13092. _proto.removeChild = function removeChild(child) {
  13093. child = this.index(child);
  13094. this.at(child).parent = undefined;
  13095. this.nodes.splice(child, 1);
  13096. var index;
  13097. for (var id in this.indexes) {
  13098. index = this.indexes[id];
  13099. if (index >= child) {
  13100. this.indexes[id] = index - 1;
  13101. }
  13102. }
  13103. return this;
  13104. };
  13105. _proto.removeAll = function removeAll() {
  13106. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13107. var node = _step.value;
  13108. node.parent = undefined;
  13109. }
  13110. this.nodes = [];
  13111. return this;
  13112. };
  13113. _proto.empty = function empty() {
  13114. return this.removeAll();
  13115. };
  13116. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13117. newNode.parent = this;
  13118. var oldIndex = this.index(oldNode);
  13119. this.nodes.splice(oldIndex + 1, 0, newNode);
  13120. newNode.parent = this;
  13121. var index;
  13122. for (var id in this.indexes) {
  13123. index = this.indexes[id];
  13124. if (oldIndex <= index) {
  13125. this.indexes[id] = index + 1;
  13126. }
  13127. }
  13128. return this;
  13129. };
  13130. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13131. newNode.parent = this;
  13132. var oldIndex = this.index(oldNode);
  13133. this.nodes.splice(oldIndex, 0, newNode);
  13134. newNode.parent = this;
  13135. var index;
  13136. for (var id in this.indexes) {
  13137. index = this.indexes[id];
  13138. if (index <= oldIndex) {
  13139. this.indexes[id] = index + 1;
  13140. }
  13141. }
  13142. return this;
  13143. };
  13144. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13145. var found = undefined;
  13146. this.each(function (node) {
  13147. if (node.atPosition) {
  13148. var foundChild = node.atPosition(line, col);
  13149. if (foundChild) {
  13150. found = foundChild;
  13151. return false;
  13152. }
  13153. } else if (node.isAtPosition(line, col)) {
  13154. found = node;
  13155. return false;
  13156. }
  13157. });
  13158. return found;
  13159. }
  13160. /**
  13161. * Return the most specific node at the line and column number given.
  13162. * The source location is based on the original parsed location, locations aren't
  13163. * updated as selector nodes are mutated.
  13164. *
  13165. * Note that this location is relative to the location of the first character
  13166. * of the selector, and not the location of the selector in the overall document
  13167. * when used in conjunction with postcss.
  13168. *
  13169. * If not found, returns undefined.
  13170. * @param {number} line The line number of the node to find. (1-based index)
  13171. * @param {number} col The column number of the node to find. (1-based index)
  13172. */;
  13173. _proto.atPosition = function atPosition(line, col) {
  13174. if (this.isAtPosition(line, col)) {
  13175. return this._findChildAtPosition(line, col) || this;
  13176. } else {
  13177. return undefined;
  13178. }
  13179. };
  13180. _proto._inferEndPosition = function _inferEndPosition() {
  13181. if (this.last && this.last.source && this.last.source.end) {
  13182. this.source = this.source || {};
  13183. this.source.end = this.source.end || {};
  13184. Object.assign(this.source.end, this.last.source.end);
  13185. }
  13186. };
  13187. _proto.each = function each(callback) {
  13188. if (!this.lastEach) {
  13189. this.lastEach = 0;
  13190. }
  13191. if (!this.indexes) {
  13192. this.indexes = {};
  13193. }
  13194. this.lastEach++;
  13195. var id = this.lastEach;
  13196. this.indexes[id] = 0;
  13197. if (!this.length) {
  13198. return undefined;
  13199. }
  13200. var index, result;
  13201. while (this.indexes[id] < this.length) {
  13202. index = this.indexes[id];
  13203. result = callback(this.at(index), index);
  13204. if (result === false) {
  13205. break;
  13206. }
  13207. this.indexes[id] += 1;
  13208. }
  13209. delete this.indexes[id];
  13210. if (result === false) {
  13211. return false;
  13212. }
  13213. };
  13214. _proto.walk = function walk(callback) {
  13215. return this.each(function (node, i) {
  13216. var result = callback(node, i);
  13217. if (result !== false && node.length) {
  13218. result = node.walk(callback);
  13219. }
  13220. if (result === false) {
  13221. return false;
  13222. }
  13223. });
  13224. };
  13225. _proto.walkAttributes = function walkAttributes(callback) {
  13226. var _this2 = this;
  13227. return this.walk(function (selector) {
  13228. if (selector.type === types.ATTRIBUTE) {
  13229. return callback.call(_this2, selector);
  13230. }
  13231. });
  13232. };
  13233. _proto.walkClasses = function walkClasses(callback) {
  13234. var _this3 = this;
  13235. return this.walk(function (selector) {
  13236. if (selector.type === types.CLASS) {
  13237. return callback.call(_this3, selector);
  13238. }
  13239. });
  13240. };
  13241. _proto.walkCombinators = function walkCombinators(callback) {
  13242. var _this4 = this;
  13243. return this.walk(function (selector) {
  13244. if (selector.type === types.COMBINATOR) {
  13245. return callback.call(_this4, selector);
  13246. }
  13247. });
  13248. };
  13249. _proto.walkComments = function walkComments(callback) {
  13250. var _this5 = this;
  13251. return this.walk(function (selector) {
  13252. if (selector.type === types.COMMENT) {
  13253. return callback.call(_this5, selector);
  13254. }
  13255. });
  13256. };
  13257. _proto.walkIds = function walkIds(callback) {
  13258. var _this6 = this;
  13259. return this.walk(function (selector) {
  13260. if (selector.type === types.ID) {
  13261. return callback.call(_this6, selector);
  13262. }
  13263. });
  13264. };
  13265. _proto.walkNesting = function walkNesting(callback) {
  13266. var _this7 = this;
  13267. return this.walk(function (selector) {
  13268. if (selector.type === types.NESTING) {
  13269. return callback.call(_this7, selector);
  13270. }
  13271. });
  13272. };
  13273. _proto.walkPseudos = function walkPseudos(callback) {
  13274. var _this8 = this;
  13275. return this.walk(function (selector) {
  13276. if (selector.type === types.PSEUDO) {
  13277. return callback.call(_this8, selector);
  13278. }
  13279. });
  13280. };
  13281. _proto.walkTags = function walkTags(callback) {
  13282. var _this9 = this;
  13283. return this.walk(function (selector) {
  13284. if (selector.type === types.TAG) {
  13285. return callback.call(_this9, selector);
  13286. }
  13287. });
  13288. };
  13289. _proto.walkUniversals = function walkUniversals(callback) {
  13290. var _this10 = this;
  13291. return this.walk(function (selector) {
  13292. if (selector.type === types.UNIVERSAL) {
  13293. return callback.call(_this10, selector);
  13294. }
  13295. });
  13296. };
  13297. _proto.split = function split(callback) {
  13298. var _this11 = this;
  13299. var current = [];
  13300. return this.reduce(function (memo, node, index) {
  13301. var split = callback.call(_this11, node);
  13302. current.push(node);
  13303. if (split) {
  13304. memo.push(current);
  13305. current = [];
  13306. } else if (index === _this11.length - 1) {
  13307. memo.push(current);
  13308. }
  13309. return memo;
  13310. }, []);
  13311. };
  13312. _proto.map = function map(callback) {
  13313. return this.nodes.map(callback);
  13314. };
  13315. _proto.reduce = function reduce(callback, memo) {
  13316. return this.nodes.reduce(callback, memo);
  13317. };
  13318. _proto.every = function every(callback) {
  13319. return this.nodes.every(callback);
  13320. };
  13321. _proto.some = function some(callback) {
  13322. return this.nodes.some(callback);
  13323. };
  13324. _proto.filter = function filter(callback) {
  13325. return this.nodes.filter(callback);
  13326. };
  13327. _proto.sort = function sort(callback) {
  13328. return this.nodes.sort(callback);
  13329. };
  13330. _proto.toString = function toString() {
  13331. return this.map(String).join('');
  13332. };
  13333. _createClass(Container, [{
  13334. key: "first",
  13335. get: function get() {
  13336. return this.at(0);
  13337. }
  13338. }, {
  13339. key: "last",
  13340. get: function get() {
  13341. return this.at(this.length - 1);
  13342. }
  13343. }, {
  13344. key: "length",
  13345. get: function get() {
  13346. return this.nodes.length;
  13347. }
  13348. }]);
  13349. return Container;
  13350. }(_node["default"]);
  13351. exports["default"] = Container;
  13352. module.exports = exports.default;
  13353. } (container, container.exports));
  13354. return container.exports;
  13355. }
  13356. var hasRequiredRoot;
  13357. function requireRoot () {
  13358. if (hasRequiredRoot) return root.exports;
  13359. hasRequiredRoot = 1;
  13360. (function (module, exports) {
  13361. exports.__esModule = true;
  13362. exports["default"] = void 0;
  13363. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13364. var _types = /*@__PURE__*/ requireTypes();
  13365. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13366. 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); } }
  13367. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13368. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13369. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13370. var Root = /*#__PURE__*/function (_Container) {
  13371. _inheritsLoose(Root, _Container);
  13372. function Root(opts) {
  13373. var _this;
  13374. _this = _Container.call(this, opts) || this;
  13375. _this.type = _types.ROOT;
  13376. return _this;
  13377. }
  13378. var _proto = Root.prototype;
  13379. _proto.toString = function toString() {
  13380. var str = this.reduce(function (memo, selector) {
  13381. memo.push(String(selector));
  13382. return memo;
  13383. }, []).join(',');
  13384. return this.trailingComma ? str + ',' : str;
  13385. };
  13386. _proto.error = function error(message, options) {
  13387. if (this._error) {
  13388. return this._error(message, options);
  13389. } else {
  13390. return new Error(message);
  13391. }
  13392. };
  13393. _createClass(Root, [{
  13394. key: "errorGenerator",
  13395. set: function set(handler) {
  13396. this._error = handler;
  13397. }
  13398. }]);
  13399. return Root;
  13400. }(_container["default"]);
  13401. exports["default"] = Root;
  13402. module.exports = exports.default;
  13403. } (root, root.exports));
  13404. return root.exports;
  13405. }
  13406. var selector = {exports: {}};
  13407. var hasRequiredSelector;
  13408. function requireSelector () {
  13409. if (hasRequiredSelector) return selector.exports;
  13410. hasRequiredSelector = 1;
  13411. (function (module, exports) {
  13412. exports.__esModule = true;
  13413. exports["default"] = void 0;
  13414. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13415. var _types = /*@__PURE__*/ requireTypes();
  13416. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13417. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13418. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13419. var Selector = /*#__PURE__*/function (_Container) {
  13420. _inheritsLoose(Selector, _Container);
  13421. function Selector(opts) {
  13422. var _this;
  13423. _this = _Container.call(this, opts) || this;
  13424. _this.type = _types.SELECTOR;
  13425. return _this;
  13426. }
  13427. return Selector;
  13428. }(_container["default"]);
  13429. exports["default"] = Selector;
  13430. module.exports = exports.default;
  13431. } (selector, selector.exports));
  13432. return selector.exports;
  13433. }
  13434. var className = {exports: {}};
  13435. var hasRequiredClassName;
  13436. function requireClassName () {
  13437. if (hasRequiredClassName) return className.exports;
  13438. hasRequiredClassName = 1;
  13439. (function (module, exports) {
  13440. exports.__esModule = true;
  13441. exports["default"] = void 0;
  13442. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13443. var _util = /*@__PURE__*/ requireUtil();
  13444. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13445. var _types = /*@__PURE__*/ requireTypes();
  13446. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13447. 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); } }
  13448. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13449. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13450. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13451. var ClassName = /*#__PURE__*/function (_Node) {
  13452. _inheritsLoose(ClassName, _Node);
  13453. function ClassName(opts) {
  13454. var _this;
  13455. _this = _Node.call(this, opts) || this;
  13456. _this.type = _types.CLASS;
  13457. _this._constructed = true;
  13458. return _this;
  13459. }
  13460. var _proto = ClassName.prototype;
  13461. _proto.valueToString = function valueToString() {
  13462. return '.' + _Node.prototype.valueToString.call(this);
  13463. };
  13464. _createClass(ClassName, [{
  13465. key: "value",
  13466. get: function get() {
  13467. return this._value;
  13468. },
  13469. set: function set(v) {
  13470. if (this._constructed) {
  13471. var escaped = (0, _cssesc["default"])(v, {
  13472. isIdentifier: true
  13473. });
  13474. if (escaped !== v) {
  13475. (0, _util.ensureObject)(this, "raws");
  13476. this.raws.value = escaped;
  13477. } else if (this.raws) {
  13478. delete this.raws.value;
  13479. }
  13480. }
  13481. this._value = v;
  13482. }
  13483. }]);
  13484. return ClassName;
  13485. }(_node["default"]);
  13486. exports["default"] = ClassName;
  13487. module.exports = exports.default;
  13488. } (className, className.exports));
  13489. return className.exports;
  13490. }
  13491. var comment = {exports: {}};
  13492. var hasRequiredComment;
  13493. function requireComment () {
  13494. if (hasRequiredComment) return comment.exports;
  13495. hasRequiredComment = 1;
  13496. (function (module, exports) {
  13497. exports.__esModule = true;
  13498. exports["default"] = void 0;
  13499. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13500. var _types = /*@__PURE__*/ requireTypes();
  13501. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13502. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13503. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13504. var Comment = /*#__PURE__*/function (_Node) {
  13505. _inheritsLoose(Comment, _Node);
  13506. function Comment(opts) {
  13507. var _this;
  13508. _this = _Node.call(this, opts) || this;
  13509. _this.type = _types.COMMENT;
  13510. return _this;
  13511. }
  13512. return Comment;
  13513. }(_node["default"]);
  13514. exports["default"] = Comment;
  13515. module.exports = exports.default;
  13516. } (comment, comment.exports));
  13517. return comment.exports;
  13518. }
  13519. var id = {exports: {}};
  13520. var hasRequiredId;
  13521. function requireId () {
  13522. if (hasRequiredId) return id.exports;
  13523. hasRequiredId = 1;
  13524. (function (module, exports) {
  13525. exports.__esModule = true;
  13526. exports["default"] = void 0;
  13527. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13528. var _types = /*@__PURE__*/ requireTypes();
  13529. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13530. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13531. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13532. var ID = /*#__PURE__*/function (_Node) {
  13533. _inheritsLoose(ID, _Node);
  13534. function ID(opts) {
  13535. var _this;
  13536. _this = _Node.call(this, opts) || this;
  13537. _this.type = _types.ID;
  13538. return _this;
  13539. }
  13540. var _proto = ID.prototype;
  13541. _proto.valueToString = function valueToString() {
  13542. return '#' + _Node.prototype.valueToString.call(this);
  13543. };
  13544. return ID;
  13545. }(_node["default"]);
  13546. exports["default"] = ID;
  13547. module.exports = exports.default;
  13548. } (id, id.exports));
  13549. return id.exports;
  13550. }
  13551. var tag = {exports: {}};
  13552. var namespace = {exports: {}};
  13553. var hasRequiredNamespace;
  13554. function requireNamespace () {
  13555. if (hasRequiredNamespace) return namespace.exports;
  13556. hasRequiredNamespace = 1;
  13557. (function (module, exports) {
  13558. exports.__esModule = true;
  13559. exports["default"] = void 0;
  13560. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13561. var _util = /*@__PURE__*/ requireUtil();
  13562. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13563. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13564. 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); } }
  13565. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13566. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13567. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13568. var Namespace = /*#__PURE__*/function (_Node) {
  13569. _inheritsLoose(Namespace, _Node);
  13570. function Namespace() {
  13571. return _Node.apply(this, arguments) || this;
  13572. }
  13573. var _proto = Namespace.prototype;
  13574. _proto.qualifiedName = function qualifiedName(value) {
  13575. if (this.namespace) {
  13576. return this.namespaceString + "|" + value;
  13577. } else {
  13578. return value;
  13579. }
  13580. };
  13581. _proto.valueToString = function valueToString() {
  13582. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  13583. };
  13584. _createClass(Namespace, [{
  13585. key: "namespace",
  13586. get: function get() {
  13587. return this._namespace;
  13588. },
  13589. set: function set(namespace) {
  13590. if (namespace === true || namespace === "*" || namespace === "&") {
  13591. this._namespace = namespace;
  13592. if (this.raws) {
  13593. delete this.raws.namespace;
  13594. }
  13595. return;
  13596. }
  13597. var escaped = (0, _cssesc["default"])(namespace, {
  13598. isIdentifier: true
  13599. });
  13600. this._namespace = namespace;
  13601. if (escaped !== namespace) {
  13602. (0, _util.ensureObject)(this, "raws");
  13603. this.raws.namespace = escaped;
  13604. } else if (this.raws) {
  13605. delete this.raws.namespace;
  13606. }
  13607. }
  13608. }, {
  13609. key: "ns",
  13610. get: function get() {
  13611. return this._namespace;
  13612. },
  13613. set: function set(namespace) {
  13614. this.namespace = namespace;
  13615. }
  13616. }, {
  13617. key: "namespaceString",
  13618. get: function get() {
  13619. if (this.namespace) {
  13620. var ns = this.stringifyProperty("namespace");
  13621. if (ns === true) {
  13622. return '';
  13623. } else {
  13624. return ns;
  13625. }
  13626. } else {
  13627. return '';
  13628. }
  13629. }
  13630. }]);
  13631. return Namespace;
  13632. }(_node["default"]);
  13633. exports["default"] = Namespace;
  13634. module.exports = exports.default;
  13635. } (namespace, namespace.exports));
  13636. return namespace.exports;
  13637. }
  13638. var hasRequiredTag;
  13639. function requireTag () {
  13640. if (hasRequiredTag) return tag.exports;
  13641. hasRequiredTag = 1;
  13642. (function (module, exports) {
  13643. exports.__esModule = true;
  13644. exports["default"] = void 0;
  13645. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13646. var _types = /*@__PURE__*/ requireTypes();
  13647. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13648. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13649. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13650. var Tag = /*#__PURE__*/function (_Namespace) {
  13651. _inheritsLoose(Tag, _Namespace);
  13652. function Tag(opts) {
  13653. var _this;
  13654. _this = _Namespace.call(this, opts) || this;
  13655. _this.type = _types.TAG;
  13656. return _this;
  13657. }
  13658. return Tag;
  13659. }(_namespace["default"]);
  13660. exports["default"] = Tag;
  13661. module.exports = exports.default;
  13662. } (tag, tag.exports));
  13663. return tag.exports;
  13664. }
  13665. var string = {exports: {}};
  13666. var hasRequiredString;
  13667. function requireString () {
  13668. if (hasRequiredString) return string.exports;
  13669. hasRequiredString = 1;
  13670. (function (module, exports) {
  13671. exports.__esModule = true;
  13672. exports["default"] = void 0;
  13673. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13674. var _types = /*@__PURE__*/ requireTypes();
  13675. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13676. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13677. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13678. var String = /*#__PURE__*/function (_Node) {
  13679. _inheritsLoose(String, _Node);
  13680. function String(opts) {
  13681. var _this;
  13682. _this = _Node.call(this, opts) || this;
  13683. _this.type = _types.STRING;
  13684. return _this;
  13685. }
  13686. return String;
  13687. }(_node["default"]);
  13688. exports["default"] = String;
  13689. module.exports = exports.default;
  13690. } (string, string.exports));
  13691. return string.exports;
  13692. }
  13693. var pseudo = {exports: {}};
  13694. var hasRequiredPseudo;
  13695. function requirePseudo () {
  13696. if (hasRequiredPseudo) return pseudo.exports;
  13697. hasRequiredPseudo = 1;
  13698. (function (module, exports) {
  13699. exports.__esModule = true;
  13700. exports["default"] = void 0;
  13701. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13702. var _types = /*@__PURE__*/ requireTypes();
  13703. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13704. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13705. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13706. var Pseudo = /*#__PURE__*/function (_Container) {
  13707. _inheritsLoose(Pseudo, _Container);
  13708. function Pseudo(opts) {
  13709. var _this;
  13710. _this = _Container.call(this, opts) || this;
  13711. _this.type = _types.PSEUDO;
  13712. return _this;
  13713. }
  13714. var _proto = Pseudo.prototype;
  13715. _proto.toString = function toString() {
  13716. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  13717. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  13718. };
  13719. return Pseudo;
  13720. }(_container["default"]);
  13721. exports["default"] = Pseudo;
  13722. module.exports = exports.default;
  13723. } (pseudo, pseudo.exports));
  13724. return pseudo.exports;
  13725. }
  13726. var attribute = {};
  13727. var hasRequiredAttribute;
  13728. function requireAttribute () {
  13729. if (hasRequiredAttribute) return attribute;
  13730. hasRequiredAttribute = 1;
  13731. (function (exports) {
  13732. exports.__esModule = true;
  13733. exports["default"] = void 0;
  13734. exports.unescapeValue = unescapeValue;
  13735. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13736. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13737. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13738. var _types = /*@__PURE__*/ requireTypes();
  13739. var _CSSESC_QUOTE_OPTIONS;
  13740. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13741. 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); } }
  13742. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  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 deprecate = /*@__PURE__*/ requireNode$1();
  13746. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  13747. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  13748. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  13749. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  13750. function unescapeValue(value) {
  13751. var deprecatedUsage = false;
  13752. var quoteMark = null;
  13753. var unescaped = value;
  13754. var m = unescaped.match(WRAPPED_IN_QUOTES);
  13755. if (m) {
  13756. quoteMark = m[1];
  13757. unescaped = m[2];
  13758. }
  13759. unescaped = (0, _unesc["default"])(unescaped);
  13760. if (unescaped !== value) {
  13761. deprecatedUsage = true;
  13762. }
  13763. return {
  13764. deprecatedUsage: deprecatedUsage,
  13765. unescaped: unescaped,
  13766. quoteMark: quoteMark
  13767. };
  13768. }
  13769. function handleDeprecatedContructorOpts(opts) {
  13770. if (opts.quoteMark !== undefined) {
  13771. return opts;
  13772. }
  13773. if (opts.value === undefined) {
  13774. return opts;
  13775. }
  13776. warnOfDeprecatedConstructor();
  13777. var _unescapeValue = unescapeValue(opts.value),
  13778. quoteMark = _unescapeValue.quoteMark,
  13779. unescaped = _unescapeValue.unescaped;
  13780. if (!opts.raws) {
  13781. opts.raws = {};
  13782. }
  13783. if (opts.raws.value === undefined) {
  13784. opts.raws.value = opts.value;
  13785. }
  13786. opts.value = unescaped;
  13787. opts.quoteMark = quoteMark;
  13788. return opts;
  13789. }
  13790. var Attribute = /*#__PURE__*/function (_Namespace) {
  13791. _inheritsLoose(Attribute, _Namespace);
  13792. function Attribute(opts) {
  13793. var _this;
  13794. if (opts === void 0) {
  13795. opts = {};
  13796. }
  13797. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  13798. _this.type = _types.ATTRIBUTE;
  13799. _this.raws = _this.raws || {};
  13800. Object.defineProperty(_this.raws, 'unquoted', {
  13801. get: deprecate(function () {
  13802. return _this.value;
  13803. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  13804. set: deprecate(function () {
  13805. return _this.value;
  13806. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  13807. });
  13808. _this._constructed = true;
  13809. return _this;
  13810. }
  13811. /**
  13812. * Returns the Attribute's value quoted such that it would be legal to use
  13813. * in the value of a css file. The original value's quotation setting
  13814. * used for stringification is left unchanged. See `setValue(value, options)`
  13815. * if you want to control the quote settings of a new value for the attribute.
  13816. *
  13817. * You can also change the quotation used for the current value by setting quoteMark.
  13818. *
  13819. * Options:
  13820. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  13821. * option is not set, the original value for quoteMark will be used. If
  13822. * indeterminate, a double quote is used. The legal values are:
  13823. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  13824. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  13825. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  13826. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  13827. * over the quoteMark option value.
  13828. * * smart {boolean} - if true, will select a quote mark based on the value
  13829. * and the other options specified here. See the `smartQuoteMark()`
  13830. * method.
  13831. **/
  13832. var _proto = Attribute.prototype;
  13833. _proto.getQuotedValue = function getQuotedValue(options) {
  13834. if (options === void 0) {
  13835. options = {};
  13836. }
  13837. var quoteMark = this._determineQuoteMark(options);
  13838. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  13839. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  13840. return escaped;
  13841. };
  13842. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  13843. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  13844. }
  13845. /**
  13846. * Set the unescaped value with the specified quotation options. The value
  13847. * provided must not include any wrapping quote marks -- those quotes will
  13848. * be interpreted as part of the value and escaped accordingly.
  13849. */;
  13850. _proto.setValue = function setValue(value, options) {
  13851. if (options === void 0) {
  13852. options = {};
  13853. }
  13854. this._value = value;
  13855. this._quoteMark = this._determineQuoteMark(options);
  13856. this._syncRawValue();
  13857. }
  13858. /**
  13859. * Intelligently select a quoteMark value based on the value's contents. If
  13860. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  13861. * mark will be picked that minimizes the number of escapes.
  13862. *
  13863. * If there's no clear winner, the quote mark from these options is used,
  13864. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  13865. * true). If the quoteMark is unspecified, a double quote is used.
  13866. *
  13867. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  13868. * from the quoteValue method.
  13869. */;
  13870. _proto.smartQuoteMark = function smartQuoteMark(options) {
  13871. var v = this.value;
  13872. var numSingleQuotes = v.replace(/[^']/g, '').length;
  13873. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  13874. if (numSingleQuotes + numDoubleQuotes === 0) {
  13875. var escaped = (0, _cssesc["default"])(v, {
  13876. isIdentifier: true
  13877. });
  13878. if (escaped === v) {
  13879. return Attribute.NO_QUOTE;
  13880. } else {
  13881. var pref = this.preferredQuoteMark(options);
  13882. if (pref === Attribute.NO_QUOTE) {
  13883. // pick a quote mark that isn't none and see if it's smaller
  13884. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  13885. var opts = CSSESC_QUOTE_OPTIONS[quote];
  13886. var quoteValue = (0, _cssesc["default"])(v, opts);
  13887. if (quoteValue.length < escaped.length) {
  13888. return quote;
  13889. }
  13890. }
  13891. return pref;
  13892. }
  13893. } else if (numDoubleQuotes === numSingleQuotes) {
  13894. return this.preferredQuoteMark(options);
  13895. } else if (numDoubleQuotes < numSingleQuotes) {
  13896. return Attribute.DOUBLE_QUOTE;
  13897. } else {
  13898. return Attribute.SINGLE_QUOTE;
  13899. }
  13900. }
  13901. /**
  13902. * Selects the preferred quote mark based on the options and the current quote mark value.
  13903. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  13904. * instead.
  13905. */;
  13906. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  13907. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  13908. if (quoteMark === undefined) {
  13909. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  13910. }
  13911. if (quoteMark === undefined) {
  13912. quoteMark = Attribute.DOUBLE_QUOTE;
  13913. }
  13914. return quoteMark;
  13915. };
  13916. _proto._syncRawValue = function _syncRawValue() {
  13917. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  13918. if (rawValue === this._value) {
  13919. if (this.raws) {
  13920. delete this.raws.value;
  13921. }
  13922. } else {
  13923. this.raws.value = rawValue;
  13924. }
  13925. };
  13926. _proto._handleEscapes = function _handleEscapes(prop, value) {
  13927. if (this._constructed) {
  13928. var escaped = (0, _cssesc["default"])(value, {
  13929. isIdentifier: true
  13930. });
  13931. if (escaped !== value) {
  13932. this.raws[prop] = escaped;
  13933. } else {
  13934. delete this.raws[prop];
  13935. }
  13936. }
  13937. };
  13938. _proto._spacesFor = function _spacesFor(name) {
  13939. var attrSpaces = {
  13940. before: '',
  13941. after: ''
  13942. };
  13943. var spaces = this.spaces[name] || {};
  13944. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  13945. return Object.assign(attrSpaces, spaces, rawSpaces);
  13946. };
  13947. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  13948. if (spaceName === void 0) {
  13949. spaceName = name;
  13950. }
  13951. if (concat === void 0) {
  13952. concat = defaultAttrConcat;
  13953. }
  13954. var attrSpaces = this._spacesFor(spaceName);
  13955. return concat(this.stringifyProperty(name), attrSpaces);
  13956. }
  13957. /**
  13958. * returns the offset of the attribute part specified relative to the
  13959. * start of the node of the output string.
  13960. *
  13961. * * "ns" - alias for "namespace"
  13962. * * "namespace" - the namespace if it exists.
  13963. * * "attribute" - the attribute name
  13964. * * "attributeNS" - the start of the attribute or its namespace
  13965. * * "operator" - the match operator of the attribute
  13966. * * "value" - The value (string or identifier)
  13967. * * "insensitive" - the case insensitivity flag;
  13968. * @param part One of the possible values inside an attribute.
  13969. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  13970. */;
  13971. _proto.offsetOf = function offsetOf(name) {
  13972. var count = 1;
  13973. var attributeSpaces = this._spacesFor("attribute");
  13974. count += attributeSpaces.before.length;
  13975. if (name === "namespace" || name === "ns") {
  13976. return this.namespace ? count : -1;
  13977. }
  13978. if (name === "attributeNS") {
  13979. return count;
  13980. }
  13981. count += this.namespaceString.length;
  13982. if (this.namespace) {
  13983. count += 1;
  13984. }
  13985. if (name === "attribute") {
  13986. return count;
  13987. }
  13988. count += this.stringifyProperty("attribute").length;
  13989. count += attributeSpaces.after.length;
  13990. var operatorSpaces = this._spacesFor("operator");
  13991. count += operatorSpaces.before.length;
  13992. var operator = this.stringifyProperty("operator");
  13993. if (name === "operator") {
  13994. return operator ? count : -1;
  13995. }
  13996. count += operator.length;
  13997. count += operatorSpaces.after.length;
  13998. var valueSpaces = this._spacesFor("value");
  13999. count += valueSpaces.before.length;
  14000. var value = this.stringifyProperty("value");
  14001. if (name === "value") {
  14002. return value ? count : -1;
  14003. }
  14004. count += value.length;
  14005. count += valueSpaces.after.length;
  14006. var insensitiveSpaces = this._spacesFor("insensitive");
  14007. count += insensitiveSpaces.before.length;
  14008. if (name === "insensitive") {
  14009. return this.insensitive ? count : -1;
  14010. }
  14011. return -1;
  14012. };
  14013. _proto.toString = function toString() {
  14014. var _this2 = this;
  14015. var selector = [this.rawSpaceBefore, '['];
  14016. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14017. if (this.operator && (this.value || this.value === '')) {
  14018. selector.push(this._stringFor('operator'));
  14019. selector.push(this._stringFor('value'));
  14020. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14021. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14022. attrSpaces.before = " ";
  14023. }
  14024. return defaultAttrConcat(attrValue, attrSpaces);
  14025. }));
  14026. }
  14027. selector.push(']');
  14028. selector.push(this.rawSpaceAfter);
  14029. return selector.join('');
  14030. };
  14031. _createClass(Attribute, [{
  14032. key: "quoted",
  14033. get: function get() {
  14034. var qm = this.quoteMark;
  14035. return qm === "'" || qm === '"';
  14036. },
  14037. set: function set(value) {
  14038. warnOfDeprecatedQuotedAssignment();
  14039. }
  14040. /**
  14041. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14042. * returns `null` if the value is not quoted.
  14043. * returns `undefined` if the quotation state is unknown (this can happen when
  14044. * the attribute is constructed without specifying a quote mark.)
  14045. */
  14046. }, {
  14047. key: "quoteMark",
  14048. get: function get() {
  14049. return this._quoteMark;
  14050. }
  14051. /**
  14052. * Set the quote mark to be used by this attribute's value.
  14053. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14054. * value is updated accordingly.
  14055. *
  14056. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14057. */,
  14058. set: function set(quoteMark) {
  14059. if (!this._constructed) {
  14060. this._quoteMark = quoteMark;
  14061. return;
  14062. }
  14063. if (this._quoteMark !== quoteMark) {
  14064. this._quoteMark = quoteMark;
  14065. this._syncRawValue();
  14066. }
  14067. }
  14068. }, {
  14069. key: "qualifiedAttribute",
  14070. get: function get() {
  14071. return this.qualifiedName(this.raws.attribute || this.attribute);
  14072. }
  14073. }, {
  14074. key: "insensitiveFlag",
  14075. get: function get() {
  14076. return this.insensitive ? 'i' : '';
  14077. }
  14078. }, {
  14079. key: "value",
  14080. get: function get() {
  14081. return this._value;
  14082. },
  14083. set:
  14084. /**
  14085. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14086. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14087. * is unescaped during parsing and any quote marks are removed.
  14088. *
  14089. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14090. * a deprecation warning is raised when the new value contains any characters that would
  14091. * require escaping (including if it contains wrapped quotes).
  14092. *
  14093. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14094. * how the new value is quoted.
  14095. */
  14096. function set(v) {
  14097. if (this._constructed) {
  14098. var _unescapeValue2 = unescapeValue(v),
  14099. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14100. unescaped = _unescapeValue2.unescaped,
  14101. quoteMark = _unescapeValue2.quoteMark;
  14102. if (deprecatedUsage) {
  14103. warnOfDeprecatedValueAssignment();
  14104. }
  14105. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14106. return;
  14107. }
  14108. this._value = unescaped;
  14109. this._quoteMark = quoteMark;
  14110. this._syncRawValue();
  14111. } else {
  14112. this._value = v;
  14113. }
  14114. }
  14115. }, {
  14116. key: "insensitive",
  14117. get: function get() {
  14118. return this._insensitive;
  14119. }
  14120. /**
  14121. * Set the case insensitive flag.
  14122. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14123. * of the attribute is updated accordingly.
  14124. *
  14125. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14126. */,
  14127. set: function set(insensitive) {
  14128. if (!insensitive) {
  14129. this._insensitive = false;
  14130. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14131. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14132. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14133. this.raws.insensitiveFlag = undefined;
  14134. }
  14135. }
  14136. this._insensitive = insensitive;
  14137. }
  14138. }, {
  14139. key: "attribute",
  14140. get: function get() {
  14141. return this._attribute;
  14142. },
  14143. set: function set(name) {
  14144. this._handleEscapes("attribute", name);
  14145. this._attribute = name;
  14146. }
  14147. }]);
  14148. return Attribute;
  14149. }(_namespace["default"]);
  14150. exports["default"] = Attribute;
  14151. Attribute.NO_QUOTE = null;
  14152. Attribute.SINGLE_QUOTE = "'";
  14153. Attribute.DOUBLE_QUOTE = '"';
  14154. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14155. "'": {
  14156. quotes: 'single',
  14157. wrap: true
  14158. },
  14159. '"': {
  14160. quotes: 'double',
  14161. wrap: true
  14162. }
  14163. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14164. isIdentifier: true
  14165. }, _CSSESC_QUOTE_OPTIONS);
  14166. function defaultAttrConcat(attrValue, attrSpaces) {
  14167. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14168. }
  14169. } (attribute));
  14170. return attribute;
  14171. }
  14172. var universal = {exports: {}};
  14173. var hasRequiredUniversal;
  14174. function requireUniversal () {
  14175. if (hasRequiredUniversal) return universal.exports;
  14176. hasRequiredUniversal = 1;
  14177. (function (module, exports) {
  14178. exports.__esModule = true;
  14179. exports["default"] = void 0;
  14180. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14181. var _types = /*@__PURE__*/ requireTypes();
  14182. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14183. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14184. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14185. var Universal = /*#__PURE__*/function (_Namespace) {
  14186. _inheritsLoose(Universal, _Namespace);
  14187. function Universal(opts) {
  14188. var _this;
  14189. _this = _Namespace.call(this, opts) || this;
  14190. _this.type = _types.UNIVERSAL;
  14191. _this.value = '*';
  14192. return _this;
  14193. }
  14194. return Universal;
  14195. }(_namespace["default"]);
  14196. exports["default"] = Universal;
  14197. module.exports = exports.default;
  14198. } (universal, universal.exports));
  14199. return universal.exports;
  14200. }
  14201. var combinator = {exports: {}};
  14202. var hasRequiredCombinator;
  14203. function requireCombinator () {
  14204. if (hasRequiredCombinator) return combinator.exports;
  14205. hasRequiredCombinator = 1;
  14206. (function (module, exports) {
  14207. exports.__esModule = true;
  14208. exports["default"] = void 0;
  14209. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14210. var _types = /*@__PURE__*/ requireTypes();
  14211. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14212. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14213. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14214. var Combinator = /*#__PURE__*/function (_Node) {
  14215. _inheritsLoose(Combinator, _Node);
  14216. function Combinator(opts) {
  14217. var _this;
  14218. _this = _Node.call(this, opts) || this;
  14219. _this.type = _types.COMBINATOR;
  14220. return _this;
  14221. }
  14222. return Combinator;
  14223. }(_node["default"]);
  14224. exports["default"] = Combinator;
  14225. module.exports = exports.default;
  14226. } (combinator, combinator.exports));
  14227. return combinator.exports;
  14228. }
  14229. var nesting = {exports: {}};
  14230. var hasRequiredNesting;
  14231. function requireNesting () {
  14232. if (hasRequiredNesting) return nesting.exports;
  14233. hasRequiredNesting = 1;
  14234. (function (module, exports) {
  14235. exports.__esModule = true;
  14236. exports["default"] = void 0;
  14237. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14238. var _types = /*@__PURE__*/ requireTypes();
  14239. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14240. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14241. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14242. var Nesting = /*#__PURE__*/function (_Node) {
  14243. _inheritsLoose(Nesting, _Node);
  14244. function Nesting(opts) {
  14245. var _this;
  14246. _this = _Node.call(this, opts) || this;
  14247. _this.type = _types.NESTING;
  14248. _this.value = '&';
  14249. return _this;
  14250. }
  14251. return Nesting;
  14252. }(_node["default"]);
  14253. exports["default"] = Nesting;
  14254. module.exports = exports.default;
  14255. } (nesting, nesting.exports));
  14256. return nesting.exports;
  14257. }
  14258. var sortAscending = {exports: {}};
  14259. var hasRequiredSortAscending;
  14260. function requireSortAscending () {
  14261. if (hasRequiredSortAscending) return sortAscending.exports;
  14262. hasRequiredSortAscending = 1;
  14263. (function (module, exports) {
  14264. exports.__esModule = true;
  14265. exports["default"] = sortAscending;
  14266. function sortAscending(list) {
  14267. return list.sort(function (a, b) {
  14268. return a - b;
  14269. });
  14270. }
  14271. module.exports = exports.default;
  14272. } (sortAscending, sortAscending.exports));
  14273. return sortAscending.exports;
  14274. }
  14275. var tokenize = {};
  14276. var tokenTypes = {};
  14277. var hasRequiredTokenTypes;
  14278. function requireTokenTypes () {
  14279. if (hasRequiredTokenTypes) return tokenTypes;
  14280. hasRequiredTokenTypes = 1;
  14281. tokenTypes.__esModule = true;
  14282. 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;
  14283. var ampersand = 38; // `&`.charCodeAt(0);
  14284. tokenTypes.ampersand = ampersand;
  14285. var asterisk = 42; // `*`.charCodeAt(0);
  14286. tokenTypes.asterisk = asterisk;
  14287. var at = 64; // `@`.charCodeAt(0);
  14288. tokenTypes.at = at;
  14289. var comma = 44; // `,`.charCodeAt(0);
  14290. tokenTypes.comma = comma;
  14291. var colon = 58; // `:`.charCodeAt(0);
  14292. tokenTypes.colon = colon;
  14293. var semicolon = 59; // `;`.charCodeAt(0);
  14294. tokenTypes.semicolon = semicolon;
  14295. var openParenthesis = 40; // `(`.charCodeAt(0);
  14296. tokenTypes.openParenthesis = openParenthesis;
  14297. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14298. tokenTypes.closeParenthesis = closeParenthesis;
  14299. var openSquare = 91; // `[`.charCodeAt(0);
  14300. tokenTypes.openSquare = openSquare;
  14301. var closeSquare = 93; // `]`.charCodeAt(0);
  14302. tokenTypes.closeSquare = closeSquare;
  14303. var dollar = 36; // `$`.charCodeAt(0);
  14304. tokenTypes.dollar = dollar;
  14305. var tilde = 126; // `~`.charCodeAt(0);
  14306. tokenTypes.tilde = tilde;
  14307. var caret = 94; // `^`.charCodeAt(0);
  14308. tokenTypes.caret = caret;
  14309. var plus = 43; // `+`.charCodeAt(0);
  14310. tokenTypes.plus = plus;
  14311. var equals = 61; // `=`.charCodeAt(0);
  14312. tokenTypes.equals = equals;
  14313. var pipe = 124; // `|`.charCodeAt(0);
  14314. tokenTypes.pipe = pipe;
  14315. var greaterThan = 62; // `>`.charCodeAt(0);
  14316. tokenTypes.greaterThan = greaterThan;
  14317. var space = 32; // ` `.charCodeAt(0);
  14318. tokenTypes.space = space;
  14319. var singleQuote = 39; // `'`.charCodeAt(0);
  14320. tokenTypes.singleQuote = singleQuote;
  14321. var doubleQuote = 34; // `"`.charCodeAt(0);
  14322. tokenTypes.doubleQuote = doubleQuote;
  14323. var slash = 47; // `/`.charCodeAt(0);
  14324. tokenTypes.slash = slash;
  14325. var bang = 33; // `!`.charCodeAt(0);
  14326. tokenTypes.bang = bang;
  14327. var backslash = 92; // '\\'.charCodeAt(0);
  14328. tokenTypes.backslash = backslash;
  14329. var cr = 13; // '\r'.charCodeAt(0);
  14330. tokenTypes.cr = cr;
  14331. var feed = 12; // '\f'.charCodeAt(0);
  14332. tokenTypes.feed = feed;
  14333. var newline = 10; // '\n'.charCodeAt(0);
  14334. tokenTypes.newline = newline;
  14335. var tab = 9; // '\t'.charCodeAt(0);
  14336. // Expose aliases primarily for readability.
  14337. tokenTypes.tab = tab;
  14338. var str = singleQuote;
  14339. // No good single character representation!
  14340. tokenTypes.str = str;
  14341. var comment = -1;
  14342. tokenTypes.comment = comment;
  14343. var word = -2;
  14344. tokenTypes.word = word;
  14345. var combinator = -3;
  14346. tokenTypes.combinator = combinator;
  14347. return tokenTypes;
  14348. }
  14349. var hasRequiredTokenize;
  14350. function requireTokenize () {
  14351. if (hasRequiredTokenize) return tokenize;
  14352. hasRequiredTokenize = 1;
  14353. (function (exports) {
  14354. exports.__esModule = true;
  14355. exports.FIELDS = void 0;
  14356. exports["default"] = tokenize;
  14357. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14358. var _unescapable, _wordDelimiters;
  14359. 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); }
  14360. 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; }
  14361. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14362. 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);
  14363. var hex = {};
  14364. var hexChars = "0123456789abcdefABCDEF";
  14365. for (var i = 0; i < hexChars.length; i++) {
  14366. hex[hexChars.charCodeAt(i)] = true;
  14367. }
  14368. /**
  14369. * Returns the last index of the bar css word
  14370. * @param {string} css The string in which the word begins
  14371. * @param {number} start The index into the string where word's first letter occurs
  14372. */
  14373. function consumeWord(css, start) {
  14374. var next = start;
  14375. var code;
  14376. do {
  14377. code = css.charCodeAt(next);
  14378. if (wordDelimiters[code]) {
  14379. return next - 1;
  14380. } else if (code === t.backslash) {
  14381. next = consumeEscape(css, next) + 1;
  14382. } else {
  14383. // All other characters are part of the word
  14384. next++;
  14385. }
  14386. } while (next < css.length);
  14387. return next - 1;
  14388. }
  14389. /**
  14390. * Returns the last index of the escape sequence
  14391. * @param {string} css The string in which the sequence begins
  14392. * @param {number} start The index into the string where escape character (`\`) occurs.
  14393. */
  14394. function consumeEscape(css, start) {
  14395. var next = start;
  14396. var code = css.charCodeAt(next + 1);
  14397. if (unescapable[code]) ; else if (hex[code]) {
  14398. var hexDigits = 0;
  14399. // consume up to 6 hex chars
  14400. do {
  14401. next++;
  14402. hexDigits++;
  14403. code = css.charCodeAt(next + 1);
  14404. } while (hex[code] && hexDigits < 6);
  14405. // if fewer than 6 hex chars, a trailing space ends the escape
  14406. if (hexDigits < 6 && code === t.space) {
  14407. next++;
  14408. }
  14409. } else {
  14410. // the next char is part of the current word
  14411. next++;
  14412. }
  14413. return next;
  14414. }
  14415. var FIELDS = {
  14416. TYPE: 0,
  14417. START_LINE: 1,
  14418. START_COL: 2,
  14419. END_LINE: 3,
  14420. END_COL: 4,
  14421. START_POS: 5,
  14422. END_POS: 6
  14423. };
  14424. exports.FIELDS = FIELDS;
  14425. function tokenize(input) {
  14426. var tokens = [];
  14427. var css = input.css.valueOf();
  14428. var _css = css,
  14429. length = _css.length;
  14430. var offset = -1;
  14431. var line = 1;
  14432. var start = 0;
  14433. var end = 0;
  14434. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14435. function unclosed(what, fix) {
  14436. if (input.safe) {
  14437. // fyi: this is never set to true.
  14438. css += fix;
  14439. next = css.length - 1;
  14440. } else {
  14441. throw input.error('Unclosed ' + what, line, start - offset, start);
  14442. }
  14443. }
  14444. while (start < length) {
  14445. code = css.charCodeAt(start);
  14446. if (code === t.newline) {
  14447. offset = start;
  14448. line += 1;
  14449. }
  14450. switch (code) {
  14451. case t.space:
  14452. case t.tab:
  14453. case t.newline:
  14454. case t.cr:
  14455. case t.feed:
  14456. next = start;
  14457. do {
  14458. next += 1;
  14459. code = css.charCodeAt(next);
  14460. if (code === t.newline) {
  14461. offset = next;
  14462. line += 1;
  14463. }
  14464. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  14465. tokenType = t.space;
  14466. endLine = line;
  14467. endColumn = next - offset - 1;
  14468. end = next;
  14469. break;
  14470. case t.plus:
  14471. case t.greaterThan:
  14472. case t.tilde:
  14473. case t.pipe:
  14474. next = start;
  14475. do {
  14476. next += 1;
  14477. code = css.charCodeAt(next);
  14478. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  14479. tokenType = t.combinator;
  14480. endLine = line;
  14481. endColumn = start - offset;
  14482. end = next;
  14483. break;
  14484. // Consume these characters as single tokens.
  14485. case t.asterisk:
  14486. case t.ampersand:
  14487. case t.bang:
  14488. case t.comma:
  14489. case t.equals:
  14490. case t.dollar:
  14491. case t.caret:
  14492. case t.openSquare:
  14493. case t.closeSquare:
  14494. case t.colon:
  14495. case t.semicolon:
  14496. case t.openParenthesis:
  14497. case t.closeParenthesis:
  14498. next = start;
  14499. tokenType = code;
  14500. endLine = line;
  14501. endColumn = start - offset;
  14502. end = next + 1;
  14503. break;
  14504. case t.singleQuote:
  14505. case t.doubleQuote:
  14506. quote = code === t.singleQuote ? "'" : '"';
  14507. next = start;
  14508. do {
  14509. escaped = false;
  14510. next = css.indexOf(quote, next + 1);
  14511. if (next === -1) {
  14512. unclosed('quote', quote);
  14513. }
  14514. escapePos = next;
  14515. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  14516. escapePos -= 1;
  14517. escaped = !escaped;
  14518. }
  14519. } while (escaped);
  14520. tokenType = t.str;
  14521. endLine = line;
  14522. endColumn = start - offset;
  14523. end = next + 1;
  14524. break;
  14525. default:
  14526. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  14527. next = css.indexOf('*/', start + 2) + 1;
  14528. if (next === 0) {
  14529. unclosed('comment', '*/');
  14530. }
  14531. content = css.slice(start, next + 1);
  14532. lines = content.split('\n');
  14533. last = lines.length - 1;
  14534. if (last > 0) {
  14535. nextLine = line + last;
  14536. nextOffset = next - lines[last].length;
  14537. } else {
  14538. nextLine = line;
  14539. nextOffset = offset;
  14540. }
  14541. tokenType = t.comment;
  14542. line = nextLine;
  14543. endLine = nextLine;
  14544. endColumn = next - nextOffset;
  14545. } else if (code === t.slash) {
  14546. next = start;
  14547. tokenType = code;
  14548. endLine = line;
  14549. endColumn = start - offset;
  14550. end = next + 1;
  14551. } else {
  14552. next = consumeWord(css, start);
  14553. tokenType = t.word;
  14554. endLine = line;
  14555. endColumn = next - offset;
  14556. }
  14557. end = next + 1;
  14558. break;
  14559. }
  14560. // Ensure that the token structure remains consistent
  14561. tokens.push([tokenType,
  14562. // [0] Token type
  14563. line,
  14564. // [1] Starting line
  14565. start - offset,
  14566. // [2] Starting column
  14567. endLine,
  14568. // [3] Ending line
  14569. endColumn,
  14570. // [4] Ending column
  14571. start,
  14572. // [5] Start position / Source index
  14573. end // [6] End position
  14574. ]);
  14575. // Reset offset for the next token
  14576. if (nextOffset) {
  14577. offset = nextOffset;
  14578. nextOffset = null;
  14579. }
  14580. start = end;
  14581. }
  14582. return tokens;
  14583. }
  14584. } (tokenize));
  14585. return tokenize;
  14586. }
  14587. var hasRequiredParser;
  14588. function requireParser () {
  14589. if (hasRequiredParser) return parser.exports;
  14590. hasRequiredParser = 1;
  14591. (function (module, exports) {
  14592. exports.__esModule = true;
  14593. exports["default"] = void 0;
  14594. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  14595. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  14596. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  14597. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  14598. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  14599. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  14600. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  14601. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  14602. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  14603. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  14604. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  14605. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  14606. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  14607. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  14608. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14609. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  14610. var _util = /*@__PURE__*/ requireUtil();
  14611. var _WHITESPACE_TOKENS, _Object$assign;
  14612. 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); }
  14613. 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; }
  14614. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14615. 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); } }
  14616. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14617. 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);
  14618. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  14619. function tokenStart(token) {
  14620. return {
  14621. line: token[_tokenize.FIELDS.START_LINE],
  14622. column: token[_tokenize.FIELDS.START_COL]
  14623. };
  14624. }
  14625. function tokenEnd(token) {
  14626. return {
  14627. line: token[_tokenize.FIELDS.END_LINE],
  14628. column: token[_tokenize.FIELDS.END_COL]
  14629. };
  14630. }
  14631. function getSource(startLine, startColumn, endLine, endColumn) {
  14632. return {
  14633. start: {
  14634. line: startLine,
  14635. column: startColumn
  14636. },
  14637. end: {
  14638. line: endLine,
  14639. column: endColumn
  14640. }
  14641. };
  14642. }
  14643. function getTokenSource(token) {
  14644. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  14645. }
  14646. function getTokenSourceSpan(startToken, endToken) {
  14647. if (!startToken) {
  14648. return undefined;
  14649. }
  14650. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  14651. }
  14652. function unescapeProp(node, prop) {
  14653. var value = node[prop];
  14654. if (typeof value !== "string") {
  14655. return;
  14656. }
  14657. if (value.indexOf("\\") !== -1) {
  14658. (0, _util.ensureObject)(node, 'raws');
  14659. node[prop] = (0, _util.unesc)(value);
  14660. if (node.raws[prop] === undefined) {
  14661. node.raws[prop] = value;
  14662. }
  14663. }
  14664. return node;
  14665. }
  14666. function indexesOf(array, item) {
  14667. var i = -1;
  14668. var indexes = [];
  14669. while ((i = array.indexOf(item, i + 1)) !== -1) {
  14670. indexes.push(i);
  14671. }
  14672. return indexes;
  14673. }
  14674. function uniqs() {
  14675. var list = Array.prototype.concat.apply([], arguments);
  14676. return list.filter(function (item, i) {
  14677. return i === list.indexOf(item);
  14678. });
  14679. }
  14680. var Parser = /*#__PURE__*/function () {
  14681. function Parser(rule, options) {
  14682. if (options === void 0) {
  14683. options = {};
  14684. }
  14685. this.rule = rule;
  14686. this.options = Object.assign({
  14687. lossy: false,
  14688. safe: false
  14689. }, options);
  14690. this.position = 0;
  14691. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  14692. this.tokens = (0, _tokenize["default"])({
  14693. css: this.css,
  14694. error: this._errorGenerator(),
  14695. safe: this.options.safe
  14696. });
  14697. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  14698. this.root = new _root["default"]({
  14699. source: rootSource
  14700. });
  14701. this.root.errorGenerator = this._errorGenerator();
  14702. var selector = new _selector["default"]({
  14703. source: {
  14704. start: {
  14705. line: 1,
  14706. column: 1
  14707. }
  14708. },
  14709. sourceIndex: 0
  14710. });
  14711. this.root.append(selector);
  14712. this.current = selector;
  14713. this.loop();
  14714. }
  14715. var _proto = Parser.prototype;
  14716. _proto._errorGenerator = function _errorGenerator() {
  14717. var _this = this;
  14718. return function (message, errorOptions) {
  14719. if (typeof _this.rule === 'string') {
  14720. return new Error(message);
  14721. }
  14722. return _this.rule.error(message, errorOptions);
  14723. };
  14724. };
  14725. _proto.attribute = function attribute() {
  14726. var attr = [];
  14727. var startingToken = this.currToken;
  14728. this.position++;
  14729. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14730. attr.push(this.currToken);
  14731. this.position++;
  14732. }
  14733. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14734. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  14735. }
  14736. var len = attr.length;
  14737. var node = {
  14738. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  14739. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  14740. };
  14741. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  14742. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  14743. }
  14744. var pos = 0;
  14745. var spaceBefore = '';
  14746. var commentBefore = '';
  14747. var lastAdded = null;
  14748. var spaceAfterMeaningfulToken = false;
  14749. while (pos < len) {
  14750. var token = attr[pos];
  14751. var content = this.content(token);
  14752. var next = attr[pos + 1];
  14753. switch (token[_tokenize.FIELDS.TYPE]) {
  14754. case tokens.space:
  14755. // if (
  14756. // len === 1 ||
  14757. // pos === 0 && this.content(next) === '|'
  14758. // ) {
  14759. // return this.expected('attribute', token[TOKEN.START_POS], content);
  14760. // }
  14761. spaceAfterMeaningfulToken = true;
  14762. if (this.options.lossy) {
  14763. break;
  14764. }
  14765. if (lastAdded) {
  14766. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  14767. var prevContent = node.spaces[lastAdded].after || '';
  14768. node.spaces[lastAdded].after = prevContent + content;
  14769. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  14770. if (existingComment) {
  14771. node.raws.spaces[lastAdded].after = existingComment + content;
  14772. }
  14773. } else {
  14774. spaceBefore = spaceBefore + content;
  14775. commentBefore = commentBefore + content;
  14776. }
  14777. break;
  14778. case tokens.asterisk:
  14779. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14780. node.operator = content;
  14781. lastAdded = 'operator';
  14782. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  14783. if (spaceBefore) {
  14784. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14785. node.spaces.attribute.before = spaceBefore;
  14786. spaceBefore = '';
  14787. }
  14788. if (commentBefore) {
  14789. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14790. node.raws.spaces.attribute.before = spaceBefore;
  14791. commentBefore = '';
  14792. }
  14793. node.namespace = (node.namespace || "") + content;
  14794. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  14795. if (rawValue) {
  14796. node.raws.namespace += content;
  14797. }
  14798. lastAdded = 'namespace';
  14799. }
  14800. spaceAfterMeaningfulToken = false;
  14801. break;
  14802. case tokens.dollar:
  14803. if (lastAdded === "value") {
  14804. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  14805. node.value += "$";
  14806. if (oldRawValue) {
  14807. node.raws.value = oldRawValue + "$";
  14808. }
  14809. break;
  14810. }
  14811. // Falls through
  14812. case tokens.caret:
  14813. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14814. node.operator = content;
  14815. lastAdded = 'operator';
  14816. }
  14817. spaceAfterMeaningfulToken = false;
  14818. break;
  14819. case tokens.combinator:
  14820. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14821. node.operator = content;
  14822. lastAdded = 'operator';
  14823. }
  14824. if (content !== '|') {
  14825. spaceAfterMeaningfulToken = false;
  14826. break;
  14827. }
  14828. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14829. node.operator = content;
  14830. lastAdded = 'operator';
  14831. } else if (!node.namespace && !node.attribute) {
  14832. node.namespace = true;
  14833. }
  14834. spaceAfterMeaningfulToken = false;
  14835. break;
  14836. case tokens.word:
  14837. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  14838. // this look-ahead probably fails with comment nodes involved.
  14839. !node.operator && !node.namespace) {
  14840. node.namespace = content;
  14841. lastAdded = 'namespace';
  14842. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  14843. if (spaceBefore) {
  14844. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14845. node.spaces.attribute.before = spaceBefore;
  14846. spaceBefore = '';
  14847. }
  14848. if (commentBefore) {
  14849. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14850. node.raws.spaces.attribute.before = commentBefore;
  14851. commentBefore = '';
  14852. }
  14853. node.attribute = (node.attribute || "") + content;
  14854. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  14855. if (_rawValue) {
  14856. node.raws.attribute += content;
  14857. }
  14858. lastAdded = 'attribute';
  14859. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  14860. var _unescaped = (0, _util.unesc)(content);
  14861. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  14862. var oldValue = node.value || '';
  14863. node.value = oldValue + _unescaped;
  14864. node.quoteMark = null;
  14865. if (_unescaped !== content || _oldRawValue) {
  14866. (0, _util.ensureObject)(node, 'raws');
  14867. node.raws.value = (_oldRawValue || oldValue) + content;
  14868. }
  14869. lastAdded = 'value';
  14870. } else {
  14871. var insensitive = content === 'i' || content === "I";
  14872. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  14873. node.insensitive = insensitive;
  14874. if (!insensitive || content === "I") {
  14875. (0, _util.ensureObject)(node, 'raws');
  14876. node.raws.insensitiveFlag = content;
  14877. }
  14878. lastAdded = 'insensitive';
  14879. if (spaceBefore) {
  14880. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  14881. node.spaces.insensitive.before = spaceBefore;
  14882. spaceBefore = '';
  14883. }
  14884. if (commentBefore) {
  14885. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  14886. node.raws.spaces.insensitive.before = commentBefore;
  14887. commentBefore = '';
  14888. }
  14889. } else if (node.value || node.value === '') {
  14890. lastAdded = 'value';
  14891. node.value += content;
  14892. if (node.raws.value) {
  14893. node.raws.value += content;
  14894. }
  14895. }
  14896. }
  14897. spaceAfterMeaningfulToken = false;
  14898. break;
  14899. case tokens.str:
  14900. if (!node.attribute || !node.operator) {
  14901. return this.error("Expected an attribute followed by an operator preceding the string.", {
  14902. index: token[_tokenize.FIELDS.START_POS]
  14903. });
  14904. }
  14905. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  14906. unescaped = _unescapeValue.unescaped,
  14907. quoteMark = _unescapeValue.quoteMark;
  14908. node.value = unescaped;
  14909. node.quoteMark = quoteMark;
  14910. lastAdded = 'value';
  14911. (0, _util.ensureObject)(node, 'raws');
  14912. node.raws.value = content;
  14913. spaceAfterMeaningfulToken = false;
  14914. break;
  14915. case tokens.equals:
  14916. if (!node.attribute) {
  14917. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  14918. }
  14919. if (node.value) {
  14920. return this.error('Unexpected "=" found; an operator was already defined.', {
  14921. index: token[_tokenize.FIELDS.START_POS]
  14922. });
  14923. }
  14924. node.operator = node.operator ? node.operator + content : content;
  14925. lastAdded = 'operator';
  14926. spaceAfterMeaningfulToken = false;
  14927. break;
  14928. case tokens.comment:
  14929. if (lastAdded) {
  14930. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  14931. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  14932. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  14933. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  14934. node.raws.spaces[lastAdded].after = rawLastComment + content;
  14935. } else {
  14936. var lastValue = node[lastAdded] || '';
  14937. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  14938. (0, _util.ensureObject)(node, 'raws');
  14939. node.raws[lastAdded] = rawLastValue + content;
  14940. }
  14941. } else {
  14942. commentBefore = commentBefore + content;
  14943. }
  14944. break;
  14945. default:
  14946. return this.error("Unexpected \"" + content + "\" found.", {
  14947. index: token[_tokenize.FIELDS.START_POS]
  14948. });
  14949. }
  14950. pos++;
  14951. }
  14952. unescapeProp(node, "attribute");
  14953. unescapeProp(node, "namespace");
  14954. this.newNode(new _attribute["default"](node));
  14955. this.position++;
  14956. }
  14957. /**
  14958. * return a node containing meaningless garbage up to (but not including) the specified token position.
  14959. * if the token position is negative, all remaining tokens are consumed.
  14960. *
  14961. * This returns an array containing a single string node if all whitespace,
  14962. * otherwise an array of comment nodes with space before and after.
  14963. *
  14964. * These tokens are not added to the current selector, the caller can add them or use them to amend
  14965. * a previous node's space metadata.
  14966. *
  14967. * In lossy mode, this returns only comments.
  14968. */;
  14969. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  14970. if (stopPosition < 0) {
  14971. stopPosition = this.tokens.length;
  14972. }
  14973. var startPosition = this.position;
  14974. var nodes = [];
  14975. var space = "";
  14976. var lastComment = undefined;
  14977. do {
  14978. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  14979. if (!this.options.lossy) {
  14980. space += this.content();
  14981. }
  14982. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  14983. var spaces = {};
  14984. if (space) {
  14985. spaces.before = space;
  14986. space = "";
  14987. }
  14988. lastComment = new _comment["default"]({
  14989. value: this.content(),
  14990. source: getTokenSource(this.currToken),
  14991. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  14992. spaces: spaces
  14993. });
  14994. nodes.push(lastComment);
  14995. }
  14996. } while (++this.position < stopPosition);
  14997. if (space) {
  14998. if (lastComment) {
  14999. lastComment.spaces.after = space;
  15000. } else if (!this.options.lossy) {
  15001. var firstToken = this.tokens[startPosition];
  15002. var lastToken = this.tokens[this.position - 1];
  15003. nodes.push(new _string["default"]({
  15004. value: '',
  15005. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15006. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15007. spaces: {
  15008. before: space,
  15009. after: ''
  15010. }
  15011. }));
  15012. }
  15013. }
  15014. return nodes;
  15015. }
  15016. /**
  15017. *
  15018. * @param {*} nodes
  15019. */;
  15020. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15021. var _this2 = this;
  15022. if (requiredSpace === void 0) {
  15023. requiredSpace = false;
  15024. }
  15025. var space = "";
  15026. var rawSpace = "";
  15027. nodes.forEach(function (n) {
  15028. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15029. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15030. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15031. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15032. });
  15033. if (rawSpace === space) {
  15034. rawSpace = undefined;
  15035. }
  15036. var result = {
  15037. space: space,
  15038. rawSpace: rawSpace
  15039. };
  15040. return result;
  15041. };
  15042. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15043. if (position === void 0) {
  15044. position = this.position;
  15045. }
  15046. 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;
  15047. };
  15048. _proto.namedCombinator = function namedCombinator() {
  15049. if (this.isNamedCombinator()) {
  15050. var nameRaw = this.content(this.tokens[this.position + 1]);
  15051. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15052. var raws = {};
  15053. if (name !== nameRaw) {
  15054. raws.value = "/" + nameRaw + "/";
  15055. }
  15056. var node = new _combinator["default"]({
  15057. value: "/" + name + "/",
  15058. 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]),
  15059. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15060. raws: raws
  15061. });
  15062. this.position = this.position + 3;
  15063. return node;
  15064. } else {
  15065. this.unexpected();
  15066. }
  15067. };
  15068. _proto.combinator = function combinator() {
  15069. var _this3 = this;
  15070. if (this.content() === '|') {
  15071. return this.namespace();
  15072. }
  15073. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15074. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15075. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15076. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15077. if (nodes.length > 0) {
  15078. var last = this.current.last;
  15079. if (last) {
  15080. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15081. space = _this$convertWhitespa.space,
  15082. rawSpace = _this$convertWhitespa.rawSpace;
  15083. if (rawSpace !== undefined) {
  15084. last.rawSpaceAfter += rawSpace;
  15085. }
  15086. last.spaces.after += space;
  15087. } else {
  15088. nodes.forEach(function (n) {
  15089. return _this3.newNode(n);
  15090. });
  15091. }
  15092. }
  15093. return;
  15094. }
  15095. var firstToken = this.currToken;
  15096. var spaceOrDescendantSelectorNodes = undefined;
  15097. if (nextSigTokenPos > this.position) {
  15098. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15099. }
  15100. var node;
  15101. if (this.isNamedCombinator()) {
  15102. node = this.namedCombinator();
  15103. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15104. node = new _combinator["default"]({
  15105. value: this.content(),
  15106. source: getTokenSource(this.currToken),
  15107. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15108. });
  15109. this.position++;
  15110. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15111. this.unexpected();
  15112. }
  15113. if (node) {
  15114. if (spaceOrDescendantSelectorNodes) {
  15115. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15116. _space = _this$convertWhitespa2.space,
  15117. _rawSpace = _this$convertWhitespa2.rawSpace;
  15118. node.spaces.before = _space;
  15119. node.rawSpaceBefore = _rawSpace;
  15120. }
  15121. } else {
  15122. // descendant combinator
  15123. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15124. _space2 = _this$convertWhitespa3.space,
  15125. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15126. if (!_rawSpace2) {
  15127. _rawSpace2 = _space2;
  15128. }
  15129. var spaces = {};
  15130. var raws = {
  15131. spaces: {}
  15132. };
  15133. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15134. spaces.before = _space2.slice(0, _space2.length - 1);
  15135. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15136. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15137. spaces.after = _space2.slice(1);
  15138. raws.spaces.after = _rawSpace2.slice(1);
  15139. } else {
  15140. raws.value = _rawSpace2;
  15141. }
  15142. node = new _combinator["default"]({
  15143. value: ' ',
  15144. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15145. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15146. spaces: spaces,
  15147. raws: raws
  15148. });
  15149. }
  15150. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15151. node.spaces.after = this.optionalSpace(this.content());
  15152. this.position++;
  15153. }
  15154. return this.newNode(node);
  15155. };
  15156. _proto.comma = function comma() {
  15157. if (this.position === this.tokens.length - 1) {
  15158. this.root.trailingComma = true;
  15159. this.position++;
  15160. return;
  15161. }
  15162. this.current._inferEndPosition();
  15163. var selector = new _selector["default"]({
  15164. source: {
  15165. start: tokenStart(this.tokens[this.position + 1])
  15166. },
  15167. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15168. });
  15169. this.current.parent.append(selector);
  15170. this.current = selector;
  15171. this.position++;
  15172. };
  15173. _proto.comment = function comment() {
  15174. var current = this.currToken;
  15175. this.newNode(new _comment["default"]({
  15176. value: this.content(),
  15177. source: getTokenSource(current),
  15178. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15179. }));
  15180. this.position++;
  15181. };
  15182. _proto.error = function error(message, opts) {
  15183. throw this.root.error(message, opts);
  15184. };
  15185. _proto.missingBackslash = function missingBackslash() {
  15186. return this.error('Expected a backslash preceding the semicolon.', {
  15187. index: this.currToken[_tokenize.FIELDS.START_POS]
  15188. });
  15189. };
  15190. _proto.missingParenthesis = function missingParenthesis() {
  15191. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15192. };
  15193. _proto.missingSquareBracket = function missingSquareBracket() {
  15194. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15195. };
  15196. _proto.unexpected = function unexpected() {
  15197. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15198. };
  15199. _proto.unexpectedPipe = function unexpectedPipe() {
  15200. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15201. };
  15202. _proto.namespace = function namespace() {
  15203. var before = this.prevToken && this.content(this.prevToken) || true;
  15204. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15205. this.position++;
  15206. return this.word(before);
  15207. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15208. this.position++;
  15209. return this.universal(before);
  15210. }
  15211. this.unexpectedPipe();
  15212. };
  15213. _proto.nesting = function nesting() {
  15214. if (this.nextToken) {
  15215. var nextContent = this.content(this.nextToken);
  15216. if (nextContent === "|") {
  15217. this.position++;
  15218. return;
  15219. }
  15220. }
  15221. var current = this.currToken;
  15222. this.newNode(new _nesting["default"]({
  15223. value: this.content(),
  15224. source: getTokenSource(current),
  15225. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15226. }));
  15227. this.position++;
  15228. };
  15229. _proto.parentheses = function parentheses() {
  15230. var last = this.current.last;
  15231. var unbalanced = 1;
  15232. this.position++;
  15233. if (last && last.type === types.PSEUDO) {
  15234. var selector = new _selector["default"]({
  15235. source: {
  15236. start: tokenStart(this.tokens[this.position])
  15237. },
  15238. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15239. });
  15240. var cache = this.current;
  15241. last.append(selector);
  15242. this.current = selector;
  15243. while (this.position < this.tokens.length && unbalanced) {
  15244. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15245. unbalanced++;
  15246. }
  15247. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15248. unbalanced--;
  15249. }
  15250. if (unbalanced) {
  15251. this.parse();
  15252. } else {
  15253. this.current.source.end = tokenEnd(this.currToken);
  15254. this.current.parent.source.end = tokenEnd(this.currToken);
  15255. this.position++;
  15256. }
  15257. }
  15258. this.current = cache;
  15259. } else {
  15260. // I think this case should be an error. It's used to implement a basic parse of media queries
  15261. // but I don't think it's a good idea.
  15262. var parenStart = this.currToken;
  15263. var parenValue = "(";
  15264. var parenEnd;
  15265. while (this.position < this.tokens.length && unbalanced) {
  15266. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15267. unbalanced++;
  15268. }
  15269. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15270. unbalanced--;
  15271. }
  15272. parenEnd = this.currToken;
  15273. parenValue += this.parseParenthesisToken(this.currToken);
  15274. this.position++;
  15275. }
  15276. if (last) {
  15277. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15278. } else {
  15279. this.newNode(new _string["default"]({
  15280. value: parenValue,
  15281. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15282. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15283. }));
  15284. }
  15285. }
  15286. if (unbalanced) {
  15287. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15288. }
  15289. };
  15290. _proto.pseudo = function pseudo() {
  15291. var _this4 = this;
  15292. var pseudoStr = '';
  15293. var startingToken = this.currToken;
  15294. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15295. pseudoStr += this.content();
  15296. this.position++;
  15297. }
  15298. if (!this.currToken) {
  15299. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15300. }
  15301. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15302. this.splitWord(false, function (first, length) {
  15303. pseudoStr += first;
  15304. _this4.newNode(new _pseudo["default"]({
  15305. value: pseudoStr,
  15306. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15307. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15308. }));
  15309. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15310. _this4.error('Misplaced parenthesis.', {
  15311. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15312. });
  15313. }
  15314. });
  15315. } else {
  15316. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15317. }
  15318. };
  15319. _proto.space = function space() {
  15320. var content = this.content();
  15321. // Handle space before and after the selector
  15322. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15323. return node.type === 'comment';
  15324. })) {
  15325. this.spaces = this.optionalSpace(content);
  15326. this.position++;
  15327. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15328. this.current.last.spaces.after = this.optionalSpace(content);
  15329. this.position++;
  15330. } else {
  15331. this.combinator();
  15332. }
  15333. };
  15334. _proto.string = function string() {
  15335. var current = this.currToken;
  15336. this.newNode(new _string["default"]({
  15337. value: this.content(),
  15338. source: getTokenSource(current),
  15339. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15340. }));
  15341. this.position++;
  15342. };
  15343. _proto.universal = function universal(namespace) {
  15344. var nextToken = this.nextToken;
  15345. if (nextToken && this.content(nextToken) === '|') {
  15346. this.position++;
  15347. return this.namespace();
  15348. }
  15349. var current = this.currToken;
  15350. this.newNode(new _universal["default"]({
  15351. value: this.content(),
  15352. source: getTokenSource(current),
  15353. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15354. }), namespace);
  15355. this.position++;
  15356. };
  15357. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15358. var _this5 = this;
  15359. var nextToken = this.nextToken;
  15360. var word = this.content();
  15361. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15362. this.position++;
  15363. var current = this.content();
  15364. word += current;
  15365. if (current.lastIndexOf('\\') === current.length - 1) {
  15366. var next = this.nextToken;
  15367. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15368. word += this.requiredSpace(this.content(next));
  15369. this.position++;
  15370. }
  15371. }
  15372. nextToken = this.nextToken;
  15373. }
  15374. var hasClass = indexesOf(word, '.').filter(function (i) {
  15375. // Allow escaped dot within class name
  15376. var escapedDot = word[i - 1] === '\\';
  15377. // Allow decimal numbers percent in @keyframes
  15378. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15379. return !escapedDot && !isKeyframesPercent;
  15380. });
  15381. var hasId = indexesOf(word, '#').filter(function (i) {
  15382. return word[i - 1] !== '\\';
  15383. });
  15384. // Eliminate Sass interpolations from the list of id indexes
  15385. var interpolations = indexesOf(word, '#{');
  15386. if (interpolations.length) {
  15387. hasId = hasId.filter(function (hashIndex) {
  15388. return !~interpolations.indexOf(hashIndex);
  15389. });
  15390. }
  15391. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15392. indices.forEach(function (ind, i) {
  15393. var index = indices[i + 1] || word.length;
  15394. var value = word.slice(ind, index);
  15395. if (i === 0 && firstCallback) {
  15396. return firstCallback.call(_this5, value, indices.length);
  15397. }
  15398. var node;
  15399. var current = _this5.currToken;
  15400. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15401. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15402. if (~hasClass.indexOf(ind)) {
  15403. var classNameOpts = {
  15404. value: value.slice(1),
  15405. source: source,
  15406. sourceIndex: sourceIndex
  15407. };
  15408. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15409. } else if (~hasId.indexOf(ind)) {
  15410. var idOpts = {
  15411. value: value.slice(1),
  15412. source: source,
  15413. sourceIndex: sourceIndex
  15414. };
  15415. node = new _id["default"](unescapeProp(idOpts, "value"));
  15416. } else {
  15417. var tagOpts = {
  15418. value: value,
  15419. source: source,
  15420. sourceIndex: sourceIndex
  15421. };
  15422. unescapeProp(tagOpts, "value");
  15423. node = new _tag["default"](tagOpts);
  15424. }
  15425. _this5.newNode(node, namespace);
  15426. // Ensure that the namespace is used only once
  15427. namespace = null;
  15428. });
  15429. this.position++;
  15430. };
  15431. _proto.word = function word(namespace) {
  15432. var nextToken = this.nextToken;
  15433. if (nextToken && this.content(nextToken) === '|') {
  15434. this.position++;
  15435. return this.namespace();
  15436. }
  15437. return this.splitWord(namespace);
  15438. };
  15439. _proto.loop = function loop() {
  15440. while (this.position < this.tokens.length) {
  15441. this.parse(true);
  15442. }
  15443. this.current._inferEndPosition();
  15444. return this.root;
  15445. };
  15446. _proto.parse = function parse(throwOnParenthesis) {
  15447. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  15448. case tokens.space:
  15449. this.space();
  15450. break;
  15451. case tokens.comment:
  15452. this.comment();
  15453. break;
  15454. case tokens.openParenthesis:
  15455. this.parentheses();
  15456. break;
  15457. case tokens.closeParenthesis:
  15458. if (throwOnParenthesis) {
  15459. this.missingParenthesis();
  15460. }
  15461. break;
  15462. case tokens.openSquare:
  15463. this.attribute();
  15464. break;
  15465. case tokens.dollar:
  15466. case tokens.caret:
  15467. case tokens.equals:
  15468. case tokens.word:
  15469. this.word();
  15470. break;
  15471. case tokens.colon:
  15472. this.pseudo();
  15473. break;
  15474. case tokens.comma:
  15475. this.comma();
  15476. break;
  15477. case tokens.asterisk:
  15478. this.universal();
  15479. break;
  15480. case tokens.ampersand:
  15481. this.nesting();
  15482. break;
  15483. case tokens.slash:
  15484. case tokens.combinator:
  15485. this.combinator();
  15486. break;
  15487. case tokens.str:
  15488. this.string();
  15489. break;
  15490. // These cases throw; no break needed.
  15491. case tokens.closeSquare:
  15492. this.missingSquareBracket();
  15493. case tokens.semicolon:
  15494. this.missingBackslash();
  15495. default:
  15496. this.unexpected();
  15497. }
  15498. }
  15499. /**
  15500. * Helpers
  15501. */;
  15502. _proto.expected = function expected(description, index, found) {
  15503. if (Array.isArray(description)) {
  15504. var last = description.pop();
  15505. description = description.join(', ') + " or " + last;
  15506. }
  15507. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  15508. if (!found) {
  15509. return this.error("Expected " + an + " " + description + ".", {
  15510. index: index
  15511. });
  15512. }
  15513. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  15514. index: index
  15515. });
  15516. };
  15517. _proto.requiredSpace = function requiredSpace(space) {
  15518. return this.options.lossy ? ' ' : space;
  15519. };
  15520. _proto.optionalSpace = function optionalSpace(space) {
  15521. return this.options.lossy ? '' : space;
  15522. };
  15523. _proto.lossySpace = function lossySpace(space, required) {
  15524. if (this.options.lossy) {
  15525. return required ? ' ' : '';
  15526. } else {
  15527. return space;
  15528. }
  15529. };
  15530. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  15531. var content = this.content(token);
  15532. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  15533. return this.requiredSpace(content);
  15534. } else {
  15535. return content;
  15536. }
  15537. };
  15538. _proto.newNode = function newNode(node, namespace) {
  15539. if (namespace) {
  15540. if (/^ +$/.test(namespace)) {
  15541. if (!this.options.lossy) {
  15542. this.spaces = (this.spaces || '') + namespace;
  15543. }
  15544. namespace = true;
  15545. }
  15546. node.namespace = namespace;
  15547. unescapeProp(node, "namespace");
  15548. }
  15549. if (this.spaces) {
  15550. node.spaces.before = this.spaces;
  15551. this.spaces = '';
  15552. }
  15553. return this.current.append(node);
  15554. };
  15555. _proto.content = function content(token) {
  15556. if (token === void 0) {
  15557. token = this.currToken;
  15558. }
  15559. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  15560. };
  15561. /**
  15562. * returns the index of the next non-whitespace, non-comment token.
  15563. * returns -1 if no meaningful token is found.
  15564. */
  15565. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  15566. if (startPosition === void 0) {
  15567. startPosition = this.position + 1;
  15568. }
  15569. var searchPosition = startPosition;
  15570. while (searchPosition < this.tokens.length) {
  15571. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  15572. searchPosition++;
  15573. continue;
  15574. } else {
  15575. return searchPosition;
  15576. }
  15577. }
  15578. return -1;
  15579. };
  15580. _createClass(Parser, [{
  15581. key: "currToken",
  15582. get: function get() {
  15583. return this.tokens[this.position];
  15584. }
  15585. }, {
  15586. key: "nextToken",
  15587. get: function get() {
  15588. return this.tokens[this.position + 1];
  15589. }
  15590. }, {
  15591. key: "prevToken",
  15592. get: function get() {
  15593. return this.tokens[this.position - 1];
  15594. }
  15595. }]);
  15596. return Parser;
  15597. }();
  15598. exports["default"] = Parser;
  15599. module.exports = exports.default;
  15600. } (parser, parser.exports));
  15601. return parser.exports;
  15602. }
  15603. var hasRequiredProcessor;
  15604. function requireProcessor () {
  15605. if (hasRequiredProcessor) return processor.exports;
  15606. hasRequiredProcessor = 1;
  15607. (function (module, exports) {
  15608. exports.__esModule = true;
  15609. exports["default"] = void 0;
  15610. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  15611. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15612. var Processor = /*#__PURE__*/function () {
  15613. function Processor(func, options) {
  15614. this.func = func || function noop() {};
  15615. this.funcRes = null;
  15616. this.options = options;
  15617. }
  15618. var _proto = Processor.prototype;
  15619. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  15620. if (options === void 0) {
  15621. options = {};
  15622. }
  15623. var merged = Object.assign({}, this.options, options);
  15624. if (merged.updateSelector === false) {
  15625. return false;
  15626. } else {
  15627. return typeof rule !== "string";
  15628. }
  15629. };
  15630. _proto._isLossy = function _isLossy(options) {
  15631. if (options === void 0) {
  15632. options = {};
  15633. }
  15634. var merged = Object.assign({}, this.options, options);
  15635. if (merged.lossless === false) {
  15636. return true;
  15637. } else {
  15638. return false;
  15639. }
  15640. };
  15641. _proto._root = function _root(rule, options) {
  15642. if (options === void 0) {
  15643. options = {};
  15644. }
  15645. var parser = new _parser["default"](rule, this._parseOptions(options));
  15646. return parser.root;
  15647. };
  15648. _proto._parseOptions = function _parseOptions(options) {
  15649. return {
  15650. lossy: this._isLossy(options)
  15651. };
  15652. };
  15653. _proto._run = function _run(rule, options) {
  15654. var _this = this;
  15655. if (options === void 0) {
  15656. options = {};
  15657. }
  15658. return new Promise(function (resolve, reject) {
  15659. try {
  15660. var root = _this._root(rule, options);
  15661. Promise.resolve(_this.func(root)).then(function (transform) {
  15662. var string = undefined;
  15663. if (_this._shouldUpdateSelector(rule, options)) {
  15664. string = root.toString();
  15665. rule.selector = string;
  15666. }
  15667. return {
  15668. transform: transform,
  15669. root: root,
  15670. string: string
  15671. };
  15672. }).then(resolve, reject);
  15673. } catch (e) {
  15674. reject(e);
  15675. return;
  15676. }
  15677. });
  15678. };
  15679. _proto._runSync = function _runSync(rule, options) {
  15680. if (options === void 0) {
  15681. options = {};
  15682. }
  15683. var root = this._root(rule, options);
  15684. var transform = this.func(root);
  15685. if (transform && typeof transform.then === "function") {
  15686. throw new Error("Selector processor returned a promise to a synchronous call.");
  15687. }
  15688. var string = undefined;
  15689. if (options.updateSelector && typeof rule !== "string") {
  15690. string = root.toString();
  15691. rule.selector = string;
  15692. }
  15693. return {
  15694. transform: transform,
  15695. root: root,
  15696. string: string
  15697. };
  15698. }
  15699. /**
  15700. * Process rule into a selector AST.
  15701. *
  15702. * @param rule {postcss.Rule | string} The css selector to be processed
  15703. * @param options The options for processing
  15704. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  15705. */;
  15706. _proto.ast = function ast(rule, options) {
  15707. return this._run(rule, options).then(function (result) {
  15708. return result.root;
  15709. });
  15710. }
  15711. /**
  15712. * Process rule into a selector AST synchronously.
  15713. *
  15714. * @param rule {postcss.Rule | string} The css selector to be processed
  15715. * @param options The options for processing
  15716. * @returns {parser.Root} The AST of the selector after processing it.
  15717. */;
  15718. _proto.astSync = function astSync(rule, options) {
  15719. return this._runSync(rule, options).root;
  15720. }
  15721. /**
  15722. * Process a selector into a transformed value asynchronously
  15723. *
  15724. * @param rule {postcss.Rule | string} The css selector to be processed
  15725. * @param options The options for processing
  15726. * @returns {Promise<any>} The value returned by the processor.
  15727. */;
  15728. _proto.transform = function transform(rule, options) {
  15729. return this._run(rule, options).then(function (result) {
  15730. return result.transform;
  15731. });
  15732. }
  15733. /**
  15734. * Process a selector into a transformed value synchronously.
  15735. *
  15736. * @param rule {postcss.Rule | string} The css selector to be processed
  15737. * @param options The options for processing
  15738. * @returns {any} The value returned by the processor.
  15739. */;
  15740. _proto.transformSync = function transformSync(rule, options) {
  15741. return this._runSync(rule, options).transform;
  15742. }
  15743. /**
  15744. * Process a selector into a new selector string asynchronously.
  15745. *
  15746. * @param rule {postcss.Rule | string} The css selector to be processed
  15747. * @param options The options for processing
  15748. * @returns {string} the selector after processing.
  15749. */;
  15750. _proto.process = function process(rule, options) {
  15751. return this._run(rule, options).then(function (result) {
  15752. return result.string || result.root.toString();
  15753. });
  15754. }
  15755. /**
  15756. * Process a selector into a new selector string synchronously.
  15757. *
  15758. * @param rule {postcss.Rule | string} The css selector to be processed
  15759. * @param options The options for processing
  15760. * @returns {string} the selector after processing.
  15761. */;
  15762. _proto.processSync = function processSync(rule, options) {
  15763. var result = this._runSync(rule, options);
  15764. return result.string || result.root.toString();
  15765. };
  15766. return Processor;
  15767. }();
  15768. exports["default"] = Processor;
  15769. module.exports = exports.default;
  15770. } (processor, processor.exports));
  15771. return processor.exports;
  15772. }
  15773. var selectors = {};
  15774. var constructors = {};
  15775. var hasRequiredConstructors;
  15776. function requireConstructors () {
  15777. if (hasRequiredConstructors) return constructors;
  15778. hasRequiredConstructors = 1;
  15779. constructors.__esModule = true;
  15780. 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;
  15781. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  15782. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15783. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15784. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15785. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15786. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15787. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15788. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15789. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15790. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15791. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15792. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15793. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15794. var attribute = function attribute(opts) {
  15795. return new _attribute["default"](opts);
  15796. };
  15797. constructors.attribute = attribute;
  15798. var className = function className(opts) {
  15799. return new _className["default"](opts);
  15800. };
  15801. constructors.className = className;
  15802. var combinator = function combinator(opts) {
  15803. return new _combinator["default"](opts);
  15804. };
  15805. constructors.combinator = combinator;
  15806. var comment = function comment(opts) {
  15807. return new _comment["default"](opts);
  15808. };
  15809. constructors.comment = comment;
  15810. var id = function id(opts) {
  15811. return new _id["default"](opts);
  15812. };
  15813. constructors.id = id;
  15814. var nesting = function nesting(opts) {
  15815. return new _nesting["default"](opts);
  15816. };
  15817. constructors.nesting = nesting;
  15818. var pseudo = function pseudo(opts) {
  15819. return new _pseudo["default"](opts);
  15820. };
  15821. constructors.pseudo = pseudo;
  15822. var root = function root(opts) {
  15823. return new _root["default"](opts);
  15824. };
  15825. constructors.root = root;
  15826. var selector = function selector(opts) {
  15827. return new _selector["default"](opts);
  15828. };
  15829. constructors.selector = selector;
  15830. var string = function string(opts) {
  15831. return new _string["default"](opts);
  15832. };
  15833. constructors.string = string;
  15834. var tag = function tag(opts) {
  15835. return new _tag["default"](opts);
  15836. };
  15837. constructors.tag = tag;
  15838. var universal = function universal(opts) {
  15839. return new _universal["default"](opts);
  15840. };
  15841. constructors.universal = universal;
  15842. return constructors;
  15843. }
  15844. var guards = {};
  15845. var hasRequiredGuards;
  15846. function requireGuards () {
  15847. if (hasRequiredGuards) return guards;
  15848. hasRequiredGuards = 1;
  15849. guards.__esModule = true;
  15850. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  15851. guards.isContainer = isContainer;
  15852. guards.isIdentifier = void 0;
  15853. guards.isNamespace = isNamespace;
  15854. guards.isNesting = void 0;
  15855. guards.isNode = isNode;
  15856. guards.isPseudo = void 0;
  15857. guards.isPseudoClass = isPseudoClass;
  15858. guards.isPseudoElement = isPseudoElement;
  15859. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  15860. var _types = /*@__PURE__*/ requireTypes();
  15861. var _IS_TYPE;
  15862. 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);
  15863. function isNode(node) {
  15864. return typeof node === "object" && IS_TYPE[node.type];
  15865. }
  15866. function isNodeType(type, node) {
  15867. return isNode(node) && node.type === type;
  15868. }
  15869. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  15870. guards.isAttribute = isAttribute;
  15871. var isClassName = isNodeType.bind(null, _types.CLASS);
  15872. guards.isClassName = isClassName;
  15873. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  15874. guards.isCombinator = isCombinator;
  15875. var isComment = isNodeType.bind(null, _types.COMMENT);
  15876. guards.isComment = isComment;
  15877. var isIdentifier = isNodeType.bind(null, _types.ID);
  15878. guards.isIdentifier = isIdentifier;
  15879. var isNesting = isNodeType.bind(null, _types.NESTING);
  15880. guards.isNesting = isNesting;
  15881. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  15882. guards.isPseudo = isPseudo;
  15883. var isRoot = isNodeType.bind(null, _types.ROOT);
  15884. guards.isRoot = isRoot;
  15885. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  15886. guards.isSelector = isSelector;
  15887. var isString = isNodeType.bind(null, _types.STRING);
  15888. guards.isString = isString;
  15889. var isTag = isNodeType.bind(null, _types.TAG);
  15890. guards.isTag = isTag;
  15891. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  15892. guards.isUniversal = isUniversal;
  15893. function isPseudoElement(node) {
  15894. 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");
  15895. }
  15896. function isPseudoClass(node) {
  15897. return isPseudo(node) && !isPseudoElement(node);
  15898. }
  15899. function isContainer(node) {
  15900. return !!(isNode(node) && node.walk);
  15901. }
  15902. function isNamespace(node) {
  15903. return isAttribute(node) || isTag(node);
  15904. }
  15905. return guards;
  15906. }
  15907. var hasRequiredSelectors;
  15908. function requireSelectors () {
  15909. if (hasRequiredSelectors) return selectors;
  15910. hasRequiredSelectors = 1;
  15911. (function (exports) {
  15912. exports.__esModule = true;
  15913. var _types = /*@__PURE__*/ requireTypes();
  15914. Object.keys(_types).forEach(function (key) {
  15915. if (key === "default" || key === "__esModule") return;
  15916. if (key in exports && exports[key] === _types[key]) return;
  15917. exports[key] = _types[key];
  15918. });
  15919. var _constructors = /*@__PURE__*/ requireConstructors();
  15920. Object.keys(_constructors).forEach(function (key) {
  15921. if (key === "default" || key === "__esModule") return;
  15922. if (key in exports && exports[key] === _constructors[key]) return;
  15923. exports[key] = _constructors[key];
  15924. });
  15925. var _guards = /*@__PURE__*/ requireGuards();
  15926. Object.keys(_guards).forEach(function (key) {
  15927. if (key === "default" || key === "__esModule") return;
  15928. if (key in exports && exports[key] === _guards[key]) return;
  15929. exports[key] = _guards[key];
  15930. });
  15931. } (selectors));
  15932. return selectors;
  15933. }
  15934. var hasRequiredDist;
  15935. function requireDist () {
  15936. if (hasRequiredDist) return dist.exports;
  15937. hasRequiredDist = 1;
  15938. (function (module, exports) {
  15939. exports.__esModule = true;
  15940. exports["default"] = void 0;
  15941. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  15942. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  15943. 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); }
  15944. 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; }
  15945. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15946. var parser = function parser(processor) {
  15947. return new _processor["default"](processor);
  15948. };
  15949. Object.assign(parser, selectors);
  15950. delete parser.__esModule;
  15951. var _default = parser;
  15952. exports["default"] = _default;
  15953. module.exports = exports.default;
  15954. } (dist, dist.exports));
  15955. return dist.exports;
  15956. }
  15957. var parse;
  15958. var hasRequiredParse;
  15959. function requireParse () {
  15960. if (hasRequiredParse) return parse;
  15961. hasRequiredParse = 1;
  15962. var openParentheses = "(".charCodeAt(0);
  15963. var closeParentheses = ")".charCodeAt(0);
  15964. var singleQuote = "'".charCodeAt(0);
  15965. var doubleQuote = '"'.charCodeAt(0);
  15966. var backslash = "\\".charCodeAt(0);
  15967. var slash = "/".charCodeAt(0);
  15968. var comma = ",".charCodeAt(0);
  15969. var colon = ":".charCodeAt(0);
  15970. var star = "*".charCodeAt(0);
  15971. var uLower = "u".charCodeAt(0);
  15972. var uUpper = "U".charCodeAt(0);
  15973. var plus = "+".charCodeAt(0);
  15974. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  15975. parse = function(input) {
  15976. var tokens = [];
  15977. var value = input;
  15978. var next,
  15979. quote,
  15980. prev,
  15981. token,
  15982. escape,
  15983. escapePos,
  15984. whitespacePos,
  15985. parenthesesOpenPos;
  15986. var pos = 0;
  15987. var code = value.charCodeAt(pos);
  15988. var max = value.length;
  15989. var stack = [{ nodes: tokens }];
  15990. var balanced = 0;
  15991. var parent;
  15992. var name = "";
  15993. var before = "";
  15994. var after = "";
  15995. while (pos < max) {
  15996. // Whitespaces
  15997. if (code <= 32) {
  15998. next = pos;
  15999. do {
  16000. next += 1;
  16001. code = value.charCodeAt(next);
  16002. } while (code <= 32);
  16003. token = value.slice(pos, next);
  16004. prev = tokens[tokens.length - 1];
  16005. if (code === closeParentheses && balanced) {
  16006. after = token;
  16007. } else if (prev && prev.type === "div") {
  16008. prev.after = token;
  16009. prev.sourceEndIndex += token.length;
  16010. } else if (
  16011. code === comma ||
  16012. code === colon ||
  16013. (code === slash &&
  16014. value.charCodeAt(next + 1) !== star &&
  16015. (!parent ||
  16016. (parent && parent.type === "function" && parent.value !== "calc")))
  16017. ) {
  16018. before = token;
  16019. } else {
  16020. tokens.push({
  16021. type: "space",
  16022. sourceIndex: pos,
  16023. sourceEndIndex: next,
  16024. value: token
  16025. });
  16026. }
  16027. pos = next;
  16028. // Quotes
  16029. } else if (code === singleQuote || code === doubleQuote) {
  16030. next = pos;
  16031. quote = code === singleQuote ? "'" : '"';
  16032. token = {
  16033. type: "string",
  16034. sourceIndex: pos,
  16035. quote: quote
  16036. };
  16037. do {
  16038. escape = false;
  16039. next = value.indexOf(quote, next + 1);
  16040. if (~next) {
  16041. escapePos = next;
  16042. while (value.charCodeAt(escapePos - 1) === backslash) {
  16043. escapePos -= 1;
  16044. escape = !escape;
  16045. }
  16046. } else {
  16047. value += quote;
  16048. next = value.length - 1;
  16049. token.unclosed = true;
  16050. }
  16051. } while (escape);
  16052. token.value = value.slice(pos + 1, next);
  16053. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16054. tokens.push(token);
  16055. pos = next + 1;
  16056. code = value.charCodeAt(pos);
  16057. // Comments
  16058. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16059. next = value.indexOf("*/", pos);
  16060. token = {
  16061. type: "comment",
  16062. sourceIndex: pos,
  16063. sourceEndIndex: next + 2
  16064. };
  16065. if (next === -1) {
  16066. token.unclosed = true;
  16067. next = value.length;
  16068. token.sourceEndIndex = next;
  16069. }
  16070. token.value = value.slice(pos + 2, next);
  16071. tokens.push(token);
  16072. pos = next + 2;
  16073. code = value.charCodeAt(pos);
  16074. // Operation within calc
  16075. } else if (
  16076. (code === slash || code === star) &&
  16077. parent &&
  16078. parent.type === "function" &&
  16079. parent.value === "calc"
  16080. ) {
  16081. token = value[pos];
  16082. tokens.push({
  16083. type: "word",
  16084. sourceIndex: pos - before.length,
  16085. sourceEndIndex: pos + token.length,
  16086. value: token
  16087. });
  16088. pos += 1;
  16089. code = value.charCodeAt(pos);
  16090. // Dividers
  16091. } else if (code === slash || code === comma || code === colon) {
  16092. token = value[pos];
  16093. tokens.push({
  16094. type: "div",
  16095. sourceIndex: pos - before.length,
  16096. sourceEndIndex: pos + token.length,
  16097. value: token,
  16098. before: before,
  16099. after: ""
  16100. });
  16101. before = "";
  16102. pos += 1;
  16103. code = value.charCodeAt(pos);
  16104. // Open parentheses
  16105. } else if (openParentheses === code) {
  16106. // Whitespaces after open parentheses
  16107. next = pos;
  16108. do {
  16109. next += 1;
  16110. code = value.charCodeAt(next);
  16111. } while (code <= 32);
  16112. parenthesesOpenPos = pos;
  16113. token = {
  16114. type: "function",
  16115. sourceIndex: pos - name.length,
  16116. value: name,
  16117. before: value.slice(parenthesesOpenPos + 1, next)
  16118. };
  16119. pos = next;
  16120. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16121. next -= 1;
  16122. do {
  16123. escape = false;
  16124. next = value.indexOf(")", next + 1);
  16125. if (~next) {
  16126. escapePos = next;
  16127. while (value.charCodeAt(escapePos - 1) === backslash) {
  16128. escapePos -= 1;
  16129. escape = !escape;
  16130. }
  16131. } else {
  16132. value += ")";
  16133. next = value.length - 1;
  16134. token.unclosed = true;
  16135. }
  16136. } while (escape);
  16137. // Whitespaces before closed
  16138. whitespacePos = next;
  16139. do {
  16140. whitespacePos -= 1;
  16141. code = value.charCodeAt(whitespacePos);
  16142. } while (code <= 32);
  16143. if (parenthesesOpenPos < whitespacePos) {
  16144. if (pos !== whitespacePos + 1) {
  16145. token.nodes = [
  16146. {
  16147. type: "word",
  16148. sourceIndex: pos,
  16149. sourceEndIndex: whitespacePos + 1,
  16150. value: value.slice(pos, whitespacePos + 1)
  16151. }
  16152. ];
  16153. } else {
  16154. token.nodes = [];
  16155. }
  16156. if (token.unclosed && whitespacePos + 1 !== next) {
  16157. token.after = "";
  16158. token.nodes.push({
  16159. type: "space",
  16160. sourceIndex: whitespacePos + 1,
  16161. sourceEndIndex: next,
  16162. value: value.slice(whitespacePos + 1, next)
  16163. });
  16164. } else {
  16165. token.after = value.slice(whitespacePos + 1, next);
  16166. token.sourceEndIndex = next;
  16167. }
  16168. } else {
  16169. token.after = "";
  16170. token.nodes = [];
  16171. }
  16172. pos = next + 1;
  16173. token.sourceEndIndex = token.unclosed ? next : pos;
  16174. code = value.charCodeAt(pos);
  16175. tokens.push(token);
  16176. } else {
  16177. balanced += 1;
  16178. token.after = "";
  16179. token.sourceEndIndex = pos + 1;
  16180. tokens.push(token);
  16181. stack.push(token);
  16182. tokens = token.nodes = [];
  16183. parent = token;
  16184. }
  16185. name = "";
  16186. // Close parentheses
  16187. } else if (closeParentheses === code && balanced) {
  16188. pos += 1;
  16189. code = value.charCodeAt(pos);
  16190. parent.after = after;
  16191. parent.sourceEndIndex += after.length;
  16192. after = "";
  16193. balanced -= 1;
  16194. stack[stack.length - 1].sourceEndIndex = pos;
  16195. stack.pop();
  16196. parent = stack[balanced];
  16197. tokens = parent.nodes;
  16198. // Words
  16199. } else {
  16200. next = pos;
  16201. do {
  16202. if (code === backslash) {
  16203. next += 1;
  16204. }
  16205. next += 1;
  16206. code = value.charCodeAt(next);
  16207. } while (
  16208. next < max &&
  16209. !(
  16210. code <= 32 ||
  16211. code === singleQuote ||
  16212. code === doubleQuote ||
  16213. code === comma ||
  16214. code === colon ||
  16215. code === slash ||
  16216. code === openParentheses ||
  16217. (code === star &&
  16218. parent &&
  16219. parent.type === "function" &&
  16220. parent.value === "calc") ||
  16221. (code === slash &&
  16222. parent.type === "function" &&
  16223. parent.value === "calc") ||
  16224. (code === closeParentheses && balanced)
  16225. )
  16226. );
  16227. token = value.slice(pos, next);
  16228. if (openParentheses === code) {
  16229. name = token;
  16230. } else if (
  16231. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16232. plus === token.charCodeAt(1) &&
  16233. isUnicodeRange.test(token.slice(2))
  16234. ) {
  16235. tokens.push({
  16236. type: "unicode-range",
  16237. sourceIndex: pos,
  16238. sourceEndIndex: next,
  16239. value: token
  16240. });
  16241. } else {
  16242. tokens.push({
  16243. type: "word",
  16244. sourceIndex: pos,
  16245. sourceEndIndex: next,
  16246. value: token
  16247. });
  16248. }
  16249. pos = next;
  16250. }
  16251. }
  16252. for (pos = stack.length - 1; pos; pos -= 1) {
  16253. stack[pos].unclosed = true;
  16254. stack[pos].sourceEndIndex = value.length;
  16255. }
  16256. return stack[0].nodes;
  16257. };
  16258. return parse;
  16259. }
  16260. var walk$1;
  16261. var hasRequiredWalk;
  16262. function requireWalk () {
  16263. if (hasRequiredWalk) return walk$1;
  16264. hasRequiredWalk = 1;
  16265. walk$1 = function walk(nodes, cb, bubble) {
  16266. var i, max, node, result;
  16267. for (i = 0, max = nodes.length; i < max; i += 1) {
  16268. node = nodes[i];
  16269. if (!bubble) {
  16270. result = cb(node, i, nodes);
  16271. }
  16272. if (
  16273. result !== false &&
  16274. node.type === "function" &&
  16275. Array.isArray(node.nodes)
  16276. ) {
  16277. walk(node.nodes, cb, bubble);
  16278. }
  16279. if (bubble) {
  16280. cb(node, i, nodes);
  16281. }
  16282. }
  16283. };
  16284. return walk$1;
  16285. }
  16286. var stringify_1;
  16287. var hasRequiredStringify;
  16288. function requireStringify () {
  16289. if (hasRequiredStringify) return stringify_1;
  16290. hasRequiredStringify = 1;
  16291. function stringifyNode(node, custom) {
  16292. var type = node.type;
  16293. var value = node.value;
  16294. var buf;
  16295. var customResult;
  16296. if (custom && (customResult = custom(node)) !== undefined) {
  16297. return customResult;
  16298. } else if (type === "word" || type === "space") {
  16299. return value;
  16300. } else if (type === "string") {
  16301. buf = node.quote || "";
  16302. return buf + value + (node.unclosed ? "" : buf);
  16303. } else if (type === "comment") {
  16304. return "/*" + value + (node.unclosed ? "" : "*/");
  16305. } else if (type === "div") {
  16306. return (node.before || "") + value + (node.after || "");
  16307. } else if (Array.isArray(node.nodes)) {
  16308. buf = stringify(node.nodes, custom);
  16309. if (type !== "function") {
  16310. return buf;
  16311. }
  16312. return (
  16313. value +
  16314. "(" +
  16315. (node.before || "") +
  16316. buf +
  16317. (node.after || "") +
  16318. (node.unclosed ? "" : ")")
  16319. );
  16320. }
  16321. return value;
  16322. }
  16323. function stringify(nodes, custom) {
  16324. var result, i;
  16325. if (Array.isArray(nodes)) {
  16326. result = "";
  16327. for (i = nodes.length - 1; ~i; i -= 1) {
  16328. result = stringifyNode(nodes[i], custom) + result;
  16329. }
  16330. return result;
  16331. }
  16332. return stringifyNode(nodes, custom);
  16333. }
  16334. stringify_1 = stringify;
  16335. return stringify_1;
  16336. }
  16337. var unit;
  16338. var hasRequiredUnit;
  16339. function requireUnit () {
  16340. if (hasRequiredUnit) return unit;
  16341. hasRequiredUnit = 1;
  16342. var minus = "-".charCodeAt(0);
  16343. var plus = "+".charCodeAt(0);
  16344. var dot = ".".charCodeAt(0);
  16345. var exp = "e".charCodeAt(0);
  16346. var EXP = "E".charCodeAt(0);
  16347. // Check if three code points would start a number
  16348. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16349. function likeNumber(value) {
  16350. var code = value.charCodeAt(0);
  16351. var nextCode;
  16352. if (code === plus || code === minus) {
  16353. nextCode = value.charCodeAt(1);
  16354. if (nextCode >= 48 && nextCode <= 57) {
  16355. return true;
  16356. }
  16357. var nextNextCode = value.charCodeAt(2);
  16358. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16359. return true;
  16360. }
  16361. return false;
  16362. }
  16363. if (code === dot) {
  16364. nextCode = value.charCodeAt(1);
  16365. if (nextCode >= 48 && nextCode <= 57) {
  16366. return true;
  16367. }
  16368. return false;
  16369. }
  16370. if (code >= 48 && code <= 57) {
  16371. return true;
  16372. }
  16373. return false;
  16374. }
  16375. // Consume a number
  16376. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16377. unit = function(value) {
  16378. var pos = 0;
  16379. var length = value.length;
  16380. var code;
  16381. var nextCode;
  16382. var nextNextCode;
  16383. if (length === 0 || !likeNumber(value)) {
  16384. return false;
  16385. }
  16386. code = value.charCodeAt(pos);
  16387. if (code === plus || code === minus) {
  16388. pos++;
  16389. }
  16390. while (pos < length) {
  16391. code = value.charCodeAt(pos);
  16392. if (code < 48 || code > 57) {
  16393. break;
  16394. }
  16395. pos += 1;
  16396. }
  16397. code = value.charCodeAt(pos);
  16398. nextCode = value.charCodeAt(pos + 1);
  16399. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16400. pos += 2;
  16401. while (pos < length) {
  16402. code = value.charCodeAt(pos);
  16403. if (code < 48 || code > 57) {
  16404. break;
  16405. }
  16406. pos += 1;
  16407. }
  16408. }
  16409. code = value.charCodeAt(pos);
  16410. nextCode = value.charCodeAt(pos + 1);
  16411. nextNextCode = value.charCodeAt(pos + 2);
  16412. if (
  16413. (code === exp || code === EXP) &&
  16414. ((nextCode >= 48 && nextCode <= 57) ||
  16415. ((nextCode === plus || nextCode === minus) &&
  16416. nextNextCode >= 48 &&
  16417. nextNextCode <= 57))
  16418. ) {
  16419. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16420. while (pos < length) {
  16421. code = value.charCodeAt(pos);
  16422. if (code < 48 || code > 57) {
  16423. break;
  16424. }
  16425. pos += 1;
  16426. }
  16427. }
  16428. return {
  16429. number: value.slice(0, pos),
  16430. unit: value.slice(pos)
  16431. };
  16432. };
  16433. return unit;
  16434. }
  16435. var lib;
  16436. var hasRequiredLib;
  16437. function requireLib () {
  16438. if (hasRequiredLib) return lib;
  16439. hasRequiredLib = 1;
  16440. var parse = /*@__PURE__*/ requireParse();
  16441. var walk = /*@__PURE__*/ requireWalk();
  16442. var stringify = /*@__PURE__*/ requireStringify();
  16443. function ValueParser(value) {
  16444. if (this instanceof ValueParser) {
  16445. this.nodes = parse(value);
  16446. return this;
  16447. }
  16448. return new ValueParser(value);
  16449. }
  16450. ValueParser.prototype.toString = function() {
  16451. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  16452. };
  16453. ValueParser.prototype.walk = function(cb, bubble) {
  16454. walk(this.nodes, cb, bubble);
  16455. return this;
  16456. };
  16457. ValueParser.unit = /*@__PURE__*/ requireUnit();
  16458. ValueParser.walk = walk;
  16459. ValueParser.stringify = stringify;
  16460. lib = ValueParser;
  16461. return lib;
  16462. }
  16463. var hasRequiredSrc$2;
  16464. function requireSrc$2 () {
  16465. if (hasRequiredSrc$2) return src$2.exports;
  16466. hasRequiredSrc$2 = 1;
  16467. const selectorParser = /*@__PURE__*/ requireDist();
  16468. const valueParser = /*@__PURE__*/ requireLib();
  16469. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  16470. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  16471. function normalizeNodeArray(nodes) {
  16472. const array = [];
  16473. nodes.forEach((x) => {
  16474. if (Array.isArray(x)) {
  16475. normalizeNodeArray(x).forEach((item) => {
  16476. array.push(item);
  16477. });
  16478. } else if (x) {
  16479. array.push(x);
  16480. }
  16481. });
  16482. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  16483. array.pop();
  16484. }
  16485. return array;
  16486. }
  16487. function localizeNode(rule, mode, localAliasMap) {
  16488. const transform = (node, context) => {
  16489. if (context.ignoreNextSpacing && !isSpacing(node)) {
  16490. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  16491. }
  16492. if (context.enforceNoSpacing && isSpacing(node)) {
  16493. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  16494. }
  16495. let newNodes;
  16496. switch (node.type) {
  16497. case "root": {
  16498. let resultingGlobal;
  16499. context.hasPureGlobals = false;
  16500. newNodes = node.nodes.map((n) => {
  16501. const nContext = {
  16502. global: context.global,
  16503. lastWasSpacing: true,
  16504. hasLocals: false,
  16505. explicit: false,
  16506. };
  16507. n = transform(n, nContext);
  16508. if (typeof resultingGlobal === "undefined") {
  16509. resultingGlobal = nContext.global;
  16510. } else if (resultingGlobal !== nContext.global) {
  16511. throw new Error(
  16512. 'Inconsistent rule global/local result in rule "' +
  16513. node +
  16514. '" (multiple selectors must result in the same mode for the rule)'
  16515. );
  16516. }
  16517. if (!nContext.hasLocals) {
  16518. context.hasPureGlobals = true;
  16519. }
  16520. return n;
  16521. });
  16522. context.global = resultingGlobal;
  16523. node.nodes = normalizeNodeArray(newNodes);
  16524. break;
  16525. }
  16526. case "selector": {
  16527. newNodes = node.map((childNode) => transform(childNode, context));
  16528. node = node.clone();
  16529. node.nodes = normalizeNodeArray(newNodes);
  16530. break;
  16531. }
  16532. case "combinator": {
  16533. if (isSpacing(node)) {
  16534. if (context.ignoreNextSpacing) {
  16535. context.ignoreNextSpacing = false;
  16536. context.lastWasSpacing = false;
  16537. context.enforceNoSpacing = false;
  16538. return null;
  16539. }
  16540. context.lastWasSpacing = true;
  16541. return node;
  16542. }
  16543. break;
  16544. }
  16545. case "pseudo": {
  16546. let childContext;
  16547. const isNested = !!node.length;
  16548. const isScoped = node.value === ":local" || node.value === ":global";
  16549. const isImportExport =
  16550. node.value === ":import" || node.value === ":export";
  16551. if (isImportExport) {
  16552. context.hasLocals = true;
  16553. // :local(.foo)
  16554. } else if (isNested) {
  16555. if (isScoped) {
  16556. if (node.nodes.length === 0) {
  16557. throw new Error(`${node.value}() can't be empty`);
  16558. }
  16559. if (context.inside) {
  16560. throw new Error(
  16561. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16562. );
  16563. }
  16564. childContext = {
  16565. global: node.value === ":global",
  16566. inside: node.value,
  16567. hasLocals: false,
  16568. explicit: true,
  16569. };
  16570. newNodes = node
  16571. .map((childNode) => transform(childNode, childContext))
  16572. .reduce((acc, next) => acc.concat(next.nodes), []);
  16573. if (newNodes.length) {
  16574. const { before, after } = node.spaces;
  16575. const first = newNodes[0];
  16576. const last = newNodes[newNodes.length - 1];
  16577. first.spaces = { before, after: first.spaces.after };
  16578. last.spaces = { before: last.spaces.before, after };
  16579. }
  16580. node = newNodes;
  16581. break;
  16582. } else {
  16583. childContext = {
  16584. global: context.global,
  16585. inside: context.inside,
  16586. lastWasSpacing: true,
  16587. hasLocals: false,
  16588. explicit: context.explicit,
  16589. };
  16590. newNodes = node.map((childNode) => {
  16591. const newContext = {
  16592. ...childContext,
  16593. enforceNoSpacing: false,
  16594. };
  16595. const result = transform(childNode, newContext);
  16596. childContext.global = newContext.global;
  16597. childContext.hasLocals = newContext.hasLocals;
  16598. return result;
  16599. });
  16600. node = node.clone();
  16601. node.nodes = normalizeNodeArray(newNodes);
  16602. if (childContext.hasLocals) {
  16603. context.hasLocals = true;
  16604. }
  16605. }
  16606. break;
  16607. //:local .foo .bar
  16608. } else if (isScoped) {
  16609. if (context.inside) {
  16610. throw new Error(
  16611. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16612. );
  16613. }
  16614. const addBackSpacing = !!node.spaces.before;
  16615. context.ignoreNextSpacing = context.lastWasSpacing
  16616. ? node.value
  16617. : false;
  16618. context.enforceNoSpacing = context.lastWasSpacing
  16619. ? false
  16620. : node.value;
  16621. context.global = node.value === ":global";
  16622. context.explicit = true;
  16623. // because this node has spacing that is lost when we remove it
  16624. // we make up for it by adding an extra combinator in since adding
  16625. // spacing on the parent selector doesn't work
  16626. return addBackSpacing
  16627. ? selectorParser.combinator({ value: " " })
  16628. : null;
  16629. }
  16630. break;
  16631. }
  16632. case "id":
  16633. case "class": {
  16634. if (!node.value) {
  16635. throw new Error("Invalid class or id selector syntax");
  16636. }
  16637. if (context.global) {
  16638. break;
  16639. }
  16640. const isImportedValue = localAliasMap.has(node.value);
  16641. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  16642. if (!isImportedValue || isImportedWithExplicitScope) {
  16643. const innerNode = node.clone();
  16644. innerNode.spaces = { before: "", after: "" };
  16645. node = selectorParser.pseudo({
  16646. value: ":local",
  16647. nodes: [innerNode],
  16648. spaces: node.spaces,
  16649. });
  16650. context.hasLocals = true;
  16651. }
  16652. break;
  16653. }
  16654. case "nesting": {
  16655. if (node.value === "&") {
  16656. context.hasLocals = true;
  16657. }
  16658. }
  16659. }
  16660. context.lastWasSpacing = false;
  16661. context.ignoreNextSpacing = false;
  16662. context.enforceNoSpacing = false;
  16663. return node;
  16664. };
  16665. const rootContext = {
  16666. global: mode === "global",
  16667. hasPureGlobals: false,
  16668. };
  16669. rootContext.selector = selectorParser((root) => {
  16670. transform(root, rootContext);
  16671. }).processSync(rule, { updateSelector: false, lossless: true });
  16672. return rootContext;
  16673. }
  16674. function localizeDeclNode(node, context) {
  16675. switch (node.type) {
  16676. case "word":
  16677. if (context.localizeNextItem) {
  16678. if (!context.localAliasMap.has(node.value)) {
  16679. node.value = ":local(" + node.value + ")";
  16680. context.localizeNextItem = false;
  16681. }
  16682. }
  16683. break;
  16684. case "function":
  16685. if (
  16686. context.options &&
  16687. context.options.rewriteUrl &&
  16688. node.value.toLowerCase() === "url"
  16689. ) {
  16690. node.nodes.map((nestedNode) => {
  16691. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  16692. return;
  16693. }
  16694. let newUrl = context.options.rewriteUrl(
  16695. context.global,
  16696. nestedNode.value
  16697. );
  16698. switch (nestedNode.type) {
  16699. case "string":
  16700. if (nestedNode.quote === "'") {
  16701. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  16702. }
  16703. if (nestedNode.quote === '"') {
  16704. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  16705. }
  16706. break;
  16707. case "word":
  16708. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  16709. break;
  16710. }
  16711. nestedNode.value = newUrl;
  16712. });
  16713. }
  16714. break;
  16715. }
  16716. return node;
  16717. }
  16718. // `none` is special value, other is global values
  16719. const specialKeywords = [
  16720. "none",
  16721. "inherit",
  16722. "initial",
  16723. "revert",
  16724. "revert-layer",
  16725. "unset",
  16726. ];
  16727. function localizeDeclarationValues(localize, declaration, context) {
  16728. const valueNodes = valueParser(declaration.value);
  16729. valueNodes.walk((node, index, nodes) => {
  16730. if (
  16731. node.type === "function" &&
  16732. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  16733. ) {
  16734. return false;
  16735. }
  16736. if (
  16737. node.type === "word" &&
  16738. specialKeywords.includes(node.value.toLowerCase())
  16739. ) {
  16740. return;
  16741. }
  16742. const subContext = {
  16743. options: context.options,
  16744. global: context.global,
  16745. localizeNextItem: localize && !context.global,
  16746. localAliasMap: context.localAliasMap,
  16747. };
  16748. nodes[index] = localizeDeclNode(node, subContext);
  16749. });
  16750. declaration.value = valueNodes.toString();
  16751. }
  16752. function localizeDeclaration(declaration, context) {
  16753. const isAnimation = /animation$/i.test(declaration.prop);
  16754. if (isAnimation) {
  16755. // letter
  16756. // An uppercase letter or a lowercase letter.
  16757. //
  16758. // ident-start code point
  16759. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  16760. //
  16761. // ident code point
  16762. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  16763. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  16764. const validIdent =
  16765. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  16766. /*
  16767. The spec defines some keywords that you can use to describe properties such as the timing
  16768. function. These are still valid animation names, so as long as there is a property that accepts
  16769. a keyword, it is given priority. Only when all the properties that can take a keyword are
  16770. exhausted can the animation name be set to the keyword. I.e.
  16771. animation: infinite infinite;
  16772. The animation will repeat an infinite number of times from the first argument, and will have an
  16773. animation name of infinite from the second.
  16774. */
  16775. const animationKeywords = {
  16776. // animation-direction
  16777. $normal: 1,
  16778. $reverse: 1,
  16779. $alternate: 1,
  16780. "$alternate-reverse": 1,
  16781. // animation-fill-mode
  16782. $forwards: 1,
  16783. $backwards: 1,
  16784. $both: 1,
  16785. // animation-iteration-count
  16786. $infinite: 1,
  16787. // animation-play-state
  16788. $paused: 1,
  16789. $running: 1,
  16790. // animation-timing-function
  16791. $ease: 1,
  16792. "$ease-in": 1,
  16793. "$ease-out": 1,
  16794. "$ease-in-out": 1,
  16795. $linear: 1,
  16796. "$step-end": 1,
  16797. "$step-start": 1,
  16798. // Special
  16799. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  16800. // Global values
  16801. $initial: Infinity,
  16802. $inherit: Infinity,
  16803. $unset: Infinity,
  16804. $revert: Infinity,
  16805. "$revert-layer": Infinity,
  16806. };
  16807. let parsedAnimationKeywords = {};
  16808. const valueNodes = valueParser(declaration.value).walk((node) => {
  16809. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  16810. if (node.type === "div") {
  16811. parsedAnimationKeywords = {};
  16812. return;
  16813. }
  16814. // Do not handle nested functions
  16815. else if (node.type === "function") {
  16816. return false;
  16817. }
  16818. // Ignore all except word
  16819. else if (node.type !== "word") {
  16820. return;
  16821. }
  16822. const value = node.type === "word" ? node.value.toLowerCase() : null;
  16823. let shouldParseAnimationName = false;
  16824. if (value && validIdent.test(value)) {
  16825. if ("$" + value in animationKeywords) {
  16826. parsedAnimationKeywords["$" + value] =
  16827. "$" + value in parsedAnimationKeywords
  16828. ? parsedAnimationKeywords["$" + value] + 1
  16829. : 0;
  16830. shouldParseAnimationName =
  16831. parsedAnimationKeywords["$" + value] >=
  16832. animationKeywords["$" + value];
  16833. } else {
  16834. shouldParseAnimationName = true;
  16835. }
  16836. }
  16837. const subContext = {
  16838. options: context.options,
  16839. global: context.global,
  16840. localizeNextItem: shouldParseAnimationName && !context.global,
  16841. localAliasMap: context.localAliasMap,
  16842. };
  16843. return localizeDeclNode(node, subContext);
  16844. });
  16845. declaration.value = valueNodes.toString();
  16846. return;
  16847. }
  16848. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  16849. if (isAnimationName) {
  16850. return localizeDeclarationValues(true, declaration, context);
  16851. }
  16852. const hasUrl = /url\(/i.test(declaration.value);
  16853. if (hasUrl) {
  16854. return localizeDeclarationValues(false, declaration, context);
  16855. }
  16856. }
  16857. src$2.exports = (options = {}) => {
  16858. if (
  16859. options &&
  16860. options.mode &&
  16861. options.mode !== "global" &&
  16862. options.mode !== "local" &&
  16863. options.mode !== "pure"
  16864. ) {
  16865. throw new Error(
  16866. 'options.mode must be either "global", "local" or "pure" (default "local")'
  16867. );
  16868. }
  16869. const pureMode = options && options.mode === "pure";
  16870. const globalMode = options && options.mode === "global";
  16871. return {
  16872. postcssPlugin: "postcss-modules-local-by-default",
  16873. prepare() {
  16874. const localAliasMap = new Map();
  16875. return {
  16876. Once(root) {
  16877. const { icssImports } = extractICSS(root, false);
  16878. Object.keys(icssImports).forEach((key) => {
  16879. Object.keys(icssImports[key]).forEach((prop) => {
  16880. localAliasMap.set(prop, icssImports[key][prop]);
  16881. });
  16882. });
  16883. root.walkAtRules((atRule) => {
  16884. if (/keyframes$/i.test(atRule.name)) {
  16885. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  16886. atRule.params
  16887. );
  16888. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  16889. atRule.params
  16890. );
  16891. let globalKeyframes = globalMode;
  16892. if (globalMatch) {
  16893. if (pureMode) {
  16894. throw atRule.error(
  16895. "@keyframes :global(...) is not allowed in pure mode"
  16896. );
  16897. }
  16898. atRule.params = globalMatch[1];
  16899. globalKeyframes = true;
  16900. } else if (localMatch) {
  16901. atRule.params = localMatch[0];
  16902. globalKeyframes = false;
  16903. } else if (
  16904. atRule.params &&
  16905. !globalMode &&
  16906. !localAliasMap.has(atRule.params)
  16907. ) {
  16908. atRule.params = ":local(" + atRule.params + ")";
  16909. }
  16910. atRule.walkDecls((declaration) => {
  16911. localizeDeclaration(declaration, {
  16912. localAliasMap,
  16913. options: options,
  16914. global: globalKeyframes,
  16915. });
  16916. });
  16917. } else if (/scope$/i.test(atRule.name)) {
  16918. if (atRule.params) {
  16919. atRule.params = atRule.params
  16920. .split("to")
  16921. .map((item) => {
  16922. const selector = item.trim().slice(1, -1).trim();
  16923. const context = localizeNode(
  16924. selector,
  16925. options.mode,
  16926. localAliasMap
  16927. );
  16928. context.options = options;
  16929. context.localAliasMap = localAliasMap;
  16930. if (pureMode && context.hasPureGlobals) {
  16931. throw atRule.error(
  16932. 'Selector in at-rule"' +
  16933. selector +
  16934. '" is not pure ' +
  16935. "(pure selectors must contain at least one local class or id)"
  16936. );
  16937. }
  16938. return `(${context.selector})`;
  16939. })
  16940. .join(" to ");
  16941. }
  16942. atRule.nodes.forEach((declaration) => {
  16943. if (declaration.type === "decl") {
  16944. localizeDeclaration(declaration, {
  16945. localAliasMap,
  16946. options: options,
  16947. global: globalMode,
  16948. });
  16949. }
  16950. });
  16951. } else if (atRule.nodes) {
  16952. atRule.nodes.forEach((declaration) => {
  16953. if (declaration.type === "decl") {
  16954. localizeDeclaration(declaration, {
  16955. localAliasMap,
  16956. options: options,
  16957. global: globalMode,
  16958. });
  16959. }
  16960. });
  16961. }
  16962. });
  16963. root.walkRules((rule) => {
  16964. if (
  16965. rule.parent &&
  16966. rule.parent.type === "atrule" &&
  16967. /keyframes$/i.test(rule.parent.name)
  16968. ) {
  16969. // ignore keyframe rules
  16970. return;
  16971. }
  16972. const context = localizeNode(rule, options.mode, localAliasMap);
  16973. context.options = options;
  16974. context.localAliasMap = localAliasMap;
  16975. if (pureMode && context.hasPureGlobals) {
  16976. throw rule.error(
  16977. 'Selector "' +
  16978. rule.selector +
  16979. '" is not pure ' +
  16980. "(pure selectors must contain at least one local class or id)"
  16981. );
  16982. }
  16983. rule.selector = context.selector;
  16984. // Less-syntax mixins parse as rules with no nodes
  16985. if (rule.nodes) {
  16986. rule.nodes.forEach((declaration) =>
  16987. localizeDeclaration(declaration, context)
  16988. );
  16989. }
  16990. });
  16991. },
  16992. };
  16993. },
  16994. };
  16995. };
  16996. src$2.exports.postcss = true;
  16997. return src$2.exports;
  16998. }
  16999. var src$1;
  17000. var hasRequiredSrc$1;
  17001. function requireSrc$1 () {
  17002. if (hasRequiredSrc$1) return src$1;
  17003. hasRequiredSrc$1 = 1;
  17004. const selectorParser = /*@__PURE__*/ requireDist();
  17005. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17006. function isNestedRule(rule) {
  17007. if (!rule.parent || rule.parent.type === "root") {
  17008. return false;
  17009. }
  17010. if (rule.parent.type === "rule") {
  17011. return true;
  17012. }
  17013. return isNestedRule(rule.parent);
  17014. }
  17015. function getSingleLocalNamesForComposes(root, rule) {
  17016. if (isNestedRule(rule)) {
  17017. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17018. }
  17019. return root.nodes.map((node) => {
  17020. if (node.type !== "selector" || node.nodes.length !== 1) {
  17021. throw new Error(
  17022. `composition is only allowed when selector is single :local class name not in "${root}"`
  17023. );
  17024. }
  17025. node = node.nodes[0];
  17026. if (
  17027. node.type !== "pseudo" ||
  17028. node.value !== ":local" ||
  17029. node.nodes.length !== 1
  17030. ) {
  17031. throw new Error(
  17032. 'composition is only allowed when selector is single :local class name not in "' +
  17033. root +
  17034. '", "' +
  17035. node +
  17036. '" is weird'
  17037. );
  17038. }
  17039. node = node.first;
  17040. if (node.type !== "selector" || node.length !== 1) {
  17041. throw new Error(
  17042. 'composition is only allowed when selector is single :local class name not in "' +
  17043. root +
  17044. '", "' +
  17045. node +
  17046. '" is weird'
  17047. );
  17048. }
  17049. node = node.first;
  17050. if (node.type !== "class") {
  17051. // 'id' is not possible, because you can't compose ids
  17052. throw new Error(
  17053. 'composition is only allowed when selector is single :local class name not in "' +
  17054. root +
  17055. '", "' +
  17056. node +
  17057. '" is weird'
  17058. );
  17059. }
  17060. return node.value;
  17061. });
  17062. }
  17063. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17064. const unescapeRegExp = new RegExp(
  17065. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17066. "ig"
  17067. );
  17068. function unescape(str) {
  17069. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17070. const high = "0x" + escaped - 0x10000;
  17071. // NaN means non-codepoint
  17072. // Workaround erroneous numeric interpretation of +"0x"
  17073. return high !== high || escapedWhitespace
  17074. ? escaped
  17075. : high < 0
  17076. ? // BMP codepoint
  17077. String.fromCharCode(high + 0x10000)
  17078. : // Supplemental Plane codepoint (surrogate pair)
  17079. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17080. });
  17081. }
  17082. const plugin = (options = {}) => {
  17083. const generateScopedName =
  17084. (options && options.generateScopedName) || plugin.generateScopedName;
  17085. const generateExportEntry =
  17086. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17087. const exportGlobals = options && options.exportGlobals;
  17088. return {
  17089. postcssPlugin: "postcss-modules-scope",
  17090. Once(root, { rule }) {
  17091. const exports = Object.create(null);
  17092. function exportScopedName(name, rawName, node) {
  17093. const scopedName = generateScopedName(
  17094. rawName ? rawName : name,
  17095. root.source.input.from,
  17096. root.source.input.css,
  17097. node
  17098. );
  17099. const exportEntry = generateExportEntry(
  17100. rawName ? rawName : name,
  17101. scopedName,
  17102. root.source.input.from,
  17103. root.source.input.css,
  17104. node
  17105. );
  17106. const { key, value } = exportEntry;
  17107. exports[key] = exports[key] || [];
  17108. if (exports[key].indexOf(value) < 0) {
  17109. exports[key].push(value);
  17110. }
  17111. return scopedName;
  17112. }
  17113. function localizeNode(node) {
  17114. switch (node.type) {
  17115. case "selector":
  17116. node.nodes = node.map((item) => localizeNode(item));
  17117. return node;
  17118. case "class":
  17119. return selectorParser.className({
  17120. value: exportScopedName(
  17121. node.value,
  17122. node.raws && node.raws.value ? node.raws.value : null,
  17123. node
  17124. ),
  17125. });
  17126. case "id": {
  17127. return selectorParser.id({
  17128. value: exportScopedName(
  17129. node.value,
  17130. node.raws && node.raws.value ? node.raws.value : null,
  17131. node
  17132. ),
  17133. });
  17134. }
  17135. case "attribute": {
  17136. if (node.attribute === "class" && node.operator === "=") {
  17137. return selectorParser.attribute({
  17138. attribute: node.attribute,
  17139. operator: node.operator,
  17140. quoteMark: "'",
  17141. value: exportScopedName(node.value, null, null),
  17142. });
  17143. }
  17144. }
  17145. }
  17146. throw new Error(
  17147. `${node.type} ("${node}") is not allowed in a :local block`
  17148. );
  17149. }
  17150. function traverseNode(node) {
  17151. switch (node.type) {
  17152. case "pseudo":
  17153. if (node.value === ":local") {
  17154. if (node.nodes.length !== 1) {
  17155. throw new Error('Unexpected comma (",") in :local block');
  17156. }
  17157. const selector = localizeNode(node.first);
  17158. // move the spaces that were around the pseudo selector to the first
  17159. // non-container node
  17160. selector.first.spaces = node.spaces;
  17161. const nextNode = node.next();
  17162. if (
  17163. nextNode &&
  17164. nextNode.type === "combinator" &&
  17165. nextNode.value === " " &&
  17166. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17167. ) {
  17168. selector.last.spaces.after = " ";
  17169. }
  17170. node.replaceWith(selector);
  17171. return;
  17172. }
  17173. /* falls through */
  17174. case "root":
  17175. case "selector": {
  17176. node.each((item) => traverseNode(item));
  17177. break;
  17178. }
  17179. case "id":
  17180. case "class":
  17181. if (exportGlobals) {
  17182. exports[node.value] = [node.value];
  17183. }
  17184. break;
  17185. }
  17186. return node;
  17187. }
  17188. // Find any :import and remember imported names
  17189. const importedNames = {};
  17190. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17191. rule.walkDecls((decl) => {
  17192. importedNames[decl.prop] = true;
  17193. });
  17194. });
  17195. // Find any :local selectors
  17196. root.walkRules((rule) => {
  17197. let parsedSelector = selectorParser().astSync(rule);
  17198. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17199. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17200. const localNames = getSingleLocalNamesForComposes(
  17201. parsedSelector,
  17202. decl.parent
  17203. );
  17204. const multiple = decl.value.split(",");
  17205. multiple.forEach((value) => {
  17206. const classes = value.trim().split(/\s+/);
  17207. classes.forEach((className) => {
  17208. const global = /^global\(([^)]+)\)$/.exec(className);
  17209. if (global) {
  17210. localNames.forEach((exportedName) => {
  17211. exports[exportedName].push(global[1]);
  17212. });
  17213. } else if (hasOwnProperty.call(importedNames, className)) {
  17214. localNames.forEach((exportedName) => {
  17215. exports[exportedName].push(className);
  17216. });
  17217. } else if (hasOwnProperty.call(exports, className)) {
  17218. localNames.forEach((exportedName) => {
  17219. exports[className].forEach((item) => {
  17220. exports[exportedName].push(item);
  17221. });
  17222. });
  17223. } else {
  17224. throw decl.error(
  17225. `referenced class name "${className}" in ${decl.prop} not found`
  17226. );
  17227. }
  17228. });
  17229. });
  17230. decl.remove();
  17231. });
  17232. // Find any :local values
  17233. rule.walkDecls((decl) => {
  17234. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17235. return;
  17236. }
  17237. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17238. tokens = tokens.map((token, idx) => {
  17239. if (idx === 0 || tokens[idx - 1] === ",") {
  17240. let result = token;
  17241. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17242. if (localMatch) {
  17243. const input = localMatch.input;
  17244. const matchPattern = localMatch[0];
  17245. const matchVal = localMatch[1];
  17246. const newVal = exportScopedName(matchVal);
  17247. result = input.replace(matchPattern, newVal);
  17248. } else {
  17249. return token;
  17250. }
  17251. return result;
  17252. } else {
  17253. return token;
  17254. }
  17255. });
  17256. decl.value = tokens.join("");
  17257. });
  17258. });
  17259. // Find any :local keyframes
  17260. root.walkAtRules(/keyframes$/i, (atRule) => {
  17261. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17262. if (!localMatch) {
  17263. return;
  17264. }
  17265. atRule.params = exportScopedName(localMatch[1]);
  17266. });
  17267. root.walkAtRules(/scope$/i, (atRule) => {
  17268. if (atRule.params) {
  17269. atRule.params = atRule.params
  17270. .split("to")
  17271. .map((item) => {
  17272. const selector = item.trim().slice(1, -1).trim();
  17273. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17274. if (!localMatch) {
  17275. return `(${selector})`;
  17276. }
  17277. let parsedSelector = selectorParser().astSync(selector);
  17278. return `(${traverseNode(parsedSelector).toString()})`;
  17279. })
  17280. .join(" to ");
  17281. }
  17282. });
  17283. // If we found any :locals, insert an :export rule
  17284. const exportedNames = Object.keys(exports);
  17285. if (exportedNames.length > 0) {
  17286. const exportRule = rule({ selector: ":export" });
  17287. exportedNames.forEach((exportedName) =>
  17288. exportRule.append({
  17289. prop: exportedName,
  17290. value: exports[exportedName].join(" "),
  17291. raws: { before: "\n " },
  17292. })
  17293. );
  17294. root.append(exportRule);
  17295. }
  17296. },
  17297. };
  17298. };
  17299. plugin.postcss = true;
  17300. plugin.generateScopedName = function (name, path) {
  17301. const sanitisedPath = path
  17302. .replace(/\.[^./\\]+$/, "")
  17303. .replace(/[\W_]+/g, "_")
  17304. .replace(/^_|_$/g, "");
  17305. return `_${sanitisedPath}__${name}`.trim();
  17306. };
  17307. plugin.generateExportEntry = function (name, scopedName) {
  17308. return {
  17309. key: unescape(name),
  17310. value: unescape(scopedName),
  17311. };
  17312. };
  17313. src$1 = plugin;
  17314. return src$1;
  17315. }
  17316. var stringHash;
  17317. var hasRequiredStringHash;
  17318. function requireStringHash () {
  17319. if (hasRequiredStringHash) return stringHash;
  17320. hasRequiredStringHash = 1;
  17321. function hash(str) {
  17322. var hash = 5381,
  17323. i = str.length;
  17324. while(i) {
  17325. hash = (hash * 33) ^ str.charCodeAt(--i);
  17326. }
  17327. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17328. * integers. Since we want the results to be always positive, convert the
  17329. * signed int to an unsigned by doing an unsigned bitshift. */
  17330. return hash >>> 0;
  17331. }
  17332. stringHash = hash;
  17333. return stringHash;
  17334. }
  17335. var src = {exports: {}};
  17336. var hasRequiredSrc;
  17337. function requireSrc () {
  17338. if (hasRequiredSrc) return src.exports;
  17339. hasRequiredSrc = 1;
  17340. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17341. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17342. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17343. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17344. src.exports = (options) => {
  17345. let importIndex = 0;
  17346. const createImportedName =
  17347. (options && options.createImportedName) ||
  17348. ((importName /*, path*/) =>
  17349. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17350. return {
  17351. postcssPlugin: "postcss-modules-values",
  17352. prepare(result) {
  17353. const importAliases = [];
  17354. const definitions = {};
  17355. return {
  17356. Once(root, postcss) {
  17357. root.walkAtRules(/value/i, (atRule) => {
  17358. const matches = atRule.params.match(matchImports);
  17359. if (matches) {
  17360. let [, /*match*/ aliases, path] = matches;
  17361. // We can use constants for path names
  17362. if (definitions[path]) {
  17363. path = definitions[path];
  17364. }
  17365. const imports = aliases
  17366. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17367. .split(/\s*,\s*/)
  17368. .map((alias) => {
  17369. const tokens = matchImport.exec(alias);
  17370. if (tokens) {
  17371. const [, /*match*/ theirName, myName = theirName] = tokens;
  17372. const importedName = createImportedName(myName);
  17373. definitions[myName] = importedName;
  17374. return { theirName, importedName };
  17375. } else {
  17376. throw new Error(`@import statement "${alias}" is invalid!`);
  17377. }
  17378. });
  17379. importAliases.push({ path, imports });
  17380. atRule.remove();
  17381. return;
  17382. }
  17383. if (atRule.params.indexOf("@value") !== -1) {
  17384. result.warn("Invalid value definition: " + atRule.params);
  17385. }
  17386. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17387. matchValueDefinition
  17388. );
  17389. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17390. if (normalizedValue.length === 0) {
  17391. result.warn("Invalid value definition: " + atRule.params);
  17392. atRule.remove();
  17393. return;
  17394. }
  17395. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17396. if (!isOnlySpace) {
  17397. value = value.trim();
  17398. }
  17399. // Add to the definitions, knowing that values can refer to each other
  17400. definitions[key] = ICSSUtils.replaceValueSymbols(
  17401. value,
  17402. definitions
  17403. );
  17404. atRule.remove();
  17405. });
  17406. /* If we have no definitions, don't continue */
  17407. if (!Object.keys(definitions).length) {
  17408. return;
  17409. }
  17410. /* Perform replacements */
  17411. ICSSUtils.replaceSymbols(root, definitions);
  17412. /* 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 */
  17413. const exportDeclarations = Object.keys(definitions).map((key) =>
  17414. postcss.decl({
  17415. value: definitions[key],
  17416. prop: key,
  17417. raws: { before: "\n " },
  17418. })
  17419. );
  17420. /* Add export rules if any */
  17421. if (exportDeclarations.length > 0) {
  17422. const exportRule = postcss.rule({
  17423. selector: ":export",
  17424. raws: { after: "\n" },
  17425. });
  17426. exportRule.append(exportDeclarations);
  17427. root.prepend(exportRule);
  17428. }
  17429. /* Add import rules */
  17430. importAliases.reverse().forEach(({ path, imports }) => {
  17431. const importRule = postcss.rule({
  17432. selector: `:import(${path})`,
  17433. raws: { after: "\n" },
  17434. });
  17435. imports.forEach(({ theirName, importedName }) => {
  17436. importRule.append({
  17437. value: theirName,
  17438. prop: importedName,
  17439. raws: { before: "\n " },
  17440. });
  17441. });
  17442. root.prepend(importRule);
  17443. });
  17444. },
  17445. };
  17446. },
  17447. };
  17448. };
  17449. src.exports.postcss = true;
  17450. return src.exports;
  17451. }
  17452. var hasRequiredScoping;
  17453. function requireScoping () {
  17454. if (hasRequiredScoping) return scoping;
  17455. hasRequiredScoping = 1;
  17456. Object.defineProperty(scoping, "__esModule", {
  17457. value: true
  17458. });
  17459. scoping.behaviours = void 0;
  17460. scoping.getDefaultPlugins = getDefaultPlugins;
  17461. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  17462. scoping.getScopedNameGenerator = getScopedNameGenerator;
  17463. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  17464. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  17465. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  17466. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  17467. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  17468. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  17469. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17470. const behaviours = {
  17471. LOCAL: "local",
  17472. GLOBAL: "global"
  17473. };
  17474. scoping.behaviours = behaviours;
  17475. function getDefaultPlugins({
  17476. behaviour,
  17477. generateScopedName,
  17478. exportGlobals
  17479. }) {
  17480. const scope = (0, _postcssModulesScope.default)({
  17481. generateScopedName,
  17482. exportGlobals
  17483. });
  17484. const plugins = {
  17485. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17486. mode: "local"
  17487. }), _postcssModulesExtractImports.default, scope],
  17488. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17489. mode: "global"
  17490. }), _postcssModulesExtractImports.default, scope]
  17491. };
  17492. return plugins[behaviour];
  17493. }
  17494. function isValidBehaviour(behaviour) {
  17495. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  17496. }
  17497. function getDefaultScopeBehaviour(scopeBehaviour) {
  17498. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  17499. }
  17500. function generateScopedNameDefault(name, filename, css) {
  17501. const i = css.indexOf(`.${name}`);
  17502. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  17503. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  17504. return `_${name}_${hash}_${lineNumber}`;
  17505. }
  17506. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  17507. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  17508. if (typeof scopedNameGenerator === "function") {
  17509. return scopedNameGenerator;
  17510. }
  17511. return (0, _genericNames.default)(scopedNameGenerator, {
  17512. context: process.cwd(),
  17513. hashPrefix: hashPrefix
  17514. });
  17515. }
  17516. return scoping;
  17517. }
  17518. var hasRequiredPluginFactory;
  17519. function requirePluginFactory () {
  17520. if (hasRequiredPluginFactory) return pluginFactory;
  17521. hasRequiredPluginFactory = 1;
  17522. Object.defineProperty(pluginFactory, "__esModule", {
  17523. value: true
  17524. });
  17525. pluginFactory.makePlugin = makePlugin;
  17526. var _postcss = _interopRequireDefault(require$$0$1);
  17527. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  17528. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  17529. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  17530. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  17531. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  17532. var _scoping = /*@__PURE__*/ requireScoping();
  17533. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17534. const PLUGIN_NAME = "postcss-modules";
  17535. function isGlobalModule(globalModules, inputFile) {
  17536. return globalModules.some(regex => inputFile.match(regex));
  17537. }
  17538. function getDefaultPluginsList(opts, inputFile) {
  17539. const globalModulesList = opts.globalModulePaths || null;
  17540. const exportGlobals = opts.exportGlobals || false;
  17541. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  17542. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  17543. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  17544. return (0, _scoping.getDefaultPlugins)({
  17545. behaviour: _scoping.behaviours.GLOBAL,
  17546. generateScopedName,
  17547. exportGlobals
  17548. });
  17549. }
  17550. return (0, _scoping.getDefaultPlugins)({
  17551. behaviour: defaultBehaviour,
  17552. generateScopedName,
  17553. exportGlobals
  17554. });
  17555. }
  17556. function getLoader(opts, plugins) {
  17557. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  17558. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  17559. }
  17560. function isOurPlugin(plugin) {
  17561. return plugin.postcssPlugin === PLUGIN_NAME;
  17562. }
  17563. function makePlugin(opts) {
  17564. return {
  17565. postcssPlugin: PLUGIN_NAME,
  17566. async OnceExit(css, {
  17567. result
  17568. }) {
  17569. const getJSON = opts.getJSON || _saveJSON.default;
  17570. const inputFile = css.source.input.file;
  17571. const pluginList = getDefaultPluginsList(opts, inputFile);
  17572. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  17573. if (resultPluginIndex === -1) {
  17574. throw new Error("Plugin missing from options.");
  17575. }
  17576. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  17577. const loaderPlugins = [...earlierPlugins, ...pluginList];
  17578. const loader = getLoader(opts, loaderPlugins);
  17579. const fetcher = async (file, relativeTo, depTrace) => {
  17580. const unquoteFile = (0, _unquote.default)(file);
  17581. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  17582. };
  17583. const parser = new _Parser.default(fetcher);
  17584. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  17585. from: inputFile
  17586. });
  17587. const out = loader.finalSource;
  17588. if (out) css.prepend(out);
  17589. if (opts.localsConvention) {
  17590. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  17591. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  17592. }
  17593. result.messages.push({
  17594. type: "export",
  17595. plugin: "postcss-modules",
  17596. exportTokens: parser.exportTokens
  17597. }); // getJSON may return a promise
  17598. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  17599. }
  17600. };
  17601. }
  17602. return pluginFactory;
  17603. }
  17604. var hasRequiredBuild;
  17605. function requireBuild () {
  17606. if (hasRequiredBuild) return build.exports;
  17607. hasRequiredBuild = 1;
  17608. var _fs = require$$0;
  17609. var _fs2 = /*@__PURE__*/ requireFs();
  17610. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  17611. (0, _fs2.setFileSystem)({
  17612. readFile: _fs.readFile,
  17613. writeFile: _fs.writeFile
  17614. });
  17615. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  17616. build.exports.postcss = true;
  17617. return build.exports;
  17618. }
  17619. var buildExports = /*@__PURE__*/ requireBuild();
  17620. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  17621. function compileStyle(options) {
  17622. return doCompileStyle({
  17623. ...options,
  17624. isAsync: false
  17625. });
  17626. }
  17627. function compileStyleAsync(options) {
  17628. return doCompileStyle({
  17629. ...options,
  17630. isAsync: true
  17631. });
  17632. }
  17633. function doCompileStyle(options) {
  17634. const {
  17635. filename,
  17636. id,
  17637. scoped = false,
  17638. trim = true,
  17639. isProd = false,
  17640. modules = false,
  17641. modulesOptions = {},
  17642. preprocessLang,
  17643. postcssOptions,
  17644. postcssPlugins
  17645. } = options;
  17646. const preprocessor = preprocessLang && processors[preprocessLang];
  17647. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  17648. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  17649. const source = preProcessedSource ? preProcessedSource.code : options.source;
  17650. const shortId = id.replace(/^data-v-/, "");
  17651. const longId = `data-v-${shortId}`;
  17652. const plugins = (postcssPlugins || []).slice();
  17653. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  17654. if (trim) {
  17655. plugins.push(trimPlugin());
  17656. }
  17657. if (scoped) {
  17658. plugins.push(scopedPlugin(longId));
  17659. }
  17660. let cssModules;
  17661. if (modules) {
  17662. if (!options.isAsync) {
  17663. throw new Error(
  17664. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  17665. );
  17666. }
  17667. plugins.push(
  17668. postcssModules({
  17669. ...modulesOptions,
  17670. getJSON: (_cssFileName, json) => {
  17671. cssModules = json;
  17672. }
  17673. })
  17674. );
  17675. }
  17676. const postCSSOptions = {
  17677. ...postcssOptions,
  17678. to: filename,
  17679. from: filename
  17680. };
  17681. if (map) {
  17682. postCSSOptions.map = {
  17683. inline: false,
  17684. annotation: false,
  17685. prev: map
  17686. };
  17687. }
  17688. let result;
  17689. let code;
  17690. let outMap;
  17691. const dependencies = new Set(
  17692. preProcessedSource ? preProcessedSource.dependencies : []
  17693. );
  17694. dependencies.delete(filename);
  17695. const errors = [];
  17696. if (preProcessedSource && preProcessedSource.errors.length) {
  17697. errors.push(...preProcessedSource.errors);
  17698. }
  17699. const recordPlainCssDependencies = (messages) => {
  17700. messages.forEach((msg) => {
  17701. if (msg.type === "dependency") {
  17702. dependencies.add(msg.file);
  17703. }
  17704. });
  17705. return dependencies;
  17706. };
  17707. try {
  17708. result = require$$0$1(plugins).process(source, postCSSOptions);
  17709. if (options.isAsync) {
  17710. return result.then((result2) => ({
  17711. code: result2.css || "",
  17712. map: result2.map && result2.map.toJSON(),
  17713. errors,
  17714. modules: cssModules,
  17715. rawResult: result2,
  17716. dependencies: recordPlainCssDependencies(result2.messages)
  17717. })).catch((error) => ({
  17718. code: "",
  17719. map: void 0,
  17720. errors: [...errors, error],
  17721. rawResult: void 0,
  17722. dependencies
  17723. }));
  17724. }
  17725. recordPlainCssDependencies(result.messages);
  17726. code = result.css;
  17727. outMap = result.map;
  17728. } catch (e) {
  17729. errors.push(e);
  17730. }
  17731. return {
  17732. code: code || ``,
  17733. map: outMap && outMap.toJSON(),
  17734. errors,
  17735. rawResult: result,
  17736. dependencies
  17737. };
  17738. }
  17739. function preprocess(options, preprocessor) {
  17740. return preprocessor(
  17741. options.source,
  17742. options.inMap || options.map,
  17743. {
  17744. filename: options.filename,
  17745. ...options.preprocessOptions
  17746. },
  17747. options.preprocessCustomRequire
  17748. );
  17749. }
  17750. const UNKNOWN_TYPE = "Unknown";
  17751. function resolveObjectKey(node, computed) {
  17752. switch (node.type) {
  17753. case "StringLiteral":
  17754. case "NumericLiteral":
  17755. return String(node.value);
  17756. case "Identifier":
  17757. if (!computed) return node.name;
  17758. }
  17759. return void 0;
  17760. }
  17761. function concatStrings(strs) {
  17762. return strs.filter((s) => !!s).join(", ");
  17763. }
  17764. function isLiteralNode(node) {
  17765. return node.type.endsWith("Literal");
  17766. }
  17767. function isCallOf(node, test) {
  17768. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  17769. }
  17770. function toRuntimeTypeString(types) {
  17771. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  17772. }
  17773. function getImportedName(specifier) {
  17774. if (specifier.type === "ImportSpecifier")
  17775. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  17776. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  17777. return "default";
  17778. }
  17779. function getId(node) {
  17780. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  17781. }
  17782. const identity = (str) => str;
  17783. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  17784. const toLowerCase = (str) => str.toLowerCase();
  17785. function toFileNameLowerCase(x) {
  17786. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  17787. }
  17788. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  17789. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  17790. }
  17791. const normalize = (path$1.posix || path$1).normalize;
  17792. const windowsSlashRE = /\\/g;
  17793. function normalizePath(p) {
  17794. return normalize(p.replace(windowsSlashRE, "/"));
  17795. }
  17796. const joinPaths = (path$1.posix || path$1).join;
  17797. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  17798. function getEscapedPropName(key) {
  17799. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  17800. }
  17801. function analyzeScriptBindings(ast) {
  17802. for (const node of ast) {
  17803. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  17804. return analyzeBindingsFromOptions(node.declaration);
  17805. }
  17806. }
  17807. return {};
  17808. }
  17809. function analyzeBindingsFromOptions(node) {
  17810. const bindings = {};
  17811. Object.defineProperty(bindings, "__isScriptSetup", {
  17812. enumerable: false,
  17813. value: false
  17814. });
  17815. for (const property of node.properties) {
  17816. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  17817. if (property.key.name === "props") {
  17818. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17819. bindings[key] = "props";
  17820. }
  17821. } else if (property.key.name === "inject") {
  17822. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17823. bindings[key] = "options";
  17824. }
  17825. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  17826. for (const key of getObjectExpressionKeys(property.value)) {
  17827. bindings[key] = "options";
  17828. }
  17829. }
  17830. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  17831. for (const bodyItem of property.body.body) {
  17832. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  17833. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  17834. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  17835. }
  17836. }
  17837. }
  17838. }
  17839. }
  17840. return bindings;
  17841. }
  17842. function getObjectExpressionKeys(node) {
  17843. const keys = [];
  17844. for (const prop of node.properties) {
  17845. if (prop.type === "SpreadElement") continue;
  17846. const key = resolveObjectKey(prop.key, prop.computed);
  17847. if (key) keys.push(String(key));
  17848. }
  17849. return keys;
  17850. }
  17851. function getArrayExpressionKeys(node) {
  17852. const keys = [];
  17853. for (const element of node.elements) {
  17854. if (element && element.type === "StringLiteral") {
  17855. keys.push(element.value);
  17856. }
  17857. }
  17858. return keys;
  17859. }
  17860. function getObjectOrArrayExpressionKeys(value) {
  17861. if (value.type === "ArrayExpression") {
  17862. return getArrayExpressionKeys(value);
  17863. }
  17864. if (value.type === "ObjectExpression") {
  17865. return getObjectExpressionKeys(value);
  17866. }
  17867. return [];
  17868. }
  17869. var _a, _b;
  17870. class ScriptCompileContext {
  17871. constructor(descriptor, options) {
  17872. this.descriptor = descriptor;
  17873. this.options = options;
  17874. this.isCE = false;
  17875. this.source = this.descriptor.source;
  17876. this.filename = this.descriptor.filename;
  17877. this.s = new MagicString(this.source);
  17878. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  17879. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  17880. this.userImports = /* @__PURE__ */ Object.create(null);
  17881. // macros presence check
  17882. this.hasDefinePropsCall = false;
  17883. this.hasDefineEmitCall = false;
  17884. this.hasDefineExposeCall = false;
  17885. this.hasDefaultExportName = false;
  17886. this.hasDefaultExportRender = false;
  17887. this.hasDefineOptionsCall = false;
  17888. this.hasDefineSlotsCall = false;
  17889. this.hasDefineModelCall = false;
  17890. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  17891. // defineModel
  17892. this.modelDecls = /* @__PURE__ */ Object.create(null);
  17893. // codegen
  17894. this.bindingMetadata = {};
  17895. this.helperImports = /* @__PURE__ */ new Set();
  17896. const { script, scriptSetup } = descriptor;
  17897. const scriptLang = script && script.lang;
  17898. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  17899. this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx";
  17900. this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx";
  17901. const customElement = options.customElement;
  17902. const filename = this.descriptor.filename;
  17903. if (customElement) {
  17904. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  17905. }
  17906. const plugins = resolveParserPlugins(
  17907. scriptLang || scriptSetupLang,
  17908. options.babelParserPlugins
  17909. );
  17910. function parse(input, offset) {
  17911. try {
  17912. return parser$2.parse(input, {
  17913. plugins,
  17914. sourceType: "module"
  17915. }).program;
  17916. } catch (e) {
  17917. e.message = `[vue/compiler-sfc] ${e.message}
  17918. ${descriptor.filename}
  17919. ${shared.generateCodeFrame(
  17920. descriptor.source,
  17921. e.pos + offset,
  17922. e.pos + offset + 1
  17923. )}`;
  17924. throw e;
  17925. }
  17926. }
  17927. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  17928. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  17929. }
  17930. helper(key) {
  17931. this.helperImports.add(key);
  17932. return `_${key}`;
  17933. }
  17934. getString(node, scriptSetup = true) {
  17935. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  17936. return block.content.slice(node.start, node.end);
  17937. }
  17938. warn(msg, node, scope) {
  17939. warn(generateError(msg, node, this, scope));
  17940. }
  17941. error(msg, node, scope) {
  17942. throw new Error(
  17943. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  17944. );
  17945. }
  17946. }
  17947. function generateError(msg, node, ctx, scope) {
  17948. const offset = scope ? scope.offset : ctx.startOffset;
  17949. return `${msg}
  17950. ${(scope || ctx.descriptor).filename}
  17951. ${shared.generateCodeFrame(
  17952. (scope || ctx.descriptor).source,
  17953. node.start + offset,
  17954. node.end + offset
  17955. )}`;
  17956. }
  17957. function resolveParserPlugins(lang, userPlugins, dts = false) {
  17958. const plugins = [];
  17959. if (!userPlugins || !userPlugins.some(
  17960. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  17961. )) {
  17962. plugins.push("importAttributes");
  17963. }
  17964. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  17965. plugins.push("jsx");
  17966. } else if (userPlugins) {
  17967. userPlugins = userPlugins.filter((p) => p !== "jsx");
  17968. }
  17969. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "mtsx") {
  17970. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  17971. if (!userPlugins || !userPlugins.includes("decorators")) {
  17972. plugins.push("decorators-legacy");
  17973. }
  17974. }
  17975. if (userPlugins) {
  17976. plugins.push(...userPlugins);
  17977. }
  17978. return plugins;
  17979. }
  17980. function rewriteDefault(input, as, parserPlugins) {
  17981. const ast = parser$2.parse(input, {
  17982. sourceType: "module",
  17983. plugins: resolveParserPlugins("js", parserPlugins)
  17984. }).program.body;
  17985. const s = new MagicString(input);
  17986. rewriteDefaultAST(ast, s, as);
  17987. return s.toString();
  17988. }
  17989. function rewriteDefaultAST(ast, s, as) {
  17990. if (!hasDefaultExport(ast)) {
  17991. s.append(`
  17992. const ${as} = {}`);
  17993. return;
  17994. }
  17995. ast.forEach((node) => {
  17996. if (node.type === "ExportDefaultDeclaration") {
  17997. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  17998. let start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  17999. s.overwrite(start, node.declaration.id.start, ` class `);
  18000. s.append(`
  18001. const ${as} = ${node.declaration.id.name}`);
  18002. } else {
  18003. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18004. }
  18005. } else if (node.type === "ExportNamedDeclaration") {
  18006. for (const specifier of node.specifiers) {
  18007. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18008. if (node.source) {
  18009. if (specifier.local.name === "default") {
  18010. s.prepend(
  18011. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18012. `
  18013. );
  18014. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18015. s.remove(specifier.start, end2);
  18016. s.append(`
  18017. const ${as} = __VUE_DEFAULT__`);
  18018. continue;
  18019. } else {
  18020. s.prepend(
  18021. `import { ${s.slice(
  18022. specifier.local.start,
  18023. specifier.local.end
  18024. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18025. `
  18026. );
  18027. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18028. s.remove(specifier.start, end2);
  18029. s.append(`
  18030. const ${as} = __VUE_DEFAULT__`);
  18031. continue;
  18032. }
  18033. }
  18034. const end = specifierEnd(s, specifier.end, node.end);
  18035. s.remove(specifier.start, end);
  18036. s.append(`
  18037. const ${as} = ${specifier.local.name}`);
  18038. }
  18039. }
  18040. }
  18041. });
  18042. }
  18043. function hasDefaultExport(ast) {
  18044. for (const stmt of ast) {
  18045. if (stmt.type === "ExportDefaultDeclaration") {
  18046. return true;
  18047. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18048. (spec) => spec.exported.name === "default"
  18049. )) {
  18050. return true;
  18051. }
  18052. }
  18053. return false;
  18054. }
  18055. function specifierEnd(s, end, nodeEnd) {
  18056. let hasCommas = false;
  18057. let oldEnd = end;
  18058. while (end < nodeEnd) {
  18059. if (/\s/.test(s.slice(end, end + 1))) {
  18060. end++;
  18061. } else if (s.slice(end, end + 1) === ",") {
  18062. end++;
  18063. hasCommas = true;
  18064. break;
  18065. } else if (s.slice(end, end + 1) === "}") {
  18066. break;
  18067. }
  18068. }
  18069. return hasCommas ? end : oldEnd;
  18070. }
  18071. const normalScriptDefaultVar = `__default__`;
  18072. function processNormalScript(ctx, scopeId) {
  18073. var _a;
  18074. const script = ctx.descriptor.script;
  18075. if (script.lang && !ctx.isJS && !ctx.isTS) {
  18076. return script;
  18077. }
  18078. try {
  18079. let content = script.content;
  18080. let map = script.map;
  18081. const scriptAst = ctx.scriptAst;
  18082. const bindings = analyzeScriptBindings(scriptAst.body);
  18083. const { cssVars } = ctx.descriptor;
  18084. const { genDefaultAs, isProd } = ctx.options;
  18085. if (cssVars.length || genDefaultAs) {
  18086. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18087. const s = new MagicString(content);
  18088. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18089. content = s.toString();
  18090. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18091. content += genNormalScriptCssVarsCode(
  18092. cssVars,
  18093. bindings,
  18094. scopeId,
  18095. !!isProd,
  18096. defaultVar
  18097. );
  18098. }
  18099. if (!genDefaultAs) {
  18100. content += `
  18101. export default ${defaultVar}`;
  18102. }
  18103. }
  18104. return {
  18105. ...script,
  18106. content,
  18107. map,
  18108. bindings,
  18109. scriptAst: scriptAst.body
  18110. };
  18111. } catch (e) {
  18112. return script;
  18113. }
  18114. }
  18115. var balancedMatch;
  18116. var hasRequiredBalancedMatch;
  18117. function requireBalancedMatch () {
  18118. if (hasRequiredBalancedMatch) return balancedMatch;
  18119. hasRequiredBalancedMatch = 1;
  18120. balancedMatch = balanced;
  18121. function balanced(a, b, str) {
  18122. if (a instanceof RegExp) a = maybeMatch(a, str);
  18123. if (b instanceof RegExp) b = maybeMatch(b, str);
  18124. var r = range(a, b, str);
  18125. return r && {
  18126. start: r[0],
  18127. end: r[1],
  18128. pre: str.slice(0, r[0]),
  18129. body: str.slice(r[0] + a.length, r[1]),
  18130. post: str.slice(r[1] + b.length)
  18131. };
  18132. }
  18133. function maybeMatch(reg, str) {
  18134. var m = str.match(reg);
  18135. return m ? m[0] : null;
  18136. }
  18137. balanced.range = range;
  18138. function range(a, b, str) {
  18139. var begs, beg, left, right, result;
  18140. var ai = str.indexOf(a);
  18141. var bi = str.indexOf(b, ai + 1);
  18142. var i = ai;
  18143. if (ai >= 0 && bi > 0) {
  18144. if(a===b) {
  18145. return [ai, bi];
  18146. }
  18147. begs = [];
  18148. left = str.length;
  18149. while (i >= 0 && !result) {
  18150. if (i == ai) {
  18151. begs.push(i);
  18152. ai = str.indexOf(a, i + 1);
  18153. } else if (begs.length == 1) {
  18154. result = [ begs.pop(), bi ];
  18155. } else {
  18156. beg = begs.pop();
  18157. if (beg < left) {
  18158. left = beg;
  18159. right = bi;
  18160. }
  18161. bi = str.indexOf(b, i + 1);
  18162. }
  18163. i = ai < bi && ai >= 0 ? ai : bi;
  18164. }
  18165. if (begs.length) {
  18166. result = [ left, right ];
  18167. }
  18168. }
  18169. return result;
  18170. }
  18171. return balancedMatch;
  18172. }
  18173. var braceExpansion;
  18174. var hasRequiredBraceExpansion;
  18175. function requireBraceExpansion () {
  18176. if (hasRequiredBraceExpansion) return braceExpansion;
  18177. hasRequiredBraceExpansion = 1;
  18178. var balanced = /*@__PURE__*/ requireBalancedMatch();
  18179. braceExpansion = expandTop;
  18180. var escSlash = '\0SLASH'+Math.random()+'\0';
  18181. var escOpen = '\0OPEN'+Math.random()+'\0';
  18182. var escClose = '\0CLOSE'+Math.random()+'\0';
  18183. var escComma = '\0COMMA'+Math.random()+'\0';
  18184. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  18185. function numeric(str) {
  18186. return parseInt(str, 10) == str
  18187. ? parseInt(str, 10)
  18188. : str.charCodeAt(0);
  18189. }
  18190. function escapeBraces(str) {
  18191. return str.split('\\\\').join(escSlash)
  18192. .split('\\{').join(escOpen)
  18193. .split('\\}').join(escClose)
  18194. .split('\\,').join(escComma)
  18195. .split('\\.').join(escPeriod);
  18196. }
  18197. function unescapeBraces(str) {
  18198. return str.split(escSlash).join('\\')
  18199. .split(escOpen).join('{')
  18200. .split(escClose).join('}')
  18201. .split(escComma).join(',')
  18202. .split(escPeriod).join('.');
  18203. }
  18204. // Basically just str.split(","), but handling cases
  18205. // where we have nested braced sections, which should be
  18206. // treated as individual members, like {a,{b,c},d}
  18207. function parseCommaParts(str) {
  18208. if (!str)
  18209. return [''];
  18210. var parts = [];
  18211. var m = balanced('{', '}', str);
  18212. if (!m)
  18213. return str.split(',');
  18214. var pre = m.pre;
  18215. var body = m.body;
  18216. var post = m.post;
  18217. var p = pre.split(',');
  18218. p[p.length-1] += '{' + body + '}';
  18219. var postParts = parseCommaParts(post);
  18220. if (post.length) {
  18221. p[p.length-1] += postParts.shift();
  18222. p.push.apply(p, postParts);
  18223. }
  18224. parts.push.apply(parts, p);
  18225. return parts;
  18226. }
  18227. function expandTop(str) {
  18228. if (!str)
  18229. return [];
  18230. // I don't know why Bash 4.3 does this, but it does.
  18231. // Anything starting with {} will have the first two bytes preserved
  18232. // but *only* at the top level, so {},a}b will not expand to anything,
  18233. // but a{},b}c will be expanded to [a}c,abc].
  18234. // One could argue that this is a bug in Bash, but since the goal of
  18235. // this module is to match Bash's rules, we escape a leading {}
  18236. if (str.substr(0, 2) === '{}') {
  18237. str = '\\{\\}' + str.substr(2);
  18238. }
  18239. return expand(escapeBraces(str), true).map(unescapeBraces);
  18240. }
  18241. function embrace(str) {
  18242. return '{' + str + '}';
  18243. }
  18244. function isPadded(el) {
  18245. return /^-?0\d/.test(el);
  18246. }
  18247. function lte(i, y) {
  18248. return i <= y;
  18249. }
  18250. function gte(i, y) {
  18251. return i >= y;
  18252. }
  18253. function expand(str, isTop) {
  18254. var expansions = [];
  18255. var m = balanced('{', '}', str);
  18256. if (!m) return [str];
  18257. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18258. var pre = m.pre;
  18259. var post = m.post.length
  18260. ? expand(m.post, false)
  18261. : [''];
  18262. if (/\$$/.test(m.pre)) {
  18263. for (var k = 0; k < post.length; k++) {
  18264. var expansion = pre+ '{' + m.body + '}' + post[k];
  18265. expansions.push(expansion);
  18266. }
  18267. } else {
  18268. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18269. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18270. var isSequence = isNumericSequence || isAlphaSequence;
  18271. var isOptions = m.body.indexOf(',') >= 0;
  18272. if (!isSequence && !isOptions) {
  18273. // {a},b}
  18274. if (m.post.match(/,.*\}/)) {
  18275. str = m.pre + '{' + m.body + escClose + m.post;
  18276. return expand(str);
  18277. }
  18278. return [str];
  18279. }
  18280. var n;
  18281. if (isSequence) {
  18282. n = m.body.split(/\.\./);
  18283. } else {
  18284. n = parseCommaParts(m.body);
  18285. if (n.length === 1) {
  18286. // x{{a,b}}y ==> x{a}y x{b}y
  18287. n = expand(n[0], false).map(embrace);
  18288. if (n.length === 1) {
  18289. return post.map(function(p) {
  18290. return m.pre + n[0] + p;
  18291. });
  18292. }
  18293. }
  18294. }
  18295. // at this point, n is the parts, and we know it's not a comma set
  18296. // with a single entry.
  18297. var N;
  18298. if (isSequence) {
  18299. var x = numeric(n[0]);
  18300. var y = numeric(n[1]);
  18301. var width = Math.max(n[0].length, n[1].length);
  18302. var incr = n.length == 3
  18303. ? Math.abs(numeric(n[2]))
  18304. : 1;
  18305. var test = lte;
  18306. var reverse = y < x;
  18307. if (reverse) {
  18308. incr *= -1;
  18309. test = gte;
  18310. }
  18311. var pad = n.some(isPadded);
  18312. N = [];
  18313. for (var i = x; test(i, y); i += incr) {
  18314. var c;
  18315. if (isAlphaSequence) {
  18316. c = String.fromCharCode(i);
  18317. if (c === '\\')
  18318. c = '';
  18319. } else {
  18320. c = String(i);
  18321. if (pad) {
  18322. var need = width - c.length;
  18323. if (need > 0) {
  18324. var z = new Array(need + 1).join('0');
  18325. if (i < 0)
  18326. c = '-' + z + c.slice(1);
  18327. else
  18328. c = z + c;
  18329. }
  18330. }
  18331. }
  18332. N.push(c);
  18333. }
  18334. } else {
  18335. N = [];
  18336. for (var j = 0; j < n.length; j++) {
  18337. N.push.apply(N, expand(n[j], false));
  18338. }
  18339. }
  18340. for (var j = 0; j < N.length; j++) {
  18341. for (var k = 0; k < post.length; k++) {
  18342. var expansion = pre + N[j] + post[k];
  18343. if (!isTop || isSequence || expansion)
  18344. expansions.push(expansion);
  18345. }
  18346. }
  18347. }
  18348. return expansions;
  18349. }
  18350. return braceExpansion;
  18351. }
  18352. var braceExpansionExports = /*@__PURE__*/ requireBraceExpansion();
  18353. var expand = /*@__PURE__*/getDefaultExportFromCjs(braceExpansionExports);
  18354. const MAX_PATTERN_LENGTH = 1024 * 64;
  18355. const assertValidPattern = (pattern) => {
  18356. if (typeof pattern !== 'string') {
  18357. throw new TypeError('invalid pattern');
  18358. }
  18359. if (pattern.length > MAX_PATTERN_LENGTH) {
  18360. throw new TypeError('pattern is too long');
  18361. }
  18362. };
  18363. // translate the various posix character classes into unicode properties
  18364. // this works across all unicode locales
  18365. // { <posix class>: [<translation>, /u flag required, negated]
  18366. const posixClasses = {
  18367. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  18368. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  18369. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  18370. '[:blank:]': ['\\p{Zs}\\t', true],
  18371. '[:cntrl:]': ['\\p{Cc}', true],
  18372. '[:digit:]': ['\\p{Nd}', true],
  18373. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  18374. '[:lower:]': ['\\p{Ll}', true],
  18375. '[:print:]': ['\\p{C}', true],
  18376. '[:punct:]': ['\\p{P}', true],
  18377. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  18378. '[:upper:]': ['\\p{Lu}', true],
  18379. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  18380. '[:xdigit:]': ['A-Fa-f0-9', false],
  18381. };
  18382. // only need to escape a few things inside of brace expressions
  18383. // escapes: [ \ ] -
  18384. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  18385. // escape all regexp magic characters
  18386. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18387. // everything has already been escaped, we just have to join
  18388. const rangesToString = (ranges) => ranges.join('');
  18389. // takes a glob string at a posix brace expression, and returns
  18390. // an equivalent regular expression source, and boolean indicating
  18391. // whether the /u flag needs to be applied, and the number of chars
  18392. // consumed to parse the character class.
  18393. // This also removes out of order ranges, and returns ($.) if the
  18394. // entire class just no good.
  18395. const parseClass = (glob, position) => {
  18396. const pos = position;
  18397. /* c8 ignore start */
  18398. if (glob.charAt(pos) !== '[') {
  18399. throw new Error('not in a brace expression');
  18400. }
  18401. /* c8 ignore stop */
  18402. const ranges = [];
  18403. const negs = [];
  18404. let i = pos + 1;
  18405. let sawStart = false;
  18406. let uflag = false;
  18407. let escaping = false;
  18408. let negate = false;
  18409. let endPos = pos;
  18410. let rangeStart = '';
  18411. WHILE: while (i < glob.length) {
  18412. const c = glob.charAt(i);
  18413. if ((c === '!' || c === '^') && i === pos + 1) {
  18414. negate = true;
  18415. i++;
  18416. continue;
  18417. }
  18418. if (c === ']' && sawStart && !escaping) {
  18419. endPos = i + 1;
  18420. break;
  18421. }
  18422. sawStart = true;
  18423. if (c === '\\') {
  18424. if (!escaping) {
  18425. escaping = true;
  18426. i++;
  18427. continue;
  18428. }
  18429. // escaped \ char, fall through and treat like normal char
  18430. }
  18431. if (c === '[' && !escaping) {
  18432. // either a posix class, a collation equivalent, or just a [
  18433. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  18434. if (glob.startsWith(cls, i)) {
  18435. // invalid, [a-[] is fine, but not [a-[:alpha]]
  18436. if (rangeStart) {
  18437. return ['$.', false, glob.length - pos, true];
  18438. }
  18439. i += cls.length;
  18440. if (neg)
  18441. negs.push(unip);
  18442. else
  18443. ranges.push(unip);
  18444. uflag = uflag || u;
  18445. continue WHILE;
  18446. }
  18447. }
  18448. }
  18449. // now it's just a normal character, effectively
  18450. escaping = false;
  18451. if (rangeStart) {
  18452. // throw this range away if it's not valid, but others
  18453. // can still match.
  18454. if (c > rangeStart) {
  18455. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  18456. }
  18457. else if (c === rangeStart) {
  18458. ranges.push(braceEscape(c));
  18459. }
  18460. rangeStart = '';
  18461. i++;
  18462. continue;
  18463. }
  18464. // now might be the start of a range.
  18465. // can be either c-d or c-] or c<more...>] or c] at this point
  18466. if (glob.startsWith('-]', i + 1)) {
  18467. ranges.push(braceEscape(c + '-'));
  18468. i += 2;
  18469. continue;
  18470. }
  18471. if (glob.startsWith('-', i + 1)) {
  18472. rangeStart = c;
  18473. i += 2;
  18474. continue;
  18475. }
  18476. // not the start of a range, just a single character
  18477. ranges.push(braceEscape(c));
  18478. i++;
  18479. }
  18480. if (endPos < i) {
  18481. // didn't see the end of the class, not a valid class,
  18482. // but might still be valid as a literal match.
  18483. return ['', false, 0, false];
  18484. }
  18485. // if we got no ranges and no negates, then we have a range that
  18486. // cannot possibly match anything, and that poisons the whole glob
  18487. if (!ranges.length && !negs.length) {
  18488. return ['$.', false, glob.length - pos, true];
  18489. }
  18490. // if we got one positive range, and it's a single character, then that's
  18491. // not actually a magic pattern, it's just that one literal character.
  18492. // we should not treat that as "magic", we should just return the literal
  18493. // character. [_] is a perfectly valid way to escape glob magic chars.
  18494. if (negs.length === 0 &&
  18495. ranges.length === 1 &&
  18496. /^\\?.$/.test(ranges[0]) &&
  18497. !negate) {
  18498. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  18499. return [regexpEscape(r), false, endPos - pos, false];
  18500. }
  18501. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  18502. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  18503. const comb = ranges.length && negs.length
  18504. ? '(' + sranges + '|' + snegs + ')'
  18505. : ranges.length
  18506. ? sranges
  18507. : snegs;
  18508. return [comb, uflag, endPos - pos, true];
  18509. };
  18510. /**
  18511. * Un-escape a string that has been escaped with {@link escape}.
  18512. *
  18513. * If the {@link windowsPathsNoEscape} option is used, then square-brace
  18514. * escapes are removed, but not backslash escapes. For example, it will turn
  18515. * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
  18516. * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
  18517. *
  18518. * When `windowsPathsNoEscape` is not set, then both brace escapes and
  18519. * backslash escapes are removed.
  18520. *
  18521. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  18522. * or unescaped.
  18523. */
  18524. const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
  18525. return windowsPathsNoEscape
  18526. ? s.replace(/\[([^\/\\])\]/g, '$1')
  18527. : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
  18528. };
  18529. // parse a single path portion
  18530. const types = new Set(['!', '?', '+', '*', '@']);
  18531. const isExtglobType = (c) => types.has(c);
  18532. // Patterns that get prepended to bind to the start of either the
  18533. // entire string, or just a single path portion, to prevent dots
  18534. // and/or traversal patterns, when needed.
  18535. // Exts don't need the ^ or / bit, because the root binds that already.
  18536. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  18537. const startNoDot = '(?!\\.)';
  18538. // characters that indicate a start of pattern needs the "no dots" bit,
  18539. // because a dot *might* be matched. ( is not in the list, because in
  18540. // the case of a child extglob, it will handle the prevention itself.
  18541. const addPatternStart = new Set(['[', '.']);
  18542. // cases where traversal is A-OK, no dot prevention needed
  18543. const justDots = new Set(['..', '.']);
  18544. const reSpecials = new Set('().*{}+?[]^$\\!');
  18545. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18546. // any single thing other than /
  18547. const qmark$1 = '[^/]';
  18548. // * => any number of characters
  18549. const star$1 = qmark$1 + '*?';
  18550. // use + when we need to ensure that *something* matches, because the * is
  18551. // the only thing in the path portion.
  18552. const starNoEmpty = qmark$1 + '+?';
  18553. // remove the \ chars that we added if we end up doing a nonmagic compare
  18554. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  18555. class AST {
  18556. type;
  18557. #root;
  18558. #hasMagic;
  18559. #uflag = false;
  18560. #parts = [];
  18561. #parent;
  18562. #parentIndex;
  18563. #negs;
  18564. #filledNegs = false;
  18565. #options;
  18566. #toString;
  18567. // set to true if it's an extglob with no children
  18568. // (which really means one child of '')
  18569. #emptyExt = false;
  18570. constructor(type, parent, options = {}) {
  18571. this.type = type;
  18572. // extglobs are inherently magical
  18573. if (type)
  18574. this.#hasMagic = true;
  18575. this.#parent = parent;
  18576. this.#root = this.#parent ? this.#parent.#root : this;
  18577. this.#options = this.#root === this ? options : this.#root.#options;
  18578. this.#negs = this.#root === this ? [] : this.#root.#negs;
  18579. if (type === '!' && !this.#root.#filledNegs)
  18580. this.#negs.push(this);
  18581. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  18582. }
  18583. get hasMagic() {
  18584. /* c8 ignore start */
  18585. if (this.#hasMagic !== undefined)
  18586. return this.#hasMagic;
  18587. /* c8 ignore stop */
  18588. for (const p of this.#parts) {
  18589. if (typeof p === 'string')
  18590. continue;
  18591. if (p.type || p.hasMagic)
  18592. return (this.#hasMagic = true);
  18593. }
  18594. // note: will be undefined until we generate the regexp src and find out
  18595. return this.#hasMagic;
  18596. }
  18597. // reconstructs the pattern
  18598. toString() {
  18599. if (this.#toString !== undefined)
  18600. return this.#toString;
  18601. if (!this.type) {
  18602. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  18603. }
  18604. else {
  18605. return (this.#toString =
  18606. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  18607. }
  18608. }
  18609. #fillNegs() {
  18610. /* c8 ignore start */
  18611. if (this !== this.#root)
  18612. throw new Error('should only call on root');
  18613. if (this.#filledNegs)
  18614. return this;
  18615. /* c8 ignore stop */
  18616. // call toString() once to fill this out
  18617. this.toString();
  18618. this.#filledNegs = true;
  18619. let n;
  18620. while ((n = this.#negs.pop())) {
  18621. if (n.type !== '!')
  18622. continue;
  18623. // walk up the tree, appending everthing that comes AFTER parentIndex
  18624. let p = n;
  18625. let pp = p.#parent;
  18626. while (pp) {
  18627. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  18628. for (const part of n.#parts) {
  18629. /* c8 ignore start */
  18630. if (typeof part === 'string') {
  18631. throw new Error('string part in extglob AST??');
  18632. }
  18633. /* c8 ignore stop */
  18634. part.copyIn(pp.#parts[i]);
  18635. }
  18636. }
  18637. p = pp;
  18638. pp = p.#parent;
  18639. }
  18640. }
  18641. return this;
  18642. }
  18643. push(...parts) {
  18644. for (const p of parts) {
  18645. if (p === '')
  18646. continue;
  18647. /* c8 ignore start */
  18648. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  18649. throw new Error('invalid part: ' + p);
  18650. }
  18651. /* c8 ignore stop */
  18652. this.#parts.push(p);
  18653. }
  18654. }
  18655. toJSON() {
  18656. const ret = this.type === null
  18657. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  18658. : [this.type, ...this.#parts.map(p => p.toJSON())];
  18659. if (this.isStart() && !this.type)
  18660. ret.unshift([]);
  18661. if (this.isEnd() &&
  18662. (this === this.#root ||
  18663. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  18664. ret.push({});
  18665. }
  18666. return ret;
  18667. }
  18668. isStart() {
  18669. if (this.#root === this)
  18670. return true;
  18671. // if (this.type) return !!this.#parent?.isStart()
  18672. if (!this.#parent?.isStart())
  18673. return false;
  18674. if (this.#parentIndex === 0)
  18675. return true;
  18676. // if everything AHEAD of this is a negation, then it's still the "start"
  18677. const p = this.#parent;
  18678. for (let i = 0; i < this.#parentIndex; i++) {
  18679. const pp = p.#parts[i];
  18680. if (!(pp instanceof AST && pp.type === '!')) {
  18681. return false;
  18682. }
  18683. }
  18684. return true;
  18685. }
  18686. isEnd() {
  18687. if (this.#root === this)
  18688. return true;
  18689. if (this.#parent?.type === '!')
  18690. return true;
  18691. if (!this.#parent?.isEnd())
  18692. return false;
  18693. if (!this.type)
  18694. return this.#parent?.isEnd();
  18695. // if not root, it'll always have a parent
  18696. /* c8 ignore start */
  18697. const pl = this.#parent ? this.#parent.#parts.length : 0;
  18698. /* c8 ignore stop */
  18699. return this.#parentIndex === pl - 1;
  18700. }
  18701. copyIn(part) {
  18702. if (typeof part === 'string')
  18703. this.push(part);
  18704. else
  18705. this.push(part.clone(this));
  18706. }
  18707. clone(parent) {
  18708. const c = new AST(this.type, parent);
  18709. for (const p of this.#parts) {
  18710. c.copyIn(p);
  18711. }
  18712. return c;
  18713. }
  18714. static #parseAST(str, ast, pos, opt) {
  18715. let escaping = false;
  18716. let inBrace = false;
  18717. let braceStart = -1;
  18718. let braceNeg = false;
  18719. if (ast.type === null) {
  18720. // outside of a extglob, append until we find a start
  18721. let i = pos;
  18722. let acc = '';
  18723. while (i < str.length) {
  18724. const c = str.charAt(i++);
  18725. // still accumulate escapes at this point, but we do ignore
  18726. // starts that are escaped
  18727. if (escaping || c === '\\') {
  18728. escaping = !escaping;
  18729. acc += c;
  18730. continue;
  18731. }
  18732. if (inBrace) {
  18733. if (i === braceStart + 1) {
  18734. if (c === '^' || c === '!') {
  18735. braceNeg = true;
  18736. }
  18737. }
  18738. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18739. inBrace = false;
  18740. }
  18741. acc += c;
  18742. continue;
  18743. }
  18744. else if (c === '[') {
  18745. inBrace = true;
  18746. braceStart = i;
  18747. braceNeg = false;
  18748. acc += c;
  18749. continue;
  18750. }
  18751. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  18752. ast.push(acc);
  18753. acc = '';
  18754. const ext = new AST(c, ast);
  18755. i = AST.#parseAST(str, ext, i, opt);
  18756. ast.push(ext);
  18757. continue;
  18758. }
  18759. acc += c;
  18760. }
  18761. ast.push(acc);
  18762. return i;
  18763. }
  18764. // some kind of extglob, pos is at the (
  18765. // find the next | or )
  18766. let i = pos + 1;
  18767. let part = new AST(null, ast);
  18768. const parts = [];
  18769. let acc = '';
  18770. while (i < str.length) {
  18771. const c = str.charAt(i++);
  18772. // still accumulate escapes at this point, but we do ignore
  18773. // starts that are escaped
  18774. if (escaping || c === '\\') {
  18775. escaping = !escaping;
  18776. acc += c;
  18777. continue;
  18778. }
  18779. if (inBrace) {
  18780. if (i === braceStart + 1) {
  18781. if (c === '^' || c === '!') {
  18782. braceNeg = true;
  18783. }
  18784. }
  18785. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18786. inBrace = false;
  18787. }
  18788. acc += c;
  18789. continue;
  18790. }
  18791. else if (c === '[') {
  18792. inBrace = true;
  18793. braceStart = i;
  18794. braceNeg = false;
  18795. acc += c;
  18796. continue;
  18797. }
  18798. if (isExtglobType(c) && str.charAt(i) === '(') {
  18799. part.push(acc);
  18800. acc = '';
  18801. const ext = new AST(c, part);
  18802. part.push(ext);
  18803. i = AST.#parseAST(str, ext, i, opt);
  18804. continue;
  18805. }
  18806. if (c === '|') {
  18807. part.push(acc);
  18808. acc = '';
  18809. parts.push(part);
  18810. part = new AST(null, ast);
  18811. continue;
  18812. }
  18813. if (c === ')') {
  18814. if (acc === '' && ast.#parts.length === 0) {
  18815. ast.#emptyExt = true;
  18816. }
  18817. part.push(acc);
  18818. acc = '';
  18819. ast.push(...parts, part);
  18820. return i;
  18821. }
  18822. acc += c;
  18823. }
  18824. // unfinished extglob
  18825. // if we got here, it was a malformed extglob! not an extglob, but
  18826. // maybe something else in there.
  18827. ast.type = null;
  18828. ast.#hasMagic = undefined;
  18829. ast.#parts = [str.substring(pos - 1)];
  18830. return i;
  18831. }
  18832. static fromGlob(pattern, options = {}) {
  18833. const ast = new AST(null, undefined, options);
  18834. AST.#parseAST(pattern, ast, 0, options);
  18835. return ast;
  18836. }
  18837. // returns the regular expression if there's magic, or the unescaped
  18838. // string if not.
  18839. toMMPattern() {
  18840. // should only be called on root
  18841. /* c8 ignore start */
  18842. if (this !== this.#root)
  18843. return this.#root.toMMPattern();
  18844. /* c8 ignore stop */
  18845. const glob = this.toString();
  18846. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  18847. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  18848. // still need a regular expression if we have to case-insensitively
  18849. // match capital/lowercase characters.
  18850. const anyMagic = hasMagic ||
  18851. this.#hasMagic ||
  18852. (this.#options.nocase &&
  18853. !this.#options.nocaseMagicOnly &&
  18854. glob.toUpperCase() !== glob.toLowerCase());
  18855. if (!anyMagic) {
  18856. return body;
  18857. }
  18858. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  18859. return Object.assign(new RegExp(`^${re}$`, flags), {
  18860. _src: re,
  18861. _glob: glob,
  18862. });
  18863. }
  18864. get options() {
  18865. return this.#options;
  18866. }
  18867. // returns the string match, the regexp source, whether there's magic
  18868. // in the regexp (so a regular expression is required) and whether or
  18869. // not the uflag is needed for the regular expression (for posix classes)
  18870. // TODO: instead of injecting the start/end at this point, just return
  18871. // the BODY of the regexp, along with the start/end portions suitable
  18872. // for binding the start/end in either a joined full-path makeRe context
  18873. // (where we bind to (^|/), or a standalone matchPart context (where
  18874. // we bind to ^, and not /). Otherwise slashes get duped!
  18875. //
  18876. // In part-matching mode, the start is:
  18877. // - if not isStart: nothing
  18878. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  18879. // - if dots allowed or not possible: ^
  18880. // - if dots possible and not allowed: ^(?!\.)
  18881. // end is:
  18882. // - if not isEnd(): nothing
  18883. // - else: $
  18884. //
  18885. // In full-path matching mode, we put the slash at the START of the
  18886. // pattern, so start is:
  18887. // - if first pattern: same as part-matching mode
  18888. // - if not isStart(): nothing
  18889. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  18890. // - if dots allowed or not possible: /
  18891. // - if dots possible and not allowed: /(?!\.)
  18892. // end is:
  18893. // - if last pattern, same as part-matching mode
  18894. // - else nothing
  18895. //
  18896. // Always put the (?:$|/) on negated tails, though, because that has to be
  18897. // there to bind the end of the negated pattern portion, and it's easier to
  18898. // just stick it in now rather than try to inject it later in the middle of
  18899. // the pattern.
  18900. //
  18901. // We can just always return the same end, and leave it up to the caller
  18902. // to know whether it's going to be used joined or in parts.
  18903. // And, if the start is adjusted slightly, can do the same there:
  18904. // - if not isStart: nothing
  18905. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  18906. // - if dots allowed or not possible: (?:/|^)
  18907. // - if dots possible and not allowed: (?:/|^)(?!\.)
  18908. //
  18909. // But it's better to have a simpler binding without a conditional, for
  18910. // performance, so probably better to return both start options.
  18911. //
  18912. // Then the caller just ignores the end if it's not the first pattern,
  18913. // and the start always gets applied.
  18914. //
  18915. // But that's always going to be $ if it's the ending pattern, or nothing,
  18916. // so the caller can just attach $ at the end of the pattern when building.
  18917. //
  18918. // So the todo is:
  18919. // - better detect what kind of start is needed
  18920. // - return both flavors of starting pattern
  18921. // - attach $ at the end of the pattern when creating the actual RegExp
  18922. //
  18923. // Ah, but wait, no, that all only applies to the root when the first pattern
  18924. // is not an extglob. If the first pattern IS an extglob, then we need all
  18925. // that dot prevention biz to live in the extglob portions, because eg
  18926. // +(*|.x*) can match .xy but not .yx.
  18927. //
  18928. // So, return the two flavors if it's #root and the first child is not an
  18929. // AST, otherwise leave it to the child AST to handle it, and there,
  18930. // use the (?:^|/) style of start binding.
  18931. //
  18932. // Even simplified further:
  18933. // - Since the start for a join is eg /(?!\.) and the start for a part
  18934. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  18935. // or start or whatever) and prepend ^ or / at the Regexp construction.
  18936. toRegExpSource(allowDot) {
  18937. const dot = allowDot ?? !!this.#options.dot;
  18938. if (this.#root === this)
  18939. this.#fillNegs();
  18940. if (!this.type) {
  18941. const noEmpty = this.isStart() && this.isEnd();
  18942. const src = this.#parts
  18943. .map(p => {
  18944. const [re, _, hasMagic, uflag] = typeof p === 'string'
  18945. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  18946. : p.toRegExpSource(allowDot);
  18947. this.#hasMagic = this.#hasMagic || hasMagic;
  18948. this.#uflag = this.#uflag || uflag;
  18949. return re;
  18950. })
  18951. .join('');
  18952. let start = '';
  18953. if (this.isStart()) {
  18954. if (typeof this.#parts[0] === 'string') {
  18955. // this is the string that will match the start of the pattern,
  18956. // so we need to protect against dots and such.
  18957. // '.' and '..' cannot match unless the pattern is that exactly,
  18958. // even if it starts with . or dot:true is set.
  18959. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  18960. if (!dotTravAllowed) {
  18961. const aps = addPatternStart;
  18962. // check if we have a possibility of matching . or ..,
  18963. // and prevent that.
  18964. const needNoTrav =
  18965. // dots are allowed, and the pattern starts with [ or .
  18966. (dot && aps.has(src.charAt(0))) ||
  18967. // the pattern starts with \., and then [ or .
  18968. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  18969. // the pattern starts with \.\., and then [ or .
  18970. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  18971. // no need to prevent dots if it can't match a dot, or if a
  18972. // sub-pattern will be preventing it anyway.
  18973. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  18974. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  18975. }
  18976. }
  18977. }
  18978. // append the "end of path portion" pattern to negation tails
  18979. let end = '';
  18980. if (this.isEnd() &&
  18981. this.#root.#filledNegs &&
  18982. this.#parent?.type === '!') {
  18983. end = '(?:$|\\/)';
  18984. }
  18985. const final = start + src + end;
  18986. return [
  18987. final,
  18988. unescape(src),
  18989. (this.#hasMagic = !!this.#hasMagic),
  18990. this.#uflag,
  18991. ];
  18992. }
  18993. // We need to calculate the body *twice* if it's a repeat pattern
  18994. // at the start, once in nodot mode, then again in dot mode, so a
  18995. // pattern like *(?) can match 'x.y'
  18996. const repeated = this.type === '*' || this.type === '+';
  18997. // some kind of extglob
  18998. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  18999. let body = this.#partsToRegExp(dot);
  19000. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19001. // invalid extglob, has to at least be *something* present, if it's
  19002. // the entire path portion.
  19003. const s = this.toString();
  19004. this.#parts = [s];
  19005. this.type = null;
  19006. this.#hasMagic = undefined;
  19007. return [s, unescape(this.toString()), false, false];
  19008. }
  19009. // XXX abstract out this map method
  19010. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
  19011. ? ''
  19012. : this.#partsToRegExp(true);
  19013. if (bodyDotAllowed === body) {
  19014. bodyDotAllowed = '';
  19015. }
  19016. if (bodyDotAllowed) {
  19017. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19018. }
  19019. // an empty !() is exactly equivalent to a starNoEmpty
  19020. let final = '';
  19021. if (this.type === '!' && this.#emptyExt) {
  19022. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19023. }
  19024. else {
  19025. const close = this.type === '!'
  19026. ? // !() must match something,but !(x) can match ''
  19027. '))' +
  19028. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19029. star$1 +
  19030. ')'
  19031. : this.type === '@'
  19032. ? ')'
  19033. : this.type === '?'
  19034. ? ')?'
  19035. : this.type === '+' && bodyDotAllowed
  19036. ? ')'
  19037. : this.type === '*' && bodyDotAllowed
  19038. ? `)?`
  19039. : `)${this.type}`;
  19040. final = start + body + close;
  19041. }
  19042. return [
  19043. final,
  19044. unescape(body),
  19045. (this.#hasMagic = !!this.#hasMagic),
  19046. this.#uflag,
  19047. ];
  19048. }
  19049. #partsToRegExp(dot) {
  19050. return this.#parts
  19051. .map(p => {
  19052. // extglob ASTs should only contain parent ASTs
  19053. /* c8 ignore start */
  19054. if (typeof p === 'string') {
  19055. throw new Error('string type in extglob ast??');
  19056. }
  19057. /* c8 ignore stop */
  19058. // can ignore hasMagic, because extglobs are already always magic
  19059. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19060. this.#uflag = this.#uflag || uflag;
  19061. return re;
  19062. })
  19063. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19064. .join('|');
  19065. }
  19066. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19067. let escaping = false;
  19068. let re = '';
  19069. let uflag = false;
  19070. for (let i = 0; i < glob.length; i++) {
  19071. const c = glob.charAt(i);
  19072. if (escaping) {
  19073. escaping = false;
  19074. re += (reSpecials.has(c) ? '\\' : '') + c;
  19075. continue;
  19076. }
  19077. if (c === '\\') {
  19078. if (i === glob.length - 1) {
  19079. re += '\\\\';
  19080. }
  19081. else {
  19082. escaping = true;
  19083. }
  19084. continue;
  19085. }
  19086. if (c === '[') {
  19087. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  19088. if (consumed) {
  19089. re += src;
  19090. uflag = uflag || needUflag;
  19091. i += consumed - 1;
  19092. hasMagic = hasMagic || magic;
  19093. continue;
  19094. }
  19095. }
  19096. if (c === '*') {
  19097. if (noEmpty && glob === '*')
  19098. re += starNoEmpty;
  19099. else
  19100. re += star$1;
  19101. hasMagic = true;
  19102. continue;
  19103. }
  19104. if (c === '?') {
  19105. re += qmark$1;
  19106. hasMagic = true;
  19107. continue;
  19108. }
  19109. re += regExpEscape$1(c);
  19110. }
  19111. return [re, unescape(glob), !!hasMagic, uflag];
  19112. }
  19113. }
  19114. /**
  19115. * Escape all magic characters in a glob pattern.
  19116. *
  19117. * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
  19118. * option is used, then characters are escaped by wrapping in `[]`, because
  19119. * a magic character wrapped in a character class can only be satisfied by
  19120. * that exact character. In this mode, `\` is _not_ escaped, because it is
  19121. * not interpreted as a magic character, but instead as a path separator.
  19122. */
  19123. const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
  19124. // don't need to escape +@! because we escape the parens
  19125. // that make those magic, and escaping ! as [!] isn't valid,
  19126. // because [!]] is a valid glob class meaning not ']'.
  19127. return windowsPathsNoEscape
  19128. ? s.replace(/[?*()[\]]/g, '[$&]')
  19129. : s.replace(/[?*()[\]\\]/g, '\\$&');
  19130. };
  19131. const minimatch = (p, pattern, options = {}) => {
  19132. assertValidPattern(pattern);
  19133. // shortcut: comments match nothing.
  19134. if (!options.nocomment && pattern.charAt(0) === '#') {
  19135. return false;
  19136. }
  19137. return new Minimatch(pattern, options).match(p);
  19138. };
  19139. // Optimized checking for the most common glob patterns.
  19140. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  19141. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  19142. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  19143. const starDotExtTestNocase = (ext) => {
  19144. ext = ext.toLowerCase();
  19145. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  19146. };
  19147. const starDotExtTestNocaseDot = (ext) => {
  19148. ext = ext.toLowerCase();
  19149. return (f) => f.toLowerCase().endsWith(ext);
  19150. };
  19151. const starDotStarRE = /^\*+\.\*+$/;
  19152. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  19153. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  19154. const dotStarRE = /^\.\*+$/;
  19155. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  19156. const starRE = /^\*+$/;
  19157. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  19158. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  19159. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  19160. const qmarksTestNocase = ([$0, ext = '']) => {
  19161. const noext = qmarksTestNoExt([$0]);
  19162. if (!ext)
  19163. return noext;
  19164. ext = ext.toLowerCase();
  19165. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19166. };
  19167. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  19168. const noext = qmarksTestNoExtDot([$0]);
  19169. if (!ext)
  19170. return noext;
  19171. ext = ext.toLowerCase();
  19172. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19173. };
  19174. const qmarksTestDot = ([$0, ext = '']) => {
  19175. const noext = qmarksTestNoExtDot([$0]);
  19176. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19177. };
  19178. const qmarksTest = ([$0, ext = '']) => {
  19179. const noext = qmarksTestNoExt([$0]);
  19180. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19181. };
  19182. const qmarksTestNoExt = ([$0]) => {
  19183. const len = $0.length;
  19184. return (f) => f.length === len && !f.startsWith('.');
  19185. };
  19186. const qmarksTestNoExtDot = ([$0]) => {
  19187. const len = $0.length;
  19188. return (f) => f.length === len && f !== '.' && f !== '..';
  19189. };
  19190. /* c8 ignore start */
  19191. const defaultPlatform = (typeof process === 'object' && process
  19192. ? (typeof process.env === 'object' &&
  19193. process.env &&
  19194. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  19195. process.platform
  19196. : 'posix');
  19197. const path = {
  19198. win32: { sep: '\\' },
  19199. posix: { sep: '/' },
  19200. };
  19201. /* c8 ignore stop */
  19202. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  19203. minimatch.sep = sep;
  19204. const GLOBSTAR = Symbol('globstar **');
  19205. minimatch.GLOBSTAR = GLOBSTAR;
  19206. // any single thing other than /
  19207. // don't need to escape / when using new RegExp()
  19208. const qmark = '[^/]';
  19209. // * => any number of characters
  19210. const star = qmark + '*?';
  19211. // ** when dots are allowed. Anything goes, except .. and .
  19212. // not (^ or / followed by one or two dots followed by $ or /),
  19213. // followed by anything, any number of times.
  19214. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  19215. // not a ^ or / followed by a dot,
  19216. // followed by anything, any number of times.
  19217. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  19218. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  19219. minimatch.filter = filter;
  19220. const ext = (a, b = {}) => Object.assign({}, a, b);
  19221. const defaults = (def) => {
  19222. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  19223. return minimatch;
  19224. }
  19225. const orig = minimatch;
  19226. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  19227. return Object.assign(m, {
  19228. Minimatch: class Minimatch extends orig.Minimatch {
  19229. constructor(pattern, options = {}) {
  19230. super(pattern, ext(def, options));
  19231. }
  19232. static defaults(options) {
  19233. return orig.defaults(ext(def, options)).Minimatch;
  19234. }
  19235. },
  19236. AST: class AST extends orig.AST {
  19237. /* c8 ignore start */
  19238. constructor(type, parent, options = {}) {
  19239. super(type, parent, ext(def, options));
  19240. }
  19241. /* c8 ignore stop */
  19242. static fromGlob(pattern, options = {}) {
  19243. return orig.AST.fromGlob(pattern, ext(def, options));
  19244. }
  19245. },
  19246. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  19247. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  19248. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  19249. defaults: (options) => orig.defaults(ext(def, options)),
  19250. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  19251. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  19252. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  19253. sep: orig.sep,
  19254. GLOBSTAR: GLOBSTAR,
  19255. });
  19256. };
  19257. minimatch.defaults = defaults;
  19258. // Brace expansion:
  19259. // a{b,c}d -> abd acd
  19260. // a{b,}c -> abc ac
  19261. // a{0..3}d -> a0d a1d a2d a3d
  19262. // a{b,c{d,e}f}g -> abg acdfg acefg
  19263. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19264. //
  19265. // Invalid sets are not expanded.
  19266. // a{2..}b -> a{2..}b
  19267. // a{b}c -> a{b}c
  19268. const braceExpand = (pattern, options = {}) => {
  19269. assertValidPattern(pattern);
  19270. // Thanks to Yeting Li <https://github.com/yetingli> for
  19271. // improving this regexp to avoid a ReDOS vulnerability.
  19272. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  19273. // shortcut. no need to expand.
  19274. return [pattern];
  19275. }
  19276. return expand(pattern);
  19277. };
  19278. minimatch.braceExpand = braceExpand;
  19279. // parse a component of the expanded set.
  19280. // At this point, no pattern may contain "/" in it
  19281. // so we're going to return a 2d array, where each entry is the full
  19282. // pattern, split on '/', and then turned into a regular expression.
  19283. // A regexp is made at the end which joins each array with an
  19284. // escaped /, and another full one which joins each regexp with |.
  19285. //
  19286. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19287. // when it is the *only* thing in a path portion. Otherwise, any series
  19288. // of * is equivalent to a single *. Globstar behavior is enabled by
  19289. // default, and can be disabled by setting options.noglobstar.
  19290. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  19291. minimatch.makeRe = makeRe;
  19292. const match = (list, pattern, options = {}) => {
  19293. const mm = new Minimatch(pattern, options);
  19294. list = list.filter(f => mm.match(f));
  19295. if (mm.options.nonull && !list.length) {
  19296. list.push(pattern);
  19297. }
  19298. return list;
  19299. };
  19300. minimatch.match = match;
  19301. // replace stuff like \* with *
  19302. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  19303. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19304. class Minimatch {
  19305. options;
  19306. set;
  19307. pattern;
  19308. windowsPathsNoEscape;
  19309. nonegate;
  19310. negate;
  19311. comment;
  19312. empty;
  19313. preserveMultipleSlashes;
  19314. partial;
  19315. globSet;
  19316. globParts;
  19317. nocase;
  19318. isWindows;
  19319. platform;
  19320. windowsNoMagicRoot;
  19321. regexp;
  19322. constructor(pattern, options = {}) {
  19323. assertValidPattern(pattern);
  19324. options = options || {};
  19325. this.options = options;
  19326. this.pattern = pattern;
  19327. this.platform = options.platform || defaultPlatform;
  19328. this.isWindows = this.platform === 'win32';
  19329. this.windowsPathsNoEscape =
  19330. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  19331. if (this.windowsPathsNoEscape) {
  19332. this.pattern = this.pattern.replace(/\\/g, '/');
  19333. }
  19334. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  19335. this.regexp = null;
  19336. this.negate = false;
  19337. this.nonegate = !!options.nonegate;
  19338. this.comment = false;
  19339. this.empty = false;
  19340. this.partial = !!options.partial;
  19341. this.nocase = !!this.options.nocase;
  19342. this.windowsNoMagicRoot =
  19343. options.windowsNoMagicRoot !== undefined
  19344. ? options.windowsNoMagicRoot
  19345. : !!(this.isWindows && this.nocase);
  19346. this.globSet = [];
  19347. this.globParts = [];
  19348. this.set = [];
  19349. // make the set of regexps etc.
  19350. this.make();
  19351. }
  19352. hasMagic() {
  19353. if (this.options.magicalBraces && this.set.length > 1) {
  19354. return true;
  19355. }
  19356. for (const pattern of this.set) {
  19357. for (const part of pattern) {
  19358. if (typeof part !== 'string')
  19359. return true;
  19360. }
  19361. }
  19362. return false;
  19363. }
  19364. debug(..._) { }
  19365. make() {
  19366. const pattern = this.pattern;
  19367. const options = this.options;
  19368. // empty patterns and comments match nothing.
  19369. if (!options.nocomment && pattern.charAt(0) === '#') {
  19370. this.comment = true;
  19371. return;
  19372. }
  19373. if (!pattern) {
  19374. this.empty = true;
  19375. return;
  19376. }
  19377. // step 1: figure out negation, etc.
  19378. this.parseNegate();
  19379. // step 2: expand braces
  19380. this.globSet = [...new Set(this.braceExpand())];
  19381. if (options.debug) {
  19382. this.debug = (...args) => console.error(...args);
  19383. }
  19384. this.debug(this.pattern, this.globSet);
  19385. // step 3: now we have a set, so turn each one into a series of
  19386. // path-portion matching patterns.
  19387. // These will be regexps, except in the case of "**", which is
  19388. // set to the GLOBSTAR object for globstar behavior,
  19389. // and will not contain any / characters
  19390. //
  19391. // First, we preprocess to make the glob pattern sets a bit simpler
  19392. // and deduped. There are some perf-killing patterns that can cause
  19393. // problems with a glob walk, but we can simplify them down a bit.
  19394. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  19395. this.globParts = this.preprocess(rawGlobParts);
  19396. this.debug(this.pattern, this.globParts);
  19397. // glob --> regexps
  19398. let set = this.globParts.map((s, _, __) => {
  19399. if (this.isWindows && this.windowsNoMagicRoot) {
  19400. // check if it's a drive or unc path.
  19401. const isUNC = s[0] === '' &&
  19402. s[1] === '' &&
  19403. (s[2] === '?' || !globMagic.test(s[2])) &&
  19404. !globMagic.test(s[3]);
  19405. const isDrive = /^[a-z]:/i.test(s[0]);
  19406. if (isUNC) {
  19407. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  19408. }
  19409. else if (isDrive) {
  19410. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  19411. }
  19412. }
  19413. return s.map(ss => this.parse(ss));
  19414. });
  19415. this.debug(this.pattern, set);
  19416. // filter out everything that didn't compile properly.
  19417. this.set = set.filter(s => s.indexOf(false) === -1);
  19418. // do not treat the ? in UNC paths as magic
  19419. if (this.isWindows) {
  19420. for (let i = 0; i < this.set.length; i++) {
  19421. const p = this.set[i];
  19422. if (p[0] === '' &&
  19423. p[1] === '' &&
  19424. this.globParts[i][2] === '?' &&
  19425. typeof p[3] === 'string' &&
  19426. /^[a-z]:$/i.test(p[3])) {
  19427. p[2] = '?';
  19428. }
  19429. }
  19430. }
  19431. this.debug(this.pattern, this.set);
  19432. }
  19433. // various transforms to equivalent pattern sets that are
  19434. // faster to process in a filesystem walk. The goal is to
  19435. // eliminate what we can, and push all ** patterns as far
  19436. // to the right as possible, even if it increases the number
  19437. // of patterns that we have to process.
  19438. preprocess(globParts) {
  19439. // if we're not in globstar mode, then turn all ** into *
  19440. if (this.options.noglobstar) {
  19441. for (let i = 0; i < globParts.length; i++) {
  19442. for (let j = 0; j < globParts[i].length; j++) {
  19443. if (globParts[i][j] === '**') {
  19444. globParts[i][j] = '*';
  19445. }
  19446. }
  19447. }
  19448. }
  19449. const { optimizationLevel = 1 } = this.options;
  19450. if (optimizationLevel >= 2) {
  19451. // aggressive optimization for the purpose of fs walking
  19452. globParts = this.firstPhasePreProcess(globParts);
  19453. globParts = this.secondPhasePreProcess(globParts);
  19454. }
  19455. else if (optimizationLevel >= 1) {
  19456. // just basic optimizations to remove some .. parts
  19457. globParts = this.levelOneOptimize(globParts);
  19458. }
  19459. else {
  19460. // just collapse multiple ** portions into one
  19461. globParts = this.adjascentGlobstarOptimize(globParts);
  19462. }
  19463. return globParts;
  19464. }
  19465. // just get rid of adjascent ** portions
  19466. adjascentGlobstarOptimize(globParts) {
  19467. return globParts.map(parts => {
  19468. let gs = -1;
  19469. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19470. let i = gs;
  19471. while (parts[i + 1] === '**') {
  19472. i++;
  19473. }
  19474. if (i !== gs) {
  19475. parts.splice(gs, i - gs);
  19476. }
  19477. }
  19478. return parts;
  19479. });
  19480. }
  19481. // get rid of adjascent ** and resolve .. portions
  19482. levelOneOptimize(globParts) {
  19483. return globParts.map(parts => {
  19484. parts = parts.reduce((set, part) => {
  19485. const prev = set[set.length - 1];
  19486. if (part === '**' && prev === '**') {
  19487. return set;
  19488. }
  19489. if (part === '..') {
  19490. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  19491. set.pop();
  19492. return set;
  19493. }
  19494. }
  19495. set.push(part);
  19496. return set;
  19497. }, []);
  19498. return parts.length === 0 ? [''] : parts;
  19499. });
  19500. }
  19501. levelTwoFileOptimize(parts) {
  19502. if (!Array.isArray(parts)) {
  19503. parts = this.slashSplit(parts);
  19504. }
  19505. let didSomething = false;
  19506. do {
  19507. didSomething = false;
  19508. // <pre>/<e>/<rest> -> <pre>/<rest>
  19509. if (!this.preserveMultipleSlashes) {
  19510. for (let i = 1; i < parts.length - 1; i++) {
  19511. const p = parts[i];
  19512. // don't squeeze out UNC patterns
  19513. if (i === 1 && p === '' && parts[0] === '')
  19514. continue;
  19515. if (p === '.' || p === '') {
  19516. didSomething = true;
  19517. parts.splice(i, 1);
  19518. i--;
  19519. }
  19520. }
  19521. if (parts[0] === '.' &&
  19522. parts.length === 2 &&
  19523. (parts[1] === '.' || parts[1] === '')) {
  19524. didSomething = true;
  19525. parts.pop();
  19526. }
  19527. }
  19528. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19529. let dd = 0;
  19530. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19531. const p = parts[dd - 1];
  19532. if (p && p !== '.' && p !== '..' && p !== '**') {
  19533. didSomething = true;
  19534. parts.splice(dd - 1, 2);
  19535. dd -= 2;
  19536. }
  19537. }
  19538. } while (didSomething);
  19539. return parts.length === 0 ? [''] : parts;
  19540. }
  19541. // First phase: single-pattern processing
  19542. // <pre> is 1 or more portions
  19543. // <rest> is 1 or more portions
  19544. // <p> is any portion other than ., .., '', or **
  19545. // <e> is . or ''
  19546. //
  19547. // **/.. is *brutal* for filesystem walking performance, because
  19548. // it effectively resets the recursive walk each time it occurs,
  19549. // and ** cannot be reduced out by a .. pattern part like a regexp
  19550. // or most strings (other than .., ., and '') can be.
  19551. //
  19552. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19553. // <pre>/<e>/<rest> -> <pre>/<rest>
  19554. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19555. // **/**/<rest> -> **/<rest>
  19556. //
  19557. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  19558. // this WOULD be allowed if ** did follow symlinks, or * didn't
  19559. firstPhasePreProcess(globParts) {
  19560. let didSomething = false;
  19561. do {
  19562. didSomething = false;
  19563. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19564. for (let parts of globParts) {
  19565. let gs = -1;
  19566. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19567. let gss = gs;
  19568. while (parts[gss + 1] === '**') {
  19569. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  19570. gss++;
  19571. }
  19572. // eg, if gs is 2 and gss is 4, that means we have 3 **
  19573. // parts, and can remove 2 of them.
  19574. if (gss > gs) {
  19575. parts.splice(gs + 1, gss - gs);
  19576. }
  19577. let next = parts[gs + 1];
  19578. const p = parts[gs + 2];
  19579. const p2 = parts[gs + 3];
  19580. if (next !== '..')
  19581. continue;
  19582. if (!p ||
  19583. p === '.' ||
  19584. p === '..' ||
  19585. !p2 ||
  19586. p2 === '.' ||
  19587. p2 === '..') {
  19588. continue;
  19589. }
  19590. didSomething = true;
  19591. // edit parts in place, and push the new one
  19592. parts.splice(gs, 1);
  19593. const other = parts.slice(0);
  19594. other[gs] = '**';
  19595. globParts.push(other);
  19596. gs--;
  19597. }
  19598. // <pre>/<e>/<rest> -> <pre>/<rest>
  19599. if (!this.preserveMultipleSlashes) {
  19600. for (let i = 1; i < parts.length - 1; i++) {
  19601. const p = parts[i];
  19602. // don't squeeze out UNC patterns
  19603. if (i === 1 && p === '' && parts[0] === '')
  19604. continue;
  19605. if (p === '.' || p === '') {
  19606. didSomething = true;
  19607. parts.splice(i, 1);
  19608. i--;
  19609. }
  19610. }
  19611. if (parts[0] === '.' &&
  19612. parts.length === 2 &&
  19613. (parts[1] === '.' || parts[1] === '')) {
  19614. didSomething = true;
  19615. parts.pop();
  19616. }
  19617. }
  19618. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19619. let dd = 0;
  19620. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19621. const p = parts[dd - 1];
  19622. if (p && p !== '.' && p !== '..' && p !== '**') {
  19623. didSomething = true;
  19624. const needDot = dd === 1 && parts[dd + 1] === '**';
  19625. const splin = needDot ? ['.'] : [];
  19626. parts.splice(dd - 1, 2, ...splin);
  19627. if (parts.length === 0)
  19628. parts.push('');
  19629. dd -= 2;
  19630. }
  19631. }
  19632. }
  19633. } while (didSomething);
  19634. return globParts;
  19635. }
  19636. // second phase: multi-pattern dedupes
  19637. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  19638. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  19639. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  19640. //
  19641. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  19642. // ^-- not valid because ** doens't follow symlinks
  19643. secondPhasePreProcess(globParts) {
  19644. for (let i = 0; i < globParts.length - 1; i++) {
  19645. for (let j = i + 1; j < globParts.length; j++) {
  19646. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  19647. if (matched) {
  19648. globParts[i] = [];
  19649. globParts[j] = matched;
  19650. break;
  19651. }
  19652. }
  19653. }
  19654. return globParts.filter(gs => gs.length);
  19655. }
  19656. partsMatch(a, b, emptyGSMatch = false) {
  19657. let ai = 0;
  19658. let bi = 0;
  19659. let result = [];
  19660. let which = '';
  19661. while (ai < a.length && bi < b.length) {
  19662. if (a[ai] === b[bi]) {
  19663. result.push(which === 'b' ? b[bi] : a[ai]);
  19664. ai++;
  19665. bi++;
  19666. }
  19667. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  19668. result.push(a[ai]);
  19669. ai++;
  19670. }
  19671. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  19672. result.push(b[bi]);
  19673. bi++;
  19674. }
  19675. else if (a[ai] === '*' &&
  19676. b[bi] &&
  19677. (this.options.dot || !b[bi].startsWith('.')) &&
  19678. b[bi] !== '**') {
  19679. if (which === 'b')
  19680. return false;
  19681. which = 'a';
  19682. result.push(a[ai]);
  19683. ai++;
  19684. bi++;
  19685. }
  19686. else if (b[bi] === '*' &&
  19687. a[ai] &&
  19688. (this.options.dot || !a[ai].startsWith('.')) &&
  19689. a[ai] !== '**') {
  19690. if (which === 'a')
  19691. return false;
  19692. which = 'b';
  19693. result.push(b[bi]);
  19694. ai++;
  19695. bi++;
  19696. }
  19697. else {
  19698. return false;
  19699. }
  19700. }
  19701. // if we fall out of the loop, it means they two are identical
  19702. // as long as their lengths match
  19703. return a.length === b.length && result;
  19704. }
  19705. parseNegate() {
  19706. if (this.nonegate)
  19707. return;
  19708. const pattern = this.pattern;
  19709. let negate = false;
  19710. let negateOffset = 0;
  19711. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  19712. negate = !negate;
  19713. negateOffset++;
  19714. }
  19715. if (negateOffset)
  19716. this.pattern = pattern.slice(negateOffset);
  19717. this.negate = negate;
  19718. }
  19719. // set partial to true to test if, for example,
  19720. // "/a/b" matches the start of "/*/b/*/d"
  19721. // Partial means, if you run out of file before you run
  19722. // out of pattern, then that's fine, as long as all
  19723. // the parts match.
  19724. matchOne(file, pattern, partial = false) {
  19725. const options = this.options;
  19726. // UNC paths like //?/X:/... can match X:/... and vice versa
  19727. // Drive letters in absolute drive or unc paths are always compared
  19728. // case-insensitively.
  19729. if (this.isWindows) {
  19730. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  19731. const fileUNC = !fileDrive &&
  19732. file[0] === '' &&
  19733. file[1] === '' &&
  19734. file[2] === '?' &&
  19735. /^[a-z]:$/i.test(file[3]);
  19736. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  19737. const patternUNC = !patternDrive &&
  19738. pattern[0] === '' &&
  19739. pattern[1] === '' &&
  19740. pattern[2] === '?' &&
  19741. typeof pattern[3] === 'string' &&
  19742. /^[a-z]:$/i.test(pattern[3]);
  19743. const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
  19744. const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
  19745. if (typeof fdi === 'number' && typeof pdi === 'number') {
  19746. const [fd, pd] = [file[fdi], pattern[pdi]];
  19747. if (fd.toLowerCase() === pd.toLowerCase()) {
  19748. pattern[pdi] = fd;
  19749. if (pdi > fdi) {
  19750. pattern = pattern.slice(pdi);
  19751. }
  19752. else if (fdi > pdi) {
  19753. file = file.slice(fdi);
  19754. }
  19755. }
  19756. }
  19757. }
  19758. // resolve and reduce . and .. portions in the file as well.
  19759. // dont' need to do the second phase, because it's only one string[]
  19760. const { optimizationLevel = 1 } = this.options;
  19761. if (optimizationLevel >= 2) {
  19762. file = this.levelTwoFileOptimize(file);
  19763. }
  19764. this.debug('matchOne', this, { file, pattern });
  19765. this.debug('matchOne', file.length, pattern.length);
  19766. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  19767. this.debug('matchOne loop');
  19768. var p = pattern[pi];
  19769. var f = file[fi];
  19770. this.debug(pattern, p, f);
  19771. // should be impossible.
  19772. // some invalid regexp stuff in the set.
  19773. /* c8 ignore start */
  19774. if (p === false) {
  19775. return false;
  19776. }
  19777. /* c8 ignore stop */
  19778. if (p === GLOBSTAR) {
  19779. this.debug('GLOBSTAR', [pattern, p, f]);
  19780. // "**"
  19781. // a/**/b/**/c would match the following:
  19782. // a/b/x/y/z/c
  19783. // a/x/y/z/b/c
  19784. // a/b/x/b/x/c
  19785. // a/b/c
  19786. // To do this, take the rest of the pattern after
  19787. // the **, and see if it would match the file remainder.
  19788. // If so, return success.
  19789. // If not, the ** "swallows" a segment, and try again.
  19790. // This is recursively awful.
  19791. //
  19792. // a/**/b/**/c matching a/b/x/y/z/c
  19793. // - a matches a
  19794. // - doublestar
  19795. // - matchOne(b/x/y/z/c, b/**/c)
  19796. // - b matches b
  19797. // - doublestar
  19798. // - matchOne(x/y/z/c, c) -> no
  19799. // - matchOne(y/z/c, c) -> no
  19800. // - matchOne(z/c, c) -> no
  19801. // - matchOne(c, c) yes, hit
  19802. var fr = fi;
  19803. var pr = pi + 1;
  19804. if (pr === pl) {
  19805. this.debug('** at the end');
  19806. // a ** at the end will just swallow the rest.
  19807. // We have found a match.
  19808. // however, it will not swallow /.x, unless
  19809. // options.dot is set.
  19810. // . and .. are *never* matched by **, for explosively
  19811. // exponential reasons.
  19812. for (; fi < fl; fi++) {
  19813. if (file[fi] === '.' ||
  19814. file[fi] === '..' ||
  19815. (!options.dot && file[fi].charAt(0) === '.'))
  19816. return false;
  19817. }
  19818. return true;
  19819. }
  19820. // ok, let's see if we can swallow whatever we can.
  19821. while (fr < fl) {
  19822. var swallowee = file[fr];
  19823. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  19824. // XXX remove this slice. Just pass the start index.
  19825. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  19826. this.debug('globstar found match!', fr, fl, swallowee);
  19827. // found a match.
  19828. return true;
  19829. }
  19830. else {
  19831. // can't swallow "." or ".." ever.
  19832. // can only swallow ".foo" when explicitly asked.
  19833. if (swallowee === '.' ||
  19834. swallowee === '..' ||
  19835. (!options.dot && swallowee.charAt(0) === '.')) {
  19836. this.debug('dot detected!', file, fr, pattern, pr);
  19837. break;
  19838. }
  19839. // ** swallows a segment, and continue.
  19840. this.debug('globstar swallow a segment, and continue');
  19841. fr++;
  19842. }
  19843. }
  19844. // no match was found.
  19845. // However, in partial mode, we can't say this is necessarily over.
  19846. /* c8 ignore start */
  19847. if (partial) {
  19848. // ran out of file
  19849. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  19850. if (fr === fl) {
  19851. return true;
  19852. }
  19853. }
  19854. /* c8 ignore stop */
  19855. return false;
  19856. }
  19857. // something other than **
  19858. // non-magic patterns just have to match exactly
  19859. // patterns with magic have been turned into regexps.
  19860. let hit;
  19861. if (typeof p === 'string') {
  19862. hit = f === p;
  19863. this.debug('string match', p, f, hit);
  19864. }
  19865. else {
  19866. hit = p.test(f);
  19867. this.debug('pattern match', p, f, hit);
  19868. }
  19869. if (!hit)
  19870. return false;
  19871. }
  19872. // Note: ending in / means that we'll get a final ""
  19873. // at the end of the pattern. This can only match a
  19874. // corresponding "" at the end of the file.
  19875. // If the file ends in /, then it can only match a
  19876. // a pattern that ends in /, unless the pattern just
  19877. // doesn't have any more for it. But, a/b/ should *not*
  19878. // match "a/b/*", even though "" matches against the
  19879. // [^/]*? pattern, except in partial mode, where it might
  19880. // simply not be reached yet.
  19881. // However, a/b/ should still satisfy a/*
  19882. // now either we fell off the end of the pattern, or we're done.
  19883. if (fi === fl && pi === pl) {
  19884. // ran out of pattern and filename at the same time.
  19885. // an exact hit!
  19886. return true;
  19887. }
  19888. else if (fi === fl) {
  19889. // ran out of file, but still had pattern left.
  19890. // this is ok if we're doing the match as part of
  19891. // a glob fs traversal.
  19892. return partial;
  19893. }
  19894. else if (pi === pl) {
  19895. // ran out of pattern, still have file left.
  19896. // this is only acceptable if we're on the very last
  19897. // empty segment of a file with a trailing slash.
  19898. // a/* should match a/b/
  19899. return fi === fl - 1 && file[fi] === '';
  19900. /* c8 ignore start */
  19901. }
  19902. else {
  19903. // should be unreachable.
  19904. throw new Error('wtf?');
  19905. }
  19906. /* c8 ignore stop */
  19907. }
  19908. braceExpand() {
  19909. return braceExpand(this.pattern, this.options);
  19910. }
  19911. parse(pattern) {
  19912. assertValidPattern(pattern);
  19913. const options = this.options;
  19914. // shortcuts
  19915. if (pattern === '**')
  19916. return GLOBSTAR;
  19917. if (pattern === '')
  19918. return '';
  19919. // far and away, the most common glob pattern parts are
  19920. // *, *.*, and *.<ext> Add a fast check method for those.
  19921. let m;
  19922. let fastTest = null;
  19923. if ((m = pattern.match(starRE))) {
  19924. fastTest = options.dot ? starTestDot : starTest;
  19925. }
  19926. else if ((m = pattern.match(starDotExtRE))) {
  19927. fastTest = (options.nocase
  19928. ? options.dot
  19929. ? starDotExtTestNocaseDot
  19930. : starDotExtTestNocase
  19931. : options.dot
  19932. ? starDotExtTestDot
  19933. : starDotExtTest)(m[1]);
  19934. }
  19935. else if ((m = pattern.match(qmarksRE))) {
  19936. fastTest = (options.nocase
  19937. ? options.dot
  19938. ? qmarksTestNocaseDot
  19939. : qmarksTestNocase
  19940. : options.dot
  19941. ? qmarksTestDot
  19942. : qmarksTest)(m);
  19943. }
  19944. else if ((m = pattern.match(starDotStarRE))) {
  19945. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  19946. }
  19947. else if ((m = pattern.match(dotStarRE))) {
  19948. fastTest = dotStarTest;
  19949. }
  19950. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  19951. if (fastTest && typeof re === 'object') {
  19952. // Avoids overriding in frozen environments
  19953. Reflect.defineProperty(re, 'test', { value: fastTest });
  19954. }
  19955. return re;
  19956. }
  19957. makeRe() {
  19958. if (this.regexp || this.regexp === false)
  19959. return this.regexp;
  19960. // at this point, this.set is a 2d array of partial
  19961. // pattern strings, or "**".
  19962. //
  19963. // It's better to use .match(). This function shouldn't
  19964. // be used, really, but it's pretty convenient sometimes,
  19965. // when you just want to work with a regex.
  19966. const set = this.set;
  19967. if (!set.length) {
  19968. this.regexp = false;
  19969. return this.regexp;
  19970. }
  19971. const options = this.options;
  19972. const twoStar = options.noglobstar
  19973. ? star
  19974. : options.dot
  19975. ? twoStarDot
  19976. : twoStarNoDot;
  19977. const flags = new Set(options.nocase ? ['i'] : []);
  19978. // regexpify non-globstar patterns
  19979. // if ** is only item, then we just do one twoStar
  19980. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  19981. // if ** is last, append (\/twoStar|) to previous
  19982. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  19983. // then filter out GLOBSTAR symbols
  19984. let re = set
  19985. .map(pattern => {
  19986. const pp = pattern.map(p => {
  19987. if (p instanceof RegExp) {
  19988. for (const f of p.flags.split(''))
  19989. flags.add(f);
  19990. }
  19991. return typeof p === 'string'
  19992. ? regExpEscape(p)
  19993. : p === GLOBSTAR
  19994. ? GLOBSTAR
  19995. : p._src;
  19996. });
  19997. pp.forEach((p, i) => {
  19998. const next = pp[i + 1];
  19999. const prev = pp[i - 1];
  20000. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  20001. return;
  20002. }
  20003. if (prev === undefined) {
  20004. if (next !== undefined && next !== GLOBSTAR) {
  20005. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  20006. }
  20007. else {
  20008. pp[i] = twoStar;
  20009. }
  20010. }
  20011. else if (next === undefined) {
  20012. pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
  20013. }
  20014. else if (next !== GLOBSTAR) {
  20015. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  20016. pp[i + 1] = GLOBSTAR;
  20017. }
  20018. });
  20019. return pp.filter(p => p !== GLOBSTAR).join('/');
  20020. })
  20021. .join('|');
  20022. // need to wrap in parens if we had more than one thing with |,
  20023. // otherwise only the first will be anchored to ^ and the last to $
  20024. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  20025. // must match entire pattern
  20026. // ending in a * or ** will make it less strict.
  20027. re = '^' + open + re + close + '$';
  20028. // can match anything, as long as it's not this.
  20029. if (this.negate)
  20030. re = '^(?!' + re + ').+$';
  20031. try {
  20032. this.regexp = new RegExp(re, [...flags].join(''));
  20033. /* c8 ignore start */
  20034. }
  20035. catch (ex) {
  20036. // should be impossible
  20037. this.regexp = false;
  20038. }
  20039. /* c8 ignore stop */
  20040. return this.regexp;
  20041. }
  20042. slashSplit(p) {
  20043. // if p starts with // on windows, we preserve that
  20044. // so that UNC paths aren't broken. Otherwise, any number of
  20045. // / characters are coalesced into one, unless
  20046. // preserveMultipleSlashes is set to true.
  20047. if (this.preserveMultipleSlashes) {
  20048. return p.split('/');
  20049. }
  20050. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  20051. // add an extra '' for the one we lose
  20052. return ['', ...p.split(/\/+/)];
  20053. }
  20054. else {
  20055. return p.split(/\/+/);
  20056. }
  20057. }
  20058. match(f, partial = this.partial) {
  20059. this.debug('match', f, this.pattern);
  20060. // short-circuit in the case of busted things.
  20061. // comments, etc.
  20062. if (this.comment) {
  20063. return false;
  20064. }
  20065. if (this.empty) {
  20066. return f === '';
  20067. }
  20068. if (f === '/' && partial) {
  20069. return true;
  20070. }
  20071. const options = this.options;
  20072. // windows: need to use /, not \
  20073. if (this.isWindows) {
  20074. f = f.split('\\').join('/');
  20075. }
  20076. // treat the test path as a set of pathparts.
  20077. const ff = this.slashSplit(f);
  20078. this.debug(this.pattern, 'split', ff);
  20079. // just ONE of the pattern sets in this.set needs to match
  20080. // in order for it to be valid. If negating, then just one
  20081. // match means that we have failed.
  20082. // Either way, return on the first hit.
  20083. const set = this.set;
  20084. this.debug(this.pattern, 'set', set);
  20085. // Find the basename of the path by looking for the last non-empty segment
  20086. let filename = ff[ff.length - 1];
  20087. if (!filename) {
  20088. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  20089. filename = ff[i];
  20090. }
  20091. }
  20092. for (let i = 0; i < set.length; i++) {
  20093. const pattern = set[i];
  20094. let file = ff;
  20095. if (options.matchBase && pattern.length === 1) {
  20096. file = [filename];
  20097. }
  20098. const hit = this.matchOne(file, pattern, partial);
  20099. if (hit) {
  20100. if (options.flipNegate) {
  20101. return true;
  20102. }
  20103. return !this.negate;
  20104. }
  20105. }
  20106. // didn't get any hits. this is success if it's a negative
  20107. // pattern, failure otherwise.
  20108. if (options.flipNegate) {
  20109. return false;
  20110. }
  20111. return this.negate;
  20112. }
  20113. static defaults(def) {
  20114. return minimatch.defaults(def).Minimatch;
  20115. }
  20116. }
  20117. /* c8 ignore stop */
  20118. minimatch.AST = AST;
  20119. minimatch.Minimatch = Minimatch;
  20120. minimatch.escape = escape;
  20121. minimatch.unescape = unescape;
  20122. class TypeScope {
  20123. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  20124. this.filename = filename;
  20125. this.source = source;
  20126. this.offset = offset;
  20127. this.imports = imports;
  20128. this.types = types;
  20129. this.declares = declares;
  20130. this.isGenericScope = false;
  20131. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  20132. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  20133. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  20134. }
  20135. }
  20136. function resolveTypeElements(ctx, node, scope, typeParameters) {
  20137. const canCache = !typeParameters;
  20138. if (canCache && node._resolvedElements) {
  20139. return node._resolvedElements;
  20140. }
  20141. const resolved = innerResolveTypeElements(
  20142. ctx,
  20143. node,
  20144. node._ownerScope || scope || ctxToScope(ctx),
  20145. typeParameters
  20146. );
  20147. return canCache ? node._resolvedElements = resolved : resolved;
  20148. }
  20149. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  20150. var _a, _b;
  20151. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  20152. return { props: {} };
  20153. }
  20154. switch (node.type) {
  20155. case "TSTypeLiteral":
  20156. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  20157. case "TSInterfaceDeclaration":
  20158. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  20159. case "TSTypeAliasDeclaration":
  20160. case "TSTypeAnnotation":
  20161. case "TSParenthesizedType":
  20162. return resolveTypeElements(
  20163. ctx,
  20164. node.typeAnnotation,
  20165. scope,
  20166. typeParameters
  20167. );
  20168. case "TSFunctionType": {
  20169. return { props: {}, calls: [node] };
  20170. }
  20171. case "TSUnionType":
  20172. case "TSIntersectionType":
  20173. return mergeElements(
  20174. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  20175. node.type
  20176. );
  20177. case "TSMappedType":
  20178. return resolveMappedType(ctx, node, scope, typeParameters);
  20179. case "TSIndexedAccessType": {
  20180. const types = resolveIndexType(ctx, node, scope);
  20181. return mergeElements(
  20182. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  20183. "TSUnionType"
  20184. );
  20185. }
  20186. case "TSExpressionWithTypeArguments":
  20187. // referenced by interface extends
  20188. case "TSTypeReference": {
  20189. const typeName = getReferenceName(node);
  20190. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  20191. return resolveExtractPropTypes(
  20192. resolveTypeElements(
  20193. ctx,
  20194. node.typeParameters.params[0],
  20195. scope,
  20196. typeParameters
  20197. ),
  20198. scope
  20199. );
  20200. }
  20201. const resolved = resolveTypeReference(ctx, node, scope);
  20202. if (resolved) {
  20203. let typeParams;
  20204. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  20205. typeParams = /* @__PURE__ */ Object.create(null);
  20206. resolved.typeParameters.params.forEach((p, i) => {
  20207. let param = typeParameters && typeParameters[p.name];
  20208. if (!param) param = node.typeParameters.params[i];
  20209. typeParams[p.name] = param;
  20210. });
  20211. }
  20212. return resolveTypeElements(
  20213. ctx,
  20214. resolved,
  20215. resolved._ownerScope,
  20216. typeParams
  20217. );
  20218. } else {
  20219. if (typeof typeName === "string") {
  20220. if (typeParameters && typeParameters[typeName]) {
  20221. return resolveTypeElements(
  20222. ctx,
  20223. typeParameters[typeName],
  20224. scope,
  20225. typeParameters
  20226. );
  20227. }
  20228. if (
  20229. // @ts-expect-error
  20230. SupportedBuiltinsSet.has(typeName)
  20231. ) {
  20232. return resolveBuiltin(
  20233. ctx,
  20234. node,
  20235. typeName,
  20236. scope,
  20237. typeParameters
  20238. );
  20239. } else if (typeName === "ReturnType" && node.typeParameters) {
  20240. const ret = resolveReturnType(
  20241. ctx,
  20242. node.typeParameters.params[0],
  20243. scope
  20244. );
  20245. if (ret) {
  20246. return resolveTypeElements(ctx, ret, scope);
  20247. }
  20248. }
  20249. }
  20250. return ctx.error(
  20251. `Unresolvable type reference or unsupported built-in utility type`,
  20252. node,
  20253. scope
  20254. );
  20255. }
  20256. }
  20257. case "TSImportType": {
  20258. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  20259. return resolveExtractPropTypes(
  20260. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  20261. scope
  20262. );
  20263. }
  20264. const sourceScope = importSourceToScope(
  20265. ctx,
  20266. node.argument,
  20267. scope,
  20268. node.argument.value
  20269. );
  20270. const resolved = resolveTypeReference(ctx, node, sourceScope);
  20271. if (resolved) {
  20272. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20273. }
  20274. break;
  20275. }
  20276. case "TSTypeQuery":
  20277. {
  20278. const resolved = resolveTypeReference(ctx, node, scope);
  20279. if (resolved) {
  20280. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20281. }
  20282. }
  20283. break;
  20284. }
  20285. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  20286. }
  20287. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  20288. const res = { props: {} };
  20289. for (const e of elements) {
  20290. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  20291. if (typeParameters) {
  20292. scope = createChildScope(scope);
  20293. scope.isGenericScope = true;
  20294. Object.assign(scope.types, typeParameters);
  20295. }
  20296. e._ownerScope = scope;
  20297. const name = getId(e.key);
  20298. if (name && !e.computed) {
  20299. res.props[name] = e;
  20300. } else if (e.key.type === "TemplateLiteral") {
  20301. for (const key of resolveTemplateKeys(ctx, e.key, scope)) {
  20302. res.props[key] = e;
  20303. }
  20304. } else {
  20305. ctx.error(
  20306. `Unsupported computed key in type referenced by a macro`,
  20307. e.key,
  20308. scope
  20309. );
  20310. }
  20311. } else if (e.type === "TSCallSignatureDeclaration") {
  20312. (res.calls || (res.calls = [])).push(e);
  20313. }
  20314. }
  20315. return res;
  20316. }
  20317. function mergeElements(maps, type) {
  20318. if (maps.length === 1) return maps[0];
  20319. const res = { props: {} };
  20320. const { props: baseProps } = res;
  20321. for (const { props, calls } of maps) {
  20322. for (const key in props) {
  20323. if (!shared.hasOwn(baseProps, key)) {
  20324. baseProps[key] = props[key];
  20325. } else {
  20326. baseProps[key] = createProperty(
  20327. baseProps[key].key,
  20328. {
  20329. type,
  20330. // @ts-expect-error
  20331. types: [baseProps[key], props[key]]
  20332. },
  20333. baseProps[key]._ownerScope,
  20334. baseProps[key].optional || props[key].optional
  20335. );
  20336. }
  20337. }
  20338. if (calls) {
  20339. (res.calls || (res.calls = [])).push(...calls);
  20340. }
  20341. }
  20342. return res;
  20343. }
  20344. function createProperty(key, typeAnnotation, scope, optional) {
  20345. return {
  20346. type: "TSPropertySignature",
  20347. key,
  20348. kind: "get",
  20349. optional,
  20350. typeAnnotation: {
  20351. type: "TSTypeAnnotation",
  20352. typeAnnotation
  20353. },
  20354. _ownerScope: scope
  20355. };
  20356. }
  20357. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  20358. const base = typeElementsToMap(
  20359. ctx,
  20360. node.body.body,
  20361. node._ownerScope,
  20362. typeParameters
  20363. );
  20364. if (node.extends) {
  20365. for (const ext of node.extends) {
  20366. try {
  20367. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  20368. for (const key in props) {
  20369. if (!shared.hasOwn(base.props, key)) {
  20370. base.props[key] = props[key];
  20371. }
  20372. }
  20373. if (calls) {
  20374. ;
  20375. (base.calls || (base.calls = [])).push(...calls);
  20376. }
  20377. } catch (e) {
  20378. ctx.error(
  20379. `Failed to resolve extends base type.
  20380. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  20381. interface Props extends /* @vue-ignore */ Base {}
  20382. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  20383. ext,
  20384. scope
  20385. );
  20386. }
  20387. }
  20388. }
  20389. return base;
  20390. }
  20391. function resolveMappedType(ctx, node, scope, typeParameters) {
  20392. const res = { props: {} };
  20393. let keys;
  20394. if (node.nameType) {
  20395. const { name, constraint } = node.typeParameter;
  20396. scope = createChildScope(scope);
  20397. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  20398. keys = resolveStringType(ctx, node.nameType, scope);
  20399. } else {
  20400. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  20401. }
  20402. for (const key of keys) {
  20403. res.props[key] = createProperty(
  20404. {
  20405. type: "Identifier",
  20406. name: key
  20407. },
  20408. node.typeAnnotation,
  20409. scope,
  20410. !!node.optional
  20411. );
  20412. }
  20413. return res;
  20414. }
  20415. function resolveIndexType(ctx, node, scope) {
  20416. var _a, _b;
  20417. if (node.indexType.type === "TSNumberKeyword") {
  20418. return resolveArrayElementType(ctx, node.objectType, scope);
  20419. }
  20420. const { indexType, objectType } = node;
  20421. const types = [];
  20422. let keys;
  20423. let resolved;
  20424. if (indexType.type === "TSStringKeyword") {
  20425. resolved = resolveTypeElements(ctx, objectType, scope);
  20426. keys = Object.keys(resolved.props);
  20427. } else {
  20428. keys = resolveStringType(ctx, indexType, scope);
  20429. resolved = resolveTypeElements(ctx, objectType, scope);
  20430. }
  20431. for (const key of keys) {
  20432. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  20433. if (targetType) {
  20434. targetType._ownerScope = resolved.props[key]._ownerScope;
  20435. types.push(targetType);
  20436. }
  20437. }
  20438. return types;
  20439. }
  20440. function resolveArrayElementType(ctx, node, scope) {
  20441. if (node.type === "TSArrayType") {
  20442. return [node.elementType];
  20443. }
  20444. if (node.type === "TSTupleType") {
  20445. return node.elementTypes.map(
  20446. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  20447. );
  20448. }
  20449. if (node.type === "TSTypeReference") {
  20450. if (getReferenceName(node) === "Array" && node.typeParameters) {
  20451. return node.typeParameters.params;
  20452. } else {
  20453. const resolved = resolveTypeReference(ctx, node, scope);
  20454. if (resolved) {
  20455. return resolveArrayElementType(ctx, resolved, scope);
  20456. }
  20457. }
  20458. }
  20459. return ctx.error(
  20460. "Failed to resolve element type from target type",
  20461. node,
  20462. scope
  20463. );
  20464. }
  20465. function resolveStringType(ctx, node, scope) {
  20466. switch (node.type) {
  20467. case "StringLiteral":
  20468. return [node.value];
  20469. case "TSLiteralType":
  20470. return resolveStringType(ctx, node.literal, scope);
  20471. case "TSUnionType":
  20472. return node.types.map((t) => resolveStringType(ctx, t, scope)).flat();
  20473. case "TemplateLiteral": {
  20474. return resolveTemplateKeys(ctx, node, scope);
  20475. }
  20476. case "TSTypeReference": {
  20477. const resolved = resolveTypeReference(ctx, node, scope);
  20478. if (resolved) {
  20479. return resolveStringType(ctx, resolved, scope);
  20480. }
  20481. if (node.typeName.type === "Identifier") {
  20482. const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope);
  20483. switch (node.typeName.name) {
  20484. case "Extract":
  20485. return getParam(1);
  20486. case "Exclude": {
  20487. const excluded = getParam(1);
  20488. return getParam().filter((s) => !excluded.includes(s));
  20489. }
  20490. case "Uppercase":
  20491. return getParam().map((s) => s.toUpperCase());
  20492. case "Lowercase":
  20493. return getParam().map((s) => s.toLowerCase());
  20494. case "Capitalize":
  20495. return getParam().map(shared.capitalize);
  20496. case "Uncapitalize":
  20497. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  20498. default:
  20499. ctx.error(
  20500. "Unsupported type when resolving index type",
  20501. node.typeName,
  20502. scope
  20503. );
  20504. }
  20505. }
  20506. }
  20507. }
  20508. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  20509. }
  20510. function resolveTemplateKeys(ctx, node, scope) {
  20511. if (!node.expressions.length) {
  20512. return [node.quasis[0].value.raw];
  20513. }
  20514. const res = [];
  20515. const e = node.expressions[0];
  20516. const q = node.quasis[0];
  20517. const leading = q ? q.value.raw : ``;
  20518. const resolved = resolveStringType(ctx, e, scope);
  20519. const restResolved = resolveTemplateKeys(
  20520. ctx,
  20521. {
  20522. ...node,
  20523. expressions: node.expressions.slice(1),
  20524. quasis: q ? node.quasis.slice(1) : node.quasis
  20525. },
  20526. scope
  20527. );
  20528. for (const r of resolved) {
  20529. for (const rr of restResolved) {
  20530. res.push(leading + r + rr);
  20531. }
  20532. }
  20533. return res;
  20534. }
  20535. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  20536. "Partial",
  20537. "Required",
  20538. "Readonly",
  20539. "Pick",
  20540. "Omit"
  20541. ]);
  20542. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  20543. const t = resolveTypeElements(
  20544. ctx,
  20545. node.typeParameters.params[0],
  20546. scope,
  20547. typeParameters
  20548. );
  20549. switch (name) {
  20550. case "Partial": {
  20551. const res2 = { props: {}, calls: t.calls };
  20552. Object.keys(t.props).forEach((key) => {
  20553. res2.props[key] = { ...t.props[key], optional: true };
  20554. });
  20555. return res2;
  20556. }
  20557. case "Required": {
  20558. const res2 = { props: {}, calls: t.calls };
  20559. Object.keys(t.props).forEach((key) => {
  20560. res2.props[key] = { ...t.props[key], optional: false };
  20561. });
  20562. return res2;
  20563. }
  20564. case "Readonly":
  20565. return t;
  20566. case "Pick": {
  20567. const picked = resolveStringType(
  20568. ctx,
  20569. node.typeParameters.params[1],
  20570. scope
  20571. );
  20572. const res2 = { props: {}, calls: t.calls };
  20573. for (const key of picked) {
  20574. res2.props[key] = t.props[key];
  20575. }
  20576. return res2;
  20577. }
  20578. case "Omit":
  20579. const omitted = resolveStringType(
  20580. ctx,
  20581. node.typeParameters.params[1],
  20582. scope
  20583. );
  20584. const res = { props: {}, calls: t.calls };
  20585. for (const key in t.props) {
  20586. if (!omitted.includes(key)) {
  20587. res.props[key] = t.props[key];
  20588. }
  20589. }
  20590. return res;
  20591. }
  20592. }
  20593. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  20594. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  20595. if (canCache && node._resolvedReference) {
  20596. return node._resolvedReference;
  20597. }
  20598. const resolved = innerResolveTypeReference(
  20599. ctx,
  20600. scope || ctxToScope(ctx),
  20601. name || getReferenceName(node),
  20602. node,
  20603. onlyExported
  20604. );
  20605. return canCache ? node._resolvedReference = resolved : resolved;
  20606. }
  20607. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  20608. if (typeof name === "string") {
  20609. if (scope.imports[name]) {
  20610. return resolveTypeFromImport(ctx, node, name, scope);
  20611. } else {
  20612. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  20613. if (lookupSource[name]) {
  20614. return lookupSource[name];
  20615. } else {
  20616. const globalScopes = resolveGlobalScope(ctx);
  20617. if (globalScopes) {
  20618. for (const s of globalScopes) {
  20619. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  20620. if (src[name]) {
  20621. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  20622. return src[name];
  20623. }
  20624. }
  20625. }
  20626. }
  20627. }
  20628. } else {
  20629. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  20630. if (ns) {
  20631. if (ns.type !== "TSModuleDeclaration") {
  20632. ns = ns._ns;
  20633. }
  20634. if (ns) {
  20635. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  20636. return innerResolveTypeReference(
  20637. ctx,
  20638. childScope,
  20639. name.length > 2 ? name.slice(1) : name[name.length - 1],
  20640. node,
  20641. !ns.declare
  20642. );
  20643. }
  20644. }
  20645. }
  20646. }
  20647. function getReferenceName(node) {
  20648. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  20649. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  20650. return ref.name;
  20651. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  20652. return qualifiedNameToPath(ref);
  20653. } else {
  20654. return "default";
  20655. }
  20656. }
  20657. function qualifiedNameToPath(node) {
  20658. if (node.type === "Identifier") {
  20659. return [node.name];
  20660. } else {
  20661. return [...qualifiedNameToPath(node.left), node.right.name];
  20662. }
  20663. }
  20664. function resolveGlobalScope(ctx) {
  20665. if (ctx.options.globalTypeFiles) {
  20666. const fs = resolveFS(ctx);
  20667. if (!fs) {
  20668. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  20669. }
  20670. return ctx.options.globalTypeFiles.map(
  20671. (file) => fileToScope(ctx, normalizePath(file), true)
  20672. );
  20673. }
  20674. }
  20675. let ts;
  20676. let loadTS;
  20677. function registerTS(_loadTS) {
  20678. loadTS = () => {
  20679. try {
  20680. return _loadTS();
  20681. } catch (err) {
  20682. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  20683. throw new Error(
  20684. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.'
  20685. );
  20686. } else {
  20687. throw new Error(
  20688. "Failed to load TypeScript for resolving imported types."
  20689. );
  20690. }
  20691. }
  20692. };
  20693. }
  20694. function resolveFS(ctx) {
  20695. if (ctx.fs) {
  20696. return ctx.fs;
  20697. }
  20698. if (!ts && loadTS) {
  20699. ts = loadTS();
  20700. }
  20701. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  20702. if (!fs) {
  20703. return;
  20704. }
  20705. return ctx.fs = {
  20706. fileExists(file) {
  20707. if (file.endsWith(".vue.ts")) {
  20708. file = file.replace(/\.ts$/, "");
  20709. }
  20710. return fs.fileExists(file);
  20711. },
  20712. readFile(file) {
  20713. if (file.endsWith(".vue.ts")) {
  20714. file = file.replace(/\.ts$/, "");
  20715. }
  20716. return fs.readFile(file);
  20717. },
  20718. realpath: fs.realpath
  20719. };
  20720. }
  20721. function resolveTypeFromImport(ctx, node, name, scope) {
  20722. const { source, imported } = scope.imports[name];
  20723. const sourceScope = importSourceToScope(ctx, node, scope, source);
  20724. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  20725. }
  20726. function importSourceToScope(ctx, node, scope, source) {
  20727. let fs;
  20728. try {
  20729. fs = resolveFS(ctx);
  20730. } catch (err) {
  20731. return ctx.error(err.message, node, scope);
  20732. }
  20733. if (!fs) {
  20734. return ctx.error(
  20735. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  20736. node,
  20737. scope
  20738. );
  20739. }
  20740. let resolved = scope.resolvedImportSources[source];
  20741. if (!resolved) {
  20742. if (source.startsWith("..")) {
  20743. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  20744. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  20745. resolved = resolveExt(filename, fs);
  20746. } else if (source[0] === ".") {
  20747. const filename = joinPaths(path$1.dirname(scope.filename), source);
  20748. resolved = resolveExt(filename, fs);
  20749. } else {
  20750. if (!ts) {
  20751. if (loadTS) ts = loadTS();
  20752. if (!ts) {
  20753. return ctx.error(
  20754. `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.`,
  20755. node,
  20756. scope
  20757. );
  20758. }
  20759. }
  20760. resolved = resolveWithTS(scope.filename, source, ts, fs);
  20761. }
  20762. if (resolved) {
  20763. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  20764. }
  20765. }
  20766. if (resolved) {
  20767. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  20768. return fileToScope(ctx, resolved);
  20769. } else {
  20770. return ctx.error(
  20771. `Failed to resolve import source ${JSON.stringify(source)}.`,
  20772. node,
  20773. scope
  20774. );
  20775. }
  20776. }
  20777. function resolveExt(filename, fs) {
  20778. filename = filename.replace(/\.js$/, "");
  20779. const tryResolve = (filename2) => {
  20780. if (fs.fileExists(filename2)) return filename2;
  20781. };
  20782. 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`));
  20783. }
  20784. const tsConfigCache = createCache();
  20785. const tsConfigRefMap = /* @__PURE__ */ new Map();
  20786. function resolveWithTS(containingFile, source, ts2, fs) {
  20787. var _a, _b;
  20788. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  20789. let tsCompilerOptions;
  20790. let tsResolveCache;
  20791. if (configPath) {
  20792. let configs;
  20793. const normalizedConfigPath = normalizePath(configPath);
  20794. const cached = tsConfigCache.get(normalizedConfigPath);
  20795. if (!cached) {
  20796. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  20797. tsConfigCache.set(normalizedConfigPath, configs);
  20798. } else {
  20799. configs = cached;
  20800. }
  20801. let matchedConfig;
  20802. if (configs.length === 1) {
  20803. matchedConfig = configs[0];
  20804. } else {
  20805. for (const c of configs) {
  20806. const base = normalizePath(
  20807. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  20808. );
  20809. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  20810. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  20811. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, joinPaths(base, p))))) {
  20812. if (excluded && excluded.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  20813. continue;
  20814. }
  20815. matchedConfig = c;
  20816. break;
  20817. }
  20818. }
  20819. if (!matchedConfig) {
  20820. matchedConfig = configs[configs.length - 1];
  20821. }
  20822. }
  20823. tsCompilerOptions = matchedConfig.config.options;
  20824. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  20825. process__namespace.cwd(),
  20826. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  20827. tsCompilerOptions
  20828. ));
  20829. } else {
  20830. tsCompilerOptions = {};
  20831. }
  20832. const res = ts2.resolveModuleName(
  20833. source,
  20834. containingFile,
  20835. tsCompilerOptions,
  20836. fs,
  20837. tsResolveCache
  20838. );
  20839. if (res.resolvedModule) {
  20840. let filename = res.resolvedModule.resolvedFileName;
  20841. if (filename.endsWith(".vue.ts")) {
  20842. filename = filename.replace(/\.ts$/, "");
  20843. }
  20844. return fs.realpath ? fs.realpath(filename) : filename;
  20845. }
  20846. }
  20847. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  20848. const parseConfigHost = ts2.sys;
  20849. const config = ts2.parseJsonConfigFileContent(
  20850. ts2.readConfigFile(configPath, fs.readFile).config,
  20851. parseConfigHost,
  20852. path$1.dirname(configPath),
  20853. void 0,
  20854. configPath
  20855. );
  20856. const res = [config];
  20857. visited.add(configPath);
  20858. if (config.projectReferences) {
  20859. for (const ref of config.projectReferences) {
  20860. const refPath = ts2.resolveProjectReferencePath(ref);
  20861. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  20862. continue;
  20863. }
  20864. tsConfigRefMap.set(refPath, configPath);
  20865. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  20866. }
  20867. }
  20868. return res;
  20869. }
  20870. const fileToScopeCache = createCache();
  20871. function invalidateTypeCache(filename) {
  20872. filename = normalizePath(filename);
  20873. fileToScopeCache.delete(filename);
  20874. tsConfigCache.delete(filename);
  20875. const affectedConfig = tsConfigRefMap.get(filename);
  20876. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  20877. }
  20878. function fileToScope(ctx, filename, asGlobal = false) {
  20879. const cached = fileToScopeCache.get(filename);
  20880. if (cached) {
  20881. return cached;
  20882. }
  20883. const fs = resolveFS(ctx);
  20884. const source = fs.readFile(filename) || "";
  20885. const body = parseFile(filename, source, ctx.options.babelParserPlugins);
  20886. const scope = new TypeScope(filename, source, 0, recordImports(body));
  20887. recordTypes(ctx, body, scope, asGlobal);
  20888. fileToScopeCache.set(filename, scope);
  20889. return scope;
  20890. }
  20891. function parseFile(filename, content, parserPlugins) {
  20892. const ext = path$1.extname(filename);
  20893. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".mtsx") {
  20894. return parser$2.parse(content, {
  20895. plugins: resolveParserPlugins(
  20896. ext.slice(1),
  20897. parserPlugins,
  20898. /\.d\.m?ts$/.test(filename)
  20899. ),
  20900. sourceType: "module"
  20901. }).program.body;
  20902. } else if (ext === ".vue") {
  20903. const {
  20904. descriptor: { script, scriptSetup }
  20905. } = parse$1(content);
  20906. if (!script && !scriptSetup) {
  20907. return [];
  20908. }
  20909. const scriptOffset = script ? script.loc.start.offset : Infinity;
  20910. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  20911. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  20912. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  20913. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  20914. if (secondBlock) {
  20915. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  20916. }
  20917. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  20918. return parser$2.parse(scriptContent, {
  20919. plugins: resolveParserPlugins(lang, parserPlugins),
  20920. sourceType: "module"
  20921. }).program.body;
  20922. }
  20923. return [];
  20924. }
  20925. function ctxToScope(ctx) {
  20926. if (ctx.scope) {
  20927. return ctx.scope;
  20928. }
  20929. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  20930. const scope = new TypeScope(
  20931. ctx.filename,
  20932. ctx.source,
  20933. "startOffset" in ctx ? ctx.startOffset : 0,
  20934. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  20935. );
  20936. recordTypes(ctx, body, scope);
  20937. return ctx.scope = scope;
  20938. }
  20939. function moduleDeclToScope(ctx, node, parentScope) {
  20940. if (node._resolvedChildScope) {
  20941. return node._resolvedChildScope;
  20942. }
  20943. const scope = createChildScope(parentScope);
  20944. if (node.body.type === "TSModuleDeclaration") {
  20945. const decl = node.body;
  20946. decl._ownerScope = scope;
  20947. const id = getId(decl.id);
  20948. scope.types[id] = scope.exportedTypes[id] = decl;
  20949. } else {
  20950. recordTypes(ctx, node.body.body, scope);
  20951. }
  20952. return node._resolvedChildScope = scope;
  20953. }
  20954. function createChildScope(parentScope) {
  20955. return new TypeScope(
  20956. parentScope.filename,
  20957. parentScope.source,
  20958. parentScope.offset,
  20959. Object.create(parentScope.imports),
  20960. Object.create(parentScope.types),
  20961. Object.create(parentScope.declares)
  20962. );
  20963. }
  20964. const importExportRE = /^Import|^Export/;
  20965. function recordTypes(ctx, body, scope, asGlobal = false) {
  20966. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  20967. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  20968. for (const stmt of body) {
  20969. if (asGlobal) {
  20970. if (isAmbient) {
  20971. if (stmt.declare) {
  20972. recordType(stmt, types, declares);
  20973. }
  20974. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  20975. for (const s of stmt.body.body) {
  20976. recordType(s, types, declares);
  20977. }
  20978. }
  20979. } else {
  20980. recordType(stmt, types, declares);
  20981. }
  20982. }
  20983. if (!asGlobal) {
  20984. for (const stmt of body) {
  20985. if (stmt.type === "ExportNamedDeclaration") {
  20986. if (stmt.declaration) {
  20987. recordType(stmt.declaration, types, declares);
  20988. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  20989. } else {
  20990. for (const spec of stmt.specifiers) {
  20991. if (spec.type === "ExportSpecifier") {
  20992. const local = spec.local.name;
  20993. const exported = getId(spec.exported);
  20994. if (stmt.source) {
  20995. imports[exported] = {
  20996. source: stmt.source.value,
  20997. imported: local
  20998. };
  20999. exportedTypes[exported] = {
  21000. type: "TSTypeReference",
  21001. typeName: {
  21002. type: "Identifier",
  21003. name: local
  21004. },
  21005. _ownerScope: scope
  21006. };
  21007. } else if (types[local]) {
  21008. exportedTypes[exported] = types[local];
  21009. }
  21010. }
  21011. }
  21012. }
  21013. } else if (stmt.type === "ExportAllDeclaration") {
  21014. const sourceScope = importSourceToScope(
  21015. ctx,
  21016. stmt.source,
  21017. scope,
  21018. stmt.source.value
  21019. );
  21020. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  21021. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  21022. if (stmt.declaration.type !== "Identifier") {
  21023. recordType(stmt.declaration, types, declares, "default");
  21024. recordType(
  21025. stmt.declaration,
  21026. exportedTypes,
  21027. exportedDeclares,
  21028. "default"
  21029. );
  21030. } else if (types[stmt.declaration.name]) {
  21031. exportedTypes["default"] = types[stmt.declaration.name];
  21032. }
  21033. }
  21034. }
  21035. }
  21036. for (const key of Object.keys(types)) {
  21037. const node = types[key];
  21038. node._ownerScope = scope;
  21039. if (node._ns) node._ns._ownerScope = scope;
  21040. }
  21041. for (const key of Object.keys(declares)) {
  21042. declares[key]._ownerScope = scope;
  21043. }
  21044. }
  21045. function recordType(node, types, declares, overwriteId) {
  21046. switch (node.type) {
  21047. case "TSInterfaceDeclaration":
  21048. case "TSEnumDeclaration":
  21049. case "TSModuleDeclaration": {
  21050. const id = overwriteId || getId(node.id);
  21051. let existing = types[id];
  21052. if (existing) {
  21053. if (node.type === "TSModuleDeclaration") {
  21054. if (existing.type === "TSModuleDeclaration") {
  21055. mergeNamespaces(existing, node);
  21056. } else {
  21057. attachNamespace(existing, node);
  21058. }
  21059. break;
  21060. }
  21061. if (existing.type === "TSModuleDeclaration") {
  21062. types[id] = node;
  21063. attachNamespace(node, existing);
  21064. break;
  21065. }
  21066. if (existing.type !== node.type) {
  21067. break;
  21068. }
  21069. if (node.type === "TSInterfaceDeclaration") {
  21070. existing.body.body.push(...node.body.body);
  21071. } else {
  21072. existing.members.push(...node.members);
  21073. }
  21074. } else {
  21075. types[id] = node;
  21076. }
  21077. break;
  21078. }
  21079. case "ClassDeclaration":
  21080. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  21081. break;
  21082. case "TSTypeAliasDeclaration":
  21083. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  21084. break;
  21085. case "TSDeclareFunction":
  21086. if (node.id) declares[node.id.name] = node;
  21087. break;
  21088. case "VariableDeclaration": {
  21089. if (node.declare) {
  21090. for (const decl of node.declarations) {
  21091. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  21092. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  21093. }
  21094. }
  21095. }
  21096. break;
  21097. }
  21098. }
  21099. }
  21100. function mergeNamespaces(to, from) {
  21101. const toBody = to.body;
  21102. const fromBody = from.body;
  21103. if (toBody.type === "TSModuleDeclaration") {
  21104. if (fromBody.type === "TSModuleDeclaration") {
  21105. mergeNamespaces(toBody, fromBody);
  21106. } else {
  21107. fromBody.body.push({
  21108. type: "ExportNamedDeclaration",
  21109. declaration: toBody,
  21110. exportKind: "type",
  21111. specifiers: []
  21112. });
  21113. }
  21114. } else if (fromBody.type === "TSModuleDeclaration") {
  21115. toBody.body.push({
  21116. type: "ExportNamedDeclaration",
  21117. declaration: fromBody,
  21118. exportKind: "type",
  21119. specifiers: []
  21120. });
  21121. } else {
  21122. toBody.body.push(...fromBody.body);
  21123. }
  21124. }
  21125. function attachNamespace(to, ns) {
  21126. if (!to._ns) {
  21127. to._ns = ns;
  21128. } else {
  21129. mergeNamespaces(to._ns, ns);
  21130. }
  21131. }
  21132. function recordImports(body) {
  21133. const imports = /* @__PURE__ */ Object.create(null);
  21134. for (const s of body) {
  21135. recordImport(s, imports);
  21136. }
  21137. return imports;
  21138. }
  21139. function recordImport(node, imports) {
  21140. if (node.type !== "ImportDeclaration") {
  21141. return;
  21142. }
  21143. for (const s of node.specifiers) {
  21144. imports[s.local.name] = {
  21145. imported: getImportedName(s),
  21146. source: node.source.value
  21147. };
  21148. }
  21149. }
  21150. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false) {
  21151. try {
  21152. switch (node.type) {
  21153. case "TSStringKeyword":
  21154. return ["String"];
  21155. case "TSNumberKeyword":
  21156. return ["Number"];
  21157. case "TSBooleanKeyword":
  21158. return ["Boolean"];
  21159. case "TSObjectKeyword":
  21160. return ["Object"];
  21161. case "TSNullKeyword":
  21162. return ["null"];
  21163. case "TSTypeLiteral":
  21164. case "TSInterfaceDeclaration": {
  21165. const types = /* @__PURE__ */ new Set();
  21166. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  21167. for (const m of members) {
  21168. if (isKeyOf) {
  21169. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  21170. types.add("Number");
  21171. } else if (m.type === "TSIndexSignature") {
  21172. const annotation = m.parameters[0].typeAnnotation;
  21173. if (annotation && annotation.type !== "Noop") {
  21174. const type = inferRuntimeType(
  21175. ctx,
  21176. annotation.typeAnnotation,
  21177. scope
  21178. )[0];
  21179. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  21180. types.add(type);
  21181. }
  21182. } else {
  21183. types.add("String");
  21184. }
  21185. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  21186. types.add("Function");
  21187. } else {
  21188. types.add("Object");
  21189. }
  21190. }
  21191. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  21192. }
  21193. case "TSPropertySignature":
  21194. if (node.typeAnnotation) {
  21195. return inferRuntimeType(
  21196. ctx,
  21197. node.typeAnnotation.typeAnnotation,
  21198. scope
  21199. );
  21200. }
  21201. break;
  21202. case "TSMethodSignature":
  21203. case "TSFunctionType":
  21204. return ["Function"];
  21205. case "TSArrayType":
  21206. case "TSTupleType":
  21207. return ["Array"];
  21208. case "TSLiteralType":
  21209. switch (node.literal.type) {
  21210. case "StringLiteral":
  21211. return ["String"];
  21212. case "BooleanLiteral":
  21213. return ["Boolean"];
  21214. case "NumericLiteral":
  21215. case "BigIntLiteral":
  21216. return ["Number"];
  21217. default:
  21218. return [UNKNOWN_TYPE];
  21219. }
  21220. case "TSTypeReference": {
  21221. const resolved = resolveTypeReference(ctx, node, scope);
  21222. if (resolved) {
  21223. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  21224. }
  21225. if (node.typeName.type === "Identifier") {
  21226. if (isKeyOf) {
  21227. switch (node.typeName.name) {
  21228. case "String":
  21229. case "Array":
  21230. case "ArrayLike":
  21231. case "Parameters":
  21232. case "ConstructorParameters":
  21233. case "ReadonlyArray":
  21234. return ["String", "Number"];
  21235. // TS built-in utility types
  21236. case "Record":
  21237. case "Partial":
  21238. case "Required":
  21239. case "Readonly":
  21240. if (node.typeParameters && node.typeParameters.params[0]) {
  21241. return inferRuntimeType(
  21242. ctx,
  21243. node.typeParameters.params[0],
  21244. scope,
  21245. true
  21246. );
  21247. }
  21248. break;
  21249. case "Pick":
  21250. case "Extract":
  21251. if (node.typeParameters && node.typeParameters.params[1]) {
  21252. return inferRuntimeType(
  21253. ctx,
  21254. node.typeParameters.params[1],
  21255. scope
  21256. );
  21257. }
  21258. break;
  21259. case "Function":
  21260. case "Object":
  21261. case "Set":
  21262. case "Map":
  21263. case "WeakSet":
  21264. case "WeakMap":
  21265. case "Date":
  21266. case "Promise":
  21267. case "Error":
  21268. case "Uppercase":
  21269. case "Lowercase":
  21270. case "Capitalize":
  21271. case "Uncapitalize":
  21272. case "ReadonlyMap":
  21273. case "ReadonlySet":
  21274. return ["String"];
  21275. }
  21276. } else {
  21277. switch (node.typeName.name) {
  21278. case "Array":
  21279. case "Function":
  21280. case "Object":
  21281. case "Set":
  21282. case "Map":
  21283. case "WeakSet":
  21284. case "WeakMap":
  21285. case "Date":
  21286. case "Promise":
  21287. case "Error":
  21288. return [node.typeName.name];
  21289. // TS built-in utility types
  21290. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  21291. case "Partial":
  21292. case "Required":
  21293. case "Readonly":
  21294. case "Record":
  21295. case "Pick":
  21296. case "Omit":
  21297. case "InstanceType":
  21298. return ["Object"];
  21299. case "Uppercase":
  21300. case "Lowercase":
  21301. case "Capitalize":
  21302. case "Uncapitalize":
  21303. return ["String"];
  21304. case "Parameters":
  21305. case "ConstructorParameters":
  21306. case "ReadonlyArray":
  21307. return ["Array"];
  21308. case "ReadonlyMap":
  21309. return ["Map"];
  21310. case "ReadonlySet":
  21311. return ["Set"];
  21312. case "NonNullable":
  21313. if (node.typeParameters && node.typeParameters.params[0]) {
  21314. return inferRuntimeType(
  21315. ctx,
  21316. node.typeParameters.params[0],
  21317. scope
  21318. ).filter((t) => t !== "null");
  21319. }
  21320. break;
  21321. case "Extract":
  21322. if (node.typeParameters && node.typeParameters.params[1]) {
  21323. return inferRuntimeType(
  21324. ctx,
  21325. node.typeParameters.params[1],
  21326. scope
  21327. );
  21328. }
  21329. break;
  21330. case "Exclude":
  21331. case "OmitThisParameter":
  21332. if (node.typeParameters && node.typeParameters.params[0]) {
  21333. return inferRuntimeType(
  21334. ctx,
  21335. node.typeParameters.params[0],
  21336. scope
  21337. );
  21338. }
  21339. break;
  21340. }
  21341. }
  21342. }
  21343. break;
  21344. }
  21345. case "TSParenthesizedType":
  21346. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  21347. case "TSUnionType":
  21348. return flattenTypes(ctx, node.types, scope, isKeyOf);
  21349. case "TSIntersectionType": {
  21350. return flattenTypes(ctx, node.types, scope, isKeyOf).filter(
  21351. (t) => t !== UNKNOWN_TYPE
  21352. );
  21353. }
  21354. case "TSEnumDeclaration":
  21355. return inferEnumType(node);
  21356. case "TSSymbolKeyword":
  21357. return ["Symbol"];
  21358. case "TSIndexedAccessType": {
  21359. const types = resolveIndexType(ctx, node, scope);
  21360. return flattenTypes(ctx, types, scope, isKeyOf);
  21361. }
  21362. case "ClassDeclaration":
  21363. return ["Object"];
  21364. case "TSImportType": {
  21365. const sourceScope = importSourceToScope(
  21366. ctx,
  21367. node.argument,
  21368. scope,
  21369. node.argument.value
  21370. );
  21371. const resolved = resolveTypeReference(ctx, node, sourceScope);
  21372. if (resolved) {
  21373. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  21374. }
  21375. break;
  21376. }
  21377. case "TSTypeQuery": {
  21378. const id = node.exprName;
  21379. if (id.type === "Identifier") {
  21380. const matched = scope.declares[id.name];
  21381. if (matched) {
  21382. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  21383. }
  21384. }
  21385. break;
  21386. }
  21387. // e.g. readonly
  21388. case "TSTypeOperator": {
  21389. return inferRuntimeType(
  21390. ctx,
  21391. node.typeAnnotation,
  21392. scope,
  21393. node.operator === "keyof"
  21394. );
  21395. }
  21396. case "TSAnyKeyword": {
  21397. if (isKeyOf) {
  21398. return ["String", "Number", "Symbol"];
  21399. }
  21400. break;
  21401. }
  21402. }
  21403. } catch (e) {
  21404. }
  21405. return [UNKNOWN_TYPE];
  21406. }
  21407. function flattenTypes(ctx, types, scope, isKeyOf = false) {
  21408. if (types.length === 1) {
  21409. return inferRuntimeType(ctx, types[0], scope, isKeyOf);
  21410. }
  21411. return [
  21412. ...new Set(
  21413. [].concat(
  21414. ...types.map((t) => inferRuntimeType(ctx, t, scope, isKeyOf))
  21415. )
  21416. )
  21417. ];
  21418. }
  21419. function inferEnumType(node) {
  21420. const types = /* @__PURE__ */ new Set();
  21421. for (const m of node.members) {
  21422. if (m.initializer) {
  21423. switch (m.initializer.type) {
  21424. case "StringLiteral":
  21425. types.add("String");
  21426. break;
  21427. case "NumericLiteral":
  21428. types.add("Number");
  21429. break;
  21430. }
  21431. }
  21432. }
  21433. return types.size ? [...types] : ["Number"];
  21434. }
  21435. function resolveExtractPropTypes({ props }, scope) {
  21436. const res = { props: {} };
  21437. for (const key in props) {
  21438. const raw = props[key];
  21439. res.props[key] = reverseInferType(
  21440. raw.key,
  21441. raw.typeAnnotation.typeAnnotation,
  21442. scope
  21443. );
  21444. }
  21445. return res;
  21446. }
  21447. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  21448. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  21449. const typeType = findStaticPropertyType(node, "type");
  21450. if (typeType) {
  21451. const requiredType = findStaticPropertyType(node, "required");
  21452. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  21453. return reverseInferType(key, typeType, scope, optional2, false);
  21454. }
  21455. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  21456. if (node.typeName.name.endsWith("Constructor")) {
  21457. return createProperty(
  21458. key,
  21459. ctorToType(node.typeName.name),
  21460. scope,
  21461. optional
  21462. );
  21463. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  21464. return createProperty(key, node.typeParameters.params[0], scope, optional);
  21465. }
  21466. }
  21467. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  21468. for (const t of node.typeParameters.params) {
  21469. const inferred = reverseInferType(key, t, scope, optional);
  21470. if (inferred) return inferred;
  21471. }
  21472. }
  21473. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  21474. }
  21475. function ctorToType(ctorType) {
  21476. const ctor = ctorType.slice(0, -11);
  21477. switch (ctor) {
  21478. case "String":
  21479. case "Number":
  21480. case "Boolean":
  21481. return { type: `TS${ctor}Keyword` };
  21482. case "Array":
  21483. case "Function":
  21484. case "Object":
  21485. case "Set":
  21486. case "Map":
  21487. case "WeakSet":
  21488. case "WeakMap":
  21489. case "Date":
  21490. case "Promise":
  21491. return {
  21492. type: "TSTypeReference",
  21493. typeName: { type: "Identifier", name: ctor }
  21494. };
  21495. }
  21496. return { type: `TSNullKeyword` };
  21497. }
  21498. function findStaticPropertyType(node, key) {
  21499. const prop = node.members.find(
  21500. (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation
  21501. );
  21502. return prop && prop.typeAnnotation.typeAnnotation;
  21503. }
  21504. function resolveReturnType(ctx, arg, scope) {
  21505. var _a;
  21506. let resolved = arg;
  21507. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  21508. resolved = resolveTypeReference(ctx, arg, scope);
  21509. }
  21510. if (!resolved) return;
  21511. if (resolved.type === "TSFunctionType") {
  21512. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  21513. }
  21514. if (resolved.type === "TSDeclareFunction") {
  21515. return resolved.returnType;
  21516. }
  21517. }
  21518. function resolveUnionType(ctx, node, scope) {
  21519. if (node.type === "TSTypeReference") {
  21520. const resolved = resolveTypeReference(ctx, node, scope);
  21521. if (resolved) node = resolved;
  21522. }
  21523. let types;
  21524. if (node.type === "TSUnionType") {
  21525. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  21526. } else {
  21527. types = [node];
  21528. }
  21529. return types;
  21530. }
  21531. const DEFINE_MODEL = "defineModel";
  21532. function processDefineModel(ctx, node, declId) {
  21533. if (!isCallOf(node, DEFINE_MODEL)) {
  21534. return false;
  21535. }
  21536. ctx.hasDefineModelCall = true;
  21537. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  21538. let modelName;
  21539. let options;
  21540. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  21541. const hasName = arg0 && arg0.type === "StringLiteral";
  21542. if (hasName) {
  21543. modelName = arg0.value;
  21544. options = node.arguments[1];
  21545. } else {
  21546. modelName = "modelValue";
  21547. options = arg0;
  21548. }
  21549. if (ctx.modelDecls[modelName]) {
  21550. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  21551. }
  21552. let optionsString = options && ctx.getString(options);
  21553. let optionsRemoved = !options;
  21554. const runtimeOptionNodes = [];
  21555. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  21556. let removed = 0;
  21557. for (let i = options.properties.length - 1; i >= 0; i--) {
  21558. const p = options.properties[i];
  21559. const next = options.properties[i + 1];
  21560. const start = p.start;
  21561. const end = next ? next.start : options.end - 1;
  21562. 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"))) {
  21563. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  21564. } else {
  21565. removed++;
  21566. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  21567. runtimeOptionNodes.push(p);
  21568. }
  21569. }
  21570. if (removed === options.properties.length) {
  21571. optionsRemoved = true;
  21572. ctx.s.remove(
  21573. ctx.startOffset + (hasName ? arg0.end : options.start),
  21574. ctx.startOffset + options.end
  21575. );
  21576. }
  21577. }
  21578. ctx.modelDecls[modelName] = {
  21579. type,
  21580. options: optionsString,
  21581. runtimeOptionNodes,
  21582. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  21583. };
  21584. ctx.bindingMetadata[modelName] = "props";
  21585. ctx.s.overwrite(
  21586. ctx.startOffset + node.callee.start,
  21587. ctx.startOffset + node.callee.end,
  21588. ctx.helper("useModel")
  21589. );
  21590. ctx.s.appendLeft(
  21591. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  21592. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  21593. );
  21594. return true;
  21595. }
  21596. function genModelProps(ctx) {
  21597. if (!ctx.hasDefineModelCall) return;
  21598. const isProd = !!ctx.options.isProd;
  21599. let modelPropsDecl = "";
  21600. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  21601. ctx.modelDecls
  21602. )) {
  21603. let skipCheck = false;
  21604. let codegenOptions = ``;
  21605. let runtimeTypes = type && inferRuntimeType(ctx, type);
  21606. if (runtimeTypes) {
  21607. const hasBoolean = runtimeTypes.includes("Boolean");
  21608. const hasFunction = runtimeTypes.includes("Function");
  21609. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  21610. if (hasUnknownType) {
  21611. if (hasBoolean || hasFunction) {
  21612. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  21613. skipCheck = true;
  21614. } else {
  21615. runtimeTypes = ["null"];
  21616. }
  21617. }
  21618. if (!isProd) {
  21619. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  21620. } else if (hasBoolean || runtimeOptions && hasFunction) {
  21621. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  21622. } else ;
  21623. }
  21624. let decl;
  21625. if (codegenOptions && runtimeOptions) {
  21626. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  21627. } else if (codegenOptions) {
  21628. decl = `{ ${codegenOptions} }`;
  21629. } else if (runtimeOptions) {
  21630. decl = runtimeOptions;
  21631. } else {
  21632. decl = `{}`;
  21633. }
  21634. modelPropsDecl += `
  21635. ${JSON.stringify(name)}: ${decl},`;
  21636. const modifierPropName = JSON.stringify(
  21637. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  21638. );
  21639. modelPropsDecl += `
  21640. ${modifierPropName}: {},`;
  21641. }
  21642. return `{${modelPropsDecl}
  21643. }`;
  21644. }
  21645. const DEFINE_PROPS = "defineProps";
  21646. const WITH_DEFAULTS = "withDefaults";
  21647. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  21648. if (!isCallOf(node, DEFINE_PROPS)) {
  21649. return processWithDefaults(ctx, node, declId);
  21650. }
  21651. if (ctx.hasDefinePropsCall) {
  21652. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  21653. }
  21654. ctx.hasDefinePropsCall = true;
  21655. ctx.propsRuntimeDecl = node.arguments[0];
  21656. if (ctx.propsRuntimeDecl) {
  21657. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  21658. if (!(key in ctx.bindingMetadata)) {
  21659. ctx.bindingMetadata[key] = "props";
  21660. }
  21661. }
  21662. }
  21663. if (node.typeParameters) {
  21664. if (ctx.propsRuntimeDecl) {
  21665. ctx.error(
  21666. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  21667. node
  21668. );
  21669. }
  21670. ctx.propsTypeDecl = node.typeParameters.params[0];
  21671. }
  21672. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  21673. processPropsDestructure(ctx, declId);
  21674. }
  21675. ctx.propsCall = node;
  21676. ctx.propsDecl = declId;
  21677. return true;
  21678. }
  21679. function processWithDefaults(ctx, node, declId) {
  21680. if (!isCallOf(node, WITH_DEFAULTS)) {
  21681. return false;
  21682. }
  21683. if (!processDefineProps(
  21684. ctx,
  21685. node.arguments[0],
  21686. declId,
  21687. true
  21688. )) {
  21689. ctx.error(
  21690. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  21691. node.arguments[0] || node
  21692. );
  21693. }
  21694. if (ctx.propsRuntimeDecl) {
  21695. ctx.error(
  21696. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  21697. node
  21698. );
  21699. }
  21700. if (declId && declId.type === "ObjectPattern") {
  21701. ctx.warn(
  21702. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  21703. Reactive destructure will be disabled when using withDefaults().
  21704. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  21705. node.callee
  21706. );
  21707. }
  21708. ctx.propsRuntimeDefaults = node.arguments[1];
  21709. if (!ctx.propsRuntimeDefaults) {
  21710. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  21711. }
  21712. ctx.propsCall = node;
  21713. return true;
  21714. }
  21715. function genRuntimeProps(ctx) {
  21716. let propsDecls;
  21717. if (ctx.propsRuntimeDecl) {
  21718. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  21719. if (ctx.propsDestructureDecl) {
  21720. const defaults = [];
  21721. for (const key in ctx.propsDestructuredBindings) {
  21722. const d = genDestructuredDefaultValue(ctx, key);
  21723. const finalKey = getEscapedPropName(key);
  21724. if (d)
  21725. defaults.push(
  21726. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  21727. );
  21728. }
  21729. if (defaults.length) {
  21730. propsDecls = `/*@__PURE__*/${ctx.helper(
  21731. `mergeDefaults`
  21732. )}(${propsDecls}, {
  21733. ${defaults.join(",\n ")}
  21734. })`;
  21735. }
  21736. }
  21737. } else if (ctx.propsTypeDecl) {
  21738. propsDecls = extractRuntimeProps(ctx);
  21739. }
  21740. const modelsDecls = genModelProps(ctx);
  21741. if (propsDecls && modelsDecls) {
  21742. return `/*@__PURE__*/${ctx.helper(
  21743. "mergeModels"
  21744. )}(${propsDecls}, ${modelsDecls})`;
  21745. } else {
  21746. return modelsDecls || propsDecls;
  21747. }
  21748. }
  21749. function extractRuntimeProps(ctx) {
  21750. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  21751. if (!props.length) {
  21752. return;
  21753. }
  21754. const propStrings = [];
  21755. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  21756. for (const prop of props) {
  21757. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  21758. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  21759. ctx.bindingMetadata[prop.key] = "props";
  21760. }
  21761. }
  21762. let propsDecls = `{
  21763. ${propStrings.join(",\n ")}
  21764. }`;
  21765. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  21766. propsDecls = `/*@__PURE__*/${ctx.helper(
  21767. "mergeDefaults"
  21768. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  21769. }
  21770. return propsDecls;
  21771. }
  21772. function resolveRuntimePropsFromType(ctx, node) {
  21773. const props = [];
  21774. const elements = resolveTypeElements(ctx, node);
  21775. for (const key in elements.props) {
  21776. const e = elements.props[key];
  21777. let type = inferRuntimeType(ctx, e);
  21778. let skipCheck = false;
  21779. if (type.includes(UNKNOWN_TYPE)) {
  21780. if (type.includes("Boolean") || type.includes("Function")) {
  21781. type = type.filter((t) => t !== UNKNOWN_TYPE);
  21782. skipCheck = true;
  21783. } else {
  21784. type = ["null"];
  21785. }
  21786. }
  21787. props.push({
  21788. key,
  21789. required: !e.optional,
  21790. type: type || [`null`],
  21791. skipCheck
  21792. });
  21793. }
  21794. return props;
  21795. }
  21796. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  21797. let defaultString;
  21798. const destructured = genDestructuredDefaultValue(ctx, key, type);
  21799. if (destructured) {
  21800. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  21801. } else if (hasStaticDefaults) {
  21802. const prop = ctx.propsRuntimeDefaults.properties.find(
  21803. (node) => {
  21804. if (node.type === "SpreadElement") return false;
  21805. return resolveObjectKey(node.key, node.computed) === key;
  21806. }
  21807. );
  21808. if (prop) {
  21809. if (prop.type === "ObjectProperty") {
  21810. defaultString = `default: ${ctx.getString(prop.value)}`;
  21811. } else {
  21812. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  21813. }
  21814. }
  21815. }
  21816. const finalKey = getEscapedPropName(key);
  21817. if (!ctx.options.isProd) {
  21818. return `${finalKey}: { ${concatStrings([
  21819. `type: ${toRuntimeTypeString(type)}`,
  21820. `required: ${required}`,
  21821. skipCheck && "skipCheck: true",
  21822. defaultString
  21823. ])} }`;
  21824. } else if (type.some(
  21825. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  21826. )) {
  21827. return `${finalKey}: { ${concatStrings([
  21828. `type: ${toRuntimeTypeString(type)}`,
  21829. defaultString
  21830. ])} }`;
  21831. } else {
  21832. if (ctx.isCE) {
  21833. if (defaultString) {
  21834. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  21835. type
  21836. )} }`}`;
  21837. } else {
  21838. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  21839. }
  21840. }
  21841. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  21842. }
  21843. }
  21844. function hasStaticWithDefaults(ctx) {
  21845. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  21846. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  21847. ));
  21848. }
  21849. function genDestructuredDefaultValue(ctx, key, inferredType) {
  21850. const destructured = ctx.propsDestructuredBindings[key];
  21851. const defaultVal = destructured && destructured.default;
  21852. if (defaultVal) {
  21853. const value = ctx.getString(defaultVal);
  21854. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  21855. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  21856. const valueType = inferValueType(unwrapped);
  21857. if (valueType && !inferredType.includes(valueType)) {
  21858. ctx.error(
  21859. `Default value of prop "${key}" does not match declared type.`,
  21860. unwrapped
  21861. );
  21862. }
  21863. }
  21864. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  21865. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  21866. return {
  21867. valueString: needFactoryWrap ? `() => (${value})` : value,
  21868. needSkipFactory
  21869. };
  21870. }
  21871. }
  21872. function inferValueType(node) {
  21873. switch (node.type) {
  21874. case "StringLiteral":
  21875. return "String";
  21876. case "NumericLiteral":
  21877. return "Number";
  21878. case "BooleanLiteral":
  21879. return "Boolean";
  21880. case "ObjectExpression":
  21881. return "Object";
  21882. case "ArrayExpression":
  21883. return "Array";
  21884. case "FunctionExpression":
  21885. case "ArrowFunctionExpression":
  21886. return "Function";
  21887. }
  21888. }
  21889. function processPropsDestructure(ctx, declId) {
  21890. if (ctx.options.propsDestructure === "error") {
  21891. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  21892. } else if (ctx.options.propsDestructure === false) {
  21893. return;
  21894. }
  21895. ctx.propsDestructureDecl = declId;
  21896. const registerBinding = (key, local, defaultValue) => {
  21897. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  21898. if (local !== key) {
  21899. ctx.bindingMetadata[local] = "props-aliased";
  21900. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  21901. }
  21902. };
  21903. for (const prop of declId.properties) {
  21904. if (prop.type === "ObjectProperty") {
  21905. const propKey = resolveObjectKey(prop.key, prop.computed);
  21906. if (!propKey) {
  21907. ctx.error(
  21908. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  21909. prop.key
  21910. );
  21911. }
  21912. if (prop.value.type === "AssignmentPattern") {
  21913. const { left, right } = prop.value;
  21914. if (left.type !== "Identifier") {
  21915. ctx.error(
  21916. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  21917. left
  21918. );
  21919. }
  21920. registerBinding(propKey, left.name, right);
  21921. } else if (prop.value.type === "Identifier") {
  21922. registerBinding(propKey, prop.value.name);
  21923. } else {
  21924. ctx.error(
  21925. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  21926. prop.value
  21927. );
  21928. }
  21929. } else {
  21930. ctx.propsDestructureRestId = prop.argument.name;
  21931. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  21932. }
  21933. }
  21934. }
  21935. function transformDestructuredProps(ctx, vueImportAliases) {
  21936. if (ctx.options.propsDestructure === false) {
  21937. return;
  21938. }
  21939. const rootScope = /* @__PURE__ */ Object.create(null);
  21940. const scopeStack = [rootScope];
  21941. let currentScope = rootScope;
  21942. const excludedIds = /* @__PURE__ */ new WeakSet();
  21943. const parentStack = [];
  21944. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  21945. for (const key in ctx.propsDestructuredBindings) {
  21946. const { local } = ctx.propsDestructuredBindings[key];
  21947. rootScope[local] = true;
  21948. propsLocalToPublicMap[local] = key;
  21949. }
  21950. function pushScope() {
  21951. scopeStack.push(currentScope = Object.create(currentScope));
  21952. }
  21953. function popScope() {
  21954. scopeStack.pop();
  21955. currentScope = scopeStack[scopeStack.length - 1] || null;
  21956. }
  21957. function registerLocalBinding(id) {
  21958. excludedIds.add(id);
  21959. if (currentScope) {
  21960. currentScope[id.name] = false;
  21961. } else {
  21962. ctx.error(
  21963. "registerBinding called without active scope, something is wrong.",
  21964. id
  21965. );
  21966. }
  21967. }
  21968. function walkScope(node, isRoot = false) {
  21969. for (const stmt of node.body) {
  21970. if (stmt.type === "VariableDeclaration") {
  21971. walkVariableDeclaration(stmt, isRoot);
  21972. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  21973. if (stmt.declare || !stmt.id) continue;
  21974. registerLocalBinding(stmt.id);
  21975. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  21976. walkVariableDeclaration(stmt.left);
  21977. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  21978. walkVariableDeclaration(stmt.declaration, isRoot);
  21979. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  21980. walkVariableDeclaration(stmt.body, isRoot);
  21981. }
  21982. }
  21983. }
  21984. function walkVariableDeclaration(stmt, isRoot = false) {
  21985. if (stmt.declare) {
  21986. return;
  21987. }
  21988. for (const decl of stmt.declarations) {
  21989. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  21990. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  21991. if (isDefineProps) {
  21992. excludedIds.add(id);
  21993. } else {
  21994. registerLocalBinding(id);
  21995. }
  21996. }
  21997. }
  21998. }
  21999. function rewriteId(id, parent, parentStack2) {
  22000. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  22001. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  22002. }
  22003. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  22004. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  22005. ctx.s.appendLeft(
  22006. id.end + ctx.startOffset,
  22007. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  22008. );
  22009. }
  22010. } else {
  22011. ctx.s.overwrite(
  22012. id.start + ctx.startOffset,
  22013. id.end + ctx.startOffset,
  22014. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  22015. );
  22016. }
  22017. }
  22018. function checkUsage(node, method, alias = method) {
  22019. if (isCallOf(node, alias)) {
  22020. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22021. if (arg.type === "Identifier" && currentScope[arg.name]) {
  22022. ctx.error(
  22023. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  22024. arg
  22025. );
  22026. }
  22027. }
  22028. }
  22029. const ast = ctx.scriptSetupAst;
  22030. walkScope(ast, true);
  22031. estreeWalker.walk(ast, {
  22032. enter(node, parent) {
  22033. parent && parentStack.push(parent);
  22034. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22035. return this.skip();
  22036. }
  22037. checkUsage(node, "watch", vueImportAliases.watch);
  22038. checkUsage(node, "toRef", vueImportAliases.toRef);
  22039. if (CompilerDOM.isFunctionType(node)) {
  22040. pushScope();
  22041. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  22042. if (node.body.type === "BlockStatement") {
  22043. walkScope(node.body);
  22044. }
  22045. return;
  22046. }
  22047. if (node.type === "CatchClause") {
  22048. pushScope();
  22049. if (node.param && node.param.type === "Identifier") {
  22050. registerLocalBinding(node.param);
  22051. }
  22052. walkScope(node.body);
  22053. return;
  22054. }
  22055. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22056. pushScope();
  22057. walkScope(node);
  22058. return;
  22059. }
  22060. if (node.type === "Identifier") {
  22061. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  22062. if (currentScope[node.name]) {
  22063. rewriteId(node, parent, parentStack);
  22064. }
  22065. }
  22066. }
  22067. },
  22068. leave(node, parent) {
  22069. parent && parentStack.pop();
  22070. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node)) {
  22071. popScope();
  22072. }
  22073. }
  22074. });
  22075. }
  22076. const DEFINE_EMITS = "defineEmits";
  22077. function processDefineEmits(ctx, node, declId) {
  22078. if (!isCallOf(node, DEFINE_EMITS)) {
  22079. return false;
  22080. }
  22081. if (ctx.hasDefineEmitCall) {
  22082. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  22083. }
  22084. ctx.hasDefineEmitCall = true;
  22085. ctx.emitsRuntimeDecl = node.arguments[0];
  22086. if (node.typeParameters) {
  22087. if (ctx.emitsRuntimeDecl) {
  22088. ctx.error(
  22089. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22090. node
  22091. );
  22092. }
  22093. ctx.emitsTypeDecl = node.typeParameters.params[0];
  22094. }
  22095. ctx.emitDecl = declId;
  22096. return true;
  22097. }
  22098. function genRuntimeEmits(ctx) {
  22099. let emitsDecl = "";
  22100. if (ctx.emitsRuntimeDecl) {
  22101. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  22102. } else if (ctx.emitsTypeDecl) {
  22103. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  22104. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  22105. }
  22106. if (ctx.hasDefineModelCall) {
  22107. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  22108. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  22109. "mergeModels"
  22110. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  22111. }
  22112. return emitsDecl;
  22113. }
  22114. function extractRuntimeEmits(ctx) {
  22115. const emits = /* @__PURE__ */ new Set();
  22116. const node = ctx.emitsTypeDecl;
  22117. if (node.type === "TSFunctionType") {
  22118. extractEventNames(ctx, node.parameters[0], emits);
  22119. return emits;
  22120. }
  22121. const { props, calls } = resolveTypeElements(ctx, node);
  22122. let hasProperty = false;
  22123. for (const key in props) {
  22124. emits.add(key);
  22125. hasProperty = true;
  22126. }
  22127. if (calls) {
  22128. if (hasProperty) {
  22129. ctx.error(
  22130. `defineEmits() type cannot mixed call signature and property syntax.`,
  22131. node
  22132. );
  22133. }
  22134. for (const call of calls) {
  22135. extractEventNames(ctx, call.parameters[0], emits);
  22136. }
  22137. }
  22138. return emits;
  22139. }
  22140. function extractEventNames(ctx, eventName, emits) {
  22141. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  22142. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  22143. for (const type of types) {
  22144. if (type.type === "TSLiteralType") {
  22145. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  22146. emits.add(String(type.literal.value));
  22147. }
  22148. }
  22149. }
  22150. }
  22151. }
  22152. const DEFINE_EXPOSE = "defineExpose";
  22153. function processDefineExpose(ctx, node) {
  22154. if (isCallOf(node, DEFINE_EXPOSE)) {
  22155. if (ctx.hasDefineExposeCall) {
  22156. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  22157. }
  22158. ctx.hasDefineExposeCall = true;
  22159. return true;
  22160. }
  22161. return false;
  22162. }
  22163. const DEFINE_SLOTS = "defineSlots";
  22164. function processDefineSlots(ctx, node, declId) {
  22165. if (!isCallOf(node, DEFINE_SLOTS)) {
  22166. return false;
  22167. }
  22168. if (ctx.hasDefineSlotsCall) {
  22169. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  22170. }
  22171. ctx.hasDefineSlotsCall = true;
  22172. if (node.arguments.length > 0) {
  22173. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  22174. }
  22175. if (declId) {
  22176. ctx.s.overwrite(
  22177. ctx.startOffset + node.start,
  22178. ctx.startOffset + node.end,
  22179. `${ctx.helper("useSlots")}()`
  22180. );
  22181. }
  22182. return true;
  22183. }
  22184. const DEFINE_OPTIONS = "defineOptions";
  22185. function processDefineOptions(ctx, node) {
  22186. if (!isCallOf(node, DEFINE_OPTIONS)) {
  22187. return false;
  22188. }
  22189. if (ctx.hasDefineOptionsCall) {
  22190. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  22191. }
  22192. if (node.typeParameters) {
  22193. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  22194. }
  22195. if (!node.arguments[0]) return true;
  22196. ctx.hasDefineOptionsCall = true;
  22197. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22198. let propsOption = void 0;
  22199. let emitsOption = void 0;
  22200. let exposeOption = void 0;
  22201. let slotsOption = void 0;
  22202. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  22203. for (const prop of ctx.optionsRuntimeDecl.properties) {
  22204. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  22205. switch (prop.key.name) {
  22206. case "props":
  22207. propsOption = prop;
  22208. break;
  22209. case "emits":
  22210. emitsOption = prop;
  22211. break;
  22212. case "expose":
  22213. exposeOption = prop;
  22214. break;
  22215. case "slots":
  22216. slotsOption = prop;
  22217. break;
  22218. }
  22219. }
  22220. }
  22221. }
  22222. if (propsOption) {
  22223. ctx.error(
  22224. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  22225. propsOption
  22226. );
  22227. }
  22228. if (emitsOption) {
  22229. ctx.error(
  22230. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  22231. emitsOption
  22232. );
  22233. }
  22234. if (exposeOption) {
  22235. ctx.error(
  22236. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  22237. exposeOption
  22238. );
  22239. }
  22240. if (slotsOption) {
  22241. ctx.error(
  22242. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  22243. slotsOption
  22244. );
  22245. }
  22246. return true;
  22247. }
  22248. function processAwait(ctx, node, needSemi, isStatement) {
  22249. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  22250. const startOffset = ctx.startOffset;
  22251. const argumentStr = ctx.descriptor.source.slice(
  22252. argumentStart + startOffset,
  22253. node.argument.end + startOffset
  22254. );
  22255. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  22256. ctx.s.overwrite(
  22257. node.start + startOffset,
  22258. argumentStart + startOffset,
  22259. `${needSemi ? `;` : ``}(
  22260. ([__temp,__restore] = ${ctx.helper(
  22261. `withAsyncContext`
  22262. )}(${containsNestedAwait ? `async ` : ``}() => `
  22263. );
  22264. ctx.s.appendLeft(
  22265. node.end + startOffset,
  22266. `)),
  22267. ${isStatement ? `` : `__temp = `}await __temp,
  22268. __restore()${isStatement ? `` : `,
  22269. __temp`}
  22270. )`
  22271. );
  22272. }
  22273. const MACROS = [
  22274. DEFINE_PROPS,
  22275. DEFINE_EMITS,
  22276. DEFINE_EXPOSE,
  22277. DEFINE_OPTIONS,
  22278. DEFINE_SLOTS,
  22279. DEFINE_MODEL,
  22280. WITH_DEFAULTS
  22281. ];
  22282. function compileScript(sfc, options) {
  22283. var _a, _b, _c;
  22284. if (!options.id) {
  22285. warnOnce(
  22286. `compileScript now requires passing the \`id\` option.
  22287. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  22288. );
  22289. }
  22290. const ctx = new ScriptCompileContext(sfc, options);
  22291. const { script, scriptSetup, source, filename } = sfc;
  22292. const hoistStatic = options.hoistStatic !== false && !script;
  22293. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  22294. const scriptLang = script && script.lang;
  22295. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  22296. if (!scriptSetup) {
  22297. if (!script) {
  22298. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  22299. }
  22300. return processNormalScript(ctx, scopeId);
  22301. }
  22302. if (script && scriptLang !== scriptSetupLang) {
  22303. throw new Error(
  22304. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  22305. );
  22306. }
  22307. if (scriptSetupLang && !ctx.isJS && !ctx.isTS) {
  22308. return scriptSetup;
  22309. }
  22310. const scriptBindings = /* @__PURE__ */ Object.create(null);
  22311. const setupBindings = /* @__PURE__ */ Object.create(null);
  22312. let defaultExport;
  22313. let hasAwait = false;
  22314. let hasInlinedSsrRenderFn = false;
  22315. const startOffset = ctx.startOffset;
  22316. const endOffset = ctx.endOffset;
  22317. const scriptStartOffset = script && script.loc.start.offset;
  22318. const scriptEndOffset = script && script.loc.end.offset;
  22319. function hoistNode(node) {
  22320. const start = node.start + startOffset;
  22321. let end = node.end + startOffset;
  22322. if (node.trailingComments && node.trailingComments.length > 0) {
  22323. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  22324. end = lastCommentNode.end + startOffset;
  22325. }
  22326. while (end <= source.length) {
  22327. if (!/\s/.test(source.charAt(end))) {
  22328. break;
  22329. }
  22330. end++;
  22331. }
  22332. ctx.s.move(start, end, 0);
  22333. }
  22334. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  22335. let isUsedInTemplate = needTemplateUsageCheck;
  22336. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  22337. isUsedInTemplate = isImportUsed(local, sfc);
  22338. }
  22339. ctx.userImports[local] = {
  22340. isType,
  22341. imported,
  22342. local,
  22343. source: source2,
  22344. isFromSetup,
  22345. isUsedInTemplate
  22346. };
  22347. }
  22348. function checkInvalidScopeReference(node, method) {
  22349. if (!node) return;
  22350. CompilerDOM.walkIdentifiers(node, (id) => {
  22351. const binding = setupBindings[id.name];
  22352. if (binding && binding !== "literal-const") {
  22353. ctx.error(
  22354. `\`${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.`,
  22355. id
  22356. );
  22357. }
  22358. });
  22359. }
  22360. const scriptAst = ctx.scriptAst;
  22361. const scriptSetupAst = ctx.scriptSetupAst;
  22362. if (scriptAst) {
  22363. for (const node of scriptAst.body) {
  22364. if (node.type === "ImportDeclaration") {
  22365. for (const specifier of node.specifiers) {
  22366. const imported = getImportedName(specifier);
  22367. registerUserImport(
  22368. node.source.value,
  22369. specifier.local.name,
  22370. imported,
  22371. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22372. false,
  22373. !options.inlineTemplate
  22374. );
  22375. }
  22376. }
  22377. }
  22378. }
  22379. for (const node of scriptSetupAst.body) {
  22380. if (node.type === "ImportDeclaration") {
  22381. hoistNode(node);
  22382. let removed = 0;
  22383. const removeSpecifier = (i) => {
  22384. const removeLeft = i > removed;
  22385. removed++;
  22386. const current = node.specifiers[i];
  22387. const next = node.specifiers[i + 1];
  22388. ctx.s.remove(
  22389. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  22390. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  22391. );
  22392. };
  22393. for (let i = 0; i < node.specifiers.length; i++) {
  22394. const specifier = node.specifiers[i];
  22395. const local = specifier.local.name;
  22396. const imported = getImportedName(specifier);
  22397. const source2 = node.source.value;
  22398. const existing = ctx.userImports[local];
  22399. if (source2 === "vue" && MACROS.includes(imported)) {
  22400. if (local === imported) {
  22401. warnOnce(
  22402. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  22403. );
  22404. } else {
  22405. ctx.error(
  22406. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  22407. specifier
  22408. );
  22409. }
  22410. removeSpecifier(i);
  22411. } else if (existing) {
  22412. if (existing.source === source2 && existing.imported === imported) {
  22413. removeSpecifier(i);
  22414. } else {
  22415. ctx.error(
  22416. `different imports aliased to same local name.`,
  22417. specifier
  22418. );
  22419. }
  22420. } else {
  22421. registerUserImport(
  22422. source2,
  22423. local,
  22424. imported,
  22425. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22426. true,
  22427. !options.inlineTemplate
  22428. );
  22429. }
  22430. }
  22431. if (node.specifiers.length && removed === node.specifiers.length) {
  22432. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22433. }
  22434. }
  22435. }
  22436. const vueImportAliases = {};
  22437. for (const key in ctx.userImports) {
  22438. const { source: source2, imported, local } = ctx.userImports[key];
  22439. if (source2 === "vue") vueImportAliases[imported] = local;
  22440. }
  22441. if (script && scriptAst) {
  22442. for (const node of scriptAst.body) {
  22443. if (node.type === "ExportDefaultDeclaration") {
  22444. defaultExport = node;
  22445. let optionProperties;
  22446. if (defaultExport.declaration.type === "ObjectExpression") {
  22447. optionProperties = defaultExport.declaration.properties;
  22448. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  22449. optionProperties = defaultExport.declaration.arguments[0].properties;
  22450. }
  22451. if (optionProperties) {
  22452. for (const p of optionProperties) {
  22453. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  22454. ctx.hasDefaultExportName = true;
  22455. }
  22456. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  22457. ctx.hasDefaultExportRender = true;
  22458. }
  22459. }
  22460. }
  22461. const start = node.start + scriptStartOffset;
  22462. const end = node.declaration.start + scriptStartOffset;
  22463. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  22464. } else if (node.type === "ExportNamedDeclaration") {
  22465. const defaultSpecifier = node.specifiers.find(
  22466. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  22467. );
  22468. if (defaultSpecifier) {
  22469. defaultExport = node;
  22470. if (node.specifiers.length > 1) {
  22471. ctx.s.remove(
  22472. defaultSpecifier.start + scriptStartOffset,
  22473. defaultSpecifier.end + scriptStartOffset
  22474. );
  22475. } else {
  22476. ctx.s.remove(
  22477. node.start + scriptStartOffset,
  22478. node.end + scriptStartOffset
  22479. );
  22480. }
  22481. if (node.source) {
  22482. ctx.s.prepend(
  22483. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  22484. `
  22485. );
  22486. } else {
  22487. ctx.s.appendLeft(
  22488. scriptEndOffset,
  22489. `
  22490. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  22491. `
  22492. );
  22493. }
  22494. }
  22495. if (node.declaration) {
  22496. walkDeclaration(
  22497. "script",
  22498. node.declaration,
  22499. scriptBindings,
  22500. vueImportAliases,
  22501. hoistStatic
  22502. );
  22503. }
  22504. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  22505. walkDeclaration(
  22506. "script",
  22507. node,
  22508. scriptBindings,
  22509. vueImportAliases,
  22510. hoistStatic
  22511. );
  22512. }
  22513. }
  22514. if (scriptStartOffset > startOffset) {
  22515. if (!/\n$/.test(script.content.trim())) {
  22516. ctx.s.appendLeft(scriptEndOffset, `
  22517. `);
  22518. }
  22519. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  22520. }
  22521. }
  22522. for (const node of scriptSetupAst.body) {
  22523. if (node.type === "ExpressionStatement") {
  22524. const expr = CompilerDOM.unwrapTSNode(node.expression);
  22525. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  22526. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22527. } else if (processDefineExpose(ctx, expr)) {
  22528. const callee = expr.callee;
  22529. ctx.s.overwrite(
  22530. callee.start + startOffset,
  22531. callee.end + startOffset,
  22532. "__expose"
  22533. );
  22534. } else {
  22535. processDefineModel(ctx, expr);
  22536. }
  22537. }
  22538. if (node.type === "VariableDeclaration" && !node.declare) {
  22539. const total = node.declarations.length;
  22540. let left = total;
  22541. let lastNonRemoved;
  22542. for (let i = 0; i < total; i++) {
  22543. const decl = node.declarations[i];
  22544. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  22545. if (init) {
  22546. if (processDefineOptions(ctx, init)) {
  22547. ctx.error(
  22548. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  22549. node
  22550. );
  22551. }
  22552. const isDefineProps = processDefineProps(ctx, init, decl.id);
  22553. if (ctx.propsDestructureRestId) {
  22554. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  22555. }
  22556. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  22557. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  22558. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  22559. if (left === 1) {
  22560. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22561. } else {
  22562. let start = decl.start + startOffset;
  22563. let end = decl.end + startOffset;
  22564. if (i === total - 1) {
  22565. start = node.declarations[lastNonRemoved].end + startOffset;
  22566. } else {
  22567. end = node.declarations[i + 1].start + startOffset;
  22568. }
  22569. ctx.s.remove(start, end);
  22570. left--;
  22571. }
  22572. } else if (isDefineEmits) {
  22573. ctx.s.overwrite(
  22574. startOffset + init.start,
  22575. startOffset + init.end,
  22576. "__emit"
  22577. );
  22578. } else {
  22579. lastNonRemoved = i;
  22580. }
  22581. }
  22582. }
  22583. }
  22584. let isAllLiteral = false;
  22585. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  22586. isAllLiteral = walkDeclaration(
  22587. "scriptSetup",
  22588. node,
  22589. setupBindings,
  22590. vueImportAliases,
  22591. hoistStatic,
  22592. !!ctx.propsDestructureDecl
  22593. );
  22594. }
  22595. if (hoistStatic && isAllLiteral) {
  22596. hoistNode(node);
  22597. }
  22598. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  22599. const scope = [scriptSetupAst.body];
  22600. estreeWalker.walk(node, {
  22601. enter(child, parent) {
  22602. if (CompilerDOM.isFunctionType(child)) {
  22603. this.skip();
  22604. }
  22605. if (child.type === "BlockStatement") {
  22606. scope.push(child.body);
  22607. }
  22608. if (child.type === "AwaitExpression") {
  22609. hasAwait = true;
  22610. const currentScope = scope[scope.length - 1];
  22611. const needsSemi = currentScope.some((n, i) => {
  22612. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  22613. });
  22614. processAwait(
  22615. ctx,
  22616. child,
  22617. needsSemi,
  22618. parent.type === "ExpressionStatement"
  22619. );
  22620. }
  22621. },
  22622. exit(node2) {
  22623. if (node2.type === "BlockStatement") scope.pop();
  22624. }
  22625. });
  22626. }
  22627. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  22628. ctx.error(
  22629. `<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.`,
  22630. node
  22631. );
  22632. }
  22633. if (ctx.isTS) {
  22634. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  22635. if (node.type !== "TSEnumDeclaration") {
  22636. hoistNode(node);
  22637. }
  22638. }
  22639. }
  22640. }
  22641. if (ctx.propsDestructureDecl) {
  22642. transformDestructuredProps(ctx, vueImportAliases);
  22643. }
  22644. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  22645. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  22646. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  22647. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  22648. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  22649. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  22650. for (const node of runtimeOptionNodes) {
  22651. checkInvalidScopeReference(node, DEFINE_MODEL);
  22652. }
  22653. }
  22654. if (script) {
  22655. if (startOffset < scriptStartOffset) {
  22656. ctx.s.remove(0, startOffset);
  22657. ctx.s.remove(endOffset, scriptStartOffset);
  22658. ctx.s.remove(scriptEndOffset, source.length);
  22659. } else {
  22660. ctx.s.remove(0, scriptStartOffset);
  22661. ctx.s.remove(scriptEndOffset, startOffset);
  22662. ctx.s.remove(endOffset, source.length);
  22663. }
  22664. } else {
  22665. ctx.s.remove(0, startOffset);
  22666. ctx.s.remove(endOffset, source.length);
  22667. }
  22668. if (scriptAst) {
  22669. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  22670. }
  22671. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  22672. ctx.userImports
  22673. )) {
  22674. if (isType) continue;
  22675. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  22676. }
  22677. for (const key in scriptBindings) {
  22678. ctx.bindingMetadata[key] = scriptBindings[key];
  22679. }
  22680. for (const key in setupBindings) {
  22681. ctx.bindingMetadata[key] = setupBindings[key];
  22682. }
  22683. if (sfc.cssVars.length && // no need to do this when targeting SSR
  22684. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  22685. ctx.helperImports.add(CSS_VARS_HELPER);
  22686. ctx.helperImports.add("unref");
  22687. ctx.s.prependLeft(
  22688. startOffset,
  22689. `
  22690. ${genCssVarsCode(
  22691. sfc.cssVars,
  22692. ctx.bindingMetadata,
  22693. scopeId,
  22694. !!options.isProd
  22695. )}
  22696. `
  22697. );
  22698. }
  22699. let args = `__props`;
  22700. if (ctx.propsTypeDecl) {
  22701. args += `: any`;
  22702. }
  22703. if (ctx.propsDecl) {
  22704. if (ctx.propsDestructureRestId) {
  22705. ctx.s.overwrite(
  22706. startOffset + ctx.propsCall.start,
  22707. startOffset + ctx.propsCall.end,
  22708. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  22709. Object.keys(ctx.propsDestructuredBindings)
  22710. )})`
  22711. );
  22712. ctx.s.overwrite(
  22713. startOffset + ctx.propsDestructureDecl.start,
  22714. startOffset + ctx.propsDestructureDecl.end,
  22715. ctx.propsDestructureRestId
  22716. );
  22717. } else if (!ctx.propsDestructureDecl) {
  22718. ctx.s.overwrite(
  22719. startOffset + ctx.propsCall.start,
  22720. startOffset + ctx.propsCall.end,
  22721. "__props"
  22722. );
  22723. }
  22724. }
  22725. if (hasAwait) {
  22726. const any = ctx.isTS ? `: any` : ``;
  22727. ctx.s.prependLeft(startOffset, `
  22728. let __temp${any}, __restore${any}
  22729. `);
  22730. }
  22731. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  22732. if (ctx.emitDecl) {
  22733. destructureElements.push(`emit: __emit`);
  22734. }
  22735. if (destructureElements.length) {
  22736. args += `, { ${destructureElements.join(", ")} }`;
  22737. }
  22738. let returned;
  22739. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  22740. const allBindings = {
  22741. ...scriptBindings,
  22742. ...setupBindings
  22743. };
  22744. for (const key in ctx.userImports) {
  22745. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  22746. allBindings[key] = true;
  22747. }
  22748. }
  22749. returned = `{ `;
  22750. for (const key in allBindings) {
  22751. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  22752. returned += `get ${key}() { return ${key} }, `;
  22753. } else if (ctx.bindingMetadata[key] === "setup-let") {
  22754. const setArg = key === "v" ? `_v` : `v`;
  22755. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  22756. } else {
  22757. returned += `${key}, `;
  22758. }
  22759. }
  22760. returned = returned.replace(/, $/, "") + ` }`;
  22761. } else {
  22762. if (sfc.template && !sfc.template.src) {
  22763. if (options.templateOptions && options.templateOptions.ssr) {
  22764. hasInlinedSsrRenderFn = true;
  22765. }
  22766. const { code, ast, preamble, tips, errors } = compileTemplate({
  22767. filename,
  22768. ast: sfc.template.ast,
  22769. source: sfc.template.content,
  22770. inMap: sfc.template.map,
  22771. ...options.templateOptions,
  22772. id: scopeId,
  22773. scoped: sfc.styles.some((s) => s.scoped),
  22774. isProd: options.isProd,
  22775. ssrCssVars: sfc.cssVars,
  22776. compilerOptions: {
  22777. ...options.templateOptions && options.templateOptions.compilerOptions,
  22778. inline: true,
  22779. isTS: ctx.isTS,
  22780. bindingMetadata: ctx.bindingMetadata
  22781. }
  22782. });
  22783. if (tips.length) {
  22784. tips.forEach(warnOnce);
  22785. }
  22786. const err = errors[0];
  22787. if (typeof err === "string") {
  22788. throw new Error(err);
  22789. } else if (err) {
  22790. if (err.loc) {
  22791. err.message += `
  22792. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  22793. source,
  22794. err.loc.start.offset,
  22795. err.loc.end.offset
  22796. ) + `
  22797. `;
  22798. }
  22799. throw err;
  22800. }
  22801. if (preamble) {
  22802. ctx.s.prepend(preamble);
  22803. }
  22804. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  22805. ctx.helperImports.delete("unref");
  22806. }
  22807. returned = code;
  22808. } else {
  22809. returned = `() => {}`;
  22810. }
  22811. }
  22812. if (!options.inlineTemplate && true) {
  22813. ctx.s.appendRight(
  22814. endOffset,
  22815. `
  22816. const __returned__ = ${returned}
  22817. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  22818. return __returned__
  22819. }
  22820. `
  22821. );
  22822. } else {
  22823. ctx.s.appendRight(endOffset, `
  22824. return ${returned}
  22825. }
  22826. `);
  22827. }
  22828. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  22829. let runtimeOptions = ``;
  22830. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  22831. const match = filename.match(/([^/\\]+)\.\w+$/);
  22832. if (match) {
  22833. runtimeOptions += `
  22834. __name: '${match[1]}',`;
  22835. }
  22836. }
  22837. if (hasInlinedSsrRenderFn) {
  22838. runtimeOptions += `
  22839. __ssrInlineRender: true,`;
  22840. }
  22841. const propsDecl = genRuntimeProps(ctx);
  22842. if (propsDecl) runtimeOptions += `
  22843. props: ${propsDecl},`;
  22844. const emitsDecl = genRuntimeEmits(ctx);
  22845. if (emitsDecl) runtimeOptions += `
  22846. emits: ${emitsDecl},`;
  22847. let definedOptions = "";
  22848. if (ctx.optionsRuntimeDecl) {
  22849. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  22850. }
  22851. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  22852. `;
  22853. if (ctx.isTS) {
  22854. const def = (defaultExport ? `
  22855. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  22856. ...${definedOptions},` : "");
  22857. ctx.s.prependLeft(
  22858. startOffset,
  22859. `
  22860. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  22861. `defineComponent`
  22862. )}({${def}${runtimeOptions}
  22863. ${hasAwait ? `async ` : ``}setup(${args}) {
  22864. ${exposeCall}`
  22865. );
  22866. ctx.s.appendRight(endOffset, `})`);
  22867. } else {
  22868. if (defaultExport || definedOptions) {
  22869. ctx.s.prependLeft(
  22870. startOffset,
  22871. `
  22872. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  22873. ${hasAwait ? `async ` : ``}setup(${args}) {
  22874. ${exposeCall}`
  22875. );
  22876. ctx.s.appendRight(endOffset, `})`);
  22877. } else {
  22878. ctx.s.prependLeft(
  22879. startOffset,
  22880. `
  22881. ${genDefaultAs} {${runtimeOptions}
  22882. ${hasAwait ? `async ` : ``}setup(${args}) {
  22883. ${exposeCall}`
  22884. );
  22885. ctx.s.appendRight(endOffset, `}`);
  22886. }
  22887. }
  22888. if (ctx.helperImports.size > 0) {
  22889. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  22890. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  22891. ctx.s.prepend(
  22892. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  22893. `
  22894. );
  22895. }
  22896. return {
  22897. ...scriptSetup,
  22898. bindings: ctx.bindingMetadata,
  22899. imports: ctx.userImports,
  22900. content: ctx.s.toString(),
  22901. map: options.sourceMap !== false ? ctx.s.generateMap({
  22902. source: filename,
  22903. hires: true,
  22904. includeContent: true
  22905. }) : void 0,
  22906. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  22907. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  22908. deps: ctx.deps ? [...ctx.deps] : void 0
  22909. };
  22910. }
  22911. function registerBinding(bindings, node, type) {
  22912. bindings[node.name] = type;
  22913. }
  22914. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  22915. let isAllLiteral = false;
  22916. if (node.type === "VariableDeclaration") {
  22917. const isConst = node.kind === "const";
  22918. isAllLiteral = isConst && node.declarations.every(
  22919. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  22920. );
  22921. for (const { id, init: _init } of node.declarations) {
  22922. const init = _init && CompilerDOM.unwrapTSNode(_init);
  22923. const isConstMacroCall = isConst && isCallOf(
  22924. init,
  22925. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  22926. );
  22927. if (id.type === "Identifier") {
  22928. let bindingType;
  22929. const userReactiveBinding = userImportAliases["reactive"];
  22930. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  22931. bindingType = "literal-const";
  22932. } else if (isCallOf(init, userReactiveBinding)) {
  22933. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  22934. } else if (
  22935. // if a declaration is a const literal, we can mark it so that
  22936. // the generated render fn code doesn't need to unref() it
  22937. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  22938. ) {
  22939. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  22940. } else if (isConst) {
  22941. if (isCallOf(
  22942. init,
  22943. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === DEFINE_MODEL
  22944. )) {
  22945. bindingType = "setup-ref";
  22946. } else {
  22947. bindingType = "setup-maybe-ref";
  22948. }
  22949. } else {
  22950. bindingType = "setup-let";
  22951. }
  22952. registerBinding(bindings, id, bindingType);
  22953. } else {
  22954. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  22955. continue;
  22956. }
  22957. if (id.type === "ObjectPattern") {
  22958. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  22959. } else if (id.type === "ArrayPattern") {
  22960. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  22961. }
  22962. }
  22963. }
  22964. } else if (node.type === "TSEnumDeclaration") {
  22965. isAllLiteral = node.members.every(
  22966. (member) => !member.initializer || isStaticNode(member.initializer)
  22967. );
  22968. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  22969. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  22970. bindings[node.id.name] = "setup-const";
  22971. }
  22972. return isAllLiteral;
  22973. }
  22974. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  22975. for (const p of node.properties) {
  22976. if (p.type === "ObjectProperty") {
  22977. if (p.key.type === "Identifier" && p.key === p.value) {
  22978. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  22979. registerBinding(bindings, p.key, type);
  22980. } else {
  22981. walkPattern(p.value, bindings, isConst, isDefineCall);
  22982. }
  22983. } else {
  22984. const type = isConst ? "setup-const" : "setup-let";
  22985. registerBinding(bindings, p.argument, type);
  22986. }
  22987. }
  22988. }
  22989. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  22990. for (const e of node.elements) {
  22991. e && walkPattern(e, bindings, isConst, isDefineCall);
  22992. }
  22993. }
  22994. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  22995. if (node.type === "Identifier") {
  22996. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  22997. registerBinding(bindings, node, type);
  22998. } else if (node.type === "RestElement") {
  22999. const type = isConst ? "setup-const" : "setup-let";
  23000. registerBinding(bindings, node.argument, type);
  23001. } else if (node.type === "ObjectPattern") {
  23002. walkObjectPattern(node, bindings, isConst);
  23003. } else if (node.type === "ArrayPattern") {
  23004. walkArrayPattern(node, bindings, isConst);
  23005. } else if (node.type === "AssignmentPattern") {
  23006. if (node.left.type === "Identifier") {
  23007. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23008. registerBinding(bindings, node.left, type);
  23009. } else {
  23010. walkPattern(node.left, bindings, isConst);
  23011. }
  23012. }
  23013. }
  23014. function canNeverBeRef(node, userReactiveImport) {
  23015. if (isCallOf(node, userReactiveImport)) {
  23016. return true;
  23017. }
  23018. switch (node.type) {
  23019. case "UnaryExpression":
  23020. case "BinaryExpression":
  23021. case "ArrayExpression":
  23022. case "ObjectExpression":
  23023. case "FunctionExpression":
  23024. case "ArrowFunctionExpression":
  23025. case "UpdateExpression":
  23026. case "ClassExpression":
  23027. case "TaggedTemplateExpression":
  23028. return true;
  23029. case "SequenceExpression":
  23030. return canNeverBeRef(
  23031. node.expressions[node.expressions.length - 1],
  23032. userReactiveImport
  23033. );
  23034. default:
  23035. if (isLiteralNode(node)) {
  23036. return true;
  23037. }
  23038. return false;
  23039. }
  23040. }
  23041. function isStaticNode(node) {
  23042. node = CompilerDOM.unwrapTSNode(node);
  23043. switch (node.type) {
  23044. case "UnaryExpression":
  23045. return isStaticNode(node.argument);
  23046. case "LogicalExpression":
  23047. // 1 > 2
  23048. case "BinaryExpression":
  23049. return isStaticNode(node.left) && isStaticNode(node.right);
  23050. case "ConditionalExpression": {
  23051. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  23052. }
  23053. case "SequenceExpression":
  23054. // (1, 2)
  23055. case "TemplateLiteral":
  23056. return node.expressions.every((expr) => isStaticNode(expr));
  23057. case "ParenthesizedExpression":
  23058. return isStaticNode(node.expression);
  23059. case "StringLiteral":
  23060. case "NumericLiteral":
  23061. case "BooleanLiteral":
  23062. case "NullLiteral":
  23063. case "BigIntLiteral":
  23064. return true;
  23065. }
  23066. return false;
  23067. }
  23068. const version = "3.5.13";
  23069. const parseCache = parseCache$1;
  23070. const errorMessages = {
  23071. ...CompilerDOM.errorMessages,
  23072. ...CompilerDOM.DOMErrorMessages
  23073. };
  23074. const walk = estreeWalker.walk;
  23075. const shouldTransformRef = () => false;
  23076. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  23077. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  23078. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  23079. exports.isStaticProperty = compilerCore.isStaticProperty;
  23080. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  23081. exports.MagicString = MagicString;
  23082. exports.babelParse = parser$2.parse;
  23083. exports.compileScript = compileScript;
  23084. exports.compileStyle = compileStyle;
  23085. exports.compileStyleAsync = compileStyleAsync;
  23086. exports.compileTemplate = compileTemplate;
  23087. exports.errorMessages = errorMessages;
  23088. exports.extractRuntimeEmits = extractRuntimeEmits;
  23089. exports.extractRuntimeProps = extractRuntimeProps;
  23090. exports.inferRuntimeType = inferRuntimeType;
  23091. exports.invalidateTypeCache = invalidateTypeCache;
  23092. exports.parse = parse$1;
  23093. exports.parseCache = parseCache;
  23094. exports.registerTS = registerTS;
  23095. exports.resolveTypeElements = resolveTypeElements;
  23096. exports.rewriteDefault = rewriteDefault;
  23097. exports.rewriteDefaultAST = rewriteDefaultAST;
  23098. exports.shouldTransformRef = shouldTransformRef;
  23099. exports.version = version;
  23100. exports.walk = walk;