compiler-sfc.cjs.js 817 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038
  1. /**
  2. * @vue/compiler-sfc v3.5.16
  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. var _this$nodes;
  4501. newNode.parent = this;
  4502. var oldIndex = this.index(oldNode);
  4503. var resetNode = [];
  4504. for (var i = 2; i < arguments.length; i++) {
  4505. resetNode.push(arguments[i]);
  4506. }
  4507. (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
  4508. newNode.parent = this;
  4509. var index;
  4510. for (var id in this.indexes) {
  4511. index = this.indexes[id];
  4512. if (oldIndex < index) {
  4513. this.indexes[id] = index + arguments.length - 1;
  4514. }
  4515. }
  4516. return this;
  4517. };
  4518. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4519. var _this$nodes2;
  4520. newNode.parent = this;
  4521. var oldIndex = this.index(oldNode);
  4522. var resetNode = [];
  4523. for (var i = 2; i < arguments.length; i++) {
  4524. resetNode.push(arguments[i]);
  4525. }
  4526. (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
  4527. newNode.parent = this;
  4528. var index;
  4529. for (var id in this.indexes) {
  4530. index = this.indexes[id];
  4531. if (index >= oldIndex) {
  4532. this.indexes[id] = index + arguments.length - 1;
  4533. }
  4534. }
  4535. return this;
  4536. };
  4537. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4538. var found = undefined;
  4539. this.each(function (node) {
  4540. if (node.atPosition) {
  4541. var foundChild = node.atPosition(line, col);
  4542. if (foundChild) {
  4543. found = foundChild;
  4544. return false;
  4545. }
  4546. } else if (node.isAtPosition(line, col)) {
  4547. found = node;
  4548. return false;
  4549. }
  4550. });
  4551. return found;
  4552. }
  4553. /**
  4554. * Return the most specific node at the line and column number given.
  4555. * The source location is based on the original parsed location, locations aren't
  4556. * updated as selector nodes are mutated.
  4557. *
  4558. * Note that this location is relative to the location of the first character
  4559. * of the selector, and not the location of the selector in the overall document
  4560. * when used in conjunction with postcss.
  4561. *
  4562. * If not found, returns undefined.
  4563. * @param {number} line The line number of the node to find. (1-based index)
  4564. * @param {number} col The column number of the node to find. (1-based index)
  4565. */;
  4566. _proto.atPosition = function atPosition(line, col) {
  4567. if (this.isAtPosition(line, col)) {
  4568. return this._findChildAtPosition(line, col) || this;
  4569. } else {
  4570. return undefined;
  4571. }
  4572. };
  4573. _proto._inferEndPosition = function _inferEndPosition() {
  4574. if (this.last && this.last.source && this.last.source.end) {
  4575. this.source = this.source || {};
  4576. this.source.end = this.source.end || {};
  4577. Object.assign(this.source.end, this.last.source.end);
  4578. }
  4579. };
  4580. _proto.each = function each(callback) {
  4581. if (!this.lastEach) {
  4582. this.lastEach = 0;
  4583. }
  4584. if (!this.indexes) {
  4585. this.indexes = {};
  4586. }
  4587. this.lastEach++;
  4588. var id = this.lastEach;
  4589. this.indexes[id] = 0;
  4590. if (!this.length) {
  4591. return undefined;
  4592. }
  4593. var index, result;
  4594. while (this.indexes[id] < this.length) {
  4595. index = this.indexes[id];
  4596. result = callback(this.at(index), index);
  4597. if (result === false) {
  4598. break;
  4599. }
  4600. this.indexes[id] += 1;
  4601. }
  4602. delete this.indexes[id];
  4603. if (result === false) {
  4604. return false;
  4605. }
  4606. };
  4607. _proto.walk = function walk(callback) {
  4608. return this.each(function (node, i) {
  4609. var result = callback(node, i);
  4610. if (result !== false && node.length) {
  4611. result = node.walk(callback);
  4612. }
  4613. if (result === false) {
  4614. return false;
  4615. }
  4616. });
  4617. };
  4618. _proto.walkAttributes = function walkAttributes(callback) {
  4619. var _this2 = this;
  4620. return this.walk(function (selector) {
  4621. if (selector.type === types.ATTRIBUTE) {
  4622. return callback.call(_this2, selector);
  4623. }
  4624. });
  4625. };
  4626. _proto.walkClasses = function walkClasses(callback) {
  4627. var _this3 = this;
  4628. return this.walk(function (selector) {
  4629. if (selector.type === types.CLASS) {
  4630. return callback.call(_this3, selector);
  4631. }
  4632. });
  4633. };
  4634. _proto.walkCombinators = function walkCombinators(callback) {
  4635. var _this4 = this;
  4636. return this.walk(function (selector) {
  4637. if (selector.type === types.COMBINATOR) {
  4638. return callback.call(_this4, selector);
  4639. }
  4640. });
  4641. };
  4642. _proto.walkComments = function walkComments(callback) {
  4643. var _this5 = this;
  4644. return this.walk(function (selector) {
  4645. if (selector.type === types.COMMENT) {
  4646. return callback.call(_this5, selector);
  4647. }
  4648. });
  4649. };
  4650. _proto.walkIds = function walkIds(callback) {
  4651. var _this6 = this;
  4652. return this.walk(function (selector) {
  4653. if (selector.type === types.ID) {
  4654. return callback.call(_this6, selector);
  4655. }
  4656. });
  4657. };
  4658. _proto.walkNesting = function walkNesting(callback) {
  4659. var _this7 = this;
  4660. return this.walk(function (selector) {
  4661. if (selector.type === types.NESTING) {
  4662. return callback.call(_this7, selector);
  4663. }
  4664. });
  4665. };
  4666. _proto.walkPseudos = function walkPseudos(callback) {
  4667. var _this8 = this;
  4668. return this.walk(function (selector) {
  4669. if (selector.type === types.PSEUDO) {
  4670. return callback.call(_this8, selector);
  4671. }
  4672. });
  4673. };
  4674. _proto.walkTags = function walkTags(callback) {
  4675. var _this9 = this;
  4676. return this.walk(function (selector) {
  4677. if (selector.type === types.TAG) {
  4678. return callback.call(_this9, selector);
  4679. }
  4680. });
  4681. };
  4682. _proto.walkUniversals = function walkUniversals(callback) {
  4683. var _this10 = this;
  4684. return this.walk(function (selector) {
  4685. if (selector.type === types.UNIVERSAL) {
  4686. return callback.call(_this10, selector);
  4687. }
  4688. });
  4689. };
  4690. _proto.split = function split(callback) {
  4691. var _this11 = this;
  4692. var current = [];
  4693. return this.reduce(function (memo, node, index) {
  4694. var split = callback.call(_this11, node);
  4695. current.push(node);
  4696. if (split) {
  4697. memo.push(current);
  4698. current = [];
  4699. } else if (index === _this11.length - 1) {
  4700. memo.push(current);
  4701. }
  4702. return memo;
  4703. }, []);
  4704. };
  4705. _proto.map = function map(callback) {
  4706. return this.nodes.map(callback);
  4707. };
  4708. _proto.reduce = function reduce(callback, memo) {
  4709. return this.nodes.reduce(callback, memo);
  4710. };
  4711. _proto.every = function every(callback) {
  4712. return this.nodes.every(callback);
  4713. };
  4714. _proto.some = function some(callback) {
  4715. return this.nodes.some(callback);
  4716. };
  4717. _proto.filter = function filter(callback) {
  4718. return this.nodes.filter(callback);
  4719. };
  4720. _proto.sort = function sort(callback) {
  4721. return this.nodes.sort(callback);
  4722. };
  4723. _proto.toString = function toString() {
  4724. return this.map(String).join('');
  4725. };
  4726. _createClass(Container, [{
  4727. key: "first",
  4728. get: function get() {
  4729. return this.at(0);
  4730. }
  4731. }, {
  4732. key: "last",
  4733. get: function get() {
  4734. return this.at(this.length - 1);
  4735. }
  4736. }, {
  4737. key: "length",
  4738. get: function get() {
  4739. return this.nodes.length;
  4740. }
  4741. }]);
  4742. return Container;
  4743. }(_node["default"]);
  4744. exports["default"] = Container;
  4745. module.exports = exports.default;
  4746. } (container$1, container$1.exports));
  4747. return container$1.exports;
  4748. }
  4749. var hasRequiredRoot$1;
  4750. function requireRoot$1 () {
  4751. if (hasRequiredRoot$1) return root$1.exports;
  4752. hasRequiredRoot$1 = 1;
  4753. (function (module, exports) {
  4754. exports.__esModule = true;
  4755. exports["default"] = void 0;
  4756. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4757. var _types = /*@__PURE__*/ requireTypes$1();
  4758. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4759. 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); } }
  4760. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4761. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4762. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4763. var Root = /*#__PURE__*/function (_Container) {
  4764. _inheritsLoose(Root, _Container);
  4765. function Root(opts) {
  4766. var _this;
  4767. _this = _Container.call(this, opts) || this;
  4768. _this.type = _types.ROOT;
  4769. return _this;
  4770. }
  4771. var _proto = Root.prototype;
  4772. _proto.toString = function toString() {
  4773. var str = this.reduce(function (memo, selector) {
  4774. memo.push(String(selector));
  4775. return memo;
  4776. }, []).join(',');
  4777. return this.trailingComma ? str + ',' : str;
  4778. };
  4779. _proto.error = function error(message, options) {
  4780. if (this._error) {
  4781. return this._error(message, options);
  4782. } else {
  4783. return new Error(message);
  4784. }
  4785. };
  4786. _createClass(Root, [{
  4787. key: "errorGenerator",
  4788. set: function set(handler) {
  4789. this._error = handler;
  4790. }
  4791. }]);
  4792. return Root;
  4793. }(_container["default"]);
  4794. exports["default"] = Root;
  4795. module.exports = exports.default;
  4796. } (root$1, root$1.exports));
  4797. return root$1.exports;
  4798. }
  4799. var selector$1 = {exports: {}};
  4800. var hasRequiredSelector$1;
  4801. function requireSelector$1 () {
  4802. if (hasRequiredSelector$1) return selector$1.exports;
  4803. hasRequiredSelector$1 = 1;
  4804. (function (module, exports) {
  4805. exports.__esModule = true;
  4806. exports["default"] = void 0;
  4807. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4808. var _types = /*@__PURE__*/ requireTypes$1();
  4809. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4810. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4811. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4812. var Selector = /*#__PURE__*/function (_Container) {
  4813. _inheritsLoose(Selector, _Container);
  4814. function Selector(opts) {
  4815. var _this;
  4816. _this = _Container.call(this, opts) || this;
  4817. _this.type = _types.SELECTOR;
  4818. return _this;
  4819. }
  4820. return Selector;
  4821. }(_container["default"]);
  4822. exports["default"] = Selector;
  4823. module.exports = exports.default;
  4824. } (selector$1, selector$1.exports));
  4825. return selector$1.exports;
  4826. }
  4827. var className$1 = {exports: {}};
  4828. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4829. var cssesc_1;
  4830. var hasRequiredCssesc;
  4831. function requireCssesc () {
  4832. if (hasRequiredCssesc) return cssesc_1;
  4833. hasRequiredCssesc = 1;
  4834. var object = {};
  4835. var hasOwnProperty = object.hasOwnProperty;
  4836. var merge = function merge(options, defaults) {
  4837. if (!options) {
  4838. return defaults;
  4839. }
  4840. var result = {};
  4841. for (var key in defaults) {
  4842. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4843. // only recognized option names are used.
  4844. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  4845. }
  4846. return result;
  4847. };
  4848. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4849. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4850. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4851. // https://mathiasbynens.be/notes/css-escapes#css
  4852. var cssesc = function cssesc(string, options) {
  4853. options = merge(options, cssesc.options);
  4854. if (options.quotes != 'single' && options.quotes != 'double') {
  4855. options.quotes = 'single';
  4856. }
  4857. var quote = options.quotes == 'double' ? '"' : '\'';
  4858. var isIdentifier = options.isIdentifier;
  4859. var firstChar = string.charAt(0);
  4860. var output = '';
  4861. var counter = 0;
  4862. var length = string.length;
  4863. while (counter < length) {
  4864. var character = string.charAt(counter++);
  4865. var codePoint = character.charCodeAt();
  4866. var value = void 0;
  4867. // If it’s not a printable ASCII character…
  4868. if (codePoint < 0x20 || codePoint > 0x7E) {
  4869. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4870. // It’s a high surrogate, and there is a next character.
  4871. var extra = string.charCodeAt(counter++);
  4872. if ((extra & 0xFC00) == 0xDC00) {
  4873. // next character is low surrogate
  4874. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4875. } else {
  4876. // It’s an unmatched surrogate; only append this code unit, in case
  4877. // the next code unit is the high surrogate of a surrogate pair.
  4878. counter--;
  4879. }
  4880. }
  4881. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4882. } else {
  4883. if (options.escapeEverything) {
  4884. if (regexAnySingleEscape.test(character)) {
  4885. value = '\\' + character;
  4886. } else {
  4887. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4888. }
  4889. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4890. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4891. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4892. value = '\\' + character;
  4893. } else {
  4894. value = character;
  4895. }
  4896. }
  4897. output += value;
  4898. }
  4899. if (isIdentifier) {
  4900. if (/^-[-\d]/.test(output)) {
  4901. output = '\\-' + output.slice(1);
  4902. } else if (/\d/.test(firstChar)) {
  4903. output = '\\3' + firstChar + ' ' + output.slice(1);
  4904. }
  4905. }
  4906. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4907. // since they’re redundant. Note that this is only possible if the escape
  4908. // sequence isn’t preceded by an odd number of backslashes.
  4909. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4910. if ($1 && $1.length % 2) {
  4911. // It’s not safe to remove the space, so don’t.
  4912. return $0;
  4913. }
  4914. // Strip the space.
  4915. return ($1 || '') + $2;
  4916. });
  4917. if (!isIdentifier && options.wrap) {
  4918. return quote + output + quote;
  4919. }
  4920. return output;
  4921. };
  4922. // Expose default options (so they can be overridden globally).
  4923. cssesc.options = {
  4924. 'escapeEverything': false,
  4925. 'isIdentifier': false,
  4926. 'quotes': 'single',
  4927. 'wrap': false
  4928. };
  4929. cssesc.version = '3.0.0';
  4930. cssesc_1 = cssesc;
  4931. return cssesc_1;
  4932. }
  4933. var hasRequiredClassName$1;
  4934. function requireClassName$1 () {
  4935. if (hasRequiredClassName$1) return className$1.exports;
  4936. hasRequiredClassName$1 = 1;
  4937. (function (module, exports) {
  4938. exports.__esModule = true;
  4939. exports["default"] = void 0;
  4940. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  4941. var _util = /*@__PURE__*/ requireUtil$2();
  4942. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4943. var _types = /*@__PURE__*/ requireTypes$1();
  4944. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4945. 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); } }
  4946. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4947. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4948. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4949. var ClassName = /*#__PURE__*/function (_Node) {
  4950. _inheritsLoose(ClassName, _Node);
  4951. function ClassName(opts) {
  4952. var _this;
  4953. _this = _Node.call(this, opts) || this;
  4954. _this.type = _types.CLASS;
  4955. _this._constructed = true;
  4956. return _this;
  4957. }
  4958. var _proto = ClassName.prototype;
  4959. _proto.valueToString = function valueToString() {
  4960. return '.' + _Node.prototype.valueToString.call(this);
  4961. };
  4962. _createClass(ClassName, [{
  4963. key: "value",
  4964. get: function get() {
  4965. return this._value;
  4966. },
  4967. set: function set(v) {
  4968. if (this._constructed) {
  4969. var escaped = (0, _cssesc["default"])(v, {
  4970. isIdentifier: true
  4971. });
  4972. if (escaped !== v) {
  4973. (0, _util.ensureObject)(this, "raws");
  4974. this.raws.value = escaped;
  4975. } else if (this.raws) {
  4976. delete this.raws.value;
  4977. }
  4978. }
  4979. this._value = v;
  4980. }
  4981. }]);
  4982. return ClassName;
  4983. }(_node["default"]);
  4984. exports["default"] = ClassName;
  4985. module.exports = exports.default;
  4986. } (className$1, className$1.exports));
  4987. return className$1.exports;
  4988. }
  4989. var comment$1 = {exports: {}};
  4990. var hasRequiredComment$1;
  4991. function requireComment$1 () {
  4992. if (hasRequiredComment$1) return comment$1.exports;
  4993. hasRequiredComment$1 = 1;
  4994. (function (module, exports) {
  4995. exports.__esModule = true;
  4996. exports["default"] = void 0;
  4997. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4998. var _types = /*@__PURE__*/ requireTypes$1();
  4999. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5000. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5001. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5002. var Comment = /*#__PURE__*/function (_Node) {
  5003. _inheritsLoose(Comment, _Node);
  5004. function Comment(opts) {
  5005. var _this;
  5006. _this = _Node.call(this, opts) || this;
  5007. _this.type = _types.COMMENT;
  5008. return _this;
  5009. }
  5010. return Comment;
  5011. }(_node["default"]);
  5012. exports["default"] = Comment;
  5013. module.exports = exports.default;
  5014. } (comment$1, comment$1.exports));
  5015. return comment$1.exports;
  5016. }
  5017. var id$1 = {exports: {}};
  5018. var hasRequiredId$1;
  5019. function requireId$1 () {
  5020. if (hasRequiredId$1) return id$1.exports;
  5021. hasRequiredId$1 = 1;
  5022. (function (module, exports) {
  5023. exports.__esModule = true;
  5024. exports["default"] = void 0;
  5025. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5026. var _types = /*@__PURE__*/ requireTypes$1();
  5027. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5028. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5029. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5030. var ID = /*#__PURE__*/function (_Node) {
  5031. _inheritsLoose(ID, _Node);
  5032. function ID(opts) {
  5033. var _this;
  5034. _this = _Node.call(this, opts) || this;
  5035. _this.type = _types.ID;
  5036. return _this;
  5037. }
  5038. var _proto = ID.prototype;
  5039. _proto.valueToString = function valueToString() {
  5040. return '#' + _Node.prototype.valueToString.call(this);
  5041. };
  5042. return ID;
  5043. }(_node["default"]);
  5044. exports["default"] = ID;
  5045. module.exports = exports.default;
  5046. } (id$1, id$1.exports));
  5047. return id$1.exports;
  5048. }
  5049. var tag$1 = {exports: {}};
  5050. var namespace$1 = {exports: {}};
  5051. var hasRequiredNamespace$1;
  5052. function requireNamespace$1 () {
  5053. if (hasRequiredNamespace$1) return namespace$1.exports;
  5054. hasRequiredNamespace$1 = 1;
  5055. (function (module, exports) {
  5056. exports.__esModule = true;
  5057. exports["default"] = void 0;
  5058. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5059. var _util = /*@__PURE__*/ requireUtil$2();
  5060. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5061. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5062. 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); } }
  5063. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5064. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5065. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5066. var Namespace = /*#__PURE__*/function (_Node) {
  5067. _inheritsLoose(Namespace, _Node);
  5068. function Namespace() {
  5069. return _Node.apply(this, arguments) || this;
  5070. }
  5071. var _proto = Namespace.prototype;
  5072. _proto.qualifiedName = function qualifiedName(value) {
  5073. if (this.namespace) {
  5074. return this.namespaceString + "|" + value;
  5075. } else {
  5076. return value;
  5077. }
  5078. };
  5079. _proto.valueToString = function valueToString() {
  5080. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5081. };
  5082. _createClass(Namespace, [{
  5083. key: "namespace",
  5084. get: function get() {
  5085. return this._namespace;
  5086. },
  5087. set: function set(namespace) {
  5088. if (namespace === true || namespace === "*" || namespace === "&") {
  5089. this._namespace = namespace;
  5090. if (this.raws) {
  5091. delete this.raws.namespace;
  5092. }
  5093. return;
  5094. }
  5095. var escaped = (0, _cssesc["default"])(namespace, {
  5096. isIdentifier: true
  5097. });
  5098. this._namespace = namespace;
  5099. if (escaped !== namespace) {
  5100. (0, _util.ensureObject)(this, "raws");
  5101. this.raws.namespace = escaped;
  5102. } else if (this.raws) {
  5103. delete this.raws.namespace;
  5104. }
  5105. }
  5106. }, {
  5107. key: "ns",
  5108. get: function get() {
  5109. return this._namespace;
  5110. },
  5111. set: function set(namespace) {
  5112. this.namespace = namespace;
  5113. }
  5114. }, {
  5115. key: "namespaceString",
  5116. get: function get() {
  5117. if (this.namespace) {
  5118. var ns = this.stringifyProperty("namespace");
  5119. if (ns === true) {
  5120. return '';
  5121. } else {
  5122. return ns;
  5123. }
  5124. } else {
  5125. return '';
  5126. }
  5127. }
  5128. }]);
  5129. return Namespace;
  5130. }(_node["default"]);
  5131. exports["default"] = Namespace;
  5132. module.exports = exports.default;
  5133. } (namespace$1, namespace$1.exports));
  5134. return namespace$1.exports;
  5135. }
  5136. var hasRequiredTag$1;
  5137. function requireTag$1 () {
  5138. if (hasRequiredTag$1) return tag$1.exports;
  5139. hasRequiredTag$1 = 1;
  5140. (function (module, exports) {
  5141. exports.__esModule = true;
  5142. exports["default"] = void 0;
  5143. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5144. var _types = /*@__PURE__*/ requireTypes$1();
  5145. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5146. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5147. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5148. var Tag = /*#__PURE__*/function (_Namespace) {
  5149. _inheritsLoose(Tag, _Namespace);
  5150. function Tag(opts) {
  5151. var _this;
  5152. _this = _Namespace.call(this, opts) || this;
  5153. _this.type = _types.TAG;
  5154. return _this;
  5155. }
  5156. return Tag;
  5157. }(_namespace["default"]);
  5158. exports["default"] = Tag;
  5159. module.exports = exports.default;
  5160. } (tag$1, tag$1.exports));
  5161. return tag$1.exports;
  5162. }
  5163. var string$1 = {exports: {}};
  5164. var hasRequiredString$1;
  5165. function requireString$1 () {
  5166. if (hasRequiredString$1) return string$1.exports;
  5167. hasRequiredString$1 = 1;
  5168. (function (module, exports) {
  5169. exports.__esModule = true;
  5170. exports["default"] = void 0;
  5171. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5172. var _types = /*@__PURE__*/ requireTypes$1();
  5173. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5174. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5175. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5176. var String = /*#__PURE__*/function (_Node) {
  5177. _inheritsLoose(String, _Node);
  5178. function String(opts) {
  5179. var _this;
  5180. _this = _Node.call(this, opts) || this;
  5181. _this.type = _types.STRING;
  5182. return _this;
  5183. }
  5184. return String;
  5185. }(_node["default"]);
  5186. exports["default"] = String;
  5187. module.exports = exports.default;
  5188. } (string$1, string$1.exports));
  5189. return string$1.exports;
  5190. }
  5191. var pseudo$1 = {exports: {}};
  5192. var hasRequiredPseudo$1;
  5193. function requirePseudo$1 () {
  5194. if (hasRequiredPseudo$1) return pseudo$1.exports;
  5195. hasRequiredPseudo$1 = 1;
  5196. (function (module, exports) {
  5197. exports.__esModule = true;
  5198. exports["default"] = void 0;
  5199. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  5200. var _types = /*@__PURE__*/ requireTypes$1();
  5201. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5202. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5203. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5204. var Pseudo = /*#__PURE__*/function (_Container) {
  5205. _inheritsLoose(Pseudo, _Container);
  5206. function Pseudo(opts) {
  5207. var _this;
  5208. _this = _Container.call(this, opts) || this;
  5209. _this.type = _types.PSEUDO;
  5210. return _this;
  5211. }
  5212. var _proto = Pseudo.prototype;
  5213. _proto.toString = function toString() {
  5214. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5215. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5216. };
  5217. return Pseudo;
  5218. }(_container["default"]);
  5219. exports["default"] = Pseudo;
  5220. module.exports = exports.default;
  5221. } (pseudo$1, pseudo$1.exports));
  5222. return pseudo$1.exports;
  5223. }
  5224. var attribute$1 = {};
  5225. var node$1;
  5226. var hasRequiredNode$1;
  5227. function requireNode$1 () {
  5228. if (hasRequiredNode$1) return node$1;
  5229. hasRequiredNode$1 = 1;
  5230. /**
  5231. * For Node.js, simply re-export the core `util.deprecate` function.
  5232. */
  5233. node$1 = require$$2.deprecate;
  5234. return node$1;
  5235. }
  5236. var hasRequiredAttribute$1;
  5237. function requireAttribute$1 () {
  5238. if (hasRequiredAttribute$1) return attribute$1;
  5239. hasRequiredAttribute$1 = 1;
  5240. (function (exports) {
  5241. exports.__esModule = true;
  5242. exports["default"] = void 0;
  5243. exports.unescapeValue = unescapeValue;
  5244. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5245. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  5246. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5247. var _types = /*@__PURE__*/ requireTypes$1();
  5248. var _CSSESC_QUOTE_OPTIONS;
  5249. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5250. 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); } }
  5251. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5252. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5253. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5254. var deprecate = /*@__PURE__*/ requireNode$1();
  5255. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5256. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5257. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5258. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5259. function unescapeValue(value) {
  5260. var deprecatedUsage = false;
  5261. var quoteMark = null;
  5262. var unescaped = value;
  5263. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5264. if (m) {
  5265. quoteMark = m[1];
  5266. unescaped = m[2];
  5267. }
  5268. unescaped = (0, _unesc["default"])(unescaped);
  5269. if (unescaped !== value) {
  5270. deprecatedUsage = true;
  5271. }
  5272. return {
  5273. deprecatedUsage: deprecatedUsage,
  5274. unescaped: unescaped,
  5275. quoteMark: quoteMark
  5276. };
  5277. }
  5278. function handleDeprecatedContructorOpts(opts) {
  5279. if (opts.quoteMark !== undefined) {
  5280. return opts;
  5281. }
  5282. if (opts.value === undefined) {
  5283. return opts;
  5284. }
  5285. warnOfDeprecatedConstructor();
  5286. var _unescapeValue = unescapeValue(opts.value),
  5287. quoteMark = _unescapeValue.quoteMark,
  5288. unescaped = _unescapeValue.unescaped;
  5289. if (!opts.raws) {
  5290. opts.raws = {};
  5291. }
  5292. if (opts.raws.value === undefined) {
  5293. opts.raws.value = opts.value;
  5294. }
  5295. opts.value = unescaped;
  5296. opts.quoteMark = quoteMark;
  5297. return opts;
  5298. }
  5299. var Attribute = /*#__PURE__*/function (_Namespace) {
  5300. _inheritsLoose(Attribute, _Namespace);
  5301. function Attribute(opts) {
  5302. var _this;
  5303. if (opts === void 0) {
  5304. opts = {};
  5305. }
  5306. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5307. _this.type = _types.ATTRIBUTE;
  5308. _this.raws = _this.raws || {};
  5309. Object.defineProperty(_this.raws, 'unquoted', {
  5310. get: deprecate(function () {
  5311. return _this.value;
  5312. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5313. set: deprecate(function () {
  5314. return _this.value;
  5315. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5316. });
  5317. _this._constructed = true;
  5318. return _this;
  5319. }
  5320. /**
  5321. * Returns the Attribute's value quoted such that it would be legal to use
  5322. * in the value of a css file. The original value's quotation setting
  5323. * used for stringification is left unchanged. See `setValue(value, options)`
  5324. * if you want to control the quote settings of a new value for the attribute.
  5325. *
  5326. * You can also change the quotation used for the current value by setting quoteMark.
  5327. *
  5328. * Options:
  5329. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5330. * option is not set, the original value for quoteMark will be used. If
  5331. * indeterminate, a double quote is used. The legal values are:
  5332. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5333. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5334. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5335. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5336. * over the quoteMark option value.
  5337. * * smart {boolean} - if true, will select a quote mark based on the value
  5338. * and the other options specified here. See the `smartQuoteMark()`
  5339. * method.
  5340. **/
  5341. var _proto = Attribute.prototype;
  5342. _proto.getQuotedValue = function getQuotedValue(options) {
  5343. if (options === void 0) {
  5344. options = {};
  5345. }
  5346. var quoteMark = this._determineQuoteMark(options);
  5347. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5348. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5349. return escaped;
  5350. };
  5351. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5352. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5353. }
  5354. /**
  5355. * Set the unescaped value with the specified quotation options. The value
  5356. * provided must not include any wrapping quote marks -- those quotes will
  5357. * be interpreted as part of the value and escaped accordingly.
  5358. */;
  5359. _proto.setValue = function setValue(value, options) {
  5360. if (options === void 0) {
  5361. options = {};
  5362. }
  5363. this._value = value;
  5364. this._quoteMark = this._determineQuoteMark(options);
  5365. this._syncRawValue();
  5366. }
  5367. /**
  5368. * Intelligently select a quoteMark value based on the value's contents. If
  5369. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5370. * mark will be picked that minimizes the number of escapes.
  5371. *
  5372. * If there's no clear winner, the quote mark from these options is used,
  5373. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5374. * true). If the quoteMark is unspecified, a double quote is used.
  5375. *
  5376. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5377. * from the quoteValue method.
  5378. */;
  5379. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5380. var v = this.value;
  5381. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5382. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5383. if (numSingleQuotes + numDoubleQuotes === 0) {
  5384. var escaped = (0, _cssesc["default"])(v, {
  5385. isIdentifier: true
  5386. });
  5387. if (escaped === v) {
  5388. return Attribute.NO_QUOTE;
  5389. } else {
  5390. var pref = this.preferredQuoteMark(options);
  5391. if (pref === Attribute.NO_QUOTE) {
  5392. // pick a quote mark that isn't none and see if it's smaller
  5393. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5394. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5395. var quoteValue = (0, _cssesc["default"])(v, opts);
  5396. if (quoteValue.length < escaped.length) {
  5397. return quote;
  5398. }
  5399. }
  5400. return pref;
  5401. }
  5402. } else if (numDoubleQuotes === numSingleQuotes) {
  5403. return this.preferredQuoteMark(options);
  5404. } else if (numDoubleQuotes < numSingleQuotes) {
  5405. return Attribute.DOUBLE_QUOTE;
  5406. } else {
  5407. return Attribute.SINGLE_QUOTE;
  5408. }
  5409. }
  5410. /**
  5411. * Selects the preferred quote mark based on the options and the current quote mark value.
  5412. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5413. * instead.
  5414. */;
  5415. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5416. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5417. if (quoteMark === undefined) {
  5418. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5419. }
  5420. if (quoteMark === undefined) {
  5421. quoteMark = Attribute.DOUBLE_QUOTE;
  5422. }
  5423. return quoteMark;
  5424. };
  5425. _proto._syncRawValue = function _syncRawValue() {
  5426. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5427. if (rawValue === this._value) {
  5428. if (this.raws) {
  5429. delete this.raws.value;
  5430. }
  5431. } else {
  5432. this.raws.value = rawValue;
  5433. }
  5434. };
  5435. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5436. if (this._constructed) {
  5437. var escaped = (0, _cssesc["default"])(value, {
  5438. isIdentifier: true
  5439. });
  5440. if (escaped !== value) {
  5441. this.raws[prop] = escaped;
  5442. } else {
  5443. delete this.raws[prop];
  5444. }
  5445. }
  5446. };
  5447. _proto._spacesFor = function _spacesFor(name) {
  5448. var attrSpaces = {
  5449. before: '',
  5450. after: ''
  5451. };
  5452. var spaces = this.spaces[name] || {};
  5453. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5454. return Object.assign(attrSpaces, spaces, rawSpaces);
  5455. };
  5456. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5457. if (spaceName === void 0) {
  5458. spaceName = name;
  5459. }
  5460. if (concat === void 0) {
  5461. concat = defaultAttrConcat;
  5462. }
  5463. var attrSpaces = this._spacesFor(spaceName);
  5464. return concat(this.stringifyProperty(name), attrSpaces);
  5465. }
  5466. /**
  5467. * returns the offset of the attribute part specified relative to the
  5468. * start of the node of the output string.
  5469. *
  5470. * * "ns" - alias for "namespace"
  5471. * * "namespace" - the namespace if it exists.
  5472. * * "attribute" - the attribute name
  5473. * * "attributeNS" - the start of the attribute or its namespace
  5474. * * "operator" - the match operator of the attribute
  5475. * * "value" - The value (string or identifier)
  5476. * * "insensitive" - the case insensitivity flag;
  5477. * @param part One of the possible values inside an attribute.
  5478. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5479. */;
  5480. _proto.offsetOf = function offsetOf(name) {
  5481. var count = 1;
  5482. var attributeSpaces = this._spacesFor("attribute");
  5483. count += attributeSpaces.before.length;
  5484. if (name === "namespace" || name === "ns") {
  5485. return this.namespace ? count : -1;
  5486. }
  5487. if (name === "attributeNS") {
  5488. return count;
  5489. }
  5490. count += this.namespaceString.length;
  5491. if (this.namespace) {
  5492. count += 1;
  5493. }
  5494. if (name === "attribute") {
  5495. return count;
  5496. }
  5497. count += this.stringifyProperty("attribute").length;
  5498. count += attributeSpaces.after.length;
  5499. var operatorSpaces = this._spacesFor("operator");
  5500. count += operatorSpaces.before.length;
  5501. var operator = this.stringifyProperty("operator");
  5502. if (name === "operator") {
  5503. return operator ? count : -1;
  5504. }
  5505. count += operator.length;
  5506. count += operatorSpaces.after.length;
  5507. var valueSpaces = this._spacesFor("value");
  5508. count += valueSpaces.before.length;
  5509. var value = this.stringifyProperty("value");
  5510. if (name === "value") {
  5511. return value ? count : -1;
  5512. }
  5513. count += value.length;
  5514. count += valueSpaces.after.length;
  5515. var insensitiveSpaces = this._spacesFor("insensitive");
  5516. count += insensitiveSpaces.before.length;
  5517. if (name === "insensitive") {
  5518. return this.insensitive ? count : -1;
  5519. }
  5520. return -1;
  5521. };
  5522. _proto.toString = function toString() {
  5523. var _this2 = this;
  5524. var selector = [this.rawSpaceBefore, '['];
  5525. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5526. if (this.operator && (this.value || this.value === '')) {
  5527. selector.push(this._stringFor('operator'));
  5528. selector.push(this._stringFor('value'));
  5529. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5530. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5531. attrSpaces.before = " ";
  5532. }
  5533. return defaultAttrConcat(attrValue, attrSpaces);
  5534. }));
  5535. }
  5536. selector.push(']');
  5537. selector.push(this.rawSpaceAfter);
  5538. return selector.join('');
  5539. };
  5540. _createClass(Attribute, [{
  5541. key: "quoted",
  5542. get: function get() {
  5543. var qm = this.quoteMark;
  5544. return qm === "'" || qm === '"';
  5545. },
  5546. set: function set(value) {
  5547. warnOfDeprecatedQuotedAssignment();
  5548. }
  5549. /**
  5550. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5551. * returns `null` if the value is not quoted.
  5552. * returns `undefined` if the quotation state is unknown (this can happen when
  5553. * the attribute is constructed without specifying a quote mark.)
  5554. */
  5555. }, {
  5556. key: "quoteMark",
  5557. get: function get() {
  5558. return this._quoteMark;
  5559. }
  5560. /**
  5561. * Set the quote mark to be used by this attribute's value.
  5562. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5563. * value is updated accordingly.
  5564. *
  5565. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5566. */,
  5567. set: function set(quoteMark) {
  5568. if (!this._constructed) {
  5569. this._quoteMark = quoteMark;
  5570. return;
  5571. }
  5572. if (this._quoteMark !== quoteMark) {
  5573. this._quoteMark = quoteMark;
  5574. this._syncRawValue();
  5575. }
  5576. }
  5577. }, {
  5578. key: "qualifiedAttribute",
  5579. get: function get() {
  5580. return this.qualifiedName(this.raws.attribute || this.attribute);
  5581. }
  5582. }, {
  5583. key: "insensitiveFlag",
  5584. get: function get() {
  5585. return this.insensitive ? 'i' : '';
  5586. }
  5587. }, {
  5588. key: "value",
  5589. get: function get() {
  5590. return this._value;
  5591. },
  5592. set:
  5593. /**
  5594. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5595. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5596. * is unescaped during parsing and any quote marks are removed.
  5597. *
  5598. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5599. * a deprecation warning is raised when the new value contains any characters that would
  5600. * require escaping (including if it contains wrapped quotes).
  5601. *
  5602. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5603. * how the new value is quoted.
  5604. */
  5605. function set(v) {
  5606. if (this._constructed) {
  5607. var _unescapeValue2 = unescapeValue(v),
  5608. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5609. unescaped = _unescapeValue2.unescaped,
  5610. quoteMark = _unescapeValue2.quoteMark;
  5611. if (deprecatedUsage) {
  5612. warnOfDeprecatedValueAssignment();
  5613. }
  5614. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5615. return;
  5616. }
  5617. this._value = unescaped;
  5618. this._quoteMark = quoteMark;
  5619. this._syncRawValue();
  5620. } else {
  5621. this._value = v;
  5622. }
  5623. }
  5624. }, {
  5625. key: "insensitive",
  5626. get: function get() {
  5627. return this._insensitive;
  5628. }
  5629. /**
  5630. * Set the case insensitive flag.
  5631. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5632. * of the attribute is updated accordingly.
  5633. *
  5634. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5635. */,
  5636. set: function set(insensitive) {
  5637. if (!insensitive) {
  5638. this._insensitive = false;
  5639. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5640. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5641. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5642. this.raws.insensitiveFlag = undefined;
  5643. }
  5644. }
  5645. this._insensitive = insensitive;
  5646. }
  5647. }, {
  5648. key: "attribute",
  5649. get: function get() {
  5650. return this._attribute;
  5651. },
  5652. set: function set(name) {
  5653. this._handleEscapes("attribute", name);
  5654. this._attribute = name;
  5655. }
  5656. }]);
  5657. return Attribute;
  5658. }(_namespace["default"]);
  5659. exports["default"] = Attribute;
  5660. Attribute.NO_QUOTE = null;
  5661. Attribute.SINGLE_QUOTE = "'";
  5662. Attribute.DOUBLE_QUOTE = '"';
  5663. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5664. "'": {
  5665. quotes: 'single',
  5666. wrap: true
  5667. },
  5668. '"': {
  5669. quotes: 'double',
  5670. wrap: true
  5671. }
  5672. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5673. isIdentifier: true
  5674. }, _CSSESC_QUOTE_OPTIONS);
  5675. function defaultAttrConcat(attrValue, attrSpaces) {
  5676. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5677. }
  5678. } (attribute$1));
  5679. return attribute$1;
  5680. }
  5681. var universal$1 = {exports: {}};
  5682. var hasRequiredUniversal$1;
  5683. function requireUniversal$1 () {
  5684. if (hasRequiredUniversal$1) return universal$1.exports;
  5685. hasRequiredUniversal$1 = 1;
  5686. (function (module, exports) {
  5687. exports.__esModule = true;
  5688. exports["default"] = void 0;
  5689. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5690. var _types = /*@__PURE__*/ requireTypes$1();
  5691. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5692. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5693. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5694. var Universal = /*#__PURE__*/function (_Namespace) {
  5695. _inheritsLoose(Universal, _Namespace);
  5696. function Universal(opts) {
  5697. var _this;
  5698. _this = _Namespace.call(this, opts) || this;
  5699. _this.type = _types.UNIVERSAL;
  5700. _this.value = '*';
  5701. return _this;
  5702. }
  5703. return Universal;
  5704. }(_namespace["default"]);
  5705. exports["default"] = Universal;
  5706. module.exports = exports.default;
  5707. } (universal$1, universal$1.exports));
  5708. return universal$1.exports;
  5709. }
  5710. var combinator$1 = {exports: {}};
  5711. var hasRequiredCombinator$1;
  5712. function requireCombinator$1 () {
  5713. if (hasRequiredCombinator$1) return combinator$1.exports;
  5714. hasRequiredCombinator$1 = 1;
  5715. (function (module, exports) {
  5716. exports.__esModule = true;
  5717. exports["default"] = void 0;
  5718. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5719. var _types = /*@__PURE__*/ requireTypes$1();
  5720. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5721. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5722. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5723. var Combinator = /*#__PURE__*/function (_Node) {
  5724. _inheritsLoose(Combinator, _Node);
  5725. function Combinator(opts) {
  5726. var _this;
  5727. _this = _Node.call(this, opts) || this;
  5728. _this.type = _types.COMBINATOR;
  5729. return _this;
  5730. }
  5731. return Combinator;
  5732. }(_node["default"]);
  5733. exports["default"] = Combinator;
  5734. module.exports = exports.default;
  5735. } (combinator$1, combinator$1.exports));
  5736. return combinator$1.exports;
  5737. }
  5738. var nesting$1 = {exports: {}};
  5739. var hasRequiredNesting$1;
  5740. function requireNesting$1 () {
  5741. if (hasRequiredNesting$1) return nesting$1.exports;
  5742. hasRequiredNesting$1 = 1;
  5743. (function (module, exports) {
  5744. exports.__esModule = true;
  5745. exports["default"] = void 0;
  5746. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5747. var _types = /*@__PURE__*/ requireTypes$1();
  5748. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5749. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5750. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5751. var Nesting = /*#__PURE__*/function (_Node) {
  5752. _inheritsLoose(Nesting, _Node);
  5753. function Nesting(opts) {
  5754. var _this;
  5755. _this = _Node.call(this, opts) || this;
  5756. _this.type = _types.NESTING;
  5757. _this.value = '&';
  5758. return _this;
  5759. }
  5760. return Nesting;
  5761. }(_node["default"]);
  5762. exports["default"] = Nesting;
  5763. module.exports = exports.default;
  5764. } (nesting$1, nesting$1.exports));
  5765. return nesting$1.exports;
  5766. }
  5767. var sortAscending$1 = {exports: {}};
  5768. var hasRequiredSortAscending$1;
  5769. function requireSortAscending$1 () {
  5770. if (hasRequiredSortAscending$1) return sortAscending$1.exports;
  5771. hasRequiredSortAscending$1 = 1;
  5772. (function (module, exports) {
  5773. exports.__esModule = true;
  5774. exports["default"] = sortAscending;
  5775. function sortAscending(list) {
  5776. return list.sort(function (a, b) {
  5777. return a - b;
  5778. });
  5779. }
  5780. module.exports = exports.default;
  5781. } (sortAscending$1, sortAscending$1.exports));
  5782. return sortAscending$1.exports;
  5783. }
  5784. var tokenize$1 = {};
  5785. var tokenTypes$1 = {};
  5786. var hasRequiredTokenTypes$1;
  5787. function requireTokenTypes$1 () {
  5788. if (hasRequiredTokenTypes$1) return tokenTypes$1;
  5789. hasRequiredTokenTypes$1 = 1;
  5790. tokenTypes$1.__esModule = true;
  5791. 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;
  5792. var ampersand = 38; // `&`.charCodeAt(0);
  5793. tokenTypes$1.ampersand = ampersand;
  5794. var asterisk = 42; // `*`.charCodeAt(0);
  5795. tokenTypes$1.asterisk = asterisk;
  5796. var at = 64; // `@`.charCodeAt(0);
  5797. tokenTypes$1.at = at;
  5798. var comma = 44; // `,`.charCodeAt(0);
  5799. tokenTypes$1.comma = comma;
  5800. var colon = 58; // `:`.charCodeAt(0);
  5801. tokenTypes$1.colon = colon;
  5802. var semicolon = 59; // `;`.charCodeAt(0);
  5803. tokenTypes$1.semicolon = semicolon;
  5804. var openParenthesis = 40; // `(`.charCodeAt(0);
  5805. tokenTypes$1.openParenthesis = openParenthesis;
  5806. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5807. tokenTypes$1.closeParenthesis = closeParenthesis;
  5808. var openSquare = 91; // `[`.charCodeAt(0);
  5809. tokenTypes$1.openSquare = openSquare;
  5810. var closeSquare = 93; // `]`.charCodeAt(0);
  5811. tokenTypes$1.closeSquare = closeSquare;
  5812. var dollar = 36; // `$`.charCodeAt(0);
  5813. tokenTypes$1.dollar = dollar;
  5814. var tilde = 126; // `~`.charCodeAt(0);
  5815. tokenTypes$1.tilde = tilde;
  5816. var caret = 94; // `^`.charCodeAt(0);
  5817. tokenTypes$1.caret = caret;
  5818. var plus = 43; // `+`.charCodeAt(0);
  5819. tokenTypes$1.plus = plus;
  5820. var equals = 61; // `=`.charCodeAt(0);
  5821. tokenTypes$1.equals = equals;
  5822. var pipe = 124; // `|`.charCodeAt(0);
  5823. tokenTypes$1.pipe = pipe;
  5824. var greaterThan = 62; // `>`.charCodeAt(0);
  5825. tokenTypes$1.greaterThan = greaterThan;
  5826. var space = 32; // ` `.charCodeAt(0);
  5827. tokenTypes$1.space = space;
  5828. var singleQuote = 39; // `'`.charCodeAt(0);
  5829. tokenTypes$1.singleQuote = singleQuote;
  5830. var doubleQuote = 34; // `"`.charCodeAt(0);
  5831. tokenTypes$1.doubleQuote = doubleQuote;
  5832. var slash = 47; // `/`.charCodeAt(0);
  5833. tokenTypes$1.slash = slash;
  5834. var bang = 33; // `!`.charCodeAt(0);
  5835. tokenTypes$1.bang = bang;
  5836. var backslash = 92; // '\\'.charCodeAt(0);
  5837. tokenTypes$1.backslash = backslash;
  5838. var cr = 13; // '\r'.charCodeAt(0);
  5839. tokenTypes$1.cr = cr;
  5840. var feed = 12; // '\f'.charCodeAt(0);
  5841. tokenTypes$1.feed = feed;
  5842. var newline = 10; // '\n'.charCodeAt(0);
  5843. tokenTypes$1.newline = newline;
  5844. var tab = 9; // '\t'.charCodeAt(0);
  5845. // Expose aliases primarily for readability.
  5846. tokenTypes$1.tab = tab;
  5847. var str = singleQuote;
  5848. // No good single character representation!
  5849. tokenTypes$1.str = str;
  5850. var comment = -1;
  5851. tokenTypes$1.comment = comment;
  5852. var word = -2;
  5853. tokenTypes$1.word = word;
  5854. var combinator = -3;
  5855. tokenTypes$1.combinator = combinator;
  5856. return tokenTypes$1;
  5857. }
  5858. var hasRequiredTokenize$1;
  5859. function requireTokenize$1 () {
  5860. if (hasRequiredTokenize$1) return tokenize$1;
  5861. hasRequiredTokenize$1 = 1;
  5862. (function (exports) {
  5863. exports.__esModule = true;
  5864. exports.FIELDS = void 0;
  5865. exports["default"] = tokenize;
  5866. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  5867. var _unescapable, _wordDelimiters;
  5868. 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); }
  5869. 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; }
  5870. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5871. 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);
  5872. var hex = {};
  5873. var hexChars = "0123456789abcdefABCDEF";
  5874. for (var i = 0; i < hexChars.length; i++) {
  5875. hex[hexChars.charCodeAt(i)] = true;
  5876. }
  5877. /**
  5878. * Returns the last index of the bar css word
  5879. * @param {string} css The string in which the word begins
  5880. * @param {number} start The index into the string where word's first letter occurs
  5881. */
  5882. function consumeWord(css, start) {
  5883. var next = start;
  5884. var code;
  5885. do {
  5886. code = css.charCodeAt(next);
  5887. if (wordDelimiters[code]) {
  5888. return next - 1;
  5889. } else if (code === t.backslash) {
  5890. next = consumeEscape(css, next) + 1;
  5891. } else {
  5892. // All other characters are part of the word
  5893. next++;
  5894. }
  5895. } while (next < css.length);
  5896. return next - 1;
  5897. }
  5898. /**
  5899. * Returns the last index of the escape sequence
  5900. * @param {string} css The string in which the sequence begins
  5901. * @param {number} start The index into the string where escape character (`\`) occurs.
  5902. */
  5903. function consumeEscape(css, start) {
  5904. var next = start;
  5905. var code = css.charCodeAt(next + 1);
  5906. if (unescapable[code]) ; else if (hex[code]) {
  5907. var hexDigits = 0;
  5908. // consume up to 6 hex chars
  5909. do {
  5910. next++;
  5911. hexDigits++;
  5912. code = css.charCodeAt(next + 1);
  5913. } while (hex[code] && hexDigits < 6);
  5914. // if fewer than 6 hex chars, a trailing space ends the escape
  5915. if (hexDigits < 6 && code === t.space) {
  5916. next++;
  5917. }
  5918. } else {
  5919. // the next char is part of the current word
  5920. next++;
  5921. }
  5922. return next;
  5923. }
  5924. var FIELDS = {
  5925. TYPE: 0,
  5926. START_LINE: 1,
  5927. START_COL: 2,
  5928. END_LINE: 3,
  5929. END_COL: 4,
  5930. START_POS: 5,
  5931. END_POS: 6
  5932. };
  5933. exports.FIELDS = FIELDS;
  5934. function tokenize(input) {
  5935. var tokens = [];
  5936. var css = input.css.valueOf();
  5937. var _css = css,
  5938. length = _css.length;
  5939. var offset = -1;
  5940. var line = 1;
  5941. var start = 0;
  5942. var end = 0;
  5943. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5944. function unclosed(what, fix) {
  5945. if (input.safe) {
  5946. // fyi: this is never set to true.
  5947. css += fix;
  5948. next = css.length - 1;
  5949. } else {
  5950. throw input.error('Unclosed ' + what, line, start - offset, start);
  5951. }
  5952. }
  5953. while (start < length) {
  5954. code = css.charCodeAt(start);
  5955. if (code === t.newline) {
  5956. offset = start;
  5957. line += 1;
  5958. }
  5959. switch (code) {
  5960. case t.space:
  5961. case t.tab:
  5962. case t.newline:
  5963. case t.cr:
  5964. case t.feed:
  5965. next = start;
  5966. do {
  5967. next += 1;
  5968. code = css.charCodeAt(next);
  5969. if (code === t.newline) {
  5970. offset = next;
  5971. line += 1;
  5972. }
  5973. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  5974. tokenType = t.space;
  5975. endLine = line;
  5976. endColumn = next - offset - 1;
  5977. end = next;
  5978. break;
  5979. case t.plus:
  5980. case t.greaterThan:
  5981. case t.tilde:
  5982. case t.pipe:
  5983. next = start;
  5984. do {
  5985. next += 1;
  5986. code = css.charCodeAt(next);
  5987. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  5988. tokenType = t.combinator;
  5989. endLine = line;
  5990. endColumn = start - offset;
  5991. end = next;
  5992. break;
  5993. // Consume these characters as single tokens.
  5994. case t.asterisk:
  5995. case t.ampersand:
  5996. case t.bang:
  5997. case t.comma:
  5998. case t.equals:
  5999. case t.dollar:
  6000. case t.caret:
  6001. case t.openSquare:
  6002. case t.closeSquare:
  6003. case t.colon:
  6004. case t.semicolon:
  6005. case t.openParenthesis:
  6006. case t.closeParenthesis:
  6007. next = start;
  6008. tokenType = code;
  6009. endLine = line;
  6010. endColumn = start - offset;
  6011. end = next + 1;
  6012. break;
  6013. case t.singleQuote:
  6014. case t.doubleQuote:
  6015. quote = code === t.singleQuote ? "'" : '"';
  6016. next = start;
  6017. do {
  6018. escaped = false;
  6019. next = css.indexOf(quote, next + 1);
  6020. if (next === -1) {
  6021. unclosed('quote', quote);
  6022. }
  6023. escapePos = next;
  6024. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6025. escapePos -= 1;
  6026. escaped = !escaped;
  6027. }
  6028. } while (escaped);
  6029. tokenType = t.str;
  6030. endLine = line;
  6031. endColumn = start - offset;
  6032. end = next + 1;
  6033. break;
  6034. default:
  6035. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6036. next = css.indexOf('*/', start + 2) + 1;
  6037. if (next === 0) {
  6038. unclosed('comment', '*/');
  6039. }
  6040. content = css.slice(start, next + 1);
  6041. lines = content.split('\n');
  6042. last = lines.length - 1;
  6043. if (last > 0) {
  6044. nextLine = line + last;
  6045. nextOffset = next - lines[last].length;
  6046. } else {
  6047. nextLine = line;
  6048. nextOffset = offset;
  6049. }
  6050. tokenType = t.comment;
  6051. line = nextLine;
  6052. endLine = nextLine;
  6053. endColumn = next - nextOffset;
  6054. } else if (code === t.slash) {
  6055. next = start;
  6056. tokenType = code;
  6057. endLine = line;
  6058. endColumn = start - offset;
  6059. end = next + 1;
  6060. } else {
  6061. next = consumeWord(css, start);
  6062. tokenType = t.word;
  6063. endLine = line;
  6064. endColumn = next - offset;
  6065. }
  6066. end = next + 1;
  6067. break;
  6068. }
  6069. // Ensure that the token structure remains consistent
  6070. tokens.push([tokenType,
  6071. // [0] Token type
  6072. line,
  6073. // [1] Starting line
  6074. start - offset,
  6075. // [2] Starting column
  6076. endLine,
  6077. // [3] Ending line
  6078. endColumn,
  6079. // [4] Ending column
  6080. start,
  6081. // [5] Start position / Source index
  6082. end // [6] End position
  6083. ]);
  6084. // Reset offset for the next token
  6085. if (nextOffset) {
  6086. offset = nextOffset;
  6087. nextOffset = null;
  6088. }
  6089. start = end;
  6090. }
  6091. return tokens;
  6092. }
  6093. } (tokenize$1));
  6094. return tokenize$1;
  6095. }
  6096. var hasRequiredParser$2;
  6097. function requireParser$2 () {
  6098. if (hasRequiredParser$2) return parser$1.exports;
  6099. hasRequiredParser$2 = 1;
  6100. (function (module, exports) {
  6101. exports.__esModule = true;
  6102. exports["default"] = void 0;
  6103. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  6104. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  6105. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  6106. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  6107. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  6108. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  6109. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  6110. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  6111. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute$1());
  6112. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  6113. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  6114. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  6115. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending$1());
  6116. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize$1());
  6117. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  6118. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  6119. var _util = /*@__PURE__*/ requireUtil$2();
  6120. var _WHITESPACE_TOKENS, _Object$assign;
  6121. 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); }
  6122. 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; }
  6123. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6124. 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); } }
  6125. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6126. 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);
  6127. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6128. function tokenStart(token) {
  6129. return {
  6130. line: token[_tokenize.FIELDS.START_LINE],
  6131. column: token[_tokenize.FIELDS.START_COL]
  6132. };
  6133. }
  6134. function tokenEnd(token) {
  6135. return {
  6136. line: token[_tokenize.FIELDS.END_LINE],
  6137. column: token[_tokenize.FIELDS.END_COL]
  6138. };
  6139. }
  6140. function getSource(startLine, startColumn, endLine, endColumn) {
  6141. return {
  6142. start: {
  6143. line: startLine,
  6144. column: startColumn
  6145. },
  6146. end: {
  6147. line: endLine,
  6148. column: endColumn
  6149. }
  6150. };
  6151. }
  6152. function getTokenSource(token) {
  6153. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6154. }
  6155. function getTokenSourceSpan(startToken, endToken) {
  6156. if (!startToken) {
  6157. return undefined;
  6158. }
  6159. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6160. }
  6161. function unescapeProp(node, prop) {
  6162. var value = node[prop];
  6163. if (typeof value !== "string") {
  6164. return;
  6165. }
  6166. if (value.indexOf("\\") !== -1) {
  6167. (0, _util.ensureObject)(node, 'raws');
  6168. node[prop] = (0, _util.unesc)(value);
  6169. if (node.raws[prop] === undefined) {
  6170. node.raws[prop] = value;
  6171. }
  6172. }
  6173. return node;
  6174. }
  6175. function indexesOf(array, item) {
  6176. var i = -1;
  6177. var indexes = [];
  6178. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6179. indexes.push(i);
  6180. }
  6181. return indexes;
  6182. }
  6183. function uniqs() {
  6184. var list = Array.prototype.concat.apply([], arguments);
  6185. return list.filter(function (item, i) {
  6186. return i === list.indexOf(item);
  6187. });
  6188. }
  6189. var Parser = /*#__PURE__*/function () {
  6190. function Parser(rule, options) {
  6191. if (options === void 0) {
  6192. options = {};
  6193. }
  6194. this.rule = rule;
  6195. this.options = Object.assign({
  6196. lossy: false,
  6197. safe: false
  6198. }, options);
  6199. this.position = 0;
  6200. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6201. this.tokens = (0, _tokenize["default"])({
  6202. css: this.css,
  6203. error: this._errorGenerator(),
  6204. safe: this.options.safe
  6205. });
  6206. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6207. this.root = new _root["default"]({
  6208. source: rootSource
  6209. });
  6210. this.root.errorGenerator = this._errorGenerator();
  6211. var selector = new _selector["default"]({
  6212. source: {
  6213. start: {
  6214. line: 1,
  6215. column: 1
  6216. }
  6217. },
  6218. sourceIndex: 0
  6219. });
  6220. this.root.append(selector);
  6221. this.current = selector;
  6222. this.loop();
  6223. }
  6224. var _proto = Parser.prototype;
  6225. _proto._errorGenerator = function _errorGenerator() {
  6226. var _this = this;
  6227. return function (message, errorOptions) {
  6228. if (typeof _this.rule === 'string') {
  6229. return new Error(message);
  6230. }
  6231. return _this.rule.error(message, errorOptions);
  6232. };
  6233. };
  6234. _proto.attribute = function attribute() {
  6235. var attr = [];
  6236. var startingToken = this.currToken;
  6237. this.position++;
  6238. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6239. attr.push(this.currToken);
  6240. this.position++;
  6241. }
  6242. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6243. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6244. }
  6245. var len = attr.length;
  6246. var node = {
  6247. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6248. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6249. };
  6250. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6251. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6252. }
  6253. var pos = 0;
  6254. var spaceBefore = '';
  6255. var commentBefore = '';
  6256. var lastAdded = null;
  6257. var spaceAfterMeaningfulToken = false;
  6258. while (pos < len) {
  6259. var token = attr[pos];
  6260. var content = this.content(token);
  6261. var next = attr[pos + 1];
  6262. switch (token[_tokenize.FIELDS.TYPE]) {
  6263. case tokens.space:
  6264. // if (
  6265. // len === 1 ||
  6266. // pos === 0 && this.content(next) === '|'
  6267. // ) {
  6268. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6269. // }
  6270. spaceAfterMeaningfulToken = true;
  6271. if (this.options.lossy) {
  6272. break;
  6273. }
  6274. if (lastAdded) {
  6275. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6276. var prevContent = node.spaces[lastAdded].after || '';
  6277. node.spaces[lastAdded].after = prevContent + content;
  6278. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6279. if (existingComment) {
  6280. node.raws.spaces[lastAdded].after = existingComment + content;
  6281. }
  6282. } else {
  6283. spaceBefore = spaceBefore + content;
  6284. commentBefore = commentBefore + content;
  6285. }
  6286. break;
  6287. case tokens.asterisk:
  6288. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6289. node.operator = content;
  6290. lastAdded = 'operator';
  6291. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6292. if (spaceBefore) {
  6293. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6294. node.spaces.attribute.before = spaceBefore;
  6295. spaceBefore = '';
  6296. }
  6297. if (commentBefore) {
  6298. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6299. node.raws.spaces.attribute.before = spaceBefore;
  6300. commentBefore = '';
  6301. }
  6302. node.namespace = (node.namespace || "") + content;
  6303. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6304. if (rawValue) {
  6305. node.raws.namespace += content;
  6306. }
  6307. lastAdded = 'namespace';
  6308. }
  6309. spaceAfterMeaningfulToken = false;
  6310. break;
  6311. case tokens.dollar:
  6312. if (lastAdded === "value") {
  6313. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6314. node.value += "$";
  6315. if (oldRawValue) {
  6316. node.raws.value = oldRawValue + "$";
  6317. }
  6318. break;
  6319. }
  6320. // Falls through
  6321. case tokens.caret:
  6322. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6323. node.operator = content;
  6324. lastAdded = 'operator';
  6325. }
  6326. spaceAfterMeaningfulToken = false;
  6327. break;
  6328. case tokens.combinator:
  6329. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6330. node.operator = content;
  6331. lastAdded = 'operator';
  6332. }
  6333. if (content !== '|') {
  6334. spaceAfterMeaningfulToken = false;
  6335. break;
  6336. }
  6337. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6338. node.operator = content;
  6339. lastAdded = 'operator';
  6340. } else if (!node.namespace && !node.attribute) {
  6341. node.namespace = true;
  6342. }
  6343. spaceAfterMeaningfulToken = false;
  6344. break;
  6345. case tokens.word:
  6346. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6347. // this look-ahead probably fails with comment nodes involved.
  6348. !node.operator && !node.namespace) {
  6349. node.namespace = content;
  6350. lastAdded = 'namespace';
  6351. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6352. if (spaceBefore) {
  6353. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6354. node.spaces.attribute.before = spaceBefore;
  6355. spaceBefore = '';
  6356. }
  6357. if (commentBefore) {
  6358. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6359. node.raws.spaces.attribute.before = commentBefore;
  6360. commentBefore = '';
  6361. }
  6362. node.attribute = (node.attribute || "") + content;
  6363. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6364. if (_rawValue) {
  6365. node.raws.attribute += content;
  6366. }
  6367. lastAdded = 'attribute';
  6368. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6369. var _unescaped = (0, _util.unesc)(content);
  6370. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6371. var oldValue = node.value || '';
  6372. node.value = oldValue + _unescaped;
  6373. node.quoteMark = null;
  6374. if (_unescaped !== content || _oldRawValue) {
  6375. (0, _util.ensureObject)(node, 'raws');
  6376. node.raws.value = (_oldRawValue || oldValue) + content;
  6377. }
  6378. lastAdded = 'value';
  6379. } else {
  6380. var insensitive = content === 'i' || content === "I";
  6381. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6382. node.insensitive = insensitive;
  6383. if (!insensitive || content === "I") {
  6384. (0, _util.ensureObject)(node, 'raws');
  6385. node.raws.insensitiveFlag = content;
  6386. }
  6387. lastAdded = 'insensitive';
  6388. if (spaceBefore) {
  6389. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6390. node.spaces.insensitive.before = spaceBefore;
  6391. spaceBefore = '';
  6392. }
  6393. if (commentBefore) {
  6394. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6395. node.raws.spaces.insensitive.before = commentBefore;
  6396. commentBefore = '';
  6397. }
  6398. } else if (node.value || node.value === '') {
  6399. lastAdded = 'value';
  6400. node.value += content;
  6401. if (node.raws.value) {
  6402. node.raws.value += content;
  6403. }
  6404. }
  6405. }
  6406. spaceAfterMeaningfulToken = false;
  6407. break;
  6408. case tokens.str:
  6409. if (!node.attribute || !node.operator) {
  6410. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6411. index: token[_tokenize.FIELDS.START_POS]
  6412. });
  6413. }
  6414. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6415. unescaped = _unescapeValue.unescaped,
  6416. quoteMark = _unescapeValue.quoteMark;
  6417. node.value = unescaped;
  6418. node.quoteMark = quoteMark;
  6419. lastAdded = 'value';
  6420. (0, _util.ensureObject)(node, 'raws');
  6421. node.raws.value = content;
  6422. spaceAfterMeaningfulToken = false;
  6423. break;
  6424. case tokens.equals:
  6425. if (!node.attribute) {
  6426. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6427. }
  6428. if (node.value) {
  6429. return this.error('Unexpected "=" found; an operator was already defined.', {
  6430. index: token[_tokenize.FIELDS.START_POS]
  6431. });
  6432. }
  6433. node.operator = node.operator ? node.operator + content : content;
  6434. lastAdded = 'operator';
  6435. spaceAfterMeaningfulToken = false;
  6436. break;
  6437. case tokens.comment:
  6438. if (lastAdded) {
  6439. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6440. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6441. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6442. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6443. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6444. } else {
  6445. var lastValue = node[lastAdded] || '';
  6446. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6447. (0, _util.ensureObject)(node, 'raws');
  6448. node.raws[lastAdded] = rawLastValue + content;
  6449. }
  6450. } else {
  6451. commentBefore = commentBefore + content;
  6452. }
  6453. break;
  6454. default:
  6455. return this.error("Unexpected \"" + content + "\" found.", {
  6456. index: token[_tokenize.FIELDS.START_POS]
  6457. });
  6458. }
  6459. pos++;
  6460. }
  6461. unescapeProp(node, "attribute");
  6462. unescapeProp(node, "namespace");
  6463. this.newNode(new _attribute["default"](node));
  6464. this.position++;
  6465. }
  6466. /**
  6467. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6468. * if the token position is negative, all remaining tokens are consumed.
  6469. *
  6470. * This returns an array containing a single string node if all whitespace,
  6471. * otherwise an array of comment nodes with space before and after.
  6472. *
  6473. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6474. * a previous node's space metadata.
  6475. *
  6476. * In lossy mode, this returns only comments.
  6477. */;
  6478. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6479. if (stopPosition < 0) {
  6480. stopPosition = this.tokens.length;
  6481. }
  6482. var startPosition = this.position;
  6483. var nodes = [];
  6484. var space = "";
  6485. var lastComment = undefined;
  6486. do {
  6487. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6488. if (!this.options.lossy) {
  6489. space += this.content();
  6490. }
  6491. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6492. var spaces = {};
  6493. if (space) {
  6494. spaces.before = space;
  6495. space = "";
  6496. }
  6497. lastComment = new _comment["default"]({
  6498. value: this.content(),
  6499. source: getTokenSource(this.currToken),
  6500. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6501. spaces: spaces
  6502. });
  6503. nodes.push(lastComment);
  6504. }
  6505. } while (++this.position < stopPosition);
  6506. if (space) {
  6507. if (lastComment) {
  6508. lastComment.spaces.after = space;
  6509. } else if (!this.options.lossy) {
  6510. var firstToken = this.tokens[startPosition];
  6511. var lastToken = this.tokens[this.position - 1];
  6512. nodes.push(new _string["default"]({
  6513. value: '',
  6514. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6515. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6516. spaces: {
  6517. before: space,
  6518. after: ''
  6519. }
  6520. }));
  6521. }
  6522. }
  6523. return nodes;
  6524. }
  6525. /**
  6526. *
  6527. * @param {*} nodes
  6528. */;
  6529. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6530. var _this2 = this;
  6531. if (requiredSpace === void 0) {
  6532. requiredSpace = false;
  6533. }
  6534. var space = "";
  6535. var rawSpace = "";
  6536. nodes.forEach(function (n) {
  6537. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6538. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6539. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6540. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6541. });
  6542. if (rawSpace === space) {
  6543. rawSpace = undefined;
  6544. }
  6545. var result = {
  6546. space: space,
  6547. rawSpace: rawSpace
  6548. };
  6549. return result;
  6550. };
  6551. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6552. if (position === void 0) {
  6553. position = this.position;
  6554. }
  6555. 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;
  6556. };
  6557. _proto.namedCombinator = function namedCombinator() {
  6558. if (this.isNamedCombinator()) {
  6559. var nameRaw = this.content(this.tokens[this.position + 1]);
  6560. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6561. var raws = {};
  6562. if (name !== nameRaw) {
  6563. raws.value = "/" + nameRaw + "/";
  6564. }
  6565. var node = new _combinator["default"]({
  6566. value: "/" + name + "/",
  6567. 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]),
  6568. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6569. raws: raws
  6570. });
  6571. this.position = this.position + 3;
  6572. return node;
  6573. } else {
  6574. this.unexpected();
  6575. }
  6576. };
  6577. _proto.combinator = function combinator() {
  6578. var _this3 = this;
  6579. if (this.content() === '|') {
  6580. return this.namespace();
  6581. }
  6582. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6583. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6584. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6585. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6586. if (nodes.length > 0) {
  6587. var last = this.current.last;
  6588. if (last) {
  6589. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6590. space = _this$convertWhitespa.space,
  6591. rawSpace = _this$convertWhitespa.rawSpace;
  6592. if (rawSpace !== undefined) {
  6593. last.rawSpaceAfter += rawSpace;
  6594. }
  6595. last.spaces.after += space;
  6596. } else {
  6597. nodes.forEach(function (n) {
  6598. return _this3.newNode(n);
  6599. });
  6600. }
  6601. }
  6602. return;
  6603. }
  6604. var firstToken = this.currToken;
  6605. var spaceOrDescendantSelectorNodes = undefined;
  6606. if (nextSigTokenPos > this.position) {
  6607. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6608. }
  6609. var node;
  6610. if (this.isNamedCombinator()) {
  6611. node = this.namedCombinator();
  6612. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6613. node = new _combinator["default"]({
  6614. value: this.content(),
  6615. source: getTokenSource(this.currToken),
  6616. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6617. });
  6618. this.position++;
  6619. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6620. this.unexpected();
  6621. }
  6622. if (node) {
  6623. if (spaceOrDescendantSelectorNodes) {
  6624. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6625. _space = _this$convertWhitespa2.space,
  6626. _rawSpace = _this$convertWhitespa2.rawSpace;
  6627. node.spaces.before = _space;
  6628. node.rawSpaceBefore = _rawSpace;
  6629. }
  6630. } else {
  6631. // descendant combinator
  6632. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6633. _space2 = _this$convertWhitespa3.space,
  6634. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6635. if (!_rawSpace2) {
  6636. _rawSpace2 = _space2;
  6637. }
  6638. var spaces = {};
  6639. var raws = {
  6640. spaces: {}
  6641. };
  6642. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6643. spaces.before = _space2.slice(0, _space2.length - 1);
  6644. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6645. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  6646. spaces.after = _space2.slice(1);
  6647. raws.spaces.after = _rawSpace2.slice(1);
  6648. } else {
  6649. raws.value = _rawSpace2;
  6650. }
  6651. node = new _combinator["default"]({
  6652. value: ' ',
  6653. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6654. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6655. spaces: spaces,
  6656. raws: raws
  6657. });
  6658. }
  6659. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6660. node.spaces.after = this.optionalSpace(this.content());
  6661. this.position++;
  6662. }
  6663. return this.newNode(node);
  6664. };
  6665. _proto.comma = function comma() {
  6666. if (this.position === this.tokens.length - 1) {
  6667. this.root.trailingComma = true;
  6668. this.position++;
  6669. return;
  6670. }
  6671. this.current._inferEndPosition();
  6672. var selector = new _selector["default"]({
  6673. source: {
  6674. start: tokenStart(this.tokens[this.position + 1])
  6675. },
  6676. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6677. });
  6678. this.current.parent.append(selector);
  6679. this.current = selector;
  6680. this.position++;
  6681. };
  6682. _proto.comment = function comment() {
  6683. var current = this.currToken;
  6684. this.newNode(new _comment["default"]({
  6685. value: this.content(),
  6686. source: getTokenSource(current),
  6687. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6688. }));
  6689. this.position++;
  6690. };
  6691. _proto.error = function error(message, opts) {
  6692. throw this.root.error(message, opts);
  6693. };
  6694. _proto.missingBackslash = function missingBackslash() {
  6695. return this.error('Expected a backslash preceding the semicolon.', {
  6696. index: this.currToken[_tokenize.FIELDS.START_POS]
  6697. });
  6698. };
  6699. _proto.missingParenthesis = function missingParenthesis() {
  6700. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6701. };
  6702. _proto.missingSquareBracket = function missingSquareBracket() {
  6703. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6704. };
  6705. _proto.unexpected = function unexpected() {
  6706. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6707. };
  6708. _proto.unexpectedPipe = function unexpectedPipe() {
  6709. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6710. };
  6711. _proto.namespace = function namespace() {
  6712. var before = this.prevToken && this.content(this.prevToken) || true;
  6713. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6714. this.position++;
  6715. return this.word(before);
  6716. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6717. this.position++;
  6718. return this.universal(before);
  6719. }
  6720. this.unexpectedPipe();
  6721. };
  6722. _proto.nesting = function nesting() {
  6723. if (this.nextToken) {
  6724. var nextContent = this.content(this.nextToken);
  6725. if (nextContent === "|") {
  6726. this.position++;
  6727. return;
  6728. }
  6729. }
  6730. var current = this.currToken;
  6731. this.newNode(new _nesting["default"]({
  6732. value: this.content(),
  6733. source: getTokenSource(current),
  6734. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6735. }));
  6736. this.position++;
  6737. };
  6738. _proto.parentheses = function parentheses() {
  6739. var last = this.current.last;
  6740. var unbalanced = 1;
  6741. this.position++;
  6742. if (last && last.type === types.PSEUDO) {
  6743. var selector = new _selector["default"]({
  6744. source: {
  6745. start: tokenStart(this.tokens[this.position])
  6746. },
  6747. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6748. });
  6749. var cache = this.current;
  6750. last.append(selector);
  6751. this.current = selector;
  6752. while (this.position < this.tokens.length && unbalanced) {
  6753. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6754. unbalanced++;
  6755. }
  6756. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6757. unbalanced--;
  6758. }
  6759. if (unbalanced) {
  6760. this.parse();
  6761. } else {
  6762. this.current.source.end = tokenEnd(this.currToken);
  6763. this.current.parent.source.end = tokenEnd(this.currToken);
  6764. this.position++;
  6765. }
  6766. }
  6767. this.current = cache;
  6768. } else {
  6769. // I think this case should be an error. It's used to implement a basic parse of media queries
  6770. // but I don't think it's a good idea.
  6771. var parenStart = this.currToken;
  6772. var parenValue = "(";
  6773. var parenEnd;
  6774. while (this.position < this.tokens.length && unbalanced) {
  6775. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6776. unbalanced++;
  6777. }
  6778. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6779. unbalanced--;
  6780. }
  6781. parenEnd = this.currToken;
  6782. parenValue += this.parseParenthesisToken(this.currToken);
  6783. this.position++;
  6784. }
  6785. if (last) {
  6786. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6787. } else {
  6788. this.newNode(new _string["default"]({
  6789. value: parenValue,
  6790. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6791. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6792. }));
  6793. }
  6794. }
  6795. if (unbalanced) {
  6796. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6797. }
  6798. };
  6799. _proto.pseudo = function pseudo() {
  6800. var _this4 = this;
  6801. var pseudoStr = '';
  6802. var startingToken = this.currToken;
  6803. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6804. pseudoStr += this.content();
  6805. this.position++;
  6806. }
  6807. if (!this.currToken) {
  6808. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6809. }
  6810. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6811. this.splitWord(false, function (first, length) {
  6812. pseudoStr += first;
  6813. _this4.newNode(new _pseudo["default"]({
  6814. value: pseudoStr,
  6815. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6816. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6817. }));
  6818. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6819. _this4.error('Misplaced parenthesis.', {
  6820. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6821. });
  6822. }
  6823. });
  6824. } else {
  6825. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6826. }
  6827. };
  6828. _proto.space = function space() {
  6829. var content = this.content();
  6830. // Handle space before and after the selector
  6831. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6832. return node.type === 'comment';
  6833. })) {
  6834. this.spaces = this.optionalSpace(content);
  6835. this.position++;
  6836. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6837. this.current.last.spaces.after = this.optionalSpace(content);
  6838. this.position++;
  6839. } else {
  6840. this.combinator();
  6841. }
  6842. };
  6843. _proto.string = function string() {
  6844. var current = this.currToken;
  6845. this.newNode(new _string["default"]({
  6846. value: this.content(),
  6847. source: getTokenSource(current),
  6848. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6849. }));
  6850. this.position++;
  6851. };
  6852. _proto.universal = function universal(namespace) {
  6853. var nextToken = this.nextToken;
  6854. if (nextToken && this.content(nextToken) === '|') {
  6855. this.position++;
  6856. return this.namespace();
  6857. }
  6858. var current = this.currToken;
  6859. this.newNode(new _universal["default"]({
  6860. value: this.content(),
  6861. source: getTokenSource(current),
  6862. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6863. }), namespace);
  6864. this.position++;
  6865. };
  6866. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6867. var _this5 = this;
  6868. var nextToken = this.nextToken;
  6869. var word = this.content();
  6870. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6871. this.position++;
  6872. var current = this.content();
  6873. word += current;
  6874. if (current.lastIndexOf('\\') === current.length - 1) {
  6875. var next = this.nextToken;
  6876. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6877. word += this.requiredSpace(this.content(next));
  6878. this.position++;
  6879. }
  6880. }
  6881. nextToken = this.nextToken;
  6882. }
  6883. var hasClass = indexesOf(word, '.').filter(function (i) {
  6884. // Allow escaped dot within class name
  6885. var escapedDot = word[i - 1] === '\\';
  6886. // Allow decimal numbers percent in @keyframes
  6887. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6888. return !escapedDot && !isKeyframesPercent;
  6889. });
  6890. var hasId = indexesOf(word, '#').filter(function (i) {
  6891. return word[i - 1] !== '\\';
  6892. });
  6893. // Eliminate Sass interpolations from the list of id indexes
  6894. var interpolations = indexesOf(word, '#{');
  6895. if (interpolations.length) {
  6896. hasId = hasId.filter(function (hashIndex) {
  6897. return !~interpolations.indexOf(hashIndex);
  6898. });
  6899. }
  6900. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6901. indices.forEach(function (ind, i) {
  6902. var index = indices[i + 1] || word.length;
  6903. var value = word.slice(ind, index);
  6904. if (i === 0 && firstCallback) {
  6905. return firstCallback.call(_this5, value, indices.length);
  6906. }
  6907. var node;
  6908. var current = _this5.currToken;
  6909. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6910. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6911. if (~hasClass.indexOf(ind)) {
  6912. var classNameOpts = {
  6913. value: value.slice(1),
  6914. source: source,
  6915. sourceIndex: sourceIndex
  6916. };
  6917. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6918. } else if (~hasId.indexOf(ind)) {
  6919. var idOpts = {
  6920. value: value.slice(1),
  6921. source: source,
  6922. sourceIndex: sourceIndex
  6923. };
  6924. node = new _id["default"](unescapeProp(idOpts, "value"));
  6925. } else {
  6926. var tagOpts = {
  6927. value: value,
  6928. source: source,
  6929. sourceIndex: sourceIndex
  6930. };
  6931. unescapeProp(tagOpts, "value");
  6932. node = new _tag["default"](tagOpts);
  6933. }
  6934. _this5.newNode(node, namespace);
  6935. // Ensure that the namespace is used only once
  6936. namespace = null;
  6937. });
  6938. this.position++;
  6939. };
  6940. _proto.word = function word(namespace) {
  6941. var nextToken = this.nextToken;
  6942. if (nextToken && this.content(nextToken) === '|') {
  6943. this.position++;
  6944. return this.namespace();
  6945. }
  6946. return this.splitWord(namespace);
  6947. };
  6948. _proto.loop = function loop() {
  6949. while (this.position < this.tokens.length) {
  6950. this.parse(true);
  6951. }
  6952. this.current._inferEndPosition();
  6953. return this.root;
  6954. };
  6955. _proto.parse = function parse(throwOnParenthesis) {
  6956. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6957. case tokens.space:
  6958. this.space();
  6959. break;
  6960. case tokens.comment:
  6961. this.comment();
  6962. break;
  6963. case tokens.openParenthesis:
  6964. this.parentheses();
  6965. break;
  6966. case tokens.closeParenthesis:
  6967. if (throwOnParenthesis) {
  6968. this.missingParenthesis();
  6969. }
  6970. break;
  6971. case tokens.openSquare:
  6972. this.attribute();
  6973. break;
  6974. case tokens.dollar:
  6975. case tokens.caret:
  6976. case tokens.equals:
  6977. case tokens.word:
  6978. this.word();
  6979. break;
  6980. case tokens.colon:
  6981. this.pseudo();
  6982. break;
  6983. case tokens.comma:
  6984. this.comma();
  6985. break;
  6986. case tokens.asterisk:
  6987. this.universal();
  6988. break;
  6989. case tokens.ampersand:
  6990. this.nesting();
  6991. break;
  6992. case tokens.slash:
  6993. case tokens.combinator:
  6994. this.combinator();
  6995. break;
  6996. case tokens.str:
  6997. this.string();
  6998. break;
  6999. // These cases throw; no break needed.
  7000. case tokens.closeSquare:
  7001. this.missingSquareBracket();
  7002. case tokens.semicolon:
  7003. this.missingBackslash();
  7004. default:
  7005. this.unexpected();
  7006. }
  7007. }
  7008. /**
  7009. * Helpers
  7010. */;
  7011. _proto.expected = function expected(description, index, found) {
  7012. if (Array.isArray(description)) {
  7013. var last = description.pop();
  7014. description = description.join(', ') + " or " + last;
  7015. }
  7016. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  7017. if (!found) {
  7018. return this.error("Expected " + an + " " + description + ".", {
  7019. index: index
  7020. });
  7021. }
  7022. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  7023. index: index
  7024. });
  7025. };
  7026. _proto.requiredSpace = function requiredSpace(space) {
  7027. return this.options.lossy ? ' ' : space;
  7028. };
  7029. _proto.optionalSpace = function optionalSpace(space) {
  7030. return this.options.lossy ? '' : space;
  7031. };
  7032. _proto.lossySpace = function lossySpace(space, required) {
  7033. if (this.options.lossy) {
  7034. return required ? ' ' : '';
  7035. } else {
  7036. return space;
  7037. }
  7038. };
  7039. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  7040. var content = this.content(token);
  7041. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  7042. return this.requiredSpace(content);
  7043. } else {
  7044. return content;
  7045. }
  7046. };
  7047. _proto.newNode = function newNode(node, namespace) {
  7048. if (namespace) {
  7049. if (/^ +$/.test(namespace)) {
  7050. if (!this.options.lossy) {
  7051. this.spaces = (this.spaces || '') + namespace;
  7052. }
  7053. namespace = true;
  7054. }
  7055. node.namespace = namespace;
  7056. unescapeProp(node, "namespace");
  7057. }
  7058. if (this.spaces) {
  7059. node.spaces.before = this.spaces;
  7060. this.spaces = '';
  7061. }
  7062. return this.current.append(node);
  7063. };
  7064. _proto.content = function content(token) {
  7065. if (token === void 0) {
  7066. token = this.currToken;
  7067. }
  7068. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  7069. };
  7070. /**
  7071. * returns the index of the next non-whitespace, non-comment token.
  7072. * returns -1 if no meaningful token is found.
  7073. */
  7074. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  7075. if (startPosition === void 0) {
  7076. startPosition = this.position + 1;
  7077. }
  7078. var searchPosition = startPosition;
  7079. while (searchPosition < this.tokens.length) {
  7080. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  7081. searchPosition++;
  7082. continue;
  7083. } else {
  7084. return searchPosition;
  7085. }
  7086. }
  7087. return -1;
  7088. };
  7089. _createClass(Parser, [{
  7090. key: "currToken",
  7091. get: function get() {
  7092. return this.tokens[this.position];
  7093. }
  7094. }, {
  7095. key: "nextToken",
  7096. get: function get() {
  7097. return this.tokens[this.position + 1];
  7098. }
  7099. }, {
  7100. key: "prevToken",
  7101. get: function get() {
  7102. return this.tokens[this.position - 1];
  7103. }
  7104. }]);
  7105. return Parser;
  7106. }();
  7107. exports["default"] = Parser;
  7108. module.exports = exports.default;
  7109. } (parser$1, parser$1.exports));
  7110. return parser$1.exports;
  7111. }
  7112. var hasRequiredProcessor$1;
  7113. function requireProcessor$1 () {
  7114. if (hasRequiredProcessor$1) return processor$1.exports;
  7115. hasRequiredProcessor$1 = 1;
  7116. (function (module, exports) {
  7117. exports.__esModule = true;
  7118. exports["default"] = void 0;
  7119. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser$2());
  7120. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7121. var Processor = /*#__PURE__*/function () {
  7122. function Processor(func, options) {
  7123. this.func = func || function noop() {};
  7124. this.funcRes = null;
  7125. this.options = options;
  7126. }
  7127. var _proto = Processor.prototype;
  7128. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7129. if (options === void 0) {
  7130. options = {};
  7131. }
  7132. var merged = Object.assign({}, this.options, options);
  7133. if (merged.updateSelector === false) {
  7134. return false;
  7135. } else {
  7136. return typeof rule !== "string";
  7137. }
  7138. };
  7139. _proto._isLossy = function _isLossy(options) {
  7140. if (options === void 0) {
  7141. options = {};
  7142. }
  7143. var merged = Object.assign({}, this.options, options);
  7144. if (merged.lossless === false) {
  7145. return true;
  7146. } else {
  7147. return false;
  7148. }
  7149. };
  7150. _proto._root = function _root(rule, options) {
  7151. if (options === void 0) {
  7152. options = {};
  7153. }
  7154. var parser = new _parser["default"](rule, this._parseOptions(options));
  7155. return parser.root;
  7156. };
  7157. _proto._parseOptions = function _parseOptions(options) {
  7158. return {
  7159. lossy: this._isLossy(options)
  7160. };
  7161. };
  7162. _proto._run = function _run(rule, options) {
  7163. var _this = this;
  7164. if (options === void 0) {
  7165. options = {};
  7166. }
  7167. return new Promise(function (resolve, reject) {
  7168. try {
  7169. var root = _this._root(rule, options);
  7170. Promise.resolve(_this.func(root)).then(function (transform) {
  7171. var string = undefined;
  7172. if (_this._shouldUpdateSelector(rule, options)) {
  7173. string = root.toString();
  7174. rule.selector = string;
  7175. }
  7176. return {
  7177. transform: transform,
  7178. root: root,
  7179. string: string
  7180. };
  7181. }).then(resolve, reject);
  7182. } catch (e) {
  7183. reject(e);
  7184. return;
  7185. }
  7186. });
  7187. };
  7188. _proto._runSync = function _runSync(rule, options) {
  7189. if (options === void 0) {
  7190. options = {};
  7191. }
  7192. var root = this._root(rule, options);
  7193. var transform = this.func(root);
  7194. if (transform && typeof transform.then === "function") {
  7195. throw new Error("Selector processor returned a promise to a synchronous call.");
  7196. }
  7197. var string = undefined;
  7198. if (options.updateSelector && typeof rule !== "string") {
  7199. string = root.toString();
  7200. rule.selector = string;
  7201. }
  7202. return {
  7203. transform: transform,
  7204. root: root,
  7205. string: string
  7206. };
  7207. }
  7208. /**
  7209. * Process rule into a selector AST.
  7210. *
  7211. * @param rule {postcss.Rule | string} The css selector to be processed
  7212. * @param options The options for processing
  7213. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7214. */;
  7215. _proto.ast = function ast(rule, options) {
  7216. return this._run(rule, options).then(function (result) {
  7217. return result.root;
  7218. });
  7219. }
  7220. /**
  7221. * Process rule into a selector AST synchronously.
  7222. *
  7223. * @param rule {postcss.Rule | string} The css selector to be processed
  7224. * @param options The options for processing
  7225. * @returns {parser.Root} The AST of the selector after processing it.
  7226. */;
  7227. _proto.astSync = function astSync(rule, options) {
  7228. return this._runSync(rule, options).root;
  7229. }
  7230. /**
  7231. * Process a selector into a transformed value asynchronously
  7232. *
  7233. * @param rule {postcss.Rule | string} The css selector to be processed
  7234. * @param options The options for processing
  7235. * @returns {Promise<any>} The value returned by the processor.
  7236. */;
  7237. _proto.transform = function transform(rule, options) {
  7238. return this._run(rule, options).then(function (result) {
  7239. return result.transform;
  7240. });
  7241. }
  7242. /**
  7243. * Process a selector into a transformed value synchronously.
  7244. *
  7245. * @param rule {postcss.Rule | string} The css selector to be processed
  7246. * @param options The options for processing
  7247. * @returns {any} The value returned by the processor.
  7248. */;
  7249. _proto.transformSync = function transformSync(rule, options) {
  7250. return this._runSync(rule, options).transform;
  7251. }
  7252. /**
  7253. * Process a selector into a new selector string asynchronously.
  7254. *
  7255. * @param rule {postcss.Rule | string} The css selector to be processed
  7256. * @param options The options for processing
  7257. * @returns {string} the selector after processing.
  7258. */;
  7259. _proto.process = function process(rule, options) {
  7260. return this._run(rule, options).then(function (result) {
  7261. return result.string || result.root.toString();
  7262. });
  7263. }
  7264. /**
  7265. * Process a selector into a new selector string synchronously.
  7266. *
  7267. * @param rule {postcss.Rule | string} The css selector to be processed
  7268. * @param options The options for processing
  7269. * @returns {string} the selector after processing.
  7270. */;
  7271. _proto.processSync = function processSync(rule, options) {
  7272. var result = this._runSync(rule, options);
  7273. return result.string || result.root.toString();
  7274. };
  7275. return Processor;
  7276. }();
  7277. exports["default"] = Processor;
  7278. module.exports = exports.default;
  7279. } (processor$1, processor$1.exports));
  7280. return processor$1.exports;
  7281. }
  7282. var selectors$1 = {};
  7283. var constructors$1 = {};
  7284. var hasRequiredConstructors$1;
  7285. function requireConstructors$1 () {
  7286. if (hasRequiredConstructors$1) return constructors$1;
  7287. hasRequiredConstructors$1 = 1;
  7288. constructors$1.__esModule = true;
  7289. 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;
  7290. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute$1());
  7291. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  7292. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  7293. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  7294. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  7295. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  7296. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  7297. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  7298. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  7299. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  7300. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  7301. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  7302. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7303. var attribute = function attribute(opts) {
  7304. return new _attribute["default"](opts);
  7305. };
  7306. constructors$1.attribute = attribute;
  7307. var className = function className(opts) {
  7308. return new _className["default"](opts);
  7309. };
  7310. constructors$1.className = className;
  7311. var combinator = function combinator(opts) {
  7312. return new _combinator["default"](opts);
  7313. };
  7314. constructors$1.combinator = combinator;
  7315. var comment = function comment(opts) {
  7316. return new _comment["default"](opts);
  7317. };
  7318. constructors$1.comment = comment;
  7319. var id = function id(opts) {
  7320. return new _id["default"](opts);
  7321. };
  7322. constructors$1.id = id;
  7323. var nesting = function nesting(opts) {
  7324. return new _nesting["default"](opts);
  7325. };
  7326. constructors$1.nesting = nesting;
  7327. var pseudo = function pseudo(opts) {
  7328. return new _pseudo["default"](opts);
  7329. };
  7330. constructors$1.pseudo = pseudo;
  7331. var root = function root(opts) {
  7332. return new _root["default"](opts);
  7333. };
  7334. constructors$1.root = root;
  7335. var selector = function selector(opts) {
  7336. return new _selector["default"](opts);
  7337. };
  7338. constructors$1.selector = selector;
  7339. var string = function string(opts) {
  7340. return new _string["default"](opts);
  7341. };
  7342. constructors$1.string = string;
  7343. var tag = function tag(opts) {
  7344. return new _tag["default"](opts);
  7345. };
  7346. constructors$1.tag = tag;
  7347. var universal = function universal(opts) {
  7348. return new _universal["default"](opts);
  7349. };
  7350. constructors$1.universal = universal;
  7351. return constructors$1;
  7352. }
  7353. var guards$1 = {};
  7354. var hasRequiredGuards$1;
  7355. function requireGuards$1 () {
  7356. if (hasRequiredGuards$1) return guards$1;
  7357. hasRequiredGuards$1 = 1;
  7358. guards$1.__esModule = true;
  7359. guards$1.isComment = guards$1.isCombinator = guards$1.isClassName = guards$1.isAttribute = void 0;
  7360. guards$1.isContainer = isContainer;
  7361. guards$1.isIdentifier = void 0;
  7362. guards$1.isNamespace = isNamespace;
  7363. guards$1.isNesting = void 0;
  7364. guards$1.isNode = isNode;
  7365. guards$1.isPseudo = void 0;
  7366. guards$1.isPseudoClass = isPseudoClass;
  7367. guards$1.isPseudoElement = isPseudoElement;
  7368. guards$1.isUniversal = guards$1.isTag = guards$1.isString = guards$1.isSelector = guards$1.isRoot = void 0;
  7369. var _types = /*@__PURE__*/ requireTypes$1();
  7370. var _IS_TYPE;
  7371. 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);
  7372. function isNode(node) {
  7373. return typeof node === "object" && IS_TYPE[node.type];
  7374. }
  7375. function isNodeType(type, node) {
  7376. return isNode(node) && node.type === type;
  7377. }
  7378. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7379. guards$1.isAttribute = isAttribute;
  7380. var isClassName = isNodeType.bind(null, _types.CLASS);
  7381. guards$1.isClassName = isClassName;
  7382. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7383. guards$1.isCombinator = isCombinator;
  7384. var isComment = isNodeType.bind(null, _types.COMMENT);
  7385. guards$1.isComment = isComment;
  7386. var isIdentifier = isNodeType.bind(null, _types.ID);
  7387. guards$1.isIdentifier = isIdentifier;
  7388. var isNesting = isNodeType.bind(null, _types.NESTING);
  7389. guards$1.isNesting = isNesting;
  7390. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7391. guards$1.isPseudo = isPseudo;
  7392. var isRoot = isNodeType.bind(null, _types.ROOT);
  7393. guards$1.isRoot = isRoot;
  7394. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7395. guards$1.isSelector = isSelector;
  7396. var isString = isNodeType.bind(null, _types.STRING);
  7397. guards$1.isString = isString;
  7398. var isTag = isNodeType.bind(null, _types.TAG);
  7399. guards$1.isTag = isTag;
  7400. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7401. guards$1.isUniversal = isUniversal;
  7402. function isPseudoElement(node) {
  7403. 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");
  7404. }
  7405. function isPseudoClass(node) {
  7406. return isPseudo(node) && !isPseudoElement(node);
  7407. }
  7408. function isContainer(node) {
  7409. return !!(isNode(node) && node.walk);
  7410. }
  7411. function isNamespace(node) {
  7412. return isAttribute(node) || isTag(node);
  7413. }
  7414. return guards$1;
  7415. }
  7416. var hasRequiredSelectors$1;
  7417. function requireSelectors$1 () {
  7418. if (hasRequiredSelectors$1) return selectors$1;
  7419. hasRequiredSelectors$1 = 1;
  7420. (function (exports) {
  7421. exports.__esModule = true;
  7422. var _types = /*@__PURE__*/ requireTypes$1();
  7423. Object.keys(_types).forEach(function (key) {
  7424. if (key === "default" || key === "__esModule") return;
  7425. if (key in exports && exports[key] === _types[key]) return;
  7426. exports[key] = _types[key];
  7427. });
  7428. var _constructors = /*@__PURE__*/ requireConstructors$1();
  7429. Object.keys(_constructors).forEach(function (key) {
  7430. if (key === "default" || key === "__esModule") return;
  7431. if (key in exports && exports[key] === _constructors[key]) return;
  7432. exports[key] = _constructors[key];
  7433. });
  7434. var _guards = /*@__PURE__*/ requireGuards$1();
  7435. Object.keys(_guards).forEach(function (key) {
  7436. if (key === "default" || key === "__esModule") return;
  7437. if (key in exports && exports[key] === _guards[key]) return;
  7438. exports[key] = _guards[key];
  7439. });
  7440. } (selectors$1));
  7441. return selectors$1;
  7442. }
  7443. var hasRequiredDist$1;
  7444. function requireDist$1 () {
  7445. if (hasRequiredDist$1) return dist$1.exports;
  7446. hasRequiredDist$1 = 1;
  7447. (function (module, exports) {
  7448. exports.__esModule = true;
  7449. exports["default"] = void 0;
  7450. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor$1());
  7451. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors$1());
  7452. 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); }
  7453. 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; }
  7454. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7455. var parser = function parser(processor) {
  7456. return new _processor["default"](processor);
  7457. };
  7458. Object.assign(parser, selectors);
  7459. delete parser.__esModule;
  7460. var _default = parser;
  7461. exports["default"] = _default;
  7462. module.exports = exports.default;
  7463. } (dist$1, dist$1.exports));
  7464. return dist$1.exports;
  7465. }
  7466. var distExports = /*@__PURE__*/ requireDist$1();
  7467. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7468. const animationNameRE = /^(-\w+-)?animation-name$/;
  7469. const animationRE = /^(-\w+-)?animation$/;
  7470. const scopedPlugin = (id = "") => {
  7471. const keyframes = /* @__PURE__ */ Object.create(null);
  7472. const shortId = id.replace(/^data-v-/, "");
  7473. return {
  7474. postcssPlugin: "vue-sfc-scoped",
  7475. Rule(rule) {
  7476. processRule(id, rule);
  7477. },
  7478. AtRule(node) {
  7479. if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7480. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7481. }
  7482. },
  7483. OnceExit(root) {
  7484. if (Object.keys(keyframes).length) {
  7485. root.walkDecls((decl) => {
  7486. if (animationNameRE.test(decl.prop)) {
  7487. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7488. }
  7489. if (animationRE.test(decl.prop)) {
  7490. decl.value = decl.value.split(",").map((v) => {
  7491. const vals = v.trim().split(/\s+/);
  7492. const i = vals.findIndex((val) => keyframes[val]);
  7493. if (i !== -1) {
  7494. vals.splice(i, 1, keyframes[vals[i]]);
  7495. return vals.join(" ");
  7496. } else {
  7497. return v;
  7498. }
  7499. }).join(",");
  7500. }
  7501. });
  7502. }
  7503. }
  7504. };
  7505. };
  7506. const processedRules = /* @__PURE__ */ new WeakSet();
  7507. function processRule(id, rule) {
  7508. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) {
  7509. return;
  7510. }
  7511. processedRules.add(rule);
  7512. let deep = false;
  7513. let parent = rule.parent;
  7514. while (parent && parent.type !== "root") {
  7515. if (parent.__deep) {
  7516. deep = true;
  7517. break;
  7518. }
  7519. parent = parent.parent;
  7520. }
  7521. rule.selector = selectorParser((selectorRoot) => {
  7522. selectorRoot.each((selector) => {
  7523. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7524. });
  7525. }).processSync(rule.selector);
  7526. }
  7527. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7528. let node = null;
  7529. let shouldInject = !deep;
  7530. selector.each((n) => {
  7531. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7532. n.value = " ";
  7533. n.spaces.before = n.spaces.after = "";
  7534. warn(
  7535. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7536. );
  7537. return false;
  7538. }
  7539. if (n.type === "pseudo") {
  7540. const { value } = n;
  7541. if (value === ":deep" || value === "::v-deep") {
  7542. rule.__deep = true;
  7543. if (n.nodes.length) {
  7544. let last = n;
  7545. n.nodes[0].each((ss) => {
  7546. selector.insertAfter(last, ss);
  7547. last = ss;
  7548. });
  7549. const prev = selector.at(selector.index(n) - 1);
  7550. if (!prev || !isSpaceCombinator(prev)) {
  7551. selector.insertAfter(
  7552. n,
  7553. selectorParser.combinator({
  7554. value: " "
  7555. })
  7556. );
  7557. }
  7558. selector.removeChild(n);
  7559. } else {
  7560. warn(
  7561. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7562. );
  7563. const prev = selector.at(selector.index(n) - 1);
  7564. if (prev && isSpaceCombinator(prev)) {
  7565. selector.removeChild(prev);
  7566. }
  7567. selector.removeChild(n);
  7568. }
  7569. return false;
  7570. }
  7571. if (value === ":slotted" || value === "::v-slotted") {
  7572. rewriteSelector(
  7573. id,
  7574. rule,
  7575. n.nodes[0],
  7576. selectorRoot,
  7577. deep,
  7578. true
  7579. );
  7580. let last = n;
  7581. n.nodes[0].each((ss) => {
  7582. selector.insertAfter(last, ss);
  7583. last = ss;
  7584. });
  7585. selector.removeChild(n);
  7586. shouldInject = false;
  7587. return false;
  7588. }
  7589. if (value === ":global" || value === "::v-global") {
  7590. selector.replaceWith(n.nodes[0]);
  7591. return false;
  7592. }
  7593. }
  7594. if (n.type === "universal") {
  7595. const prev = selector.at(selector.index(n) - 1);
  7596. const next = selector.at(selector.index(n) + 1);
  7597. if (!prev) {
  7598. if (next) {
  7599. if (next.type === "combinator" && next.value === " ") {
  7600. selector.removeChild(next);
  7601. }
  7602. selector.removeChild(n);
  7603. return;
  7604. } else {
  7605. node = selectorParser.combinator({
  7606. value: ""
  7607. });
  7608. selector.insertBefore(n, node);
  7609. selector.removeChild(n);
  7610. return false;
  7611. }
  7612. }
  7613. if (node) return;
  7614. }
  7615. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node) {
  7616. node = n;
  7617. }
  7618. });
  7619. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7620. const deep2 = rule.__deep;
  7621. if (!deep2) {
  7622. extractAndWrapNodes(rule);
  7623. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7624. for (const atnode of atruleNodes) {
  7625. extractAndWrapNodes(atnode);
  7626. }
  7627. }
  7628. shouldInject = deep2;
  7629. }
  7630. if (node) {
  7631. const { type, value } = node;
  7632. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7633. node.nodes.forEach(
  7634. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7635. );
  7636. shouldInject = false;
  7637. }
  7638. }
  7639. if (node) {
  7640. node.spaces.after = "";
  7641. } else {
  7642. selector.first.spaces.before = "";
  7643. }
  7644. if (shouldInject) {
  7645. const idToAdd = slotted ? id + "-s" : id;
  7646. selector.insertAfter(
  7647. // If node is null it means we need to inject [id] at the start
  7648. // insertAfter can handle `null` here
  7649. node,
  7650. selectorParser.attribute({
  7651. attribute: idToAdd,
  7652. value: idToAdd,
  7653. raws: {},
  7654. quoteMark: `"`
  7655. })
  7656. );
  7657. }
  7658. }
  7659. function isSpaceCombinator(node) {
  7660. return node.type === "combinator" && /^\s+$/.test(node.value);
  7661. }
  7662. function extractAndWrapNodes(parentNode) {
  7663. if (!parentNode.nodes) return;
  7664. const nodes = parentNode.nodes.filter(
  7665. (node) => node.type === "decl" || node.type === "comment"
  7666. );
  7667. if (nodes.length) {
  7668. for (const node of nodes) {
  7669. parentNode.removeChild(node);
  7670. }
  7671. const wrappedRule = new require$$0$1.Rule({
  7672. nodes,
  7673. selector: "&"
  7674. });
  7675. parentNode.prepend(wrappedRule);
  7676. }
  7677. }
  7678. scopedPlugin.postcss = true;
  7679. var sourceMap = {};
  7680. var sourceMapGenerator = {};
  7681. var base64Vlq = {};
  7682. var base64 = {};
  7683. /* -*- Mode: js; js-indent-level: 2; -*- */
  7684. var hasRequiredBase64;
  7685. function requireBase64 () {
  7686. if (hasRequiredBase64) return base64;
  7687. hasRequiredBase64 = 1;
  7688. /*
  7689. * Copyright 2011 Mozilla Foundation and contributors
  7690. * Licensed under the New BSD license. See LICENSE or:
  7691. * http://opensource.org/licenses/BSD-3-Clause
  7692. */
  7693. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7694. /**
  7695. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7696. */
  7697. base64.encode = function (number) {
  7698. if (0 <= number && number < intToCharMap.length) {
  7699. return intToCharMap[number];
  7700. }
  7701. throw new TypeError("Must be between 0 and 63: " + number);
  7702. };
  7703. /**
  7704. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7705. * failure.
  7706. */
  7707. base64.decode = function (charCode) {
  7708. var bigA = 65; // 'A'
  7709. var bigZ = 90; // 'Z'
  7710. var littleA = 97; // 'a'
  7711. var littleZ = 122; // 'z'
  7712. var zero = 48; // '0'
  7713. var nine = 57; // '9'
  7714. var plus = 43; // '+'
  7715. var slash = 47; // '/'
  7716. var littleOffset = 26;
  7717. var numberOffset = 52;
  7718. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7719. if (bigA <= charCode && charCode <= bigZ) {
  7720. return (charCode - bigA);
  7721. }
  7722. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7723. if (littleA <= charCode && charCode <= littleZ) {
  7724. return (charCode - littleA + littleOffset);
  7725. }
  7726. // 52 - 61: 0123456789
  7727. if (zero <= charCode && charCode <= nine) {
  7728. return (charCode - zero + numberOffset);
  7729. }
  7730. // 62: +
  7731. if (charCode == plus) {
  7732. return 62;
  7733. }
  7734. // 63: /
  7735. if (charCode == slash) {
  7736. return 63;
  7737. }
  7738. // Invalid base64 digit.
  7739. return -1;
  7740. };
  7741. return base64;
  7742. }
  7743. /* -*- Mode: js; js-indent-level: 2; -*- */
  7744. var hasRequiredBase64Vlq;
  7745. function requireBase64Vlq () {
  7746. if (hasRequiredBase64Vlq) return base64Vlq;
  7747. hasRequiredBase64Vlq = 1;
  7748. /*
  7749. * Copyright 2011 Mozilla Foundation and contributors
  7750. * Licensed under the New BSD license. See LICENSE or:
  7751. * http://opensource.org/licenses/BSD-3-Clause
  7752. *
  7753. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7754. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7755. *
  7756. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7757. * Redistribution and use in source and binary forms, with or without
  7758. * modification, are permitted provided that the following conditions are
  7759. * met:
  7760. *
  7761. * * Redistributions of source code must retain the above copyright
  7762. * notice, this list of conditions and the following disclaimer.
  7763. * * Redistributions in binary form must reproduce the above
  7764. * copyright notice, this list of conditions and the following
  7765. * disclaimer in the documentation and/or other materials provided
  7766. * with the distribution.
  7767. * * Neither the name of Google Inc. nor the names of its
  7768. * contributors may be used to endorse or promote products derived
  7769. * from this software without specific prior written permission.
  7770. *
  7771. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7772. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7773. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7774. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7775. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7776. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7777. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7778. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7779. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7780. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7781. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7782. */
  7783. var base64 = /*@__PURE__*/ requireBase64();
  7784. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7785. // length quantities we use in the source map spec, the first bit is the sign,
  7786. // the next four bits are the actual value, and the 6th bit is the
  7787. // continuation bit. The continuation bit tells us whether there are more
  7788. // digits in this value following this digit.
  7789. //
  7790. // Continuation
  7791. // | Sign
  7792. // | |
  7793. // V V
  7794. // 101011
  7795. var VLQ_BASE_SHIFT = 5;
  7796. // binary: 100000
  7797. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7798. // binary: 011111
  7799. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7800. // binary: 100000
  7801. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7802. /**
  7803. * Converts from a two-complement value to a value where the sign bit is
  7804. * placed in the least significant bit. For example, as decimals:
  7805. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7806. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7807. */
  7808. function toVLQSigned(aValue) {
  7809. return aValue < 0
  7810. ? ((-aValue) << 1) + 1
  7811. : (aValue << 1) + 0;
  7812. }
  7813. /**
  7814. * Converts to a two-complement value from a value where the sign bit is
  7815. * placed in the least significant bit. For example, as decimals:
  7816. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7817. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7818. */
  7819. function fromVLQSigned(aValue) {
  7820. var isNegative = (aValue & 1) === 1;
  7821. var shifted = aValue >> 1;
  7822. return isNegative
  7823. ? -shifted
  7824. : shifted;
  7825. }
  7826. /**
  7827. * Returns the base 64 VLQ encoded value.
  7828. */
  7829. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7830. var encoded = "";
  7831. var digit;
  7832. var vlq = toVLQSigned(aValue);
  7833. do {
  7834. digit = vlq & VLQ_BASE_MASK;
  7835. vlq >>>= VLQ_BASE_SHIFT;
  7836. if (vlq > 0) {
  7837. // There are still more digits in this value, so we must make sure the
  7838. // continuation bit is marked.
  7839. digit |= VLQ_CONTINUATION_BIT;
  7840. }
  7841. encoded += base64.encode(digit);
  7842. } while (vlq > 0);
  7843. return encoded;
  7844. };
  7845. /**
  7846. * Decodes the next base 64 VLQ value from the given string and returns the
  7847. * value and the rest of the string via the out parameter.
  7848. */
  7849. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7850. var strLen = aStr.length;
  7851. var result = 0;
  7852. var shift = 0;
  7853. var continuation, digit;
  7854. do {
  7855. if (aIndex >= strLen) {
  7856. throw new Error("Expected more digits in base 64 VLQ value.");
  7857. }
  7858. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7859. if (digit === -1) {
  7860. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7861. }
  7862. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7863. digit &= VLQ_BASE_MASK;
  7864. result = result + (digit << shift);
  7865. shift += VLQ_BASE_SHIFT;
  7866. } while (continuation);
  7867. aOutParam.value = fromVLQSigned(result);
  7868. aOutParam.rest = aIndex;
  7869. };
  7870. return base64Vlq;
  7871. }
  7872. var util$1 = {};
  7873. /* -*- Mode: js; js-indent-level: 2; -*- */
  7874. var hasRequiredUtil$1;
  7875. function requireUtil$1 () {
  7876. if (hasRequiredUtil$1) return util$1;
  7877. hasRequiredUtil$1 = 1;
  7878. (function (exports) {
  7879. /*
  7880. * Copyright 2011 Mozilla Foundation and contributors
  7881. * Licensed under the New BSD license. See LICENSE or:
  7882. * http://opensource.org/licenses/BSD-3-Clause
  7883. */
  7884. /**
  7885. * This is a helper function for getting values from parameter/options
  7886. * objects.
  7887. *
  7888. * @param args The object we are extracting values from
  7889. * @param name The name of the property we are getting.
  7890. * @param defaultValue An optional value to return if the property is missing
  7891. * from the object. If this is not specified and the property is missing, an
  7892. * error will be thrown.
  7893. */
  7894. function getArg(aArgs, aName, aDefaultValue) {
  7895. if (aName in aArgs) {
  7896. return aArgs[aName];
  7897. } else if (arguments.length === 3) {
  7898. return aDefaultValue;
  7899. } else {
  7900. throw new Error('"' + aName + '" is a required argument.');
  7901. }
  7902. }
  7903. exports.getArg = getArg;
  7904. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7905. var dataUrlRegexp = /^data:.+\,.+$/;
  7906. function urlParse(aUrl) {
  7907. var match = aUrl.match(urlRegexp);
  7908. if (!match) {
  7909. return null;
  7910. }
  7911. return {
  7912. scheme: match[1],
  7913. auth: match[2],
  7914. host: match[3],
  7915. port: match[4],
  7916. path: match[5]
  7917. };
  7918. }
  7919. exports.urlParse = urlParse;
  7920. function urlGenerate(aParsedUrl) {
  7921. var url = '';
  7922. if (aParsedUrl.scheme) {
  7923. url += aParsedUrl.scheme + ':';
  7924. }
  7925. url += '//';
  7926. if (aParsedUrl.auth) {
  7927. url += aParsedUrl.auth + '@';
  7928. }
  7929. if (aParsedUrl.host) {
  7930. url += aParsedUrl.host;
  7931. }
  7932. if (aParsedUrl.port) {
  7933. url += ":" + aParsedUrl.port;
  7934. }
  7935. if (aParsedUrl.path) {
  7936. url += aParsedUrl.path;
  7937. }
  7938. return url;
  7939. }
  7940. exports.urlGenerate = urlGenerate;
  7941. /**
  7942. * Normalizes a path, or the path portion of a URL:
  7943. *
  7944. * - Replaces consecutive slashes with one slash.
  7945. * - Removes unnecessary '.' parts.
  7946. * - Removes unnecessary '<dir>/..' parts.
  7947. *
  7948. * Based on code in the Node.js 'path' core module.
  7949. *
  7950. * @param aPath The path or url to normalize.
  7951. */
  7952. function normalize(aPath) {
  7953. var path = aPath;
  7954. var url = urlParse(aPath);
  7955. if (url) {
  7956. if (!url.path) {
  7957. return aPath;
  7958. }
  7959. path = url.path;
  7960. }
  7961. var isAbsolute = exports.isAbsolute(path);
  7962. var parts = path.split(/\/+/);
  7963. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7964. part = parts[i];
  7965. if (part === '.') {
  7966. parts.splice(i, 1);
  7967. } else if (part === '..') {
  7968. up++;
  7969. } else if (up > 0) {
  7970. if (part === '') {
  7971. // The first part is blank if the path is absolute. Trying to go
  7972. // above the root is a no-op. Therefore we can remove all '..' parts
  7973. // directly after the root.
  7974. parts.splice(i + 1, up);
  7975. up = 0;
  7976. } else {
  7977. parts.splice(i, 2);
  7978. up--;
  7979. }
  7980. }
  7981. }
  7982. path = parts.join('/');
  7983. if (path === '') {
  7984. path = isAbsolute ? '/' : '.';
  7985. }
  7986. if (url) {
  7987. url.path = path;
  7988. return urlGenerate(url);
  7989. }
  7990. return path;
  7991. }
  7992. exports.normalize = normalize;
  7993. /**
  7994. * Joins two paths/URLs.
  7995. *
  7996. * @param aRoot The root path or URL.
  7997. * @param aPath The path or URL to be joined with the root.
  7998. *
  7999. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  8000. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  8001. * first.
  8002. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  8003. * is updated with the result and aRoot is returned. Otherwise the result
  8004. * is returned.
  8005. * - If aPath is absolute, the result is aPath.
  8006. * - Otherwise the two paths are joined with a slash.
  8007. * - Joining for example 'http://' and 'www.example.com' is also supported.
  8008. */
  8009. function join(aRoot, aPath) {
  8010. if (aRoot === "") {
  8011. aRoot = ".";
  8012. }
  8013. if (aPath === "") {
  8014. aPath = ".";
  8015. }
  8016. var aPathUrl = urlParse(aPath);
  8017. var aRootUrl = urlParse(aRoot);
  8018. if (aRootUrl) {
  8019. aRoot = aRootUrl.path || '/';
  8020. }
  8021. // `join(foo, '//www.example.org')`
  8022. if (aPathUrl && !aPathUrl.scheme) {
  8023. if (aRootUrl) {
  8024. aPathUrl.scheme = aRootUrl.scheme;
  8025. }
  8026. return urlGenerate(aPathUrl);
  8027. }
  8028. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8029. return aPath;
  8030. }
  8031. // `join('http://', 'www.example.com')`
  8032. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8033. aRootUrl.host = aPath;
  8034. return urlGenerate(aRootUrl);
  8035. }
  8036. var joined = aPath.charAt(0) === '/'
  8037. ? aPath
  8038. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8039. if (aRootUrl) {
  8040. aRootUrl.path = joined;
  8041. return urlGenerate(aRootUrl);
  8042. }
  8043. return joined;
  8044. }
  8045. exports.join = join;
  8046. exports.isAbsolute = function (aPath) {
  8047. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8048. };
  8049. /**
  8050. * Make a path relative to a URL or another path.
  8051. *
  8052. * @param aRoot The root path or URL.
  8053. * @param aPath The path or URL to be made relative to aRoot.
  8054. */
  8055. function relative(aRoot, aPath) {
  8056. if (aRoot === "") {
  8057. aRoot = ".";
  8058. }
  8059. aRoot = aRoot.replace(/\/$/, '');
  8060. // It is possible for the path to be above the root. In this case, simply
  8061. // checking whether the root is a prefix of the path won't work. Instead, we
  8062. // need to remove components from the root one by one, until either we find
  8063. // a prefix that fits, or we run out of components to remove.
  8064. var level = 0;
  8065. while (aPath.indexOf(aRoot + '/') !== 0) {
  8066. var index = aRoot.lastIndexOf("/");
  8067. if (index < 0) {
  8068. return aPath;
  8069. }
  8070. // If the only part of the root that is left is the scheme (i.e. http://,
  8071. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8072. // have exhausted all components, so the path is not relative to the root.
  8073. aRoot = aRoot.slice(0, index);
  8074. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8075. return aPath;
  8076. }
  8077. ++level;
  8078. }
  8079. // Make sure we add a "../" for each component we removed from the root.
  8080. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8081. }
  8082. exports.relative = relative;
  8083. var supportsNullProto = (function () {
  8084. var obj = Object.create(null);
  8085. return !('__proto__' in obj);
  8086. }());
  8087. function identity (s) {
  8088. return s;
  8089. }
  8090. /**
  8091. * Because behavior goes wacky when you set `__proto__` on objects, we
  8092. * have to prefix all the strings in our set with an arbitrary character.
  8093. *
  8094. * See https://github.com/mozilla/source-map/pull/31 and
  8095. * https://github.com/mozilla/source-map/issues/30
  8096. *
  8097. * @param String aStr
  8098. */
  8099. function toSetString(aStr) {
  8100. if (isProtoString(aStr)) {
  8101. return '$' + aStr;
  8102. }
  8103. return aStr;
  8104. }
  8105. exports.toSetString = supportsNullProto ? identity : toSetString;
  8106. function fromSetString(aStr) {
  8107. if (isProtoString(aStr)) {
  8108. return aStr.slice(1);
  8109. }
  8110. return aStr;
  8111. }
  8112. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  8113. function isProtoString(s) {
  8114. if (!s) {
  8115. return false;
  8116. }
  8117. var length = s.length;
  8118. if (length < 9 /* "__proto__".length */) {
  8119. return false;
  8120. }
  8121. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8122. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8123. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8124. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8125. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8126. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8127. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8128. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8129. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8130. return false;
  8131. }
  8132. for (var i = length - 10; i >= 0; i--) {
  8133. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8134. return false;
  8135. }
  8136. }
  8137. return true;
  8138. }
  8139. /**
  8140. * Comparator between two mappings where the original positions are compared.
  8141. *
  8142. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8143. * mappings with the same original source/line/column, but different generated
  8144. * line and column the same. Useful when searching for a mapping with a
  8145. * stubbed out mapping.
  8146. */
  8147. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8148. var cmp = strcmp(mappingA.source, mappingB.source);
  8149. if (cmp !== 0) {
  8150. return cmp;
  8151. }
  8152. cmp = mappingA.originalLine - mappingB.originalLine;
  8153. if (cmp !== 0) {
  8154. return cmp;
  8155. }
  8156. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8157. if (cmp !== 0 || onlyCompareOriginal) {
  8158. return cmp;
  8159. }
  8160. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8161. if (cmp !== 0) {
  8162. return cmp;
  8163. }
  8164. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8165. if (cmp !== 0) {
  8166. return cmp;
  8167. }
  8168. return strcmp(mappingA.name, mappingB.name);
  8169. }
  8170. exports.compareByOriginalPositions = compareByOriginalPositions;
  8171. /**
  8172. * Comparator between two mappings with deflated source and name indices where
  8173. * the generated positions are compared.
  8174. *
  8175. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8176. * mappings with the same generated line and column, but different
  8177. * source/name/original line and column the same. Useful when searching for a
  8178. * mapping with a stubbed out mapping.
  8179. */
  8180. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8181. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8182. if (cmp !== 0) {
  8183. return cmp;
  8184. }
  8185. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8186. if (cmp !== 0 || onlyCompareGenerated) {
  8187. return cmp;
  8188. }
  8189. cmp = strcmp(mappingA.source, mappingB.source);
  8190. if (cmp !== 0) {
  8191. return cmp;
  8192. }
  8193. cmp = mappingA.originalLine - mappingB.originalLine;
  8194. if (cmp !== 0) {
  8195. return cmp;
  8196. }
  8197. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8198. if (cmp !== 0) {
  8199. return cmp;
  8200. }
  8201. return strcmp(mappingA.name, mappingB.name);
  8202. }
  8203. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8204. function strcmp(aStr1, aStr2) {
  8205. if (aStr1 === aStr2) {
  8206. return 0;
  8207. }
  8208. if (aStr1 === null) {
  8209. return 1; // aStr2 !== null
  8210. }
  8211. if (aStr2 === null) {
  8212. return -1; // aStr1 !== null
  8213. }
  8214. if (aStr1 > aStr2) {
  8215. return 1;
  8216. }
  8217. return -1;
  8218. }
  8219. /**
  8220. * Comparator between two mappings with inflated source and name strings where
  8221. * the generated positions are compared.
  8222. */
  8223. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8224. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8225. if (cmp !== 0) {
  8226. return cmp;
  8227. }
  8228. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8229. if (cmp !== 0) {
  8230. return cmp;
  8231. }
  8232. cmp = strcmp(mappingA.source, mappingB.source);
  8233. if (cmp !== 0) {
  8234. return cmp;
  8235. }
  8236. cmp = mappingA.originalLine - mappingB.originalLine;
  8237. if (cmp !== 0) {
  8238. return cmp;
  8239. }
  8240. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8241. if (cmp !== 0) {
  8242. return cmp;
  8243. }
  8244. return strcmp(mappingA.name, mappingB.name);
  8245. }
  8246. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8247. /**
  8248. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8249. * in the source maps specification), and then parse the string as
  8250. * JSON.
  8251. */
  8252. function parseSourceMapInput(str) {
  8253. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8254. }
  8255. exports.parseSourceMapInput = parseSourceMapInput;
  8256. /**
  8257. * Compute the URL of a source given the the source root, the source's
  8258. * URL, and the source map's URL.
  8259. */
  8260. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8261. sourceURL = sourceURL || '';
  8262. if (sourceRoot) {
  8263. // This follows what Chrome does.
  8264. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8265. sourceRoot += '/';
  8266. }
  8267. // The spec says:
  8268. // Line 4: An optional source root, useful for relocating source
  8269. // files on a server or removing repeated values in the
  8270. // “sources” entry. This value is prepended to the individual
  8271. // entries in the “source” field.
  8272. sourceURL = sourceRoot + sourceURL;
  8273. }
  8274. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8275. // a parameter. This mode is still somewhat supported, which is why
  8276. // this code block is conditional. However, it's preferable to pass
  8277. // the source map URL to SourceMapConsumer, so that this function
  8278. // can implement the source URL resolution algorithm as outlined in
  8279. // the spec. This block is basically the equivalent of:
  8280. // new URL(sourceURL, sourceMapURL).toString()
  8281. // ... except it avoids using URL, which wasn't available in the
  8282. // older releases of node still supported by this library.
  8283. //
  8284. // The spec says:
  8285. // If the sources are not absolute URLs after prepending of the
  8286. // “sourceRoot”, the sources are resolved relative to the
  8287. // SourceMap (like resolving script src in a html document).
  8288. if (sourceMapURL) {
  8289. var parsed = urlParse(sourceMapURL);
  8290. if (!parsed) {
  8291. throw new Error("sourceMapURL could not be parsed");
  8292. }
  8293. if (parsed.path) {
  8294. // Strip the last path component, but keep the "/".
  8295. var index = parsed.path.lastIndexOf('/');
  8296. if (index >= 0) {
  8297. parsed.path = parsed.path.substring(0, index + 1);
  8298. }
  8299. }
  8300. sourceURL = join(urlGenerate(parsed), sourceURL);
  8301. }
  8302. return normalize(sourceURL);
  8303. }
  8304. exports.computeSourceURL = computeSourceURL;
  8305. } (util$1));
  8306. return util$1;
  8307. }
  8308. var arraySet = {};
  8309. /* -*- Mode: js; js-indent-level: 2; -*- */
  8310. var hasRequiredArraySet;
  8311. function requireArraySet () {
  8312. if (hasRequiredArraySet) return arraySet;
  8313. hasRequiredArraySet = 1;
  8314. /*
  8315. * Copyright 2011 Mozilla Foundation and contributors
  8316. * Licensed under the New BSD license. See LICENSE or:
  8317. * http://opensource.org/licenses/BSD-3-Clause
  8318. */
  8319. var util = /*@__PURE__*/ requireUtil$1();
  8320. var has = Object.prototype.hasOwnProperty;
  8321. var hasNativeMap = typeof Map !== "undefined";
  8322. /**
  8323. * A data structure which is a combination of an array and a set. Adding a new
  8324. * member is O(1), testing for membership is O(1), and finding the index of an
  8325. * element is O(1). Removing elements from the set is not supported. Only
  8326. * strings are supported for membership.
  8327. */
  8328. function ArraySet() {
  8329. this._array = [];
  8330. this._set = hasNativeMap ? new Map() : Object.create(null);
  8331. }
  8332. /**
  8333. * Static method for creating ArraySet instances from an existing array.
  8334. */
  8335. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8336. var set = new ArraySet();
  8337. for (var i = 0, len = aArray.length; i < len; i++) {
  8338. set.add(aArray[i], aAllowDuplicates);
  8339. }
  8340. return set;
  8341. };
  8342. /**
  8343. * Return how many unique items are in this ArraySet. If duplicates have been
  8344. * added, than those do not count towards the size.
  8345. *
  8346. * @returns Number
  8347. */
  8348. ArraySet.prototype.size = function ArraySet_size() {
  8349. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8350. };
  8351. /**
  8352. * Add the given string to this set.
  8353. *
  8354. * @param String aStr
  8355. */
  8356. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8357. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8358. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8359. var idx = this._array.length;
  8360. if (!isDuplicate || aAllowDuplicates) {
  8361. this._array.push(aStr);
  8362. }
  8363. if (!isDuplicate) {
  8364. if (hasNativeMap) {
  8365. this._set.set(aStr, idx);
  8366. } else {
  8367. this._set[sStr] = idx;
  8368. }
  8369. }
  8370. };
  8371. /**
  8372. * Is the given string a member of this set?
  8373. *
  8374. * @param String aStr
  8375. */
  8376. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8377. if (hasNativeMap) {
  8378. return this._set.has(aStr);
  8379. } else {
  8380. var sStr = util.toSetString(aStr);
  8381. return has.call(this._set, sStr);
  8382. }
  8383. };
  8384. /**
  8385. * What is the index of the given string in the array?
  8386. *
  8387. * @param String aStr
  8388. */
  8389. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8390. if (hasNativeMap) {
  8391. var idx = this._set.get(aStr);
  8392. if (idx >= 0) {
  8393. return idx;
  8394. }
  8395. } else {
  8396. var sStr = util.toSetString(aStr);
  8397. if (has.call(this._set, sStr)) {
  8398. return this._set[sStr];
  8399. }
  8400. }
  8401. throw new Error('"' + aStr + '" is not in the set.');
  8402. };
  8403. /**
  8404. * What is the element at the given index?
  8405. *
  8406. * @param Number aIdx
  8407. */
  8408. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8409. if (aIdx >= 0 && aIdx < this._array.length) {
  8410. return this._array[aIdx];
  8411. }
  8412. throw new Error('No element indexed by ' + aIdx);
  8413. };
  8414. /**
  8415. * Returns the array representation of this set (which has the proper indices
  8416. * indicated by indexOf). Note that this is a copy of the internal array used
  8417. * for storing the members so that no one can mess with internal state.
  8418. */
  8419. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8420. return this._array.slice();
  8421. };
  8422. arraySet.ArraySet = ArraySet;
  8423. return arraySet;
  8424. }
  8425. var mappingList = {};
  8426. /* -*- Mode: js; js-indent-level: 2; -*- */
  8427. var hasRequiredMappingList;
  8428. function requireMappingList () {
  8429. if (hasRequiredMappingList) return mappingList;
  8430. hasRequiredMappingList = 1;
  8431. /*
  8432. * Copyright 2014 Mozilla Foundation and contributors
  8433. * Licensed under the New BSD license. See LICENSE or:
  8434. * http://opensource.org/licenses/BSD-3-Clause
  8435. */
  8436. var util = /*@__PURE__*/ requireUtil$1();
  8437. /**
  8438. * Determine whether mappingB is after mappingA with respect to generated
  8439. * position.
  8440. */
  8441. function generatedPositionAfter(mappingA, mappingB) {
  8442. // Optimized for most common case
  8443. var lineA = mappingA.generatedLine;
  8444. var lineB = mappingB.generatedLine;
  8445. var columnA = mappingA.generatedColumn;
  8446. var columnB = mappingB.generatedColumn;
  8447. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8448. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8449. }
  8450. /**
  8451. * A data structure to provide a sorted view of accumulated mappings in a
  8452. * performance conscious manner. It trades a neglibable overhead in general
  8453. * case for a large speedup in case of mappings being added in order.
  8454. */
  8455. function MappingList() {
  8456. this._array = [];
  8457. this._sorted = true;
  8458. // Serves as infimum
  8459. this._last = {generatedLine: -1, generatedColumn: 0};
  8460. }
  8461. /**
  8462. * Iterate through internal items. This method takes the same arguments that
  8463. * `Array.prototype.forEach` takes.
  8464. *
  8465. * NOTE: The order of the mappings is NOT guaranteed.
  8466. */
  8467. MappingList.prototype.unsortedForEach =
  8468. function MappingList_forEach(aCallback, aThisArg) {
  8469. this._array.forEach(aCallback, aThisArg);
  8470. };
  8471. /**
  8472. * Add the given source mapping.
  8473. *
  8474. * @param Object aMapping
  8475. */
  8476. MappingList.prototype.add = function MappingList_add(aMapping) {
  8477. if (generatedPositionAfter(this._last, aMapping)) {
  8478. this._last = aMapping;
  8479. this._array.push(aMapping);
  8480. } else {
  8481. this._sorted = false;
  8482. this._array.push(aMapping);
  8483. }
  8484. };
  8485. /**
  8486. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8487. * generated position.
  8488. *
  8489. * WARNING: This method returns internal data without copying, for
  8490. * performance. The return value must NOT be mutated, and should be treated as
  8491. * an immutable borrow. If you want to take ownership, you must make your own
  8492. * copy.
  8493. */
  8494. MappingList.prototype.toArray = function MappingList_toArray() {
  8495. if (!this._sorted) {
  8496. this._array.sort(util.compareByGeneratedPositionsInflated);
  8497. this._sorted = true;
  8498. }
  8499. return this._array;
  8500. };
  8501. mappingList.MappingList = MappingList;
  8502. return mappingList;
  8503. }
  8504. /* -*- Mode: js; js-indent-level: 2; -*- */
  8505. var hasRequiredSourceMapGenerator;
  8506. function requireSourceMapGenerator () {
  8507. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8508. hasRequiredSourceMapGenerator = 1;
  8509. /*
  8510. * Copyright 2011 Mozilla Foundation and contributors
  8511. * Licensed under the New BSD license. See LICENSE or:
  8512. * http://opensource.org/licenses/BSD-3-Clause
  8513. */
  8514. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8515. var util = /*@__PURE__*/ requireUtil$1();
  8516. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8517. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8518. /**
  8519. * An instance of the SourceMapGenerator represents a source map which is
  8520. * being built incrementally. You may pass an object with the following
  8521. * properties:
  8522. *
  8523. * - file: The filename of the generated source.
  8524. * - sourceRoot: A root for all relative URLs in this source map.
  8525. */
  8526. function SourceMapGenerator(aArgs) {
  8527. if (!aArgs) {
  8528. aArgs = {};
  8529. }
  8530. this._file = util.getArg(aArgs, 'file', null);
  8531. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8532. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8533. this._sources = new ArraySet();
  8534. this._names = new ArraySet();
  8535. this._mappings = new MappingList();
  8536. this._sourcesContents = null;
  8537. }
  8538. SourceMapGenerator.prototype._version = 3;
  8539. /**
  8540. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8541. *
  8542. * @param aSourceMapConsumer The SourceMap.
  8543. */
  8544. SourceMapGenerator.fromSourceMap =
  8545. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8546. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8547. var generator = new SourceMapGenerator({
  8548. file: aSourceMapConsumer.file,
  8549. sourceRoot: sourceRoot
  8550. });
  8551. aSourceMapConsumer.eachMapping(function (mapping) {
  8552. var newMapping = {
  8553. generated: {
  8554. line: mapping.generatedLine,
  8555. column: mapping.generatedColumn
  8556. }
  8557. };
  8558. if (mapping.source != null) {
  8559. newMapping.source = mapping.source;
  8560. if (sourceRoot != null) {
  8561. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8562. }
  8563. newMapping.original = {
  8564. line: mapping.originalLine,
  8565. column: mapping.originalColumn
  8566. };
  8567. if (mapping.name != null) {
  8568. newMapping.name = mapping.name;
  8569. }
  8570. }
  8571. generator.addMapping(newMapping);
  8572. });
  8573. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8574. var sourceRelative = sourceFile;
  8575. if (sourceRoot !== null) {
  8576. sourceRelative = util.relative(sourceRoot, sourceFile);
  8577. }
  8578. if (!generator._sources.has(sourceRelative)) {
  8579. generator._sources.add(sourceRelative);
  8580. }
  8581. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8582. if (content != null) {
  8583. generator.setSourceContent(sourceFile, content);
  8584. }
  8585. });
  8586. return generator;
  8587. };
  8588. /**
  8589. * Add a single mapping from original source line and column to the generated
  8590. * source's line and column for this source map being created. The mapping
  8591. * object should have the following properties:
  8592. *
  8593. * - generated: An object with the generated line and column positions.
  8594. * - original: An object with the original line and column positions.
  8595. * - source: The original source file (relative to the sourceRoot).
  8596. * - name: An optional original token name for this mapping.
  8597. */
  8598. SourceMapGenerator.prototype.addMapping =
  8599. function SourceMapGenerator_addMapping(aArgs) {
  8600. var generated = util.getArg(aArgs, 'generated');
  8601. var original = util.getArg(aArgs, 'original', null);
  8602. var source = util.getArg(aArgs, 'source', null);
  8603. var name = util.getArg(aArgs, 'name', null);
  8604. if (!this._skipValidation) {
  8605. this._validateMapping(generated, original, source, name);
  8606. }
  8607. if (source != null) {
  8608. source = String(source);
  8609. if (!this._sources.has(source)) {
  8610. this._sources.add(source);
  8611. }
  8612. }
  8613. if (name != null) {
  8614. name = String(name);
  8615. if (!this._names.has(name)) {
  8616. this._names.add(name);
  8617. }
  8618. }
  8619. this._mappings.add({
  8620. generatedLine: generated.line,
  8621. generatedColumn: generated.column,
  8622. originalLine: original != null && original.line,
  8623. originalColumn: original != null && original.column,
  8624. source: source,
  8625. name: name
  8626. });
  8627. };
  8628. /**
  8629. * Set the source content for a source file.
  8630. */
  8631. SourceMapGenerator.prototype.setSourceContent =
  8632. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8633. var source = aSourceFile;
  8634. if (this._sourceRoot != null) {
  8635. source = util.relative(this._sourceRoot, source);
  8636. }
  8637. if (aSourceContent != null) {
  8638. // Add the source content to the _sourcesContents map.
  8639. // Create a new _sourcesContents map if the property is null.
  8640. if (!this._sourcesContents) {
  8641. this._sourcesContents = Object.create(null);
  8642. }
  8643. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8644. } else if (this._sourcesContents) {
  8645. // Remove the source file from the _sourcesContents map.
  8646. // If the _sourcesContents map is empty, set the property to null.
  8647. delete this._sourcesContents[util.toSetString(source)];
  8648. if (Object.keys(this._sourcesContents).length === 0) {
  8649. this._sourcesContents = null;
  8650. }
  8651. }
  8652. };
  8653. /**
  8654. * Applies the mappings of a sub-source-map for a specific source file to the
  8655. * source map being generated. Each mapping to the supplied source file is
  8656. * rewritten using the supplied source map. Note: The resolution for the
  8657. * resulting mappings is the minimium of this map and the supplied map.
  8658. *
  8659. * @param aSourceMapConsumer The source map to be applied.
  8660. * @param aSourceFile Optional. The filename of the source file.
  8661. * If omitted, SourceMapConsumer's file property will be used.
  8662. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8663. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8664. * This parameter is needed when the two source maps aren't in the same
  8665. * directory, and the source map to be applied contains relative source
  8666. * paths. If so, those relative source paths need to be rewritten
  8667. * relative to the SourceMapGenerator.
  8668. */
  8669. SourceMapGenerator.prototype.applySourceMap =
  8670. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8671. var sourceFile = aSourceFile;
  8672. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8673. if (aSourceFile == null) {
  8674. if (aSourceMapConsumer.file == null) {
  8675. throw new Error(
  8676. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8677. 'or the source map\'s "file" property. Both were omitted.'
  8678. );
  8679. }
  8680. sourceFile = aSourceMapConsumer.file;
  8681. }
  8682. var sourceRoot = this._sourceRoot;
  8683. // Make "sourceFile" relative if an absolute Url is passed.
  8684. if (sourceRoot != null) {
  8685. sourceFile = util.relative(sourceRoot, sourceFile);
  8686. }
  8687. // Applying the SourceMap can add and remove items from the sources and
  8688. // the names array.
  8689. var newSources = new ArraySet();
  8690. var newNames = new ArraySet();
  8691. // Find mappings for the "sourceFile"
  8692. this._mappings.unsortedForEach(function (mapping) {
  8693. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8694. // Check if it can be mapped by the source map, then update the mapping.
  8695. var original = aSourceMapConsumer.originalPositionFor({
  8696. line: mapping.originalLine,
  8697. column: mapping.originalColumn
  8698. });
  8699. if (original.source != null) {
  8700. // Copy mapping
  8701. mapping.source = original.source;
  8702. if (aSourceMapPath != null) {
  8703. mapping.source = util.join(aSourceMapPath, mapping.source);
  8704. }
  8705. if (sourceRoot != null) {
  8706. mapping.source = util.relative(sourceRoot, mapping.source);
  8707. }
  8708. mapping.originalLine = original.line;
  8709. mapping.originalColumn = original.column;
  8710. if (original.name != null) {
  8711. mapping.name = original.name;
  8712. }
  8713. }
  8714. }
  8715. var source = mapping.source;
  8716. if (source != null && !newSources.has(source)) {
  8717. newSources.add(source);
  8718. }
  8719. var name = mapping.name;
  8720. if (name != null && !newNames.has(name)) {
  8721. newNames.add(name);
  8722. }
  8723. }, this);
  8724. this._sources = newSources;
  8725. this._names = newNames;
  8726. // Copy sourcesContents of applied map.
  8727. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8728. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8729. if (content != null) {
  8730. if (aSourceMapPath != null) {
  8731. sourceFile = util.join(aSourceMapPath, sourceFile);
  8732. }
  8733. if (sourceRoot != null) {
  8734. sourceFile = util.relative(sourceRoot, sourceFile);
  8735. }
  8736. this.setSourceContent(sourceFile, content);
  8737. }
  8738. }, this);
  8739. };
  8740. /**
  8741. * A mapping can have one of the three levels of data:
  8742. *
  8743. * 1. Just the generated position.
  8744. * 2. The Generated position, original position, and original source.
  8745. * 3. Generated and original position, original source, as well as a name
  8746. * token.
  8747. *
  8748. * To maintain consistency, we validate that any new mapping being added falls
  8749. * in to one of these categories.
  8750. */
  8751. SourceMapGenerator.prototype._validateMapping =
  8752. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8753. aName) {
  8754. // When aOriginal is truthy but has empty values for .line and .column,
  8755. // it is most likely a programmer error. In this case we throw a very
  8756. // specific error message to try to guide them the right way.
  8757. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8758. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8759. throw new Error(
  8760. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8761. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8762. 'null for the original mapping instead of an object with empty or null values.'
  8763. );
  8764. }
  8765. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8766. && aGenerated.line > 0 && aGenerated.column >= 0
  8767. && !aOriginal && !aSource && !aName) {
  8768. // Case 1.
  8769. return;
  8770. }
  8771. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8772. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8773. && aGenerated.line > 0 && aGenerated.column >= 0
  8774. && aOriginal.line > 0 && aOriginal.column >= 0
  8775. && aSource) {
  8776. // Cases 2 and 3.
  8777. return;
  8778. }
  8779. else {
  8780. throw new Error('Invalid mapping: ' + JSON.stringify({
  8781. generated: aGenerated,
  8782. source: aSource,
  8783. original: aOriginal,
  8784. name: aName
  8785. }));
  8786. }
  8787. };
  8788. /**
  8789. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8790. * specified by the source map format.
  8791. */
  8792. SourceMapGenerator.prototype._serializeMappings =
  8793. function SourceMapGenerator_serializeMappings() {
  8794. var previousGeneratedColumn = 0;
  8795. var previousGeneratedLine = 1;
  8796. var previousOriginalColumn = 0;
  8797. var previousOriginalLine = 0;
  8798. var previousName = 0;
  8799. var previousSource = 0;
  8800. var result = '';
  8801. var next;
  8802. var mapping;
  8803. var nameIdx;
  8804. var sourceIdx;
  8805. var mappings = this._mappings.toArray();
  8806. for (var i = 0, len = mappings.length; i < len; i++) {
  8807. mapping = mappings[i];
  8808. next = '';
  8809. if (mapping.generatedLine !== previousGeneratedLine) {
  8810. previousGeneratedColumn = 0;
  8811. while (mapping.generatedLine !== previousGeneratedLine) {
  8812. next += ';';
  8813. previousGeneratedLine++;
  8814. }
  8815. }
  8816. else {
  8817. if (i > 0) {
  8818. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8819. continue;
  8820. }
  8821. next += ',';
  8822. }
  8823. }
  8824. next += base64VLQ.encode(mapping.generatedColumn
  8825. - previousGeneratedColumn);
  8826. previousGeneratedColumn = mapping.generatedColumn;
  8827. if (mapping.source != null) {
  8828. sourceIdx = this._sources.indexOf(mapping.source);
  8829. next += base64VLQ.encode(sourceIdx - previousSource);
  8830. previousSource = sourceIdx;
  8831. // lines are stored 0-based in SourceMap spec version 3
  8832. next += base64VLQ.encode(mapping.originalLine - 1
  8833. - previousOriginalLine);
  8834. previousOriginalLine = mapping.originalLine - 1;
  8835. next += base64VLQ.encode(mapping.originalColumn
  8836. - previousOriginalColumn);
  8837. previousOriginalColumn = mapping.originalColumn;
  8838. if (mapping.name != null) {
  8839. nameIdx = this._names.indexOf(mapping.name);
  8840. next += base64VLQ.encode(nameIdx - previousName);
  8841. previousName = nameIdx;
  8842. }
  8843. }
  8844. result += next;
  8845. }
  8846. return result;
  8847. };
  8848. SourceMapGenerator.prototype._generateSourcesContent =
  8849. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8850. return aSources.map(function (source) {
  8851. if (!this._sourcesContents) {
  8852. return null;
  8853. }
  8854. if (aSourceRoot != null) {
  8855. source = util.relative(aSourceRoot, source);
  8856. }
  8857. var key = util.toSetString(source);
  8858. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8859. ? this._sourcesContents[key]
  8860. : null;
  8861. }, this);
  8862. };
  8863. /**
  8864. * Externalize the source map.
  8865. */
  8866. SourceMapGenerator.prototype.toJSON =
  8867. function SourceMapGenerator_toJSON() {
  8868. var map = {
  8869. version: this._version,
  8870. sources: this._sources.toArray(),
  8871. names: this._names.toArray(),
  8872. mappings: this._serializeMappings()
  8873. };
  8874. if (this._file != null) {
  8875. map.file = this._file;
  8876. }
  8877. if (this._sourceRoot != null) {
  8878. map.sourceRoot = this._sourceRoot;
  8879. }
  8880. if (this._sourcesContents) {
  8881. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8882. }
  8883. return map;
  8884. };
  8885. /**
  8886. * Render the source map being generated to a string.
  8887. */
  8888. SourceMapGenerator.prototype.toString =
  8889. function SourceMapGenerator_toString() {
  8890. return JSON.stringify(this.toJSON());
  8891. };
  8892. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  8893. return sourceMapGenerator;
  8894. }
  8895. var sourceMapConsumer = {};
  8896. var binarySearch = {};
  8897. /* -*- Mode: js; js-indent-level: 2; -*- */
  8898. var hasRequiredBinarySearch;
  8899. function requireBinarySearch () {
  8900. if (hasRequiredBinarySearch) return binarySearch;
  8901. hasRequiredBinarySearch = 1;
  8902. (function (exports) {
  8903. /*
  8904. * Copyright 2011 Mozilla Foundation and contributors
  8905. * Licensed under the New BSD license. See LICENSE or:
  8906. * http://opensource.org/licenses/BSD-3-Clause
  8907. */
  8908. exports.GREATEST_LOWER_BOUND = 1;
  8909. exports.LEAST_UPPER_BOUND = 2;
  8910. /**
  8911. * Recursive implementation of binary search.
  8912. *
  8913. * @param aLow Indices here and lower do not contain the needle.
  8914. * @param aHigh Indices here and higher do not contain the needle.
  8915. * @param aNeedle The element being searched for.
  8916. * @param aHaystack The non-empty array being searched.
  8917. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8918. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8919. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8920. * closest element that is smaller than or greater than the one we are
  8921. * searching for, respectively, if the exact element cannot be found.
  8922. */
  8923. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8924. // This function terminates when one of the following is true:
  8925. //
  8926. // 1. We find the exact element we are looking for.
  8927. //
  8928. // 2. We did not find the exact element, but we can return the index of
  8929. // the next-closest element.
  8930. //
  8931. // 3. We did not find the exact element, and there is no next-closest
  8932. // element than the one we are searching for, so we return -1.
  8933. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  8934. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  8935. if (cmp === 0) {
  8936. // Found the element we are looking for.
  8937. return mid;
  8938. }
  8939. else if (cmp > 0) {
  8940. // Our needle is greater than aHaystack[mid].
  8941. if (aHigh - mid > 1) {
  8942. // The element is in the upper half.
  8943. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  8944. }
  8945. // The exact needle element was not found in this haystack. Determine if
  8946. // we are in termination case (3) or (2) and return the appropriate thing.
  8947. if (aBias == exports.LEAST_UPPER_BOUND) {
  8948. return aHigh < aHaystack.length ? aHigh : -1;
  8949. } else {
  8950. return mid;
  8951. }
  8952. }
  8953. else {
  8954. // Our needle is less than aHaystack[mid].
  8955. if (mid - aLow > 1) {
  8956. // The element is in the lower half.
  8957. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  8958. }
  8959. // we are in termination case (3) or (2) and return the appropriate thing.
  8960. if (aBias == exports.LEAST_UPPER_BOUND) {
  8961. return mid;
  8962. } else {
  8963. return aLow < 0 ? -1 : aLow;
  8964. }
  8965. }
  8966. }
  8967. /**
  8968. * This is an implementation of binary search which will always try and return
  8969. * the index of the closest element if there is no exact hit. This is because
  8970. * mappings between original and generated line/col pairs are single points,
  8971. * and there is an implicit region between each of them, so a miss just means
  8972. * that you aren't on the very start of a region.
  8973. *
  8974. * @param aNeedle The element you are looking for.
  8975. * @param aHaystack The array that is being searched.
  8976. * @param aCompare A function which takes the needle and an element in the
  8977. * array and returns -1, 0, or 1 depending on whether the needle is less
  8978. * than, equal to, or greater than the element, respectively.
  8979. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8980. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8981. * closest element that is smaller than or greater than the one we are
  8982. * searching for, respectively, if the exact element cannot be found.
  8983. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  8984. */
  8985. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  8986. if (aHaystack.length === 0) {
  8987. return -1;
  8988. }
  8989. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  8990. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  8991. if (index < 0) {
  8992. return -1;
  8993. }
  8994. // We have found either the exact element, or the next-closest element than
  8995. // the one we are searching for. However, there may be more than one such
  8996. // element. Make sure we always return the smallest of these.
  8997. while (index - 1 >= 0) {
  8998. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  8999. break;
  9000. }
  9001. --index;
  9002. }
  9003. return index;
  9004. };
  9005. } (binarySearch));
  9006. return binarySearch;
  9007. }
  9008. var quickSort = {};
  9009. /* -*- Mode: js; js-indent-level: 2; -*- */
  9010. var hasRequiredQuickSort;
  9011. function requireQuickSort () {
  9012. if (hasRequiredQuickSort) return quickSort;
  9013. hasRequiredQuickSort = 1;
  9014. /*
  9015. * Copyright 2011 Mozilla Foundation and contributors
  9016. * Licensed under the New BSD license. See LICENSE or:
  9017. * http://opensource.org/licenses/BSD-3-Clause
  9018. */
  9019. // It turns out that some (most?) JavaScript engines don't self-host
  9020. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9021. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9022. // custom comparator function, calling back and forth between the VM's C++ and
  9023. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9024. // worse generated code for the comparator function than would be optimal. In
  9025. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9026. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9027. // a ~3500ms mean speed-up in `bench/bench.html`.
  9028. /**
  9029. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9030. *
  9031. * @param {Array} ary
  9032. * The array.
  9033. * @param {Number} x
  9034. * The index of the first item.
  9035. * @param {Number} y
  9036. * The index of the second item.
  9037. */
  9038. function swap(ary, x, y) {
  9039. var temp = ary[x];
  9040. ary[x] = ary[y];
  9041. ary[y] = temp;
  9042. }
  9043. /**
  9044. * Returns a random integer within the range `low .. high` inclusive.
  9045. *
  9046. * @param {Number} low
  9047. * The lower bound on the range.
  9048. * @param {Number} high
  9049. * The upper bound on the range.
  9050. */
  9051. function randomIntInRange(low, high) {
  9052. return Math.round(low + (Math.random() * (high - low)));
  9053. }
  9054. /**
  9055. * The Quick Sort algorithm.
  9056. *
  9057. * @param {Array} ary
  9058. * An array to sort.
  9059. * @param {function} comparator
  9060. * Function to use to compare two items.
  9061. * @param {Number} p
  9062. * Start index of the array
  9063. * @param {Number} r
  9064. * End index of the array
  9065. */
  9066. function doQuickSort(ary, comparator, p, r) {
  9067. // If our lower bound is less than our upper bound, we (1) partition the
  9068. // array into two pieces and (2) recurse on each half. If it is not, this is
  9069. // the empty array and our base case.
  9070. if (p < r) {
  9071. // (1) Partitioning.
  9072. //
  9073. // The partitioning chooses a pivot between `p` and `r` and moves all
  9074. // elements that are less than or equal to the pivot to the before it, and
  9075. // all the elements that are greater than it after it. The effect is that
  9076. // once partition is done, the pivot is in the exact place it will be when
  9077. // the array is put in sorted order, and it will not need to be moved
  9078. // again. This runs in O(n) time.
  9079. // Always choose a random pivot so that an input array which is reverse
  9080. // sorted does not cause O(n^2) running time.
  9081. var pivotIndex = randomIntInRange(p, r);
  9082. var i = p - 1;
  9083. swap(ary, pivotIndex, r);
  9084. var pivot = ary[r];
  9085. // Immediately after `j` is incremented in this loop, the following hold
  9086. // true:
  9087. //
  9088. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9089. //
  9090. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9091. for (var j = p; j < r; j++) {
  9092. if (comparator(ary[j], pivot) <= 0) {
  9093. i += 1;
  9094. swap(ary, i, j);
  9095. }
  9096. }
  9097. swap(ary, i + 1, j);
  9098. var q = i + 1;
  9099. // (2) Recurse on each half.
  9100. doQuickSort(ary, comparator, p, q - 1);
  9101. doQuickSort(ary, comparator, q + 1, r);
  9102. }
  9103. }
  9104. /**
  9105. * Sort the given array in-place with the given comparator function.
  9106. *
  9107. * @param {Array} ary
  9108. * An array to sort.
  9109. * @param {function} comparator
  9110. * Function to use to compare two items.
  9111. */
  9112. quickSort.quickSort = function (ary, comparator) {
  9113. doQuickSort(ary, comparator, 0, ary.length - 1);
  9114. };
  9115. return quickSort;
  9116. }
  9117. /* -*- Mode: js; js-indent-level: 2; -*- */
  9118. var hasRequiredSourceMapConsumer;
  9119. function requireSourceMapConsumer () {
  9120. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9121. hasRequiredSourceMapConsumer = 1;
  9122. /*
  9123. * Copyright 2011 Mozilla Foundation and contributors
  9124. * Licensed under the New BSD license. See LICENSE or:
  9125. * http://opensource.org/licenses/BSD-3-Clause
  9126. */
  9127. var util = /*@__PURE__*/ requireUtil$1();
  9128. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9129. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9130. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9131. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9132. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9133. var sourceMap = aSourceMap;
  9134. if (typeof aSourceMap === 'string') {
  9135. sourceMap = util.parseSourceMapInput(aSourceMap);
  9136. }
  9137. return sourceMap.sections != null
  9138. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9139. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9140. }
  9141. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9142. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9143. };
  9144. /**
  9145. * The version of the source mapping spec that we are consuming.
  9146. */
  9147. SourceMapConsumer.prototype._version = 3;
  9148. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9149. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9150. // are lazily instantiated, accessed via the `_generatedMappings` and
  9151. // `_originalMappings` getters respectively, and we only parse the mappings
  9152. // and create these arrays once queried for a source location. We jump through
  9153. // these hoops because there can be many thousands of mappings, and parsing
  9154. // them is expensive, so we only want to do it if we must.
  9155. //
  9156. // Each object in the arrays is of the form:
  9157. //
  9158. // {
  9159. // generatedLine: The line number in the generated code,
  9160. // generatedColumn: The column number in the generated code,
  9161. // source: The path to the original source file that generated this
  9162. // chunk of code,
  9163. // originalLine: The line number in the original source that
  9164. // corresponds to this chunk of generated code,
  9165. // originalColumn: The column number in the original source that
  9166. // corresponds to this chunk of generated code,
  9167. // name: The name of the original symbol which generated this chunk of
  9168. // code.
  9169. // }
  9170. //
  9171. // All properties except for `generatedLine` and `generatedColumn` can be
  9172. // `null`.
  9173. //
  9174. // `_generatedMappings` is ordered by the generated positions.
  9175. //
  9176. // `_originalMappings` is ordered by the original positions.
  9177. SourceMapConsumer.prototype.__generatedMappings = null;
  9178. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9179. configurable: true,
  9180. enumerable: true,
  9181. get: function () {
  9182. if (!this.__generatedMappings) {
  9183. this._parseMappings(this._mappings, this.sourceRoot);
  9184. }
  9185. return this.__generatedMappings;
  9186. }
  9187. });
  9188. SourceMapConsumer.prototype.__originalMappings = null;
  9189. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9190. configurable: true,
  9191. enumerable: true,
  9192. get: function () {
  9193. if (!this.__originalMappings) {
  9194. this._parseMappings(this._mappings, this.sourceRoot);
  9195. }
  9196. return this.__originalMappings;
  9197. }
  9198. });
  9199. SourceMapConsumer.prototype._charIsMappingSeparator =
  9200. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9201. var c = aStr.charAt(index);
  9202. return c === ";" || c === ",";
  9203. };
  9204. /**
  9205. * Parse the mappings in a string in to a data structure which we can easily
  9206. * query (the ordered arrays in the `this.__generatedMappings` and
  9207. * `this.__originalMappings` properties).
  9208. */
  9209. SourceMapConsumer.prototype._parseMappings =
  9210. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9211. throw new Error("Subclasses must implement _parseMappings");
  9212. };
  9213. SourceMapConsumer.GENERATED_ORDER = 1;
  9214. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9215. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9216. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9217. /**
  9218. * Iterate over each mapping between an original source/line/column and a
  9219. * generated line/column in this source map.
  9220. *
  9221. * @param Function aCallback
  9222. * The function that is called with each mapping.
  9223. * @param Object aContext
  9224. * Optional. If specified, this object will be the value of `this` every
  9225. * time that `aCallback` is called.
  9226. * @param aOrder
  9227. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9228. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9229. * iterate over the mappings sorted by the generated file's line/column
  9230. * order or the original's source/line/column order, respectively. Defaults to
  9231. * `SourceMapConsumer.GENERATED_ORDER`.
  9232. */
  9233. SourceMapConsumer.prototype.eachMapping =
  9234. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9235. var context = aContext || null;
  9236. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9237. var mappings;
  9238. switch (order) {
  9239. case SourceMapConsumer.GENERATED_ORDER:
  9240. mappings = this._generatedMappings;
  9241. break;
  9242. case SourceMapConsumer.ORIGINAL_ORDER:
  9243. mappings = this._originalMappings;
  9244. break;
  9245. default:
  9246. throw new Error("Unknown order of iteration.");
  9247. }
  9248. var sourceRoot = this.sourceRoot;
  9249. mappings.map(function (mapping) {
  9250. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9251. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9252. return {
  9253. source: source,
  9254. generatedLine: mapping.generatedLine,
  9255. generatedColumn: mapping.generatedColumn,
  9256. originalLine: mapping.originalLine,
  9257. originalColumn: mapping.originalColumn,
  9258. name: mapping.name === null ? null : this._names.at(mapping.name)
  9259. };
  9260. }, this).forEach(aCallback, context);
  9261. };
  9262. /**
  9263. * Returns all generated line and column information for the original source,
  9264. * line, and column provided. If no column is provided, returns all mappings
  9265. * corresponding to a either the line we are searching for or the next
  9266. * closest line that has any mappings. Otherwise, returns all mappings
  9267. * corresponding to the given line and either the column we are searching for
  9268. * or the next closest column that has any offsets.
  9269. *
  9270. * The only argument is an object with the following properties:
  9271. *
  9272. * - source: The filename of the original source.
  9273. * - line: The line number in the original source. The line number is 1-based.
  9274. * - column: Optional. the column number in the original source.
  9275. * The column number is 0-based.
  9276. *
  9277. * and an array of objects is returned, each with the following properties:
  9278. *
  9279. * - line: The line number in the generated source, or null. The
  9280. * line number is 1-based.
  9281. * - column: The column number in the generated source, or null.
  9282. * The column number is 0-based.
  9283. */
  9284. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9285. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9286. var line = util.getArg(aArgs, 'line');
  9287. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9288. // returns the index of the closest mapping less than the needle. By
  9289. // setting needle.originalColumn to 0, we thus find the last mapping for
  9290. // the given line, provided such a mapping exists.
  9291. var needle = {
  9292. source: util.getArg(aArgs, 'source'),
  9293. originalLine: line,
  9294. originalColumn: util.getArg(aArgs, 'column', 0)
  9295. };
  9296. needle.source = this._findSourceIndex(needle.source);
  9297. if (needle.source < 0) {
  9298. return [];
  9299. }
  9300. var mappings = [];
  9301. var index = this._findMapping(needle,
  9302. this._originalMappings,
  9303. "originalLine",
  9304. "originalColumn",
  9305. util.compareByOriginalPositions,
  9306. binarySearch.LEAST_UPPER_BOUND);
  9307. if (index >= 0) {
  9308. var mapping = this._originalMappings[index];
  9309. if (aArgs.column === undefined) {
  9310. var originalLine = mapping.originalLine;
  9311. // Iterate until either we run out of mappings, or we run into
  9312. // a mapping for a different line than the one we found. Since
  9313. // mappings are sorted, this is guaranteed to find all mappings for
  9314. // the line we found.
  9315. while (mapping && mapping.originalLine === originalLine) {
  9316. mappings.push({
  9317. line: util.getArg(mapping, 'generatedLine', null),
  9318. column: util.getArg(mapping, 'generatedColumn', null),
  9319. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9320. });
  9321. mapping = this._originalMappings[++index];
  9322. }
  9323. } else {
  9324. var originalColumn = mapping.originalColumn;
  9325. // Iterate until either we run out of mappings, or we run into
  9326. // a mapping for a different line than the one we were searching for.
  9327. // Since mappings are sorted, this is guaranteed to find all mappings for
  9328. // the line we are searching for.
  9329. while (mapping &&
  9330. mapping.originalLine === line &&
  9331. mapping.originalColumn == originalColumn) {
  9332. mappings.push({
  9333. line: util.getArg(mapping, 'generatedLine', null),
  9334. column: util.getArg(mapping, 'generatedColumn', null),
  9335. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9336. });
  9337. mapping = this._originalMappings[++index];
  9338. }
  9339. }
  9340. }
  9341. return mappings;
  9342. };
  9343. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9344. /**
  9345. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9346. * query for information about the original file positions by giving it a file
  9347. * position in the generated source.
  9348. *
  9349. * The first parameter is the raw source map (either as a JSON string, or
  9350. * already parsed to an object). According to the spec, source maps have the
  9351. * following attributes:
  9352. *
  9353. * - version: Which version of the source map spec this map is following.
  9354. * - sources: An array of URLs to the original source files.
  9355. * - names: An array of identifiers which can be referrenced by individual mappings.
  9356. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9357. * - sourcesContent: Optional. An array of contents of the original source files.
  9358. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9359. * - file: Optional. The generated file this source map is associated with.
  9360. *
  9361. * Here is an example source map, taken from the source map spec[0]:
  9362. *
  9363. * {
  9364. * version : 3,
  9365. * file: "out.js",
  9366. * sourceRoot : "",
  9367. * sources: ["foo.js", "bar.js"],
  9368. * names: ["src", "maps", "are", "fun"],
  9369. * mappings: "AA,AB;;ABCDE;"
  9370. * }
  9371. *
  9372. * The second parameter, if given, is a string whose value is the URL
  9373. * at which the source map was found. This URL is used to compute the
  9374. * sources array.
  9375. *
  9376. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9377. */
  9378. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9379. var sourceMap = aSourceMap;
  9380. if (typeof aSourceMap === 'string') {
  9381. sourceMap = util.parseSourceMapInput(aSourceMap);
  9382. }
  9383. var version = util.getArg(sourceMap, 'version');
  9384. var sources = util.getArg(sourceMap, 'sources');
  9385. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9386. // requires the array) to play nice here.
  9387. var names = util.getArg(sourceMap, 'names', []);
  9388. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9389. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9390. var mappings = util.getArg(sourceMap, 'mappings');
  9391. var file = util.getArg(sourceMap, 'file', null);
  9392. // Once again, Sass deviates from the spec and supplies the version as a
  9393. // string rather than a number, so we use loose equality checking here.
  9394. if (version != this._version) {
  9395. throw new Error('Unsupported version: ' + version);
  9396. }
  9397. if (sourceRoot) {
  9398. sourceRoot = util.normalize(sourceRoot);
  9399. }
  9400. sources = sources
  9401. .map(String)
  9402. // Some source maps produce relative source paths like "./foo.js" instead of
  9403. // "foo.js". Normalize these first so that future comparisons will succeed.
  9404. // See bugzil.la/1090768.
  9405. .map(util.normalize)
  9406. // Always ensure that absolute sources are internally stored relative to
  9407. // the source root, if the source root is absolute. Not doing this would
  9408. // be particularly problematic when the source root is a prefix of the
  9409. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9410. .map(function (source) {
  9411. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9412. ? util.relative(sourceRoot, source)
  9413. : source;
  9414. });
  9415. // Pass `true` below to allow duplicate names and sources. While source maps
  9416. // are intended to be compressed and deduplicated, the TypeScript compiler
  9417. // sometimes generates source maps with duplicates in them. See Github issue
  9418. // #72 and bugzil.la/889492.
  9419. this._names = ArraySet.fromArray(names.map(String), true);
  9420. this._sources = ArraySet.fromArray(sources, true);
  9421. this._absoluteSources = this._sources.toArray().map(function (s) {
  9422. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9423. });
  9424. this.sourceRoot = sourceRoot;
  9425. this.sourcesContent = sourcesContent;
  9426. this._mappings = mappings;
  9427. this._sourceMapURL = aSourceMapURL;
  9428. this.file = file;
  9429. }
  9430. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9431. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9432. /**
  9433. * Utility function to find the index of a source. Returns -1 if not
  9434. * found.
  9435. */
  9436. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9437. var relativeSource = aSource;
  9438. if (this.sourceRoot != null) {
  9439. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9440. }
  9441. if (this._sources.has(relativeSource)) {
  9442. return this._sources.indexOf(relativeSource);
  9443. }
  9444. // Maybe aSource is an absolute URL as returned by |sources|. In
  9445. // this case we can't simply undo the transform.
  9446. var i;
  9447. for (i = 0; i < this._absoluteSources.length; ++i) {
  9448. if (this._absoluteSources[i] == aSource) {
  9449. return i;
  9450. }
  9451. }
  9452. return -1;
  9453. };
  9454. /**
  9455. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9456. *
  9457. * @param SourceMapGenerator aSourceMap
  9458. * The source map that will be consumed.
  9459. * @param String aSourceMapURL
  9460. * The URL at which the source map can be found (optional)
  9461. * @returns BasicSourceMapConsumer
  9462. */
  9463. BasicSourceMapConsumer.fromSourceMap =
  9464. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9465. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9466. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9467. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9468. smc.sourceRoot = aSourceMap._sourceRoot;
  9469. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9470. smc.sourceRoot);
  9471. smc.file = aSourceMap._file;
  9472. smc._sourceMapURL = aSourceMapURL;
  9473. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9474. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9475. });
  9476. // Because we are modifying the entries (by converting string sources and
  9477. // names to indices into the sources and names ArraySets), we have to make
  9478. // a copy of the entry or else bad things happen. Shared mutable state
  9479. // strikes again! See github issue #191.
  9480. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9481. var destGeneratedMappings = smc.__generatedMappings = [];
  9482. var destOriginalMappings = smc.__originalMappings = [];
  9483. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9484. var srcMapping = generatedMappings[i];
  9485. var destMapping = new Mapping;
  9486. destMapping.generatedLine = srcMapping.generatedLine;
  9487. destMapping.generatedColumn = srcMapping.generatedColumn;
  9488. if (srcMapping.source) {
  9489. destMapping.source = sources.indexOf(srcMapping.source);
  9490. destMapping.originalLine = srcMapping.originalLine;
  9491. destMapping.originalColumn = srcMapping.originalColumn;
  9492. if (srcMapping.name) {
  9493. destMapping.name = names.indexOf(srcMapping.name);
  9494. }
  9495. destOriginalMappings.push(destMapping);
  9496. }
  9497. destGeneratedMappings.push(destMapping);
  9498. }
  9499. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9500. return smc;
  9501. };
  9502. /**
  9503. * The version of the source mapping spec that we are consuming.
  9504. */
  9505. BasicSourceMapConsumer.prototype._version = 3;
  9506. /**
  9507. * The list of original sources.
  9508. */
  9509. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9510. get: function () {
  9511. return this._absoluteSources.slice();
  9512. }
  9513. });
  9514. /**
  9515. * Provide the JIT with a nice shape / hidden class.
  9516. */
  9517. function Mapping() {
  9518. this.generatedLine = 0;
  9519. this.generatedColumn = 0;
  9520. this.source = null;
  9521. this.originalLine = null;
  9522. this.originalColumn = null;
  9523. this.name = null;
  9524. }
  9525. /**
  9526. * Parse the mappings in a string in to a data structure which we can easily
  9527. * query (the ordered arrays in the `this.__generatedMappings` and
  9528. * `this.__originalMappings` properties).
  9529. */
  9530. BasicSourceMapConsumer.prototype._parseMappings =
  9531. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9532. var generatedLine = 1;
  9533. var previousGeneratedColumn = 0;
  9534. var previousOriginalLine = 0;
  9535. var previousOriginalColumn = 0;
  9536. var previousSource = 0;
  9537. var previousName = 0;
  9538. var length = aStr.length;
  9539. var index = 0;
  9540. var cachedSegments = {};
  9541. var temp = {};
  9542. var originalMappings = [];
  9543. var generatedMappings = [];
  9544. var mapping, str, segment, end, value;
  9545. while (index < length) {
  9546. if (aStr.charAt(index) === ';') {
  9547. generatedLine++;
  9548. index++;
  9549. previousGeneratedColumn = 0;
  9550. }
  9551. else if (aStr.charAt(index) === ',') {
  9552. index++;
  9553. }
  9554. else {
  9555. mapping = new Mapping();
  9556. mapping.generatedLine = generatedLine;
  9557. // Because each offset is encoded relative to the previous one,
  9558. // many segments often have the same encoding. We can exploit this
  9559. // fact by caching the parsed variable length fields of each segment,
  9560. // allowing us to avoid a second parse if we encounter the same
  9561. // segment again.
  9562. for (end = index; end < length; end++) {
  9563. if (this._charIsMappingSeparator(aStr, end)) {
  9564. break;
  9565. }
  9566. }
  9567. str = aStr.slice(index, end);
  9568. segment = cachedSegments[str];
  9569. if (segment) {
  9570. index += str.length;
  9571. } else {
  9572. segment = [];
  9573. while (index < end) {
  9574. base64VLQ.decode(aStr, index, temp);
  9575. value = temp.value;
  9576. index = temp.rest;
  9577. segment.push(value);
  9578. }
  9579. if (segment.length === 2) {
  9580. throw new Error('Found a source, but no line and column');
  9581. }
  9582. if (segment.length === 3) {
  9583. throw new Error('Found a source and line, but no column');
  9584. }
  9585. cachedSegments[str] = segment;
  9586. }
  9587. // Generated column.
  9588. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9589. previousGeneratedColumn = mapping.generatedColumn;
  9590. if (segment.length > 1) {
  9591. // Original source.
  9592. mapping.source = previousSource + segment[1];
  9593. previousSource += segment[1];
  9594. // Original line.
  9595. mapping.originalLine = previousOriginalLine + segment[2];
  9596. previousOriginalLine = mapping.originalLine;
  9597. // Lines are stored 0-based
  9598. mapping.originalLine += 1;
  9599. // Original column.
  9600. mapping.originalColumn = previousOriginalColumn + segment[3];
  9601. previousOriginalColumn = mapping.originalColumn;
  9602. if (segment.length > 4) {
  9603. // Original name.
  9604. mapping.name = previousName + segment[4];
  9605. previousName += segment[4];
  9606. }
  9607. }
  9608. generatedMappings.push(mapping);
  9609. if (typeof mapping.originalLine === 'number') {
  9610. originalMappings.push(mapping);
  9611. }
  9612. }
  9613. }
  9614. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9615. this.__generatedMappings = generatedMappings;
  9616. quickSort(originalMappings, util.compareByOriginalPositions);
  9617. this.__originalMappings = originalMappings;
  9618. };
  9619. /**
  9620. * Find the mapping that best matches the hypothetical "needle" mapping that
  9621. * we are searching for in the given "haystack" of mappings.
  9622. */
  9623. BasicSourceMapConsumer.prototype._findMapping =
  9624. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9625. aColumnName, aComparator, aBias) {
  9626. // To return the position we are searching for, we must first find the
  9627. // mapping for the given position and then return the opposite position it
  9628. // points to. Because the mappings are sorted, we can use binary search to
  9629. // find the best mapping.
  9630. if (aNeedle[aLineName] <= 0) {
  9631. throw new TypeError('Line must be greater than or equal to 1, got '
  9632. + aNeedle[aLineName]);
  9633. }
  9634. if (aNeedle[aColumnName] < 0) {
  9635. throw new TypeError('Column must be greater than or equal to 0, got '
  9636. + aNeedle[aColumnName]);
  9637. }
  9638. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9639. };
  9640. /**
  9641. * Compute the last column for each generated mapping. The last column is
  9642. * inclusive.
  9643. */
  9644. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9645. function SourceMapConsumer_computeColumnSpans() {
  9646. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9647. var mapping = this._generatedMappings[index];
  9648. // Mappings do not contain a field for the last generated columnt. We
  9649. // can come up with an optimistic estimate, however, by assuming that
  9650. // mappings are contiguous (i.e. given two consecutive mappings, the
  9651. // first mapping ends where the second one starts).
  9652. if (index + 1 < this._generatedMappings.length) {
  9653. var nextMapping = this._generatedMappings[index + 1];
  9654. if (mapping.generatedLine === nextMapping.generatedLine) {
  9655. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9656. continue;
  9657. }
  9658. }
  9659. // The last mapping for each line spans the entire line.
  9660. mapping.lastGeneratedColumn = Infinity;
  9661. }
  9662. };
  9663. /**
  9664. * Returns the original source, line, and column information for the generated
  9665. * source's line and column positions provided. The only argument is an object
  9666. * with the following properties:
  9667. *
  9668. * - line: The line number in the generated source. The line number
  9669. * is 1-based.
  9670. * - column: The column number in the generated source. The column
  9671. * number is 0-based.
  9672. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9673. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9674. * closest element that is smaller than or greater than the one we are
  9675. * searching for, respectively, if the exact element cannot be found.
  9676. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9677. *
  9678. * and an object is returned with the following properties:
  9679. *
  9680. * - source: The original source file, or null.
  9681. * - line: The line number in the original source, or null. The
  9682. * line number is 1-based.
  9683. * - column: The column number in the original source, or null. The
  9684. * column number is 0-based.
  9685. * - name: The original identifier, or null.
  9686. */
  9687. BasicSourceMapConsumer.prototype.originalPositionFor =
  9688. function SourceMapConsumer_originalPositionFor(aArgs) {
  9689. var needle = {
  9690. generatedLine: util.getArg(aArgs, 'line'),
  9691. generatedColumn: util.getArg(aArgs, 'column')
  9692. };
  9693. var index = this._findMapping(
  9694. needle,
  9695. this._generatedMappings,
  9696. "generatedLine",
  9697. "generatedColumn",
  9698. util.compareByGeneratedPositionsDeflated,
  9699. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9700. );
  9701. if (index >= 0) {
  9702. var mapping = this._generatedMappings[index];
  9703. if (mapping.generatedLine === needle.generatedLine) {
  9704. var source = util.getArg(mapping, 'source', null);
  9705. if (source !== null) {
  9706. source = this._sources.at(source);
  9707. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9708. }
  9709. var name = util.getArg(mapping, 'name', null);
  9710. if (name !== null) {
  9711. name = this._names.at(name);
  9712. }
  9713. return {
  9714. source: source,
  9715. line: util.getArg(mapping, 'originalLine', null),
  9716. column: util.getArg(mapping, 'originalColumn', null),
  9717. name: name
  9718. };
  9719. }
  9720. }
  9721. return {
  9722. source: null,
  9723. line: null,
  9724. column: null,
  9725. name: null
  9726. };
  9727. };
  9728. /**
  9729. * Return true if we have the source content for every source in the source
  9730. * map, false otherwise.
  9731. */
  9732. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9733. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9734. if (!this.sourcesContent) {
  9735. return false;
  9736. }
  9737. return this.sourcesContent.length >= this._sources.size() &&
  9738. !this.sourcesContent.some(function (sc) { return sc == null; });
  9739. };
  9740. /**
  9741. * Returns the original source content. The only argument is the url of the
  9742. * original source file. Returns null if no original source content is
  9743. * available.
  9744. */
  9745. BasicSourceMapConsumer.prototype.sourceContentFor =
  9746. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9747. if (!this.sourcesContent) {
  9748. return null;
  9749. }
  9750. var index = this._findSourceIndex(aSource);
  9751. if (index >= 0) {
  9752. return this.sourcesContent[index];
  9753. }
  9754. var relativeSource = aSource;
  9755. if (this.sourceRoot != null) {
  9756. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9757. }
  9758. var url;
  9759. if (this.sourceRoot != null
  9760. && (url = util.urlParse(this.sourceRoot))) {
  9761. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9762. // many users. We can help them out when they expect file:// URIs to
  9763. // behave like it would if they were running a local HTTP server. See
  9764. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9765. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9766. if (url.scheme == "file"
  9767. && this._sources.has(fileUriAbsPath)) {
  9768. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9769. }
  9770. if ((!url.path || url.path == "/")
  9771. && this._sources.has("/" + relativeSource)) {
  9772. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9773. }
  9774. }
  9775. // This function is used recursively from
  9776. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9777. // don't want to throw if we can't find the source - we just want to
  9778. // return null, so we provide a flag to exit gracefully.
  9779. if (nullOnMissing) {
  9780. return null;
  9781. }
  9782. else {
  9783. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9784. }
  9785. };
  9786. /**
  9787. * Returns the generated line and column information for the original source,
  9788. * line, and column positions provided. The only argument is an object with
  9789. * the following properties:
  9790. *
  9791. * - source: The filename of the original source.
  9792. * - line: The line number in the original source. The line number
  9793. * is 1-based.
  9794. * - column: The column number in the original source. The column
  9795. * number is 0-based.
  9796. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9797. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9798. * closest element that is smaller than or greater than the one we are
  9799. * searching for, respectively, if the exact element cannot be found.
  9800. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9801. *
  9802. * and an object is returned with the following properties:
  9803. *
  9804. * - line: The line number in the generated source, or null. The
  9805. * line number is 1-based.
  9806. * - column: The column number in the generated source, or null.
  9807. * The column number is 0-based.
  9808. */
  9809. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9810. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9811. var source = util.getArg(aArgs, 'source');
  9812. source = this._findSourceIndex(source);
  9813. if (source < 0) {
  9814. return {
  9815. line: null,
  9816. column: null,
  9817. lastColumn: null
  9818. };
  9819. }
  9820. var needle = {
  9821. source: source,
  9822. originalLine: util.getArg(aArgs, 'line'),
  9823. originalColumn: util.getArg(aArgs, 'column')
  9824. };
  9825. var index = this._findMapping(
  9826. needle,
  9827. this._originalMappings,
  9828. "originalLine",
  9829. "originalColumn",
  9830. util.compareByOriginalPositions,
  9831. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9832. );
  9833. if (index >= 0) {
  9834. var mapping = this._originalMappings[index];
  9835. if (mapping.source === needle.source) {
  9836. return {
  9837. line: util.getArg(mapping, 'generatedLine', null),
  9838. column: util.getArg(mapping, 'generatedColumn', null),
  9839. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9840. };
  9841. }
  9842. }
  9843. return {
  9844. line: null,
  9845. column: null,
  9846. lastColumn: null
  9847. };
  9848. };
  9849. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9850. /**
  9851. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9852. * we can query for information. It differs from BasicSourceMapConsumer in
  9853. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9854. * input.
  9855. *
  9856. * The first parameter is a raw source map (either as a JSON string, or already
  9857. * parsed to an object). According to the spec for indexed source maps, they
  9858. * have the following attributes:
  9859. *
  9860. * - version: Which version of the source map spec this map is following.
  9861. * - file: Optional. The generated file this source map is associated with.
  9862. * - sections: A list of section definitions.
  9863. *
  9864. * Each value under the "sections" field has two fields:
  9865. * - offset: The offset into the original specified at which this section
  9866. * begins to apply, defined as an object with a "line" and "column"
  9867. * field.
  9868. * - map: A source map definition. This source map could also be indexed,
  9869. * but doesn't have to be.
  9870. *
  9871. * Instead of the "map" field, it's also possible to have a "url" field
  9872. * specifying a URL to retrieve a source map from, but that's currently
  9873. * unsupported.
  9874. *
  9875. * Here's an example source map, taken from the source map spec[0], but
  9876. * modified to omit a section which uses the "url" field.
  9877. *
  9878. * {
  9879. * version : 3,
  9880. * file: "app.js",
  9881. * sections: [{
  9882. * offset: {line:100, column:10},
  9883. * map: {
  9884. * version : 3,
  9885. * file: "section.js",
  9886. * sources: ["foo.js", "bar.js"],
  9887. * names: ["src", "maps", "are", "fun"],
  9888. * mappings: "AAAA,E;;ABCDE;"
  9889. * }
  9890. * }],
  9891. * }
  9892. *
  9893. * The second parameter, if given, is a string whose value is the URL
  9894. * at which the source map was found. This URL is used to compute the
  9895. * sources array.
  9896. *
  9897. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9898. */
  9899. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9900. var sourceMap = aSourceMap;
  9901. if (typeof aSourceMap === 'string') {
  9902. sourceMap = util.parseSourceMapInput(aSourceMap);
  9903. }
  9904. var version = util.getArg(sourceMap, 'version');
  9905. var sections = util.getArg(sourceMap, 'sections');
  9906. if (version != this._version) {
  9907. throw new Error('Unsupported version: ' + version);
  9908. }
  9909. this._sources = new ArraySet();
  9910. this._names = new ArraySet();
  9911. var lastOffset = {
  9912. line: -1,
  9913. column: 0
  9914. };
  9915. this._sections = sections.map(function (s) {
  9916. if (s.url) {
  9917. // The url field will require support for asynchronicity.
  9918. // See https://github.com/mozilla/source-map/issues/16
  9919. throw new Error('Support for url field in sections not implemented.');
  9920. }
  9921. var offset = util.getArg(s, 'offset');
  9922. var offsetLine = util.getArg(offset, 'line');
  9923. var offsetColumn = util.getArg(offset, 'column');
  9924. if (offsetLine < lastOffset.line ||
  9925. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9926. throw new Error('Section offsets must be ordered and non-overlapping.');
  9927. }
  9928. lastOffset = offset;
  9929. return {
  9930. generatedOffset: {
  9931. // The offset fields are 0-based, but we use 1-based indices when
  9932. // encoding/decoding from VLQ.
  9933. generatedLine: offsetLine + 1,
  9934. generatedColumn: offsetColumn + 1
  9935. },
  9936. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  9937. }
  9938. });
  9939. }
  9940. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9941. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  9942. /**
  9943. * The version of the source mapping spec that we are consuming.
  9944. */
  9945. IndexedSourceMapConsumer.prototype._version = 3;
  9946. /**
  9947. * The list of original sources.
  9948. */
  9949. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  9950. get: function () {
  9951. var sources = [];
  9952. for (var i = 0; i < this._sections.length; i++) {
  9953. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  9954. sources.push(this._sections[i].consumer.sources[j]);
  9955. }
  9956. }
  9957. return sources;
  9958. }
  9959. });
  9960. /**
  9961. * Returns the original source, line, and column information for the generated
  9962. * source's line and column positions provided. The only argument is an object
  9963. * with the following properties:
  9964. *
  9965. * - line: The line number in the generated source. The line number
  9966. * is 1-based.
  9967. * - column: The column number in the generated source. The column
  9968. * number is 0-based.
  9969. *
  9970. * and an object is returned with the following properties:
  9971. *
  9972. * - source: The original source file, or null.
  9973. * - line: The line number in the original source, or null. The
  9974. * line number is 1-based.
  9975. * - column: The column number in the original source, or null. The
  9976. * column number is 0-based.
  9977. * - name: The original identifier, or null.
  9978. */
  9979. IndexedSourceMapConsumer.prototype.originalPositionFor =
  9980. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  9981. var needle = {
  9982. generatedLine: util.getArg(aArgs, 'line'),
  9983. generatedColumn: util.getArg(aArgs, 'column')
  9984. };
  9985. // Find the section containing the generated position we're trying to map
  9986. // to an original position.
  9987. var sectionIndex = binarySearch.search(needle, this._sections,
  9988. function(needle, section) {
  9989. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  9990. if (cmp) {
  9991. return cmp;
  9992. }
  9993. return (needle.generatedColumn -
  9994. section.generatedOffset.generatedColumn);
  9995. });
  9996. var section = this._sections[sectionIndex];
  9997. if (!section) {
  9998. return {
  9999. source: null,
  10000. line: null,
  10001. column: null,
  10002. name: null
  10003. };
  10004. }
  10005. return section.consumer.originalPositionFor({
  10006. line: needle.generatedLine -
  10007. (section.generatedOffset.generatedLine - 1),
  10008. column: needle.generatedColumn -
  10009. (section.generatedOffset.generatedLine === needle.generatedLine
  10010. ? section.generatedOffset.generatedColumn - 1
  10011. : 0),
  10012. bias: aArgs.bias
  10013. });
  10014. };
  10015. /**
  10016. * Return true if we have the source content for every source in the source
  10017. * map, false otherwise.
  10018. */
  10019. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10020. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10021. return this._sections.every(function (s) {
  10022. return s.consumer.hasContentsOfAllSources();
  10023. });
  10024. };
  10025. /**
  10026. * Returns the original source content. The only argument is the url of the
  10027. * original source file. Returns null if no original source content is
  10028. * available.
  10029. */
  10030. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10031. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10032. for (var i = 0; i < this._sections.length; i++) {
  10033. var section = this._sections[i];
  10034. var content = section.consumer.sourceContentFor(aSource, true);
  10035. if (content) {
  10036. return content;
  10037. }
  10038. }
  10039. if (nullOnMissing) {
  10040. return null;
  10041. }
  10042. else {
  10043. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10044. }
  10045. };
  10046. /**
  10047. * Returns the generated line and column information for the original source,
  10048. * line, and column positions provided. The only argument is an object with
  10049. * the following properties:
  10050. *
  10051. * - source: The filename of the original source.
  10052. * - line: The line number in the original source. The line number
  10053. * is 1-based.
  10054. * - column: The column number in the original source. The column
  10055. * number is 0-based.
  10056. *
  10057. * and an object is returned with the following properties:
  10058. *
  10059. * - line: The line number in the generated source, or null. The
  10060. * line number is 1-based.
  10061. * - column: The column number in the generated source, or null.
  10062. * The column number is 0-based.
  10063. */
  10064. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10065. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10066. for (var i = 0; i < this._sections.length; i++) {
  10067. var section = this._sections[i];
  10068. // Only consider this section if the requested source is in the list of
  10069. // sources of the consumer.
  10070. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10071. continue;
  10072. }
  10073. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10074. if (generatedPosition) {
  10075. var ret = {
  10076. line: generatedPosition.line +
  10077. (section.generatedOffset.generatedLine - 1),
  10078. column: generatedPosition.column +
  10079. (section.generatedOffset.generatedLine === generatedPosition.line
  10080. ? section.generatedOffset.generatedColumn - 1
  10081. : 0)
  10082. };
  10083. return ret;
  10084. }
  10085. }
  10086. return {
  10087. line: null,
  10088. column: null
  10089. };
  10090. };
  10091. /**
  10092. * Parse the mappings in a string in to a data structure which we can easily
  10093. * query (the ordered arrays in the `this.__generatedMappings` and
  10094. * `this.__originalMappings` properties).
  10095. */
  10096. IndexedSourceMapConsumer.prototype._parseMappings =
  10097. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10098. this.__generatedMappings = [];
  10099. this.__originalMappings = [];
  10100. for (var i = 0; i < this._sections.length; i++) {
  10101. var section = this._sections[i];
  10102. var sectionMappings = section.consumer._generatedMappings;
  10103. for (var j = 0; j < sectionMappings.length; j++) {
  10104. var mapping = sectionMappings[j];
  10105. var source = section.consumer._sources.at(mapping.source);
  10106. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10107. this._sources.add(source);
  10108. source = this._sources.indexOf(source);
  10109. var name = null;
  10110. if (mapping.name) {
  10111. name = section.consumer._names.at(mapping.name);
  10112. this._names.add(name);
  10113. name = this._names.indexOf(name);
  10114. }
  10115. // The mappings coming from the consumer for the section have
  10116. // generated positions relative to the start of the section, so we
  10117. // need to offset them to be relative to the start of the concatenated
  10118. // generated file.
  10119. var adjustedMapping = {
  10120. source: source,
  10121. generatedLine: mapping.generatedLine +
  10122. (section.generatedOffset.generatedLine - 1),
  10123. generatedColumn: mapping.generatedColumn +
  10124. (section.generatedOffset.generatedLine === mapping.generatedLine
  10125. ? section.generatedOffset.generatedColumn - 1
  10126. : 0),
  10127. originalLine: mapping.originalLine,
  10128. originalColumn: mapping.originalColumn,
  10129. name: name
  10130. };
  10131. this.__generatedMappings.push(adjustedMapping);
  10132. if (typeof adjustedMapping.originalLine === 'number') {
  10133. this.__originalMappings.push(adjustedMapping);
  10134. }
  10135. }
  10136. }
  10137. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10138. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10139. };
  10140. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10141. return sourceMapConsumer;
  10142. }
  10143. var sourceNode = {};
  10144. /* -*- Mode: js; js-indent-level: 2; -*- */
  10145. var hasRequiredSourceNode;
  10146. function requireSourceNode () {
  10147. if (hasRequiredSourceNode) return sourceNode;
  10148. hasRequiredSourceNode = 1;
  10149. /*
  10150. * Copyright 2011 Mozilla Foundation and contributors
  10151. * Licensed under the New BSD license. See LICENSE or:
  10152. * http://opensource.org/licenses/BSD-3-Clause
  10153. */
  10154. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10155. var util = /*@__PURE__*/ requireUtil$1();
  10156. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10157. // operating systems these days (capturing the result).
  10158. var REGEX_NEWLINE = /(\r?\n)/;
  10159. // Newline character code for charCodeAt() comparisons
  10160. var NEWLINE_CODE = 10;
  10161. // Private symbol for identifying `SourceNode`s when multiple versions of
  10162. // the source-map library are loaded. This MUST NOT CHANGE across
  10163. // versions!
  10164. var isSourceNode = "$$$isSourceNode$$$";
  10165. /**
  10166. * SourceNodes provide a way to abstract over interpolating/concatenating
  10167. * snippets of generated JavaScript source code while maintaining the line and
  10168. * column information associated with the original source code.
  10169. *
  10170. * @param aLine The original line number.
  10171. * @param aColumn The original column number.
  10172. * @param aSource The original source's filename.
  10173. * @param aChunks Optional. An array of strings which are snippets of
  10174. * generated JS, or other SourceNodes.
  10175. * @param aName The original identifier.
  10176. */
  10177. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10178. this.children = [];
  10179. this.sourceContents = {};
  10180. this.line = aLine == null ? null : aLine;
  10181. this.column = aColumn == null ? null : aColumn;
  10182. this.source = aSource == null ? null : aSource;
  10183. this.name = aName == null ? null : aName;
  10184. this[isSourceNode] = true;
  10185. if (aChunks != null) this.add(aChunks);
  10186. }
  10187. /**
  10188. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10189. *
  10190. * @param aGeneratedCode The generated code
  10191. * @param aSourceMapConsumer The SourceMap for the generated code
  10192. * @param aRelativePath Optional. The path that relative sources in the
  10193. * SourceMapConsumer should be relative to.
  10194. */
  10195. SourceNode.fromStringWithSourceMap =
  10196. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10197. // The SourceNode we want to fill with the generated code
  10198. // and the SourceMap
  10199. var node = new SourceNode();
  10200. // All even indices of this array are one line of the generated code,
  10201. // while all odd indices are the newlines between two adjacent lines
  10202. // (since `REGEX_NEWLINE` captures its match).
  10203. // Processed fragments are accessed by calling `shiftNextLine`.
  10204. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10205. var remainingLinesIndex = 0;
  10206. var shiftNextLine = function() {
  10207. var lineContents = getNextLine();
  10208. // The last line of a file might not have a newline.
  10209. var newLine = getNextLine() || "";
  10210. return lineContents + newLine;
  10211. function getNextLine() {
  10212. return remainingLinesIndex < remainingLines.length ?
  10213. remainingLines[remainingLinesIndex++] : undefined;
  10214. }
  10215. };
  10216. // We need to remember the position of "remainingLines"
  10217. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10218. // The generate SourceNodes we need a code range.
  10219. // To extract it current and last mapping is used.
  10220. // Here we store the last mapping.
  10221. var lastMapping = null;
  10222. aSourceMapConsumer.eachMapping(function (mapping) {
  10223. if (lastMapping !== null) {
  10224. // We add the code from "lastMapping" to "mapping":
  10225. // First check if there is a new line in between.
  10226. if (lastGeneratedLine < mapping.generatedLine) {
  10227. // Associate first line with "lastMapping"
  10228. addMappingWithCode(lastMapping, shiftNextLine());
  10229. lastGeneratedLine++;
  10230. lastGeneratedColumn = 0;
  10231. // The remaining code is added without mapping
  10232. } else {
  10233. // There is no new line in between.
  10234. // Associate the code between "lastGeneratedColumn" and
  10235. // "mapping.generatedColumn" with "lastMapping"
  10236. var nextLine = remainingLines[remainingLinesIndex] || '';
  10237. var code = nextLine.substr(0, mapping.generatedColumn -
  10238. lastGeneratedColumn);
  10239. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10240. lastGeneratedColumn);
  10241. lastGeneratedColumn = mapping.generatedColumn;
  10242. addMappingWithCode(lastMapping, code);
  10243. // No more remaining code, continue
  10244. lastMapping = mapping;
  10245. return;
  10246. }
  10247. }
  10248. // We add the generated code until the first mapping
  10249. // to the SourceNode without any mapping.
  10250. // Each line is added as separate string.
  10251. while (lastGeneratedLine < mapping.generatedLine) {
  10252. node.add(shiftNextLine());
  10253. lastGeneratedLine++;
  10254. }
  10255. if (lastGeneratedColumn < mapping.generatedColumn) {
  10256. var nextLine = remainingLines[remainingLinesIndex] || '';
  10257. node.add(nextLine.substr(0, mapping.generatedColumn));
  10258. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10259. lastGeneratedColumn = mapping.generatedColumn;
  10260. }
  10261. lastMapping = mapping;
  10262. }, this);
  10263. // We have processed all mappings.
  10264. if (remainingLinesIndex < remainingLines.length) {
  10265. if (lastMapping) {
  10266. // Associate the remaining code in the current line with "lastMapping"
  10267. addMappingWithCode(lastMapping, shiftNextLine());
  10268. }
  10269. // and add the remaining lines without any mapping
  10270. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10271. }
  10272. // Copy sourcesContent into SourceNode
  10273. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10274. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10275. if (content != null) {
  10276. if (aRelativePath != null) {
  10277. sourceFile = util.join(aRelativePath, sourceFile);
  10278. }
  10279. node.setSourceContent(sourceFile, content);
  10280. }
  10281. });
  10282. return node;
  10283. function addMappingWithCode(mapping, code) {
  10284. if (mapping === null || mapping.source === undefined) {
  10285. node.add(code);
  10286. } else {
  10287. var source = aRelativePath
  10288. ? util.join(aRelativePath, mapping.source)
  10289. : mapping.source;
  10290. node.add(new SourceNode(mapping.originalLine,
  10291. mapping.originalColumn,
  10292. source,
  10293. code,
  10294. mapping.name));
  10295. }
  10296. }
  10297. };
  10298. /**
  10299. * Add a chunk of generated JS to this source node.
  10300. *
  10301. * @param aChunk A string snippet of generated JS code, another instance of
  10302. * SourceNode, or an array where each member is one of those things.
  10303. */
  10304. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10305. if (Array.isArray(aChunk)) {
  10306. aChunk.forEach(function (chunk) {
  10307. this.add(chunk);
  10308. }, this);
  10309. }
  10310. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10311. if (aChunk) {
  10312. this.children.push(aChunk);
  10313. }
  10314. }
  10315. else {
  10316. throw new TypeError(
  10317. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10318. );
  10319. }
  10320. return this;
  10321. };
  10322. /**
  10323. * Add a chunk of generated JS to the beginning of this source node.
  10324. *
  10325. * @param aChunk A string snippet of generated JS code, another instance of
  10326. * SourceNode, or an array where each member is one of those things.
  10327. */
  10328. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10329. if (Array.isArray(aChunk)) {
  10330. for (var i = aChunk.length-1; i >= 0; i--) {
  10331. this.prepend(aChunk[i]);
  10332. }
  10333. }
  10334. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10335. this.children.unshift(aChunk);
  10336. }
  10337. else {
  10338. throw new TypeError(
  10339. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10340. );
  10341. }
  10342. return this;
  10343. };
  10344. /**
  10345. * Walk over the tree of JS snippets in this node and its children. The
  10346. * walking function is called once for each snippet of JS and is passed that
  10347. * snippet and the its original associated source's line/column location.
  10348. *
  10349. * @param aFn The traversal function.
  10350. */
  10351. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10352. var chunk;
  10353. for (var i = 0, len = this.children.length; i < len; i++) {
  10354. chunk = this.children[i];
  10355. if (chunk[isSourceNode]) {
  10356. chunk.walk(aFn);
  10357. }
  10358. else {
  10359. if (chunk !== '') {
  10360. aFn(chunk, { source: this.source,
  10361. line: this.line,
  10362. column: this.column,
  10363. name: this.name });
  10364. }
  10365. }
  10366. }
  10367. };
  10368. /**
  10369. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10370. * each of `this.children`.
  10371. *
  10372. * @param aSep The separator.
  10373. */
  10374. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10375. var newChildren;
  10376. var i;
  10377. var len = this.children.length;
  10378. if (len > 0) {
  10379. newChildren = [];
  10380. for (i = 0; i < len-1; i++) {
  10381. newChildren.push(this.children[i]);
  10382. newChildren.push(aSep);
  10383. }
  10384. newChildren.push(this.children[i]);
  10385. this.children = newChildren;
  10386. }
  10387. return this;
  10388. };
  10389. /**
  10390. * Call String.prototype.replace on the very right-most source snippet. Useful
  10391. * for trimming whitespace from the end of a source node, etc.
  10392. *
  10393. * @param aPattern The pattern to replace.
  10394. * @param aReplacement The thing to replace the pattern with.
  10395. */
  10396. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10397. var lastChild = this.children[this.children.length - 1];
  10398. if (lastChild[isSourceNode]) {
  10399. lastChild.replaceRight(aPattern, aReplacement);
  10400. }
  10401. else if (typeof lastChild === 'string') {
  10402. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10403. }
  10404. else {
  10405. this.children.push(''.replace(aPattern, aReplacement));
  10406. }
  10407. return this;
  10408. };
  10409. /**
  10410. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10411. * in the sourcesContent field.
  10412. *
  10413. * @param aSourceFile The filename of the source file
  10414. * @param aSourceContent The content of the source file
  10415. */
  10416. SourceNode.prototype.setSourceContent =
  10417. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10418. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10419. };
  10420. /**
  10421. * Walk over the tree of SourceNodes. The walking function is called for each
  10422. * source file content and is passed the filename and source content.
  10423. *
  10424. * @param aFn The traversal function.
  10425. */
  10426. SourceNode.prototype.walkSourceContents =
  10427. function SourceNode_walkSourceContents(aFn) {
  10428. for (var i = 0, len = this.children.length; i < len; i++) {
  10429. if (this.children[i][isSourceNode]) {
  10430. this.children[i].walkSourceContents(aFn);
  10431. }
  10432. }
  10433. var sources = Object.keys(this.sourceContents);
  10434. for (var i = 0, len = sources.length; i < len; i++) {
  10435. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10436. }
  10437. };
  10438. /**
  10439. * Return the string representation of this source node. Walks over the tree
  10440. * and concatenates all the various snippets together to one string.
  10441. */
  10442. SourceNode.prototype.toString = function SourceNode_toString() {
  10443. var str = "";
  10444. this.walk(function (chunk) {
  10445. str += chunk;
  10446. });
  10447. return str;
  10448. };
  10449. /**
  10450. * Returns the string representation of this source node along with a source
  10451. * map.
  10452. */
  10453. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10454. var generated = {
  10455. code: "",
  10456. line: 1,
  10457. column: 0
  10458. };
  10459. var map = new SourceMapGenerator(aArgs);
  10460. var sourceMappingActive = false;
  10461. var lastOriginalSource = null;
  10462. var lastOriginalLine = null;
  10463. var lastOriginalColumn = null;
  10464. var lastOriginalName = null;
  10465. this.walk(function (chunk, original) {
  10466. generated.code += chunk;
  10467. if (original.source !== null
  10468. && original.line !== null
  10469. && original.column !== null) {
  10470. if(lastOriginalSource !== original.source
  10471. || lastOriginalLine !== original.line
  10472. || lastOriginalColumn !== original.column
  10473. || lastOriginalName !== original.name) {
  10474. map.addMapping({
  10475. source: original.source,
  10476. original: {
  10477. line: original.line,
  10478. column: original.column
  10479. },
  10480. generated: {
  10481. line: generated.line,
  10482. column: generated.column
  10483. },
  10484. name: original.name
  10485. });
  10486. }
  10487. lastOriginalSource = original.source;
  10488. lastOriginalLine = original.line;
  10489. lastOriginalColumn = original.column;
  10490. lastOriginalName = original.name;
  10491. sourceMappingActive = true;
  10492. } else if (sourceMappingActive) {
  10493. map.addMapping({
  10494. generated: {
  10495. line: generated.line,
  10496. column: generated.column
  10497. }
  10498. });
  10499. lastOriginalSource = null;
  10500. sourceMappingActive = false;
  10501. }
  10502. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10503. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10504. generated.line++;
  10505. generated.column = 0;
  10506. // Mappings end at eol
  10507. if (idx + 1 === length) {
  10508. lastOriginalSource = null;
  10509. sourceMappingActive = false;
  10510. } else if (sourceMappingActive) {
  10511. map.addMapping({
  10512. source: original.source,
  10513. original: {
  10514. line: original.line,
  10515. column: original.column
  10516. },
  10517. generated: {
  10518. line: generated.line,
  10519. column: generated.column
  10520. },
  10521. name: original.name
  10522. });
  10523. }
  10524. } else {
  10525. generated.column++;
  10526. }
  10527. }
  10528. });
  10529. this.walkSourceContents(function (sourceFile, sourceContent) {
  10530. map.setSourceContent(sourceFile, sourceContent);
  10531. });
  10532. return { code: generated.code, map: map };
  10533. };
  10534. sourceNode.SourceNode = SourceNode;
  10535. return sourceNode;
  10536. }
  10537. /*
  10538. * Copyright 2009-2011 Mozilla Foundation and contributors
  10539. * Licensed under the New BSD license. See LICENSE.txt or:
  10540. * http://opensource.org/licenses/BSD-3-Clause
  10541. */
  10542. var hasRequiredSourceMap;
  10543. function requireSourceMap () {
  10544. if (hasRequiredSourceMap) return sourceMap;
  10545. hasRequiredSourceMap = 1;
  10546. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10547. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10548. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10549. return sourceMap;
  10550. }
  10551. var mergeSourceMap;
  10552. var hasRequiredMergeSourceMap;
  10553. function requireMergeSourceMap () {
  10554. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10555. hasRequiredMergeSourceMap = 1;
  10556. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10557. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10558. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10559. mergeSourceMap = merge;
  10560. /**
  10561. * Merge old source map and new source map and return merged.
  10562. * If old or new source map value is falsy, return another one as it is.
  10563. *
  10564. * @param {object|string} [oldMap] old source map object
  10565. * @param {object|string} [newmap] new source map object
  10566. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10567. */
  10568. function merge(oldMap, newMap) {
  10569. if (!oldMap) return newMap
  10570. if (!newMap) return oldMap
  10571. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10572. var newMapConsumer = new SourceMapConsumer(newMap);
  10573. var mergedMapGenerator = new SourceMapGenerator();
  10574. // iterate on new map and overwrite original position of new map with one of old map
  10575. newMapConsumer.eachMapping(function(m) {
  10576. // pass when `originalLine` is null.
  10577. // It occurs in case that the node does not have origin in original code.
  10578. if (m.originalLine == null) return
  10579. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10580. line: m.originalLine,
  10581. column: m.originalColumn
  10582. });
  10583. if (origPosInOldMap.source == null) return
  10584. mergedMapGenerator.addMapping({
  10585. original: {
  10586. line: origPosInOldMap.line,
  10587. column: origPosInOldMap.column
  10588. },
  10589. generated: {
  10590. line: m.generatedLine,
  10591. column: m.generatedColumn
  10592. },
  10593. source: origPosInOldMap.source,
  10594. name: origPosInOldMap.name
  10595. });
  10596. });
  10597. var consumers = [oldMapConsumer, newMapConsumer];
  10598. consumers.forEach(function(consumer) {
  10599. consumer.sources.forEach(function(sourceFile) {
  10600. mergedMapGenerator._sources.add(sourceFile);
  10601. var sourceContent = consumer.sourceContentFor(sourceFile);
  10602. if (sourceContent != null) {
  10603. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10604. }
  10605. });
  10606. });
  10607. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10608. mergedMapGenerator._file = oldMap.file;
  10609. return JSON.parse(mergedMapGenerator.toString())
  10610. }
  10611. return mergeSourceMap;
  10612. }
  10613. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10614. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10615. const scss = (source, map, options, load = require) => {
  10616. const nodeSass = load("sass");
  10617. const { compileString, renderSync } = nodeSass;
  10618. const data = getSource(source, options.filename, options.additionalData);
  10619. let css;
  10620. let dependencies;
  10621. let sourceMap;
  10622. try {
  10623. if (compileString) {
  10624. const { pathToFileURL, fileURLToPath } = load("url");
  10625. const result = compileString(data, {
  10626. ...options,
  10627. url: pathToFileURL(options.filename),
  10628. sourceMap: !!map
  10629. });
  10630. css = result.css;
  10631. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10632. sourceMap = map ? result.sourceMap : void 0;
  10633. } else {
  10634. const result = renderSync({
  10635. ...options,
  10636. data,
  10637. file: options.filename,
  10638. outFile: options.filename,
  10639. sourceMap: !!map
  10640. });
  10641. css = result.css.toString();
  10642. dependencies = result.stats.includedFiles;
  10643. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10644. }
  10645. if (map) {
  10646. return {
  10647. code: css,
  10648. errors: [],
  10649. dependencies,
  10650. map: merge(map, sourceMap)
  10651. };
  10652. }
  10653. return { code: css, errors: [], dependencies };
  10654. } catch (e) {
  10655. return { code: "", errors: [e], dependencies: [] };
  10656. }
  10657. };
  10658. const sass = (source, map, options, load) => scss(
  10659. source,
  10660. map,
  10661. {
  10662. ...options,
  10663. indentedSyntax: true
  10664. },
  10665. load
  10666. );
  10667. const less = (source, map, options, load = require) => {
  10668. const nodeLess = load("less");
  10669. let result;
  10670. let error = null;
  10671. nodeLess.render(
  10672. getSource(source, options.filename, options.additionalData),
  10673. { ...options, syncImport: true },
  10674. (err, output) => {
  10675. error = err;
  10676. result = output;
  10677. }
  10678. );
  10679. if (error) return { code: "", errors: [error], dependencies: [] };
  10680. const dependencies = result.imports;
  10681. if (map) {
  10682. return {
  10683. code: result.css.toString(),
  10684. map: merge(map, result.map),
  10685. errors: [],
  10686. dependencies
  10687. };
  10688. }
  10689. return {
  10690. code: result.css.toString(),
  10691. errors: [],
  10692. dependencies
  10693. };
  10694. };
  10695. const styl = (source, map, options, load = require) => {
  10696. const nodeStylus = load("stylus");
  10697. try {
  10698. const ref = nodeStylus(source, options);
  10699. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10700. const result = ref.render();
  10701. const dependencies = ref.deps();
  10702. if (map) {
  10703. return {
  10704. code: result,
  10705. map: merge(map, ref.sourcemap),
  10706. errors: [],
  10707. dependencies
  10708. };
  10709. }
  10710. return { code: result, errors: [], dependencies };
  10711. } catch (e) {
  10712. return { code: "", errors: [e], dependencies: [] };
  10713. }
  10714. };
  10715. function getSource(source, filename, additionalData) {
  10716. if (!additionalData) return source;
  10717. if (shared.isFunction(additionalData)) {
  10718. return additionalData(source, filename);
  10719. }
  10720. return additionalData + source;
  10721. }
  10722. const processors = {
  10723. less,
  10724. sass,
  10725. scss,
  10726. styl,
  10727. stylus: styl
  10728. };
  10729. var build = {exports: {}};
  10730. var fs = {};
  10731. var hasRequiredFs;
  10732. function requireFs () {
  10733. if (hasRequiredFs) return fs;
  10734. hasRequiredFs = 1;
  10735. Object.defineProperty(fs, "__esModule", {
  10736. value: true
  10737. });
  10738. fs.getFileSystem = getFileSystem;
  10739. fs.setFileSystem = setFileSystem;
  10740. let fileSystem = {
  10741. readFile: () => {
  10742. throw Error("readFile not implemented");
  10743. },
  10744. writeFile: () => {
  10745. throw Error("writeFile not implemented");
  10746. }
  10747. };
  10748. function setFileSystem(fs) {
  10749. fileSystem.readFile = fs.readFile;
  10750. fileSystem.writeFile = fs.writeFile;
  10751. }
  10752. function getFileSystem() {
  10753. return fileSystem;
  10754. }
  10755. return fs;
  10756. }
  10757. var pluginFactory = {};
  10758. var unquote = {};
  10759. var hasRequiredUnquote;
  10760. function requireUnquote () {
  10761. if (hasRequiredUnquote) return unquote;
  10762. hasRequiredUnquote = 1;
  10763. Object.defineProperty(unquote, "__esModule", {
  10764. value: true
  10765. });
  10766. unquote.default = unquote$1;
  10767. // copied from https://github.com/lakenen/node-unquote
  10768. const reg = /['"]/;
  10769. function unquote$1(str) {
  10770. if (!str) {
  10771. return "";
  10772. }
  10773. if (reg.test(str.charAt(0))) {
  10774. str = str.substr(1);
  10775. }
  10776. if (reg.test(str.charAt(str.length - 1))) {
  10777. str = str.substr(0, str.length - 1);
  10778. }
  10779. return str;
  10780. }
  10781. return unquote;
  10782. }
  10783. var Parser = {};
  10784. var replaceValueSymbols_1;
  10785. var hasRequiredReplaceValueSymbols;
  10786. function requireReplaceValueSymbols () {
  10787. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10788. hasRequiredReplaceValueSymbols = 1;
  10789. const matchValueName = /[$]?[\w-]+/g;
  10790. const replaceValueSymbols = (value, replacements) => {
  10791. let matches;
  10792. while ((matches = matchValueName.exec(value))) {
  10793. const replacement = replacements[matches[0]];
  10794. if (replacement) {
  10795. value =
  10796. value.slice(0, matches.index) +
  10797. replacement +
  10798. value.slice(matchValueName.lastIndex);
  10799. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10800. }
  10801. }
  10802. return value;
  10803. };
  10804. replaceValueSymbols_1 = replaceValueSymbols;
  10805. return replaceValueSymbols_1;
  10806. }
  10807. var replaceSymbols_1;
  10808. var hasRequiredReplaceSymbols;
  10809. function requireReplaceSymbols () {
  10810. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10811. hasRequiredReplaceSymbols = 1;
  10812. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10813. const replaceSymbols = (css, replacements) => {
  10814. css.walk((node) => {
  10815. if (node.type === "decl" && node.value) {
  10816. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10817. } else if (node.type === "rule" && node.selector) {
  10818. node.selector = replaceValueSymbols(
  10819. node.selector.toString(),
  10820. replacements
  10821. );
  10822. } else if (node.type === "atrule" && node.params) {
  10823. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10824. }
  10825. });
  10826. };
  10827. replaceSymbols_1 = replaceSymbols;
  10828. return replaceSymbols_1;
  10829. }
  10830. var extractICSS_1;
  10831. var hasRequiredExtractICSS;
  10832. function requireExtractICSS () {
  10833. if (hasRequiredExtractICSS) return extractICSS_1;
  10834. hasRequiredExtractICSS = 1;
  10835. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10836. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10837. const getDeclsObject = (rule) => {
  10838. const object = {};
  10839. rule.walkDecls((decl) => {
  10840. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10841. object[before + decl.prop] = decl.value;
  10842. });
  10843. return object;
  10844. };
  10845. /**
  10846. *
  10847. * @param {string} css
  10848. * @param {boolean} removeRules
  10849. * @param {'auto' | 'rule' | 'at-rule'} mode
  10850. */
  10851. const extractICSS = (css, removeRules = true, mode = "auto") => {
  10852. const icssImports = {};
  10853. const icssExports = {};
  10854. function addImports(node, path) {
  10855. const unquoted = path.replace(/'|"/g, "");
  10856. icssImports[unquoted] = Object.assign(
  10857. icssImports[unquoted] || {},
  10858. getDeclsObject(node)
  10859. );
  10860. if (removeRules) {
  10861. node.remove();
  10862. }
  10863. }
  10864. function addExports(node) {
  10865. Object.assign(icssExports, getDeclsObject(node));
  10866. if (removeRules) {
  10867. node.remove();
  10868. }
  10869. }
  10870. css.each((node) => {
  10871. if (node.type === "rule" && mode !== "at-rule") {
  10872. if (node.selector.slice(0, 7) === ":import") {
  10873. const matches = importPattern.exec(node.selector);
  10874. if (matches) {
  10875. addImports(node, matches[1]);
  10876. }
  10877. }
  10878. if (node.selector === ":export") {
  10879. addExports(node);
  10880. }
  10881. }
  10882. if (node.type === "atrule" && mode !== "rule") {
  10883. if (node.name === "icss-import") {
  10884. const matches = balancedQuotes.exec(node.params);
  10885. if (matches) {
  10886. addImports(node, matches[1]);
  10887. }
  10888. }
  10889. if (node.name === "icss-export") {
  10890. addExports(node);
  10891. }
  10892. }
  10893. });
  10894. return { icssImports, icssExports };
  10895. };
  10896. extractICSS_1 = extractICSS;
  10897. return extractICSS_1;
  10898. }
  10899. var createICSSRules_1;
  10900. var hasRequiredCreateICSSRules;
  10901. function requireCreateICSSRules () {
  10902. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  10903. hasRequiredCreateICSSRules = 1;
  10904. const createImports = (imports, postcss, mode = "rule") => {
  10905. return Object.keys(imports).map((path) => {
  10906. const aliases = imports[path];
  10907. const declarations = Object.keys(aliases).map((key) =>
  10908. postcss.decl({
  10909. prop: key,
  10910. value: aliases[key],
  10911. raws: { before: "\n " },
  10912. })
  10913. );
  10914. const hasDeclarations = declarations.length > 0;
  10915. const rule =
  10916. mode === "rule"
  10917. ? postcss.rule({
  10918. selector: `:import('${path}')`,
  10919. raws: { after: hasDeclarations ? "\n" : "" },
  10920. })
  10921. : postcss.atRule({
  10922. name: "icss-import",
  10923. params: `'${path}'`,
  10924. raws: { after: hasDeclarations ? "\n" : "" },
  10925. });
  10926. if (hasDeclarations) {
  10927. rule.append(declarations);
  10928. }
  10929. return rule;
  10930. });
  10931. };
  10932. const createExports = (exports, postcss, mode = "rule") => {
  10933. const declarations = Object.keys(exports).map((key) =>
  10934. postcss.decl({
  10935. prop: key,
  10936. value: exports[key],
  10937. raws: { before: "\n " },
  10938. })
  10939. );
  10940. if (declarations.length === 0) {
  10941. return [];
  10942. }
  10943. const rule =
  10944. mode === "rule"
  10945. ? postcss.rule({
  10946. selector: `:export`,
  10947. raws: { after: "\n" },
  10948. })
  10949. : postcss.atRule({
  10950. name: "icss-export",
  10951. raws: { after: "\n" },
  10952. });
  10953. rule.append(declarations);
  10954. return [rule];
  10955. };
  10956. const createICSSRules = (imports, exports, postcss, mode) => [
  10957. ...createImports(imports, postcss, mode),
  10958. ...createExports(exports, postcss, mode),
  10959. ];
  10960. createICSSRules_1 = createICSSRules;
  10961. return createICSSRules_1;
  10962. }
  10963. var src$4;
  10964. var hasRequiredSrc$4;
  10965. function requireSrc$4 () {
  10966. if (hasRequiredSrc$4) return src$4;
  10967. hasRequiredSrc$4 = 1;
  10968. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10969. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  10970. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  10971. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  10972. src$4 = {
  10973. replaceValueSymbols,
  10974. replaceSymbols,
  10975. extractICSS,
  10976. createICSSRules,
  10977. };
  10978. return src$4;
  10979. }
  10980. var hasRequiredParser$1;
  10981. function requireParser$1 () {
  10982. if (hasRequiredParser$1) return Parser;
  10983. hasRequiredParser$1 = 1;
  10984. Object.defineProperty(Parser, "__esModule", {
  10985. value: true
  10986. });
  10987. Parser.default = void 0;
  10988. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  10989. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  10990. const importRegexp = /^:import\((.+)\)$/;
  10991. let Parser$1 = class Parser {
  10992. constructor(pathFetcher, trace) {
  10993. this.pathFetcher = pathFetcher;
  10994. this.plugin = this.plugin.bind(this);
  10995. this.exportTokens = {};
  10996. this.translations = {};
  10997. this.trace = trace;
  10998. }
  10999. plugin() {
  11000. const parser = this;
  11001. return {
  11002. postcssPlugin: "css-modules-parser",
  11003. async OnceExit(css) {
  11004. await Promise.all(parser.fetchAllImports(css));
  11005. parser.linkImportedSymbols(css);
  11006. return parser.extractExports(css);
  11007. }
  11008. };
  11009. }
  11010. fetchAllImports(css) {
  11011. let imports = [];
  11012. css.each(node => {
  11013. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11014. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11015. }
  11016. });
  11017. return imports;
  11018. }
  11019. linkImportedSymbols(css) {
  11020. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11021. }
  11022. extractExports(css) {
  11023. css.each(node => {
  11024. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11025. });
  11026. }
  11027. handleExport(exportNode) {
  11028. exportNode.each(decl => {
  11029. if (decl.type == "decl") {
  11030. Object.keys(this.translations).forEach(translation => {
  11031. decl.value = decl.value.replace(translation, this.translations[translation]);
  11032. });
  11033. this.exportTokens[decl.prop] = decl.value;
  11034. }
  11035. });
  11036. exportNode.remove();
  11037. }
  11038. async fetchImport(importNode, relativeTo, depNr) {
  11039. const file = importNode.selector.match(importRegexp)[1];
  11040. const depTrace = this.trace + String.fromCharCode(depNr);
  11041. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  11042. try {
  11043. importNode.each(decl => {
  11044. if (decl.type == "decl") {
  11045. this.translations[decl.prop] = exports[decl.value];
  11046. }
  11047. });
  11048. importNode.remove();
  11049. } catch (err) {
  11050. console.log(err);
  11051. }
  11052. }
  11053. };
  11054. Parser.default = Parser$1;
  11055. return Parser;
  11056. }
  11057. var saveJSON = {};
  11058. var hasRequiredSaveJSON;
  11059. function requireSaveJSON () {
  11060. if (hasRequiredSaveJSON) return saveJSON;
  11061. hasRequiredSaveJSON = 1;
  11062. Object.defineProperty(saveJSON, "__esModule", {
  11063. value: true
  11064. });
  11065. saveJSON.default = saveJSON$1;
  11066. var _fs = /*@__PURE__*/ requireFs();
  11067. function saveJSON$1(cssFile, json) {
  11068. return new Promise((resolve, reject) => {
  11069. const {
  11070. writeFile
  11071. } = (0, _fs.getFileSystem)();
  11072. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11073. });
  11074. }
  11075. return saveJSON;
  11076. }
  11077. var localsConvention = {};
  11078. /**
  11079. * lodash (Custom Build) <https://lodash.com/>
  11080. * Build: `lodash modularize exports="npm" -o ./`
  11081. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11082. * Released under MIT license <https://lodash.com/license>
  11083. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11084. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11085. */
  11086. var lodash_camelcase;
  11087. var hasRequiredLodash_camelcase;
  11088. function requireLodash_camelcase () {
  11089. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11090. hasRequiredLodash_camelcase = 1;
  11091. /** `Object#toString` result references. */
  11092. var symbolTag = '[object Symbol]';
  11093. /** Used to match words composed of alphanumeric characters. */
  11094. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11095. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11096. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11097. /** Used to compose unicode character classes. */
  11098. var rsAstralRange = '\\ud800-\\udfff',
  11099. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11100. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11101. rsDingbatRange = '\\u2700-\\u27bf',
  11102. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11103. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11104. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11105. rsPunctuationRange = '\\u2000-\\u206f',
  11106. 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',
  11107. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11108. rsVarRange = '\\ufe0e\\ufe0f',
  11109. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11110. /** Used to compose unicode capture groups. */
  11111. var rsApos = "['\u2019]",
  11112. rsAstral = '[' + rsAstralRange + ']',
  11113. rsBreak = '[' + rsBreakRange + ']',
  11114. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11115. rsDigits = '\\d+',
  11116. rsDingbat = '[' + rsDingbatRange + ']',
  11117. rsLower = '[' + rsLowerRange + ']',
  11118. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11119. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11120. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11121. rsNonAstral = '[^' + rsAstralRange + ']',
  11122. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11123. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11124. rsUpper = '[' + rsUpperRange + ']',
  11125. rsZWJ = '\\u200d';
  11126. /** Used to compose unicode regexes. */
  11127. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11128. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11129. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11130. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11131. reOptMod = rsModifier + '?',
  11132. rsOptVar = '[' + rsVarRange + ']?',
  11133. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11134. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11135. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11136. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11137. /** Used to match apostrophes. */
  11138. var reApos = RegExp(rsApos, 'g');
  11139. /**
  11140. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11141. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11142. */
  11143. var reComboMark = RegExp(rsCombo, 'g');
  11144. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11145. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11146. /** Used to match complex or compound words. */
  11147. var reUnicodeWord = RegExp([
  11148. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11149. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11150. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11151. rsUpper + '+' + rsOptUpperContr,
  11152. rsDigits,
  11153. rsEmoji
  11154. ].join('|'), 'g');
  11155. /** 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/). */
  11156. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11157. /** Used to detect strings that need a more robust regexp to match words. */
  11158. 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 ]/;
  11159. /** Used to map Latin Unicode letters to basic Latin letters. */
  11160. var deburredLetters = {
  11161. // Latin-1 Supplement block.
  11162. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11163. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11164. '\xc7': 'C', '\xe7': 'c',
  11165. '\xd0': 'D', '\xf0': 'd',
  11166. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11167. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11168. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11169. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11170. '\xd1': 'N', '\xf1': 'n',
  11171. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11172. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11173. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11174. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11175. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11176. '\xc6': 'Ae', '\xe6': 'ae',
  11177. '\xde': 'Th', '\xfe': 'th',
  11178. '\xdf': 'ss',
  11179. // Latin Extended-A block.
  11180. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11181. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11182. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11183. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11184. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11185. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11186. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11187. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11188. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11189. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11190. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11191. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11192. '\u0134': 'J', '\u0135': 'j',
  11193. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11194. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11195. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11196. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11197. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11198. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11199. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11200. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11201. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11202. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11203. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11204. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11205. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11206. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11207. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11208. '\u0174': 'W', '\u0175': 'w',
  11209. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11210. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11211. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11212. '\u0132': 'IJ', '\u0133': 'ij',
  11213. '\u0152': 'Oe', '\u0153': 'oe',
  11214. '\u0149': "'n", '\u017f': 'ss'
  11215. };
  11216. /** Detect free variable `global` from Node.js. */
  11217. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11218. /** Detect free variable `self`. */
  11219. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11220. /** Used as a reference to the global object. */
  11221. var root = freeGlobal || freeSelf || Function('return this')();
  11222. /**
  11223. * A specialized version of `_.reduce` for arrays without support for
  11224. * iteratee shorthands.
  11225. *
  11226. * @private
  11227. * @param {Array} [array] The array to iterate over.
  11228. * @param {Function} iteratee The function invoked per iteration.
  11229. * @param {*} [accumulator] The initial value.
  11230. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11231. * the initial value.
  11232. * @returns {*} Returns the accumulated value.
  11233. */
  11234. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11235. var index = -1,
  11236. length = array ? array.length : 0;
  11237. while (++index < length) {
  11238. accumulator = iteratee(accumulator, array[index], index, array);
  11239. }
  11240. return accumulator;
  11241. }
  11242. /**
  11243. * Converts an ASCII `string` to an array.
  11244. *
  11245. * @private
  11246. * @param {string} string The string to convert.
  11247. * @returns {Array} Returns the converted array.
  11248. */
  11249. function asciiToArray(string) {
  11250. return string.split('');
  11251. }
  11252. /**
  11253. * Splits an ASCII `string` into an array of its words.
  11254. *
  11255. * @private
  11256. * @param {string} The string to inspect.
  11257. * @returns {Array} Returns the words of `string`.
  11258. */
  11259. function asciiWords(string) {
  11260. return string.match(reAsciiWord) || [];
  11261. }
  11262. /**
  11263. * The base implementation of `_.propertyOf` without support for deep paths.
  11264. *
  11265. * @private
  11266. * @param {Object} object The object to query.
  11267. * @returns {Function} Returns the new accessor function.
  11268. */
  11269. function basePropertyOf(object) {
  11270. return function(key) {
  11271. return object == null ? undefined : object[key];
  11272. };
  11273. }
  11274. /**
  11275. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11276. * letters to basic Latin letters.
  11277. *
  11278. * @private
  11279. * @param {string} letter The matched letter to deburr.
  11280. * @returns {string} Returns the deburred letter.
  11281. */
  11282. var deburrLetter = basePropertyOf(deburredLetters);
  11283. /**
  11284. * Checks if `string` contains Unicode symbols.
  11285. *
  11286. * @private
  11287. * @param {string} string The string to inspect.
  11288. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11289. */
  11290. function hasUnicode(string) {
  11291. return reHasUnicode.test(string);
  11292. }
  11293. /**
  11294. * Checks if `string` contains a word composed of Unicode symbols.
  11295. *
  11296. * @private
  11297. * @param {string} string The string to inspect.
  11298. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11299. */
  11300. function hasUnicodeWord(string) {
  11301. return reHasUnicodeWord.test(string);
  11302. }
  11303. /**
  11304. * Converts `string` to an array.
  11305. *
  11306. * @private
  11307. * @param {string} string The string to convert.
  11308. * @returns {Array} Returns the converted array.
  11309. */
  11310. function stringToArray(string) {
  11311. return hasUnicode(string)
  11312. ? unicodeToArray(string)
  11313. : asciiToArray(string);
  11314. }
  11315. /**
  11316. * Converts a Unicode `string` to an array.
  11317. *
  11318. * @private
  11319. * @param {string} string The string to convert.
  11320. * @returns {Array} Returns the converted array.
  11321. */
  11322. function unicodeToArray(string) {
  11323. return string.match(reUnicode) || [];
  11324. }
  11325. /**
  11326. * Splits a Unicode `string` into an array of its words.
  11327. *
  11328. * @private
  11329. * @param {string} The string to inspect.
  11330. * @returns {Array} Returns the words of `string`.
  11331. */
  11332. function unicodeWords(string) {
  11333. return string.match(reUnicodeWord) || [];
  11334. }
  11335. /** Used for built-in method references. */
  11336. var objectProto = Object.prototype;
  11337. /**
  11338. * Used to resolve the
  11339. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11340. * of values.
  11341. */
  11342. var objectToString = objectProto.toString;
  11343. /** Built-in value references. */
  11344. var Symbol = root.Symbol;
  11345. /** Used to convert symbols to primitives and strings. */
  11346. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11347. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11348. /**
  11349. * The base implementation of `_.slice` without an iteratee call guard.
  11350. *
  11351. * @private
  11352. * @param {Array} array The array to slice.
  11353. * @param {number} [start=0] The start position.
  11354. * @param {number} [end=array.length] The end position.
  11355. * @returns {Array} Returns the slice of `array`.
  11356. */
  11357. function baseSlice(array, start, end) {
  11358. var index = -1,
  11359. length = array.length;
  11360. if (start < 0) {
  11361. start = -start > length ? 0 : (length + start);
  11362. }
  11363. end = end > length ? length : end;
  11364. if (end < 0) {
  11365. end += length;
  11366. }
  11367. length = start > end ? 0 : ((end - start) >>> 0);
  11368. start >>>= 0;
  11369. var result = Array(length);
  11370. while (++index < length) {
  11371. result[index] = array[index + start];
  11372. }
  11373. return result;
  11374. }
  11375. /**
  11376. * The base implementation of `_.toString` which doesn't convert nullish
  11377. * values to empty strings.
  11378. *
  11379. * @private
  11380. * @param {*} value The value to process.
  11381. * @returns {string} Returns the string.
  11382. */
  11383. function baseToString(value) {
  11384. // Exit early for strings to avoid a performance hit in some environments.
  11385. if (typeof value == 'string') {
  11386. return value;
  11387. }
  11388. if (isSymbol(value)) {
  11389. return symbolToString ? symbolToString.call(value) : '';
  11390. }
  11391. var result = (value + '');
  11392. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  11393. }
  11394. /**
  11395. * Casts `array` to a slice if it's needed.
  11396. *
  11397. * @private
  11398. * @param {Array} array The array to inspect.
  11399. * @param {number} start The start position.
  11400. * @param {number} [end=array.length] The end position.
  11401. * @returns {Array} Returns the cast slice.
  11402. */
  11403. function castSlice(array, start, end) {
  11404. var length = array.length;
  11405. end = end === undefined ? length : end;
  11406. return (false && end >= length) ? array : baseSlice(array, start, end);
  11407. }
  11408. /**
  11409. * Creates a function like `_.lowerFirst`.
  11410. *
  11411. * @private
  11412. * @param {string} methodName The name of the `String` case method to use.
  11413. * @returns {Function} Returns the new case function.
  11414. */
  11415. function createCaseFirst(methodName) {
  11416. return function(string) {
  11417. string = toString(string);
  11418. var strSymbols = hasUnicode(string)
  11419. ? stringToArray(string)
  11420. : undefined;
  11421. var chr = strSymbols
  11422. ? strSymbols[0]
  11423. : string.charAt(0);
  11424. var trailing = strSymbols
  11425. ? castSlice(strSymbols, 1).join('')
  11426. : string.slice(1);
  11427. return chr[methodName]() + trailing;
  11428. };
  11429. }
  11430. /**
  11431. * Creates a function like `_.camelCase`.
  11432. *
  11433. * @private
  11434. * @param {Function} callback The function to combine each word.
  11435. * @returns {Function} Returns the new compounder function.
  11436. */
  11437. function createCompounder(callback) {
  11438. return function(string) {
  11439. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11440. };
  11441. }
  11442. /**
  11443. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11444. * and has a `typeof` result of "object".
  11445. *
  11446. * @static
  11447. * @memberOf _
  11448. * @since 4.0.0
  11449. * @category Lang
  11450. * @param {*} value The value to check.
  11451. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11452. * @example
  11453. *
  11454. * _.isObjectLike({});
  11455. * // => true
  11456. *
  11457. * _.isObjectLike([1, 2, 3]);
  11458. * // => true
  11459. *
  11460. * _.isObjectLike(_.noop);
  11461. * // => false
  11462. *
  11463. * _.isObjectLike(null);
  11464. * // => false
  11465. */
  11466. function isObjectLike(value) {
  11467. return !!value && typeof value == 'object';
  11468. }
  11469. /**
  11470. * Checks if `value` is classified as a `Symbol` primitive or object.
  11471. *
  11472. * @static
  11473. * @memberOf _
  11474. * @since 4.0.0
  11475. * @category Lang
  11476. * @param {*} value The value to check.
  11477. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11478. * @example
  11479. *
  11480. * _.isSymbol(Symbol.iterator);
  11481. * // => true
  11482. *
  11483. * _.isSymbol('abc');
  11484. * // => false
  11485. */
  11486. function isSymbol(value) {
  11487. return typeof value == 'symbol' ||
  11488. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11489. }
  11490. /**
  11491. * Converts `value` to a string. An empty string is returned for `null`
  11492. * and `undefined` values. The sign of `-0` is preserved.
  11493. *
  11494. * @static
  11495. * @memberOf _
  11496. * @since 4.0.0
  11497. * @category Lang
  11498. * @param {*} value The value to process.
  11499. * @returns {string} Returns the string.
  11500. * @example
  11501. *
  11502. * _.toString(null);
  11503. * // => ''
  11504. *
  11505. * _.toString(-0);
  11506. * // => '-0'
  11507. *
  11508. * _.toString([1, 2, 3]);
  11509. * // => '1,2,3'
  11510. */
  11511. function toString(value) {
  11512. return value == null ? '' : baseToString(value);
  11513. }
  11514. /**
  11515. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11516. *
  11517. * @static
  11518. * @memberOf _
  11519. * @since 3.0.0
  11520. * @category String
  11521. * @param {string} [string=''] The string to convert.
  11522. * @returns {string} Returns the camel cased string.
  11523. * @example
  11524. *
  11525. * _.camelCase('Foo Bar');
  11526. * // => 'fooBar'
  11527. *
  11528. * _.camelCase('--foo-bar--');
  11529. * // => 'fooBar'
  11530. *
  11531. * _.camelCase('__FOO_BAR__');
  11532. * // => 'fooBar'
  11533. */
  11534. var camelCase = createCompounder(function(result, word, index) {
  11535. word = word.toLowerCase();
  11536. return result + (index ? capitalize(word) : word);
  11537. });
  11538. /**
  11539. * Converts the first character of `string` to upper case and the remaining
  11540. * to lower case.
  11541. *
  11542. * @static
  11543. * @memberOf _
  11544. * @since 3.0.0
  11545. * @category String
  11546. * @param {string} [string=''] The string to capitalize.
  11547. * @returns {string} Returns the capitalized string.
  11548. * @example
  11549. *
  11550. * _.capitalize('FRED');
  11551. * // => 'Fred'
  11552. */
  11553. function capitalize(string) {
  11554. return upperFirst(toString(string).toLowerCase());
  11555. }
  11556. /**
  11557. * Deburrs `string` by converting
  11558. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11559. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11560. * letters to basic Latin letters and removing
  11561. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11562. *
  11563. * @static
  11564. * @memberOf _
  11565. * @since 3.0.0
  11566. * @category String
  11567. * @param {string} [string=''] The string to deburr.
  11568. * @returns {string} Returns the deburred string.
  11569. * @example
  11570. *
  11571. * _.deburr('déjà vu');
  11572. * // => 'deja vu'
  11573. */
  11574. function deburr(string) {
  11575. string = toString(string);
  11576. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11577. }
  11578. /**
  11579. * Converts the first character of `string` to upper case.
  11580. *
  11581. * @static
  11582. * @memberOf _
  11583. * @since 4.0.0
  11584. * @category String
  11585. * @param {string} [string=''] The string to convert.
  11586. * @returns {string} Returns the converted string.
  11587. * @example
  11588. *
  11589. * _.upperFirst('fred');
  11590. * // => 'Fred'
  11591. *
  11592. * _.upperFirst('FRED');
  11593. * // => 'FRED'
  11594. */
  11595. var upperFirst = createCaseFirst('toUpperCase');
  11596. /**
  11597. * Splits `string` into an array of its words.
  11598. *
  11599. * @static
  11600. * @memberOf _
  11601. * @since 3.0.0
  11602. * @category String
  11603. * @param {string} [string=''] The string to inspect.
  11604. * @param {RegExp|string} [pattern] The pattern to match words.
  11605. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11606. * @returns {Array} Returns the words of `string`.
  11607. * @example
  11608. *
  11609. * _.words('fred, barney, & pebbles');
  11610. * // => ['fred', 'barney', 'pebbles']
  11611. *
  11612. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11613. * // => ['fred', 'barney', '&', 'pebbles']
  11614. */
  11615. function words(string, pattern, guard) {
  11616. string = toString(string);
  11617. pattern = pattern;
  11618. if (pattern === undefined) {
  11619. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11620. }
  11621. return string.match(pattern) || [];
  11622. }
  11623. lodash_camelcase = camelCase;
  11624. return lodash_camelcase;
  11625. }
  11626. var hasRequiredLocalsConvention;
  11627. function requireLocalsConvention () {
  11628. if (hasRequiredLocalsConvention) return localsConvention;
  11629. hasRequiredLocalsConvention = 1;
  11630. Object.defineProperty(localsConvention, "__esModule", {
  11631. value: true
  11632. });
  11633. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11634. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11635. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11636. function dashesCamelCase(string) {
  11637. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11638. }
  11639. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11640. const isFunc = typeof localsConvention === "function";
  11641. return (tokens, [className, value]) => {
  11642. if (isFunc) {
  11643. const convention = localsConvention(className, value, inputFile);
  11644. tokens[convention] = value;
  11645. return tokens;
  11646. }
  11647. switch (localsConvention) {
  11648. case "camelCase":
  11649. tokens[className] = value;
  11650. tokens[(0, _lodash.default)(className)] = value;
  11651. break;
  11652. case "camelCaseOnly":
  11653. tokens[(0, _lodash.default)(className)] = value;
  11654. break;
  11655. case "dashes":
  11656. tokens[className] = value;
  11657. tokens[dashesCamelCase(className)] = value;
  11658. break;
  11659. case "dashesOnly":
  11660. tokens[dashesCamelCase(className)] = value;
  11661. break;
  11662. }
  11663. return tokens;
  11664. };
  11665. }
  11666. return localsConvention;
  11667. }
  11668. var FileSystemLoader = {};
  11669. var hasRequiredFileSystemLoader;
  11670. function requireFileSystemLoader () {
  11671. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11672. hasRequiredFileSystemLoader = 1;
  11673. Object.defineProperty(FileSystemLoader, "__esModule", {
  11674. value: true
  11675. });
  11676. FileSystemLoader.default = void 0;
  11677. var _postcss = _interopRequireDefault(require$$0$1);
  11678. var _path = _interopRequireDefault(path$1);
  11679. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  11680. var _fs = /*@__PURE__*/ requireFs();
  11681. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11682. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11683. class Core {
  11684. constructor(plugins) {
  11685. this.plugins = plugins || Core.defaultPlugins;
  11686. }
  11687. async load(sourceString, sourcePath, trace, pathFetcher) {
  11688. const parser = new _Parser.default(pathFetcher, trace);
  11689. const plugins = this.plugins.concat([parser.plugin()]);
  11690. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11691. from: sourcePath
  11692. });
  11693. return {
  11694. injectableSource: result.css,
  11695. exportTokens: parser.exportTokens
  11696. };
  11697. }
  11698. } // Sorts dependencies in the following way:
  11699. // AAA comes before AA and A
  11700. // AB comes after AA and before A
  11701. // All Bs come after all As
  11702. // This ensures that the files are always returned in the following order:
  11703. // - In the order they were required, except
  11704. // - After all their dependencies
  11705. const traceKeySorter = (a, b) => {
  11706. if (a.length < b.length) {
  11707. return a < b.substring(0, a.length) ? -1 : 1;
  11708. }
  11709. if (a.length > b.length) {
  11710. return a.substring(0, b.length) <= b ? -1 : 1;
  11711. }
  11712. return a < b ? -1 : 1;
  11713. };
  11714. let FileSystemLoader$1 = class FileSystemLoader {
  11715. constructor(root, plugins, fileResolve) {
  11716. if (root === "/" && process.platform === "win32") {
  11717. const cwdDrive = process.cwd().slice(0, 3);
  11718. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11719. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11720. }
  11721. root = cwdDrive;
  11722. }
  11723. this.root = root;
  11724. this.fileResolve = fileResolve;
  11725. this.sources = {};
  11726. this.traces = {};
  11727. this.importNr = 0;
  11728. this.core = new Core(plugins);
  11729. this.tokensByFile = {};
  11730. this.fs = (0, _fs.getFileSystem)();
  11731. }
  11732. async fetch(_newPath, relativeTo, _trace) {
  11733. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11734. const trace = _trace || String.fromCharCode(this.importNr++);
  11735. const useFileResolve = typeof this.fileResolve === "function";
  11736. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11737. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11738. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11739. }
  11740. const relativeDir = _path.default.dirname(relativeTo);
  11741. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11742. 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
  11743. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11744. try {
  11745. fileRelativePath = require.resolve(newPath);
  11746. } catch (e) {// noop
  11747. }
  11748. }
  11749. const tokens = this.tokensByFile[fileRelativePath];
  11750. if (tokens) return tokens;
  11751. return new Promise((resolve, reject) => {
  11752. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11753. if (err) reject(err);
  11754. const {
  11755. injectableSource,
  11756. exportTokens
  11757. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11758. this.sources[fileRelativePath] = injectableSource;
  11759. this.traces[trace] = fileRelativePath;
  11760. this.tokensByFile[fileRelativePath] = exportTokens;
  11761. resolve(exportTokens);
  11762. });
  11763. });
  11764. }
  11765. get finalSource() {
  11766. const traces = this.traces;
  11767. const sources = this.sources;
  11768. let written = new Set();
  11769. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11770. const filename = traces[key];
  11771. if (written.has(filename)) {
  11772. return null;
  11773. }
  11774. written.add(filename);
  11775. return sources[filename];
  11776. }).join("");
  11777. }
  11778. };
  11779. FileSystemLoader.default = FileSystemLoader$1;
  11780. return FileSystemLoader;
  11781. }
  11782. var scoping = {};
  11783. var src$3 = {exports: {}};
  11784. var topologicalSort_1;
  11785. var hasRequiredTopologicalSort;
  11786. function requireTopologicalSort () {
  11787. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11788. hasRequiredTopologicalSort = 1;
  11789. const PERMANENT_MARKER = 2;
  11790. const TEMPORARY_MARKER = 1;
  11791. function createError(node, graph) {
  11792. const er = new Error("Nondeterministic import's order");
  11793. const related = graph[node];
  11794. const relatedNode = related.find(
  11795. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11796. );
  11797. er.nodes = [node, relatedNode];
  11798. return er;
  11799. }
  11800. function walkGraph(node, graph, state, result, strict) {
  11801. if (state[node] === PERMANENT_MARKER) {
  11802. return;
  11803. }
  11804. if (state[node] === TEMPORARY_MARKER) {
  11805. if (strict) {
  11806. return createError(node, graph);
  11807. }
  11808. return;
  11809. }
  11810. state[node] = TEMPORARY_MARKER;
  11811. const children = graph[node];
  11812. const length = children.length;
  11813. for (let i = 0; i < length; ++i) {
  11814. const error = walkGraph(children[i], graph, state, result, strict);
  11815. if (error instanceof Error) {
  11816. return error;
  11817. }
  11818. }
  11819. state[node] = PERMANENT_MARKER;
  11820. result.push(node);
  11821. }
  11822. function topologicalSort(graph, strict) {
  11823. const result = [];
  11824. const state = {};
  11825. const nodes = Object.keys(graph);
  11826. const length = nodes.length;
  11827. for (let i = 0; i < length; ++i) {
  11828. const er = walkGraph(nodes[i], graph, state, result, strict);
  11829. if (er instanceof Error) {
  11830. return er;
  11831. }
  11832. }
  11833. return result;
  11834. }
  11835. topologicalSort_1 = topologicalSort;
  11836. return topologicalSort_1;
  11837. }
  11838. var hasRequiredSrc$3;
  11839. function requireSrc$3 () {
  11840. if (hasRequiredSrc$3) return src$3.exports;
  11841. hasRequiredSrc$3 = 1;
  11842. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  11843. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11844. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11845. const VISITED_MARKER = 1;
  11846. /**
  11847. * :import('G') {}
  11848. *
  11849. * Rule
  11850. * composes: ... from 'A'
  11851. * composes: ... from 'B'
  11852. * Rule
  11853. * composes: ... from 'A'
  11854. * composes: ... from 'A'
  11855. * composes: ... from 'C'
  11856. *
  11857. * Results in:
  11858. *
  11859. * graph: {
  11860. * G: [],
  11861. * A: [],
  11862. * B: ['A'],
  11863. * C: ['A'],
  11864. * }
  11865. */
  11866. function addImportToGraph(importId, parentId, graph, visited) {
  11867. const siblingsId = parentId + "_" + "siblings";
  11868. const visitedId = parentId + "_" + importId;
  11869. if (visited[visitedId] !== VISITED_MARKER) {
  11870. if (!Array.isArray(visited[siblingsId])) {
  11871. visited[siblingsId] = [];
  11872. }
  11873. const siblings = visited[siblingsId];
  11874. if (Array.isArray(graph[importId])) {
  11875. graph[importId] = graph[importId].concat(siblings);
  11876. } else {
  11877. graph[importId] = siblings.slice();
  11878. }
  11879. visited[visitedId] = VISITED_MARKER;
  11880. siblings.push(importId);
  11881. }
  11882. }
  11883. src$3.exports = (options = {}) => {
  11884. let importIndex = 0;
  11885. const createImportedName =
  11886. typeof options.createImportedName !== "function"
  11887. ? (importName /*, path*/) =>
  11888. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11889. : options.createImportedName;
  11890. const failOnWrongOrder = options.failOnWrongOrder;
  11891. return {
  11892. postcssPlugin: "postcss-modules-extract-imports",
  11893. prepare() {
  11894. const graph = {};
  11895. const visited = {};
  11896. const existingImports = {};
  11897. const importDecls = {};
  11898. const imports = {};
  11899. return {
  11900. Once(root, postcss) {
  11901. // Check the existing imports order and save refs
  11902. root.walkRules((rule) => {
  11903. const matches = icssImport.exec(rule.selector);
  11904. if (matches) {
  11905. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11906. const importPath = doubleQuotePath || singleQuotePath;
  11907. addImportToGraph(importPath, "root", graph, visited);
  11908. existingImports[importPath] = rule;
  11909. }
  11910. });
  11911. root.walkDecls(/^composes$/, (declaration) => {
  11912. const multiple = declaration.value.split(",");
  11913. const values = [];
  11914. multiple.forEach((value) => {
  11915. const matches = value.trim().match(matchImports);
  11916. if (!matches) {
  11917. values.push(value);
  11918. return;
  11919. }
  11920. let tmpSymbols;
  11921. let [
  11922. ,
  11923. /*match*/ symbols,
  11924. doubleQuotePath,
  11925. singleQuotePath,
  11926. global,
  11927. ] = matches;
  11928. if (global) {
  11929. // Composing globals simply means changing these classes to wrap them in global(name)
  11930. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  11931. } else {
  11932. const importPath = doubleQuotePath || singleQuotePath;
  11933. let parent = declaration.parent;
  11934. let parentIndexes = "";
  11935. while (parent.type !== "root") {
  11936. parentIndexes =
  11937. parent.parent.index(parent) + "_" + parentIndexes;
  11938. parent = parent.parent;
  11939. }
  11940. const { selector } = declaration.parent;
  11941. const parentRule = `_${parentIndexes}${selector}`;
  11942. addImportToGraph(importPath, parentRule, graph, visited);
  11943. importDecls[importPath] = declaration;
  11944. imports[importPath] = imports[importPath] || {};
  11945. tmpSymbols = symbols.split(/\s+/).map((s) => {
  11946. if (!imports[importPath][s]) {
  11947. imports[importPath][s] = createImportedName(s, importPath);
  11948. }
  11949. return imports[importPath][s];
  11950. });
  11951. }
  11952. values.push(tmpSymbols.join(" "));
  11953. });
  11954. declaration.value = values.join(", ");
  11955. });
  11956. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  11957. if (importsOrder instanceof Error) {
  11958. const importPath = importsOrder.nodes.find((importPath) =>
  11959. // eslint-disable-next-line no-prototype-builtins
  11960. importDecls.hasOwnProperty(importPath)
  11961. );
  11962. const decl = importDecls[importPath];
  11963. throw decl.error(
  11964. "Failed to resolve order of composed modules " +
  11965. importsOrder.nodes
  11966. .map((importPath) => "`" + importPath + "`")
  11967. .join(", ") +
  11968. ".",
  11969. {
  11970. plugin: "postcss-modules-extract-imports",
  11971. word: "composes",
  11972. }
  11973. );
  11974. }
  11975. let lastImportRule;
  11976. importsOrder.forEach((path) => {
  11977. const importedSymbols = imports[path];
  11978. let rule = existingImports[path];
  11979. if (!rule && importedSymbols) {
  11980. rule = postcss.rule({
  11981. selector: `:import("${path}")`,
  11982. raws: { after: "\n" },
  11983. });
  11984. if (lastImportRule) {
  11985. root.insertAfter(lastImportRule, rule);
  11986. } else {
  11987. root.prepend(rule);
  11988. }
  11989. }
  11990. lastImportRule = rule;
  11991. if (!importedSymbols) {
  11992. return;
  11993. }
  11994. Object.keys(importedSymbols).forEach((importedSymbol) => {
  11995. rule.append(
  11996. postcss.decl({
  11997. value: importedSymbol,
  11998. prop: importedSymbols[importedSymbol],
  11999. raws: { before: "\n " },
  12000. })
  12001. );
  12002. });
  12003. });
  12004. },
  12005. };
  12006. },
  12007. };
  12008. };
  12009. src$3.exports.postcss = true;
  12010. return src$3.exports;
  12011. }
  12012. var wasmHash = {exports: {}};
  12013. /*
  12014. MIT License http://www.opensource.org/licenses/mit-license.php
  12015. Author Tobias Koppers @sokra
  12016. */
  12017. var hasRequiredWasmHash;
  12018. function requireWasmHash () {
  12019. if (hasRequiredWasmHash) return wasmHash.exports;
  12020. hasRequiredWasmHash = 1;
  12021. // 65536 is the size of a wasm memory page
  12022. // 64 is the maximum chunk size for every possible wasm hash implementation
  12023. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12024. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12025. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
  12026. class WasmHash {
  12027. /**
  12028. * @param {WebAssembly.Instance} instance wasm instance
  12029. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12030. * @param {number} chunkSize size of data chunks passed to wasm
  12031. * @param {number} digestSize size of digest returned by wasm
  12032. */
  12033. constructor(instance, instancesPool, chunkSize, digestSize) {
  12034. const exports = /** @type {any} */ (instance.exports);
  12035. exports.init();
  12036. this.exports = exports;
  12037. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  12038. this.buffered = 0;
  12039. this.instancesPool = instancesPool;
  12040. this.chunkSize = chunkSize;
  12041. this.digestSize = digestSize;
  12042. }
  12043. reset() {
  12044. this.buffered = 0;
  12045. this.exports.init();
  12046. }
  12047. /**
  12048. * @param {Buffer | string} data data
  12049. * @param {BufferEncoding=} encoding encoding
  12050. * @returns {this} itself
  12051. */
  12052. update(data, encoding) {
  12053. if (typeof data === "string") {
  12054. while (data.length > MAX_SHORT_STRING) {
  12055. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12056. data = data.slice(MAX_SHORT_STRING);
  12057. }
  12058. this._updateWithShortString(data, encoding);
  12059. return this;
  12060. }
  12061. this._updateWithBuffer(data);
  12062. return this;
  12063. }
  12064. /**
  12065. * @param {string} data data
  12066. * @param {BufferEncoding=} encoding encoding
  12067. * @returns {void}
  12068. */
  12069. _updateWithShortString(data, encoding) {
  12070. const { exports, buffered, mem, chunkSize } = this;
  12071. let endPos;
  12072. if (data.length < 70) {
  12073. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12074. endPos = buffered;
  12075. for (let i = 0; i < data.length; i++) {
  12076. const cc = data.charCodeAt(i);
  12077. if (cc < 0x80) {
  12078. mem[endPos++] = cc;
  12079. } else if (cc < 0x800) {
  12080. mem[endPos] = (cc >> 6) | 0xc0;
  12081. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12082. endPos += 2;
  12083. } else {
  12084. // bail-out for weird chars
  12085. endPos += mem.write(data.slice(i), endPos, encoding);
  12086. break;
  12087. }
  12088. }
  12089. } else if (encoding === "latin1") {
  12090. endPos = buffered;
  12091. for (let i = 0; i < data.length; i++) {
  12092. const cc = data.charCodeAt(i);
  12093. mem[endPos++] = cc;
  12094. }
  12095. } else {
  12096. endPos = buffered + mem.write(data, buffered, encoding);
  12097. }
  12098. } else {
  12099. endPos = buffered + mem.write(data, buffered, encoding);
  12100. }
  12101. if (endPos < chunkSize) {
  12102. this.buffered = endPos;
  12103. } else {
  12104. const l = endPos & ~(this.chunkSize - 1);
  12105. exports.update(l);
  12106. const newBuffered = endPos - l;
  12107. this.buffered = newBuffered;
  12108. if (newBuffered > 0) {
  12109. mem.copyWithin(0, l, endPos);
  12110. }
  12111. }
  12112. }
  12113. /**
  12114. * @param {Buffer} data data
  12115. * @returns {void}
  12116. */
  12117. _updateWithBuffer(data) {
  12118. const { exports, buffered, mem } = this;
  12119. const length = data.length;
  12120. if (buffered + length < this.chunkSize) {
  12121. data.copy(mem, buffered, 0, length);
  12122. this.buffered += length;
  12123. } else {
  12124. const l = (buffered + length) & ~(this.chunkSize - 1);
  12125. if (l > 65536) {
  12126. let i = 65536 - buffered;
  12127. data.copy(mem, buffered, 0, i);
  12128. exports.update(65536);
  12129. const stop = l - buffered - 65536;
  12130. while (i < stop) {
  12131. data.copy(mem, 0, i, i + 65536);
  12132. exports.update(65536);
  12133. i += 65536;
  12134. }
  12135. data.copy(mem, 0, i, l - buffered);
  12136. exports.update(l - buffered - i);
  12137. } else {
  12138. data.copy(mem, buffered, 0, l - buffered);
  12139. exports.update(l);
  12140. }
  12141. const newBuffered = length + buffered - l;
  12142. this.buffered = newBuffered;
  12143. if (newBuffered > 0) {
  12144. data.copy(mem, 0, length - newBuffered, length);
  12145. }
  12146. }
  12147. }
  12148. digest(type) {
  12149. const { exports, buffered, mem, digestSize } = this;
  12150. exports.final(buffered);
  12151. this.instancesPool.push(this);
  12152. const hex = mem.toString("latin1", 0, digestSize);
  12153. if (type === "hex") {
  12154. return hex;
  12155. }
  12156. if (type === "binary" || !type) {
  12157. return Buffer.from(hex, "hex");
  12158. }
  12159. return Buffer.from(hex, "hex").toString(type);
  12160. }
  12161. }
  12162. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12163. if (instancesPool.length > 0) {
  12164. const old = instancesPool.pop();
  12165. old.reset();
  12166. return old;
  12167. } else {
  12168. return new WasmHash(
  12169. new WebAssembly.Instance(wasmModule),
  12170. instancesPool,
  12171. chunkSize,
  12172. digestSize
  12173. );
  12174. }
  12175. };
  12176. wasmHash.exports = create;
  12177. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12178. return wasmHash.exports;
  12179. }
  12180. /*
  12181. MIT License http://www.opensource.org/licenses/mit-license.php
  12182. Author Tobias Koppers @sokra
  12183. */
  12184. var xxhash64_1;
  12185. var hasRequiredXxhash64;
  12186. function requireXxhash64 () {
  12187. if (hasRequiredXxhash64) return xxhash64_1;
  12188. hasRequiredXxhash64 = 1;
  12189. const create = /*@__PURE__*/ requireWasmHash();
  12190. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12191. const xxhash64 = new WebAssembly.Module(
  12192. Buffer.from(
  12193. // 1173 bytes
  12194. "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",
  12195. "base64"
  12196. )
  12197. );
  12198. //#endregion
  12199. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12200. return xxhash64_1;
  12201. }
  12202. var BatchedHash_1;
  12203. var hasRequiredBatchedHash;
  12204. function requireBatchedHash () {
  12205. if (hasRequiredBatchedHash) return BatchedHash_1;
  12206. hasRequiredBatchedHash = 1;
  12207. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12208. class BatchedHash {
  12209. constructor(hash) {
  12210. this.string = undefined;
  12211. this.encoding = undefined;
  12212. this.hash = hash;
  12213. }
  12214. /**
  12215. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12216. * @param {string|Buffer} data data
  12217. * @param {string=} inputEncoding data encoding
  12218. * @returns {this} updated hash
  12219. */
  12220. update(data, inputEncoding) {
  12221. if (this.string !== undefined) {
  12222. if (
  12223. typeof data === "string" &&
  12224. inputEncoding === this.encoding &&
  12225. this.string.length + data.length < MAX_SHORT_STRING
  12226. ) {
  12227. this.string += data;
  12228. return this;
  12229. }
  12230. this.hash.update(this.string, this.encoding);
  12231. this.string = undefined;
  12232. }
  12233. if (typeof data === "string") {
  12234. if (
  12235. data.length < MAX_SHORT_STRING &&
  12236. // base64 encoding is not valid since it may contain padding chars
  12237. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12238. ) {
  12239. this.string = data;
  12240. this.encoding = inputEncoding;
  12241. } else {
  12242. this.hash.update(data, inputEncoding);
  12243. }
  12244. } else {
  12245. this.hash.update(data);
  12246. }
  12247. return this;
  12248. }
  12249. /**
  12250. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12251. * @param {string=} encoding encoding of the return value
  12252. * @returns {string|Buffer} digest
  12253. */
  12254. digest(encoding) {
  12255. if (this.string !== undefined) {
  12256. this.hash.update(this.string, this.encoding);
  12257. }
  12258. return this.hash.digest(encoding);
  12259. }
  12260. }
  12261. BatchedHash_1 = BatchedHash;
  12262. return BatchedHash_1;
  12263. }
  12264. /*
  12265. MIT License http://www.opensource.org/licenses/mit-license.php
  12266. Author Tobias Koppers @sokra
  12267. */
  12268. var md4_1;
  12269. var hasRequiredMd4;
  12270. function requireMd4 () {
  12271. if (hasRequiredMd4) return md4_1;
  12272. hasRequiredMd4 = 1;
  12273. const create = /*@__PURE__*/ requireWasmHash();
  12274. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12275. const md4 = new WebAssembly.Module(
  12276. Buffer.from(
  12277. // 2150 bytes
  12278. "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=",
  12279. "base64"
  12280. )
  12281. );
  12282. //#endregion
  12283. md4_1 = create.bind(null, md4, [], 64, 32);
  12284. return md4_1;
  12285. }
  12286. var BulkUpdateDecorator_1;
  12287. var hasRequiredBulkUpdateDecorator;
  12288. function requireBulkUpdateDecorator () {
  12289. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12290. hasRequiredBulkUpdateDecorator = 1;
  12291. const BULK_SIZE = 2000;
  12292. // We are using an object instead of a Map as this will stay static during the runtime
  12293. // so access to it can be optimized by v8
  12294. const digestCaches = {};
  12295. class BulkUpdateDecorator {
  12296. /**
  12297. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12298. * @param {string=} hashKey key for caching
  12299. */
  12300. constructor(hashOrFactory, hashKey) {
  12301. this.hashKey = hashKey;
  12302. if (typeof hashOrFactory === "function") {
  12303. this.hashFactory = hashOrFactory;
  12304. this.hash = undefined;
  12305. } else {
  12306. this.hashFactory = undefined;
  12307. this.hash = hashOrFactory;
  12308. }
  12309. this.buffer = "";
  12310. }
  12311. /**
  12312. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12313. * @param {string|Buffer} data data
  12314. * @param {string=} inputEncoding data encoding
  12315. * @returns {this} updated hash
  12316. */
  12317. update(data, inputEncoding) {
  12318. if (
  12319. inputEncoding !== undefined ||
  12320. typeof data !== "string" ||
  12321. data.length > BULK_SIZE
  12322. ) {
  12323. if (this.hash === undefined) {
  12324. this.hash = this.hashFactory();
  12325. }
  12326. if (this.buffer.length > 0) {
  12327. this.hash.update(this.buffer);
  12328. this.buffer = "";
  12329. }
  12330. this.hash.update(data, inputEncoding);
  12331. } else {
  12332. this.buffer += data;
  12333. if (this.buffer.length > BULK_SIZE) {
  12334. if (this.hash === undefined) {
  12335. this.hash = this.hashFactory();
  12336. }
  12337. this.hash.update(this.buffer);
  12338. this.buffer = "";
  12339. }
  12340. }
  12341. return this;
  12342. }
  12343. /**
  12344. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12345. * @param {string=} encoding encoding of the return value
  12346. * @returns {string|Buffer} digest
  12347. */
  12348. digest(encoding) {
  12349. let digestCache;
  12350. const buffer = this.buffer;
  12351. if (this.hash === undefined) {
  12352. // short data for hash, we can use caching
  12353. const cacheKey = `${this.hashKey}-${encoding}`;
  12354. digestCache = digestCaches[cacheKey];
  12355. if (digestCache === undefined) {
  12356. digestCache = digestCaches[cacheKey] = new Map();
  12357. }
  12358. const cacheEntry = digestCache.get(buffer);
  12359. if (cacheEntry !== undefined) {
  12360. return cacheEntry;
  12361. }
  12362. this.hash = this.hashFactory();
  12363. }
  12364. if (buffer.length > 0) {
  12365. this.hash.update(buffer);
  12366. }
  12367. const digestResult = this.hash.digest(encoding);
  12368. if (digestCache !== undefined) {
  12369. digestCache.set(buffer, digestResult);
  12370. }
  12371. return digestResult;
  12372. }
  12373. }
  12374. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12375. return BulkUpdateDecorator_1;
  12376. }
  12377. var getHashDigest_1;
  12378. var hasRequiredGetHashDigest;
  12379. function requireGetHashDigest () {
  12380. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12381. hasRequiredGetHashDigest = 1;
  12382. const baseEncodeTables = {
  12383. 26: "abcdefghijklmnopqrstuvwxyz",
  12384. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12385. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12386. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12387. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12388. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12389. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12390. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12391. };
  12392. /**
  12393. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12394. * @param {number} divisor The divisor
  12395. * @return {number} Modulo (remainder) of the division
  12396. */
  12397. function divmod32(uint32Array, divisor) {
  12398. let carry = 0;
  12399. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12400. const value = carry * 0x100000000 + uint32Array[i];
  12401. carry = value % divisor;
  12402. uint32Array[i] = Math.floor(value / divisor);
  12403. }
  12404. return carry;
  12405. }
  12406. function encodeBufferToBase(buffer, base, length) {
  12407. const encodeTable = baseEncodeTables[base];
  12408. if (!encodeTable) {
  12409. throw new Error("Unknown encoding base" + base);
  12410. }
  12411. // Input bits are only enough to generate this many characters
  12412. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12413. length = Math.min(length, limit);
  12414. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12415. // Fewer numbers in the array means faster math.
  12416. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12417. // Make sure the input buffer data is copied and is not mutated by reference.
  12418. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12419. buffer.copy(Buffer.from(uint32Array.buffer));
  12420. let output = "";
  12421. for (let i = 0; i < length; i++) {
  12422. output = encodeTable[divmod32(uint32Array, base)] + output;
  12423. }
  12424. return output;
  12425. }
  12426. let crypto = undefined;
  12427. let createXXHash64 = undefined;
  12428. let createMd4 = undefined;
  12429. let BatchedHash = undefined;
  12430. let BulkUpdateDecorator = undefined;
  12431. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12432. algorithm = algorithm || "xxhash64";
  12433. maxLength = maxLength || 9999;
  12434. let hash;
  12435. if (algorithm === "xxhash64") {
  12436. if (createXXHash64 === undefined) {
  12437. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12438. if (BatchedHash === undefined) {
  12439. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12440. }
  12441. }
  12442. hash = new BatchedHash(createXXHash64());
  12443. } else if (algorithm === "md4") {
  12444. if (createMd4 === undefined) {
  12445. createMd4 = /*@__PURE__*/ requireMd4();
  12446. if (BatchedHash === undefined) {
  12447. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12448. }
  12449. }
  12450. hash = new BatchedHash(createMd4());
  12451. } else if (algorithm === "native-md4") {
  12452. if (typeof crypto === "undefined") {
  12453. crypto = require("crypto");
  12454. if (BulkUpdateDecorator === undefined) {
  12455. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12456. }
  12457. }
  12458. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12459. } else {
  12460. if (typeof crypto === "undefined") {
  12461. crypto = require("crypto");
  12462. if (BulkUpdateDecorator === undefined) {
  12463. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12464. }
  12465. }
  12466. hash = new BulkUpdateDecorator(
  12467. () => crypto.createHash(algorithm),
  12468. algorithm
  12469. );
  12470. }
  12471. hash.update(buffer);
  12472. if (
  12473. digestType === "base26" ||
  12474. digestType === "base32" ||
  12475. digestType === "base36" ||
  12476. digestType === "base49" ||
  12477. digestType === "base52" ||
  12478. digestType === "base58" ||
  12479. digestType === "base62" ||
  12480. digestType === "base64safe"
  12481. ) {
  12482. return encodeBufferToBase(
  12483. hash.digest(),
  12484. digestType === "base64safe" ? 64 : digestType.substr(4),
  12485. maxLength
  12486. );
  12487. }
  12488. return hash.digest(digestType || "hex").substr(0, maxLength);
  12489. }
  12490. getHashDigest_1 = getHashDigest;
  12491. return getHashDigest_1;
  12492. }
  12493. var interpolateName_1;
  12494. var hasRequiredInterpolateName;
  12495. function requireInterpolateName () {
  12496. if (hasRequiredInterpolateName) return interpolateName_1;
  12497. hasRequiredInterpolateName = 1;
  12498. const path = path$1;
  12499. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12500. function interpolateName(loaderContext, name, options = {}) {
  12501. let filename;
  12502. const hasQuery =
  12503. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12504. if (typeof name === "function") {
  12505. filename = name(
  12506. loaderContext.resourcePath,
  12507. hasQuery ? loaderContext.resourceQuery : undefined
  12508. );
  12509. } else {
  12510. filename = name || "[hash].[ext]";
  12511. }
  12512. const context = options.context;
  12513. const content = options.content;
  12514. const regExp = options.regExp;
  12515. let ext = "bin";
  12516. let basename = "file";
  12517. let directory = "";
  12518. let folder = "";
  12519. let query = "";
  12520. if (loaderContext.resourcePath) {
  12521. const parsed = path.parse(loaderContext.resourcePath);
  12522. let resourcePath = loaderContext.resourcePath;
  12523. if (parsed.ext) {
  12524. ext = parsed.ext.substr(1);
  12525. }
  12526. if (parsed.dir) {
  12527. basename = parsed.name;
  12528. resourcePath = parsed.dir + path.sep;
  12529. }
  12530. if (typeof context !== "undefined") {
  12531. directory = path
  12532. .relative(context, resourcePath + "_")
  12533. .replace(/\\/g, "/")
  12534. .replace(/\.\.(\/)?/g, "_$1");
  12535. directory = directory.substr(0, directory.length - 1);
  12536. } else {
  12537. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12538. }
  12539. if (directory.length <= 1) {
  12540. directory = "";
  12541. } else {
  12542. // directory.length > 1
  12543. folder = path.basename(directory);
  12544. }
  12545. }
  12546. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12547. query = loaderContext.resourceQuery;
  12548. const hashIdx = query.indexOf("#");
  12549. if (hashIdx >= 0) {
  12550. query = query.substr(0, hashIdx);
  12551. }
  12552. }
  12553. let url = filename;
  12554. if (content) {
  12555. // Match hash template
  12556. url = url
  12557. // `hash` and `contenthash` are same in `loader-utils` context
  12558. // let's keep `hash` for backward compatibility
  12559. .replace(
  12560. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12561. (all, hashType, digestType, maxLength) =>
  12562. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12563. );
  12564. }
  12565. url = url
  12566. .replace(/\[ext\]/gi, () => ext)
  12567. .replace(/\[name\]/gi, () => basename)
  12568. .replace(/\[path\]/gi, () => directory)
  12569. .replace(/\[folder\]/gi, () => folder)
  12570. .replace(/\[query\]/gi, () => query);
  12571. if (regExp && loaderContext.resourcePath) {
  12572. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12573. match &&
  12574. match.forEach((matched, i) => {
  12575. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12576. });
  12577. }
  12578. if (
  12579. typeof loaderContext.options === "object" &&
  12580. typeof loaderContext.options.customInterpolateName === "function"
  12581. ) {
  12582. url = loaderContext.options.customInterpolateName.call(
  12583. loaderContext,
  12584. url,
  12585. name,
  12586. options
  12587. );
  12588. }
  12589. return url;
  12590. }
  12591. interpolateName_1 = interpolateName;
  12592. return interpolateName_1;
  12593. }
  12594. var genericNames;
  12595. var hasRequiredGenericNames;
  12596. function requireGenericNames () {
  12597. if (hasRequiredGenericNames) return genericNames;
  12598. hasRequiredGenericNames = 1;
  12599. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12600. var path = path$1;
  12601. /**
  12602. * @param {string} pattern
  12603. * @param {object} options
  12604. * @param {string} options.context
  12605. * @param {string} options.hashPrefix
  12606. * @return {function}
  12607. */
  12608. genericNames = function createGenerator(pattern, options) {
  12609. options = options || {};
  12610. var context =
  12611. options && typeof options.context === "string"
  12612. ? options.context
  12613. : process.cwd();
  12614. var hashPrefix =
  12615. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12616. /**
  12617. * @param {string} localName Usually a class name
  12618. * @param {string} filepath Absolute path
  12619. * @return {string}
  12620. */
  12621. return function generate(localName, filepath) {
  12622. var name = pattern.replace(/\[local\]/gi, localName);
  12623. var loaderContext = {
  12624. resourcePath: filepath,
  12625. };
  12626. var loaderOptions = {
  12627. content:
  12628. hashPrefix +
  12629. path.relative(context, filepath).replace(/\\/g, "/") +
  12630. "\x00" +
  12631. localName,
  12632. context: context,
  12633. };
  12634. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12635. return genericName
  12636. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12637. .replace(/^((-?[0-9])|--)/, "_$1");
  12638. };
  12639. };
  12640. return genericNames;
  12641. }
  12642. var src$2 = {exports: {}};
  12643. var dist = {exports: {}};
  12644. var processor = {exports: {}};
  12645. var parser = {exports: {}};
  12646. var root = {exports: {}};
  12647. var container = {exports: {}};
  12648. var node = {exports: {}};
  12649. var util = {};
  12650. var unesc = {exports: {}};
  12651. var hasRequiredUnesc;
  12652. function requireUnesc () {
  12653. if (hasRequiredUnesc) return unesc.exports;
  12654. hasRequiredUnesc = 1;
  12655. (function (module, exports) {
  12656. exports.__esModule = true;
  12657. exports["default"] = unesc;
  12658. // Many thanks for this post which made this migration much easier.
  12659. // https://mathiasbynens.be/notes/css-escapes
  12660. /**
  12661. *
  12662. * @param {string} str
  12663. * @returns {[string, number]|undefined}
  12664. */
  12665. function gobbleHex(str) {
  12666. var lower = str.toLowerCase();
  12667. var hex = '';
  12668. var spaceTerminated = false;
  12669. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  12670. var code = lower.charCodeAt(i);
  12671. // check to see if we are dealing with a valid hex char [a-f|0-9]
  12672. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  12673. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  12674. spaceTerminated = code === 32;
  12675. if (!valid) {
  12676. break;
  12677. }
  12678. hex += lower[i];
  12679. }
  12680. if (hex.length === 0) {
  12681. return undefined;
  12682. }
  12683. var codePoint = parseInt(hex, 16);
  12684. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  12685. // Add special case for
  12686. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  12687. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  12688. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  12689. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  12690. }
  12691. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  12692. }
  12693. var CONTAINS_ESCAPE = /\\/;
  12694. function unesc(str) {
  12695. var needToProcess = CONTAINS_ESCAPE.test(str);
  12696. if (!needToProcess) {
  12697. return str;
  12698. }
  12699. var ret = "";
  12700. for (var i = 0; i < str.length; i++) {
  12701. if (str[i] === "\\") {
  12702. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  12703. if (gobbled !== undefined) {
  12704. ret += gobbled[0];
  12705. i += gobbled[1];
  12706. continue;
  12707. }
  12708. // Retain a pair of \\ if double escaped `\\\\`
  12709. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  12710. if (str[i + 1] === "\\") {
  12711. ret += "\\";
  12712. i++;
  12713. continue;
  12714. }
  12715. // if \\ is at the end of the string retain it
  12716. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  12717. if (str.length === i + 1) {
  12718. ret += str[i];
  12719. }
  12720. continue;
  12721. }
  12722. ret += str[i];
  12723. }
  12724. return ret;
  12725. }
  12726. module.exports = exports.default;
  12727. } (unesc, unesc.exports));
  12728. return unesc.exports;
  12729. }
  12730. var getProp = {exports: {}};
  12731. var hasRequiredGetProp;
  12732. function requireGetProp () {
  12733. if (hasRequiredGetProp) return getProp.exports;
  12734. hasRequiredGetProp = 1;
  12735. (function (module, exports) {
  12736. exports.__esModule = true;
  12737. exports["default"] = getProp;
  12738. function getProp(obj) {
  12739. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12740. props[_key - 1] = arguments[_key];
  12741. }
  12742. while (props.length > 0) {
  12743. var prop = props.shift();
  12744. if (!obj[prop]) {
  12745. return undefined;
  12746. }
  12747. obj = obj[prop];
  12748. }
  12749. return obj;
  12750. }
  12751. module.exports = exports.default;
  12752. } (getProp, getProp.exports));
  12753. return getProp.exports;
  12754. }
  12755. var ensureObject = {exports: {}};
  12756. var hasRequiredEnsureObject;
  12757. function requireEnsureObject () {
  12758. if (hasRequiredEnsureObject) return ensureObject.exports;
  12759. hasRequiredEnsureObject = 1;
  12760. (function (module, exports) {
  12761. exports.__esModule = true;
  12762. exports["default"] = ensureObject;
  12763. function ensureObject(obj) {
  12764. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12765. props[_key - 1] = arguments[_key];
  12766. }
  12767. while (props.length > 0) {
  12768. var prop = props.shift();
  12769. if (!obj[prop]) {
  12770. obj[prop] = {};
  12771. }
  12772. obj = obj[prop];
  12773. }
  12774. }
  12775. module.exports = exports.default;
  12776. } (ensureObject, ensureObject.exports));
  12777. return ensureObject.exports;
  12778. }
  12779. var stripComments = {exports: {}};
  12780. var hasRequiredStripComments;
  12781. function requireStripComments () {
  12782. if (hasRequiredStripComments) return stripComments.exports;
  12783. hasRequiredStripComments = 1;
  12784. (function (module, exports) {
  12785. exports.__esModule = true;
  12786. exports["default"] = stripComments;
  12787. function stripComments(str) {
  12788. var s = "";
  12789. var commentStart = str.indexOf("/*");
  12790. var lastEnd = 0;
  12791. while (commentStart >= 0) {
  12792. s = s + str.slice(lastEnd, commentStart);
  12793. var commentEnd = str.indexOf("*/", commentStart + 2);
  12794. if (commentEnd < 0) {
  12795. return s;
  12796. }
  12797. lastEnd = commentEnd + 2;
  12798. commentStart = str.indexOf("/*", lastEnd);
  12799. }
  12800. s = s + str.slice(lastEnd);
  12801. return s;
  12802. }
  12803. module.exports = exports.default;
  12804. } (stripComments, stripComments.exports));
  12805. return stripComments.exports;
  12806. }
  12807. var hasRequiredUtil;
  12808. function requireUtil () {
  12809. if (hasRequiredUtil) return util;
  12810. hasRequiredUtil = 1;
  12811. util.__esModule = true;
  12812. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  12813. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  12814. util.unesc = _unesc["default"];
  12815. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  12816. util.getProp = _getProp["default"];
  12817. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  12818. util.ensureObject = _ensureObject["default"];
  12819. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  12820. util.stripComments = _stripComments["default"];
  12821. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  12822. return util;
  12823. }
  12824. var hasRequiredNode;
  12825. function requireNode () {
  12826. if (hasRequiredNode) return node.exports;
  12827. hasRequiredNode = 1;
  12828. (function (module, exports) {
  12829. exports.__esModule = true;
  12830. exports["default"] = void 0;
  12831. var _util = /*@__PURE__*/ requireUtil();
  12832. 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); } }
  12833. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12834. var cloneNode = function cloneNode(obj, parent) {
  12835. if (typeof obj !== 'object' || obj === null) {
  12836. return obj;
  12837. }
  12838. var cloned = new obj.constructor();
  12839. for (var i in obj) {
  12840. if (!obj.hasOwnProperty(i)) {
  12841. continue;
  12842. }
  12843. var value = obj[i];
  12844. var type = typeof value;
  12845. if (i === 'parent' && type === 'object') {
  12846. if (parent) {
  12847. cloned[i] = parent;
  12848. }
  12849. } else if (value instanceof Array) {
  12850. cloned[i] = value.map(function (j) {
  12851. return cloneNode(j, cloned);
  12852. });
  12853. } else {
  12854. cloned[i] = cloneNode(value, cloned);
  12855. }
  12856. }
  12857. return cloned;
  12858. };
  12859. var Node = /*#__PURE__*/function () {
  12860. function Node(opts) {
  12861. if (opts === void 0) {
  12862. opts = {};
  12863. }
  12864. Object.assign(this, opts);
  12865. this.spaces = this.spaces || {};
  12866. this.spaces.before = this.spaces.before || '';
  12867. this.spaces.after = this.spaces.after || '';
  12868. }
  12869. var _proto = Node.prototype;
  12870. _proto.remove = function remove() {
  12871. if (this.parent) {
  12872. this.parent.removeChild(this);
  12873. }
  12874. this.parent = undefined;
  12875. return this;
  12876. };
  12877. _proto.replaceWith = function replaceWith() {
  12878. if (this.parent) {
  12879. for (var index in arguments) {
  12880. this.parent.insertBefore(this, arguments[index]);
  12881. }
  12882. this.remove();
  12883. }
  12884. return this;
  12885. };
  12886. _proto.next = function next() {
  12887. return this.parent.at(this.parent.index(this) + 1);
  12888. };
  12889. _proto.prev = function prev() {
  12890. return this.parent.at(this.parent.index(this) - 1);
  12891. };
  12892. _proto.clone = function clone(overrides) {
  12893. if (overrides === void 0) {
  12894. overrides = {};
  12895. }
  12896. var cloned = cloneNode(this);
  12897. for (var name in overrides) {
  12898. cloned[name] = overrides[name];
  12899. }
  12900. return cloned;
  12901. }
  12902. /**
  12903. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12904. * This allows non standard syntax to be appended to an existing property
  12905. * by specifying the escaped value. By specifying the escaped value,
  12906. * illegal characters are allowed to be directly inserted into css output.
  12907. * @param {string} name the property to set
  12908. * @param {any} value the unescaped value of the property
  12909. * @param {string} valueEscaped optional. the escaped value of the property.
  12910. */;
  12911. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  12912. if (!this.raws) {
  12913. this.raws = {};
  12914. }
  12915. var originalValue = this[name];
  12916. var originalEscaped = this.raws[name];
  12917. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  12918. if (originalEscaped || valueEscaped !== value) {
  12919. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  12920. } else {
  12921. delete this.raws[name]; // delete any escaped value that was created by the setter.
  12922. }
  12923. }
  12924. /**
  12925. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12926. * This allows the escaped value to be specified directly, allowing illegal
  12927. * characters to be directly inserted into css output.
  12928. * @param {string} name the property to set
  12929. * @param {any} value the unescaped value of the property
  12930. * @param {string} valueEscaped the escaped value of the property.
  12931. */;
  12932. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  12933. if (!this.raws) {
  12934. this.raws = {};
  12935. }
  12936. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  12937. this.raws[name] = valueEscaped;
  12938. }
  12939. /**
  12940. * When you want a value to passed through to CSS directly. This method
  12941. * deletes the corresponding raw value causing the stringifier to fallback
  12942. * to the unescaped value.
  12943. * @param {string} name the property to set.
  12944. * @param {any} value The value that is both escaped and unescaped.
  12945. */;
  12946. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  12947. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  12948. if (this.raws) {
  12949. delete this.raws[name];
  12950. }
  12951. }
  12952. /**
  12953. *
  12954. * @param {number} line The number (starting with 1)
  12955. * @param {number} column The column number (starting with 1)
  12956. */;
  12957. _proto.isAtPosition = function isAtPosition(line, column) {
  12958. if (this.source && this.source.start && this.source.end) {
  12959. if (this.source.start.line > line) {
  12960. return false;
  12961. }
  12962. if (this.source.end.line < line) {
  12963. return false;
  12964. }
  12965. if (this.source.start.line === line && this.source.start.column > column) {
  12966. return false;
  12967. }
  12968. if (this.source.end.line === line && this.source.end.column < column) {
  12969. return false;
  12970. }
  12971. return true;
  12972. }
  12973. return undefined;
  12974. };
  12975. _proto.stringifyProperty = function stringifyProperty(name) {
  12976. return this.raws && this.raws[name] || this[name];
  12977. };
  12978. _proto.valueToString = function valueToString() {
  12979. return String(this.stringifyProperty("value"));
  12980. };
  12981. _proto.toString = function toString() {
  12982. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  12983. };
  12984. _createClass(Node, [{
  12985. key: "rawSpaceBefore",
  12986. get: function get() {
  12987. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  12988. if (rawSpace === undefined) {
  12989. rawSpace = this.spaces && this.spaces.before;
  12990. }
  12991. return rawSpace || "";
  12992. },
  12993. set: function set(raw) {
  12994. (0, _util.ensureObject)(this, "raws", "spaces");
  12995. this.raws.spaces.before = raw;
  12996. }
  12997. }, {
  12998. key: "rawSpaceAfter",
  12999. get: function get() {
  13000. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  13001. if (rawSpace === undefined) {
  13002. rawSpace = this.spaces.after;
  13003. }
  13004. return rawSpace || "";
  13005. },
  13006. set: function set(raw) {
  13007. (0, _util.ensureObject)(this, "raws", "spaces");
  13008. this.raws.spaces.after = raw;
  13009. }
  13010. }]);
  13011. return Node;
  13012. }();
  13013. exports["default"] = Node;
  13014. module.exports = exports.default;
  13015. } (node, node.exports));
  13016. return node.exports;
  13017. }
  13018. var types$1 = {};
  13019. var hasRequiredTypes;
  13020. function requireTypes () {
  13021. if (hasRequiredTypes) return types$1;
  13022. hasRequiredTypes = 1;
  13023. types$1.__esModule = true;
  13024. 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;
  13025. var TAG = 'tag';
  13026. types$1.TAG = TAG;
  13027. var STRING = 'string';
  13028. types$1.STRING = STRING;
  13029. var SELECTOR = 'selector';
  13030. types$1.SELECTOR = SELECTOR;
  13031. var ROOT = 'root';
  13032. types$1.ROOT = ROOT;
  13033. var PSEUDO = 'pseudo';
  13034. types$1.PSEUDO = PSEUDO;
  13035. var NESTING = 'nesting';
  13036. types$1.NESTING = NESTING;
  13037. var ID = 'id';
  13038. types$1.ID = ID;
  13039. var COMMENT = 'comment';
  13040. types$1.COMMENT = COMMENT;
  13041. var COMBINATOR = 'combinator';
  13042. types$1.COMBINATOR = COMBINATOR;
  13043. var CLASS = 'class';
  13044. types$1.CLASS = CLASS;
  13045. var ATTRIBUTE = 'attribute';
  13046. types$1.ATTRIBUTE = ATTRIBUTE;
  13047. var UNIVERSAL = 'universal';
  13048. types$1.UNIVERSAL = UNIVERSAL;
  13049. return types$1;
  13050. }
  13051. var hasRequiredContainer;
  13052. function requireContainer () {
  13053. if (hasRequiredContainer) return container.exports;
  13054. hasRequiredContainer = 1;
  13055. (function (module, exports) {
  13056. exports.__esModule = true;
  13057. exports["default"] = void 0;
  13058. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13059. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13060. 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); }
  13061. 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; }
  13062. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13063. 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."); }
  13064. 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); }
  13065. 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; }
  13066. 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); } }
  13067. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13068. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13069. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13070. var Container = /*#__PURE__*/function (_Node) {
  13071. _inheritsLoose(Container, _Node);
  13072. function Container(opts) {
  13073. var _this;
  13074. _this = _Node.call(this, opts) || this;
  13075. if (!_this.nodes) {
  13076. _this.nodes = [];
  13077. }
  13078. return _this;
  13079. }
  13080. var _proto = Container.prototype;
  13081. _proto.append = function append(selector) {
  13082. selector.parent = this;
  13083. this.nodes.push(selector);
  13084. return this;
  13085. };
  13086. _proto.prepend = function prepend(selector) {
  13087. selector.parent = this;
  13088. this.nodes.unshift(selector);
  13089. return this;
  13090. };
  13091. _proto.at = function at(index) {
  13092. return this.nodes[index];
  13093. };
  13094. _proto.index = function index(child) {
  13095. if (typeof child === 'number') {
  13096. return child;
  13097. }
  13098. return this.nodes.indexOf(child);
  13099. };
  13100. _proto.removeChild = function removeChild(child) {
  13101. child = this.index(child);
  13102. this.at(child).parent = undefined;
  13103. this.nodes.splice(child, 1);
  13104. var index;
  13105. for (var id in this.indexes) {
  13106. index = this.indexes[id];
  13107. if (index >= child) {
  13108. this.indexes[id] = index - 1;
  13109. }
  13110. }
  13111. return this;
  13112. };
  13113. _proto.removeAll = function removeAll() {
  13114. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13115. var node = _step.value;
  13116. node.parent = undefined;
  13117. }
  13118. this.nodes = [];
  13119. return this;
  13120. };
  13121. _proto.empty = function empty() {
  13122. return this.removeAll();
  13123. };
  13124. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13125. newNode.parent = this;
  13126. var oldIndex = this.index(oldNode);
  13127. this.nodes.splice(oldIndex + 1, 0, newNode);
  13128. newNode.parent = this;
  13129. var index;
  13130. for (var id in this.indexes) {
  13131. index = this.indexes[id];
  13132. if (oldIndex <= index) {
  13133. this.indexes[id] = index + 1;
  13134. }
  13135. }
  13136. return this;
  13137. };
  13138. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13139. newNode.parent = this;
  13140. var oldIndex = this.index(oldNode);
  13141. this.nodes.splice(oldIndex, 0, newNode);
  13142. newNode.parent = this;
  13143. var index;
  13144. for (var id in this.indexes) {
  13145. index = this.indexes[id];
  13146. if (index <= oldIndex) {
  13147. this.indexes[id] = index + 1;
  13148. }
  13149. }
  13150. return this;
  13151. };
  13152. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13153. var found = undefined;
  13154. this.each(function (node) {
  13155. if (node.atPosition) {
  13156. var foundChild = node.atPosition(line, col);
  13157. if (foundChild) {
  13158. found = foundChild;
  13159. return false;
  13160. }
  13161. } else if (node.isAtPosition(line, col)) {
  13162. found = node;
  13163. return false;
  13164. }
  13165. });
  13166. return found;
  13167. }
  13168. /**
  13169. * Return the most specific node at the line and column number given.
  13170. * The source location is based on the original parsed location, locations aren't
  13171. * updated as selector nodes are mutated.
  13172. *
  13173. * Note that this location is relative to the location of the first character
  13174. * of the selector, and not the location of the selector in the overall document
  13175. * when used in conjunction with postcss.
  13176. *
  13177. * If not found, returns undefined.
  13178. * @param {number} line The line number of the node to find. (1-based index)
  13179. * @param {number} col The column number of the node to find. (1-based index)
  13180. */;
  13181. _proto.atPosition = function atPosition(line, col) {
  13182. if (this.isAtPosition(line, col)) {
  13183. return this._findChildAtPosition(line, col) || this;
  13184. } else {
  13185. return undefined;
  13186. }
  13187. };
  13188. _proto._inferEndPosition = function _inferEndPosition() {
  13189. if (this.last && this.last.source && this.last.source.end) {
  13190. this.source = this.source || {};
  13191. this.source.end = this.source.end || {};
  13192. Object.assign(this.source.end, this.last.source.end);
  13193. }
  13194. };
  13195. _proto.each = function each(callback) {
  13196. if (!this.lastEach) {
  13197. this.lastEach = 0;
  13198. }
  13199. if (!this.indexes) {
  13200. this.indexes = {};
  13201. }
  13202. this.lastEach++;
  13203. var id = this.lastEach;
  13204. this.indexes[id] = 0;
  13205. if (!this.length) {
  13206. return undefined;
  13207. }
  13208. var index, result;
  13209. while (this.indexes[id] < this.length) {
  13210. index = this.indexes[id];
  13211. result = callback(this.at(index), index);
  13212. if (result === false) {
  13213. break;
  13214. }
  13215. this.indexes[id] += 1;
  13216. }
  13217. delete this.indexes[id];
  13218. if (result === false) {
  13219. return false;
  13220. }
  13221. };
  13222. _proto.walk = function walk(callback) {
  13223. return this.each(function (node, i) {
  13224. var result = callback(node, i);
  13225. if (result !== false && node.length) {
  13226. result = node.walk(callback);
  13227. }
  13228. if (result === false) {
  13229. return false;
  13230. }
  13231. });
  13232. };
  13233. _proto.walkAttributes = function walkAttributes(callback) {
  13234. var _this2 = this;
  13235. return this.walk(function (selector) {
  13236. if (selector.type === types.ATTRIBUTE) {
  13237. return callback.call(_this2, selector);
  13238. }
  13239. });
  13240. };
  13241. _proto.walkClasses = function walkClasses(callback) {
  13242. var _this3 = this;
  13243. return this.walk(function (selector) {
  13244. if (selector.type === types.CLASS) {
  13245. return callback.call(_this3, selector);
  13246. }
  13247. });
  13248. };
  13249. _proto.walkCombinators = function walkCombinators(callback) {
  13250. var _this4 = this;
  13251. return this.walk(function (selector) {
  13252. if (selector.type === types.COMBINATOR) {
  13253. return callback.call(_this4, selector);
  13254. }
  13255. });
  13256. };
  13257. _proto.walkComments = function walkComments(callback) {
  13258. var _this5 = this;
  13259. return this.walk(function (selector) {
  13260. if (selector.type === types.COMMENT) {
  13261. return callback.call(_this5, selector);
  13262. }
  13263. });
  13264. };
  13265. _proto.walkIds = function walkIds(callback) {
  13266. var _this6 = this;
  13267. return this.walk(function (selector) {
  13268. if (selector.type === types.ID) {
  13269. return callback.call(_this6, selector);
  13270. }
  13271. });
  13272. };
  13273. _proto.walkNesting = function walkNesting(callback) {
  13274. var _this7 = this;
  13275. return this.walk(function (selector) {
  13276. if (selector.type === types.NESTING) {
  13277. return callback.call(_this7, selector);
  13278. }
  13279. });
  13280. };
  13281. _proto.walkPseudos = function walkPseudos(callback) {
  13282. var _this8 = this;
  13283. return this.walk(function (selector) {
  13284. if (selector.type === types.PSEUDO) {
  13285. return callback.call(_this8, selector);
  13286. }
  13287. });
  13288. };
  13289. _proto.walkTags = function walkTags(callback) {
  13290. var _this9 = this;
  13291. return this.walk(function (selector) {
  13292. if (selector.type === types.TAG) {
  13293. return callback.call(_this9, selector);
  13294. }
  13295. });
  13296. };
  13297. _proto.walkUniversals = function walkUniversals(callback) {
  13298. var _this10 = this;
  13299. return this.walk(function (selector) {
  13300. if (selector.type === types.UNIVERSAL) {
  13301. return callback.call(_this10, selector);
  13302. }
  13303. });
  13304. };
  13305. _proto.split = function split(callback) {
  13306. var _this11 = this;
  13307. var current = [];
  13308. return this.reduce(function (memo, node, index) {
  13309. var split = callback.call(_this11, node);
  13310. current.push(node);
  13311. if (split) {
  13312. memo.push(current);
  13313. current = [];
  13314. } else if (index === _this11.length - 1) {
  13315. memo.push(current);
  13316. }
  13317. return memo;
  13318. }, []);
  13319. };
  13320. _proto.map = function map(callback) {
  13321. return this.nodes.map(callback);
  13322. };
  13323. _proto.reduce = function reduce(callback, memo) {
  13324. return this.nodes.reduce(callback, memo);
  13325. };
  13326. _proto.every = function every(callback) {
  13327. return this.nodes.every(callback);
  13328. };
  13329. _proto.some = function some(callback) {
  13330. return this.nodes.some(callback);
  13331. };
  13332. _proto.filter = function filter(callback) {
  13333. return this.nodes.filter(callback);
  13334. };
  13335. _proto.sort = function sort(callback) {
  13336. return this.nodes.sort(callback);
  13337. };
  13338. _proto.toString = function toString() {
  13339. return this.map(String).join('');
  13340. };
  13341. _createClass(Container, [{
  13342. key: "first",
  13343. get: function get() {
  13344. return this.at(0);
  13345. }
  13346. }, {
  13347. key: "last",
  13348. get: function get() {
  13349. return this.at(this.length - 1);
  13350. }
  13351. }, {
  13352. key: "length",
  13353. get: function get() {
  13354. return this.nodes.length;
  13355. }
  13356. }]);
  13357. return Container;
  13358. }(_node["default"]);
  13359. exports["default"] = Container;
  13360. module.exports = exports.default;
  13361. } (container, container.exports));
  13362. return container.exports;
  13363. }
  13364. var hasRequiredRoot;
  13365. function requireRoot () {
  13366. if (hasRequiredRoot) return root.exports;
  13367. hasRequiredRoot = 1;
  13368. (function (module, exports) {
  13369. exports.__esModule = true;
  13370. exports["default"] = void 0;
  13371. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13372. var _types = /*@__PURE__*/ requireTypes();
  13373. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13374. 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); } }
  13375. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13376. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13377. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13378. var Root = /*#__PURE__*/function (_Container) {
  13379. _inheritsLoose(Root, _Container);
  13380. function Root(opts) {
  13381. var _this;
  13382. _this = _Container.call(this, opts) || this;
  13383. _this.type = _types.ROOT;
  13384. return _this;
  13385. }
  13386. var _proto = Root.prototype;
  13387. _proto.toString = function toString() {
  13388. var str = this.reduce(function (memo, selector) {
  13389. memo.push(String(selector));
  13390. return memo;
  13391. }, []).join(',');
  13392. return this.trailingComma ? str + ',' : str;
  13393. };
  13394. _proto.error = function error(message, options) {
  13395. if (this._error) {
  13396. return this._error(message, options);
  13397. } else {
  13398. return new Error(message);
  13399. }
  13400. };
  13401. _createClass(Root, [{
  13402. key: "errorGenerator",
  13403. set: function set(handler) {
  13404. this._error = handler;
  13405. }
  13406. }]);
  13407. return Root;
  13408. }(_container["default"]);
  13409. exports["default"] = Root;
  13410. module.exports = exports.default;
  13411. } (root, root.exports));
  13412. return root.exports;
  13413. }
  13414. var selector = {exports: {}};
  13415. var hasRequiredSelector;
  13416. function requireSelector () {
  13417. if (hasRequiredSelector) return selector.exports;
  13418. hasRequiredSelector = 1;
  13419. (function (module, exports) {
  13420. exports.__esModule = true;
  13421. exports["default"] = void 0;
  13422. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13423. var _types = /*@__PURE__*/ requireTypes();
  13424. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13425. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13426. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13427. var Selector = /*#__PURE__*/function (_Container) {
  13428. _inheritsLoose(Selector, _Container);
  13429. function Selector(opts) {
  13430. var _this;
  13431. _this = _Container.call(this, opts) || this;
  13432. _this.type = _types.SELECTOR;
  13433. return _this;
  13434. }
  13435. return Selector;
  13436. }(_container["default"]);
  13437. exports["default"] = Selector;
  13438. module.exports = exports.default;
  13439. } (selector, selector.exports));
  13440. return selector.exports;
  13441. }
  13442. var className = {exports: {}};
  13443. var hasRequiredClassName;
  13444. function requireClassName () {
  13445. if (hasRequiredClassName) return className.exports;
  13446. hasRequiredClassName = 1;
  13447. (function (module, exports) {
  13448. exports.__esModule = true;
  13449. exports["default"] = void 0;
  13450. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13451. var _util = /*@__PURE__*/ requireUtil();
  13452. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13453. var _types = /*@__PURE__*/ requireTypes();
  13454. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13455. 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); } }
  13456. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13457. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13458. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13459. var ClassName = /*#__PURE__*/function (_Node) {
  13460. _inheritsLoose(ClassName, _Node);
  13461. function ClassName(opts) {
  13462. var _this;
  13463. _this = _Node.call(this, opts) || this;
  13464. _this.type = _types.CLASS;
  13465. _this._constructed = true;
  13466. return _this;
  13467. }
  13468. var _proto = ClassName.prototype;
  13469. _proto.valueToString = function valueToString() {
  13470. return '.' + _Node.prototype.valueToString.call(this);
  13471. };
  13472. _createClass(ClassName, [{
  13473. key: "value",
  13474. get: function get() {
  13475. return this._value;
  13476. },
  13477. set: function set(v) {
  13478. if (this._constructed) {
  13479. var escaped = (0, _cssesc["default"])(v, {
  13480. isIdentifier: true
  13481. });
  13482. if (escaped !== v) {
  13483. (0, _util.ensureObject)(this, "raws");
  13484. this.raws.value = escaped;
  13485. } else if (this.raws) {
  13486. delete this.raws.value;
  13487. }
  13488. }
  13489. this._value = v;
  13490. }
  13491. }]);
  13492. return ClassName;
  13493. }(_node["default"]);
  13494. exports["default"] = ClassName;
  13495. module.exports = exports.default;
  13496. } (className, className.exports));
  13497. return className.exports;
  13498. }
  13499. var comment = {exports: {}};
  13500. var hasRequiredComment;
  13501. function requireComment () {
  13502. if (hasRequiredComment) return comment.exports;
  13503. hasRequiredComment = 1;
  13504. (function (module, exports) {
  13505. exports.__esModule = true;
  13506. exports["default"] = void 0;
  13507. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13508. var _types = /*@__PURE__*/ requireTypes();
  13509. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13510. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13511. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13512. var Comment = /*#__PURE__*/function (_Node) {
  13513. _inheritsLoose(Comment, _Node);
  13514. function Comment(opts) {
  13515. var _this;
  13516. _this = _Node.call(this, opts) || this;
  13517. _this.type = _types.COMMENT;
  13518. return _this;
  13519. }
  13520. return Comment;
  13521. }(_node["default"]);
  13522. exports["default"] = Comment;
  13523. module.exports = exports.default;
  13524. } (comment, comment.exports));
  13525. return comment.exports;
  13526. }
  13527. var id = {exports: {}};
  13528. var hasRequiredId;
  13529. function requireId () {
  13530. if (hasRequiredId) return id.exports;
  13531. hasRequiredId = 1;
  13532. (function (module, exports) {
  13533. exports.__esModule = true;
  13534. exports["default"] = void 0;
  13535. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13536. var _types = /*@__PURE__*/ requireTypes();
  13537. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13538. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13539. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13540. var ID = /*#__PURE__*/function (_Node) {
  13541. _inheritsLoose(ID, _Node);
  13542. function ID(opts) {
  13543. var _this;
  13544. _this = _Node.call(this, opts) || this;
  13545. _this.type = _types.ID;
  13546. return _this;
  13547. }
  13548. var _proto = ID.prototype;
  13549. _proto.valueToString = function valueToString() {
  13550. return '#' + _Node.prototype.valueToString.call(this);
  13551. };
  13552. return ID;
  13553. }(_node["default"]);
  13554. exports["default"] = ID;
  13555. module.exports = exports.default;
  13556. } (id, id.exports));
  13557. return id.exports;
  13558. }
  13559. var tag = {exports: {}};
  13560. var namespace = {exports: {}};
  13561. var hasRequiredNamespace;
  13562. function requireNamespace () {
  13563. if (hasRequiredNamespace) return namespace.exports;
  13564. hasRequiredNamespace = 1;
  13565. (function (module, exports) {
  13566. exports.__esModule = true;
  13567. exports["default"] = void 0;
  13568. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13569. var _util = /*@__PURE__*/ requireUtil();
  13570. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13571. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13572. 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); } }
  13573. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13574. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13575. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13576. var Namespace = /*#__PURE__*/function (_Node) {
  13577. _inheritsLoose(Namespace, _Node);
  13578. function Namespace() {
  13579. return _Node.apply(this, arguments) || this;
  13580. }
  13581. var _proto = Namespace.prototype;
  13582. _proto.qualifiedName = function qualifiedName(value) {
  13583. if (this.namespace) {
  13584. return this.namespaceString + "|" + value;
  13585. } else {
  13586. return value;
  13587. }
  13588. };
  13589. _proto.valueToString = function valueToString() {
  13590. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  13591. };
  13592. _createClass(Namespace, [{
  13593. key: "namespace",
  13594. get: function get() {
  13595. return this._namespace;
  13596. },
  13597. set: function set(namespace) {
  13598. if (namespace === true || namespace === "*" || namespace === "&") {
  13599. this._namespace = namespace;
  13600. if (this.raws) {
  13601. delete this.raws.namespace;
  13602. }
  13603. return;
  13604. }
  13605. var escaped = (0, _cssesc["default"])(namespace, {
  13606. isIdentifier: true
  13607. });
  13608. this._namespace = namespace;
  13609. if (escaped !== namespace) {
  13610. (0, _util.ensureObject)(this, "raws");
  13611. this.raws.namespace = escaped;
  13612. } else if (this.raws) {
  13613. delete this.raws.namespace;
  13614. }
  13615. }
  13616. }, {
  13617. key: "ns",
  13618. get: function get() {
  13619. return this._namespace;
  13620. },
  13621. set: function set(namespace) {
  13622. this.namespace = namespace;
  13623. }
  13624. }, {
  13625. key: "namespaceString",
  13626. get: function get() {
  13627. if (this.namespace) {
  13628. var ns = this.stringifyProperty("namespace");
  13629. if (ns === true) {
  13630. return '';
  13631. } else {
  13632. return ns;
  13633. }
  13634. } else {
  13635. return '';
  13636. }
  13637. }
  13638. }]);
  13639. return Namespace;
  13640. }(_node["default"]);
  13641. exports["default"] = Namespace;
  13642. module.exports = exports.default;
  13643. } (namespace, namespace.exports));
  13644. return namespace.exports;
  13645. }
  13646. var hasRequiredTag;
  13647. function requireTag () {
  13648. if (hasRequiredTag) return tag.exports;
  13649. hasRequiredTag = 1;
  13650. (function (module, exports) {
  13651. exports.__esModule = true;
  13652. exports["default"] = void 0;
  13653. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13654. var _types = /*@__PURE__*/ requireTypes();
  13655. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13656. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13657. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13658. var Tag = /*#__PURE__*/function (_Namespace) {
  13659. _inheritsLoose(Tag, _Namespace);
  13660. function Tag(opts) {
  13661. var _this;
  13662. _this = _Namespace.call(this, opts) || this;
  13663. _this.type = _types.TAG;
  13664. return _this;
  13665. }
  13666. return Tag;
  13667. }(_namespace["default"]);
  13668. exports["default"] = Tag;
  13669. module.exports = exports.default;
  13670. } (tag, tag.exports));
  13671. return tag.exports;
  13672. }
  13673. var string = {exports: {}};
  13674. var hasRequiredString;
  13675. function requireString () {
  13676. if (hasRequiredString) return string.exports;
  13677. hasRequiredString = 1;
  13678. (function (module, exports) {
  13679. exports.__esModule = true;
  13680. exports["default"] = void 0;
  13681. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13682. var _types = /*@__PURE__*/ requireTypes();
  13683. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13684. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13685. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13686. var String = /*#__PURE__*/function (_Node) {
  13687. _inheritsLoose(String, _Node);
  13688. function String(opts) {
  13689. var _this;
  13690. _this = _Node.call(this, opts) || this;
  13691. _this.type = _types.STRING;
  13692. return _this;
  13693. }
  13694. return String;
  13695. }(_node["default"]);
  13696. exports["default"] = String;
  13697. module.exports = exports.default;
  13698. } (string, string.exports));
  13699. return string.exports;
  13700. }
  13701. var pseudo = {exports: {}};
  13702. var hasRequiredPseudo;
  13703. function requirePseudo () {
  13704. if (hasRequiredPseudo) return pseudo.exports;
  13705. hasRequiredPseudo = 1;
  13706. (function (module, exports) {
  13707. exports.__esModule = true;
  13708. exports["default"] = void 0;
  13709. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13710. var _types = /*@__PURE__*/ requireTypes();
  13711. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13712. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13713. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13714. var Pseudo = /*#__PURE__*/function (_Container) {
  13715. _inheritsLoose(Pseudo, _Container);
  13716. function Pseudo(opts) {
  13717. var _this;
  13718. _this = _Container.call(this, opts) || this;
  13719. _this.type = _types.PSEUDO;
  13720. return _this;
  13721. }
  13722. var _proto = Pseudo.prototype;
  13723. _proto.toString = function toString() {
  13724. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  13725. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  13726. };
  13727. return Pseudo;
  13728. }(_container["default"]);
  13729. exports["default"] = Pseudo;
  13730. module.exports = exports.default;
  13731. } (pseudo, pseudo.exports));
  13732. return pseudo.exports;
  13733. }
  13734. var attribute = {};
  13735. var hasRequiredAttribute;
  13736. function requireAttribute () {
  13737. if (hasRequiredAttribute) return attribute;
  13738. hasRequiredAttribute = 1;
  13739. (function (exports) {
  13740. exports.__esModule = true;
  13741. exports["default"] = void 0;
  13742. exports.unescapeValue = unescapeValue;
  13743. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13744. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13745. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13746. var _types = /*@__PURE__*/ requireTypes();
  13747. var _CSSESC_QUOTE_OPTIONS;
  13748. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13749. 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); } }
  13750. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13751. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13752. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13753. var deprecate = /*@__PURE__*/ requireNode$1();
  13754. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  13755. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  13756. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  13757. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  13758. function unescapeValue(value) {
  13759. var deprecatedUsage = false;
  13760. var quoteMark = null;
  13761. var unescaped = value;
  13762. var m = unescaped.match(WRAPPED_IN_QUOTES);
  13763. if (m) {
  13764. quoteMark = m[1];
  13765. unescaped = m[2];
  13766. }
  13767. unescaped = (0, _unesc["default"])(unescaped);
  13768. if (unescaped !== value) {
  13769. deprecatedUsage = true;
  13770. }
  13771. return {
  13772. deprecatedUsage: deprecatedUsage,
  13773. unescaped: unescaped,
  13774. quoteMark: quoteMark
  13775. };
  13776. }
  13777. function handleDeprecatedContructorOpts(opts) {
  13778. if (opts.quoteMark !== undefined) {
  13779. return opts;
  13780. }
  13781. if (opts.value === undefined) {
  13782. return opts;
  13783. }
  13784. warnOfDeprecatedConstructor();
  13785. var _unescapeValue = unescapeValue(opts.value),
  13786. quoteMark = _unescapeValue.quoteMark,
  13787. unescaped = _unescapeValue.unescaped;
  13788. if (!opts.raws) {
  13789. opts.raws = {};
  13790. }
  13791. if (opts.raws.value === undefined) {
  13792. opts.raws.value = opts.value;
  13793. }
  13794. opts.value = unescaped;
  13795. opts.quoteMark = quoteMark;
  13796. return opts;
  13797. }
  13798. var Attribute = /*#__PURE__*/function (_Namespace) {
  13799. _inheritsLoose(Attribute, _Namespace);
  13800. function Attribute(opts) {
  13801. var _this;
  13802. if (opts === void 0) {
  13803. opts = {};
  13804. }
  13805. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  13806. _this.type = _types.ATTRIBUTE;
  13807. _this.raws = _this.raws || {};
  13808. Object.defineProperty(_this.raws, 'unquoted', {
  13809. get: deprecate(function () {
  13810. return _this.value;
  13811. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  13812. set: deprecate(function () {
  13813. return _this.value;
  13814. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  13815. });
  13816. _this._constructed = true;
  13817. return _this;
  13818. }
  13819. /**
  13820. * Returns the Attribute's value quoted such that it would be legal to use
  13821. * in the value of a css file. The original value's quotation setting
  13822. * used for stringification is left unchanged. See `setValue(value, options)`
  13823. * if you want to control the quote settings of a new value for the attribute.
  13824. *
  13825. * You can also change the quotation used for the current value by setting quoteMark.
  13826. *
  13827. * Options:
  13828. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  13829. * option is not set, the original value for quoteMark will be used. If
  13830. * indeterminate, a double quote is used. The legal values are:
  13831. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  13832. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  13833. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  13834. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  13835. * over the quoteMark option value.
  13836. * * smart {boolean} - if true, will select a quote mark based on the value
  13837. * and the other options specified here. See the `smartQuoteMark()`
  13838. * method.
  13839. **/
  13840. var _proto = Attribute.prototype;
  13841. _proto.getQuotedValue = function getQuotedValue(options) {
  13842. if (options === void 0) {
  13843. options = {};
  13844. }
  13845. var quoteMark = this._determineQuoteMark(options);
  13846. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  13847. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  13848. return escaped;
  13849. };
  13850. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  13851. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  13852. }
  13853. /**
  13854. * Set the unescaped value with the specified quotation options. The value
  13855. * provided must not include any wrapping quote marks -- those quotes will
  13856. * be interpreted as part of the value and escaped accordingly.
  13857. */;
  13858. _proto.setValue = function setValue(value, options) {
  13859. if (options === void 0) {
  13860. options = {};
  13861. }
  13862. this._value = value;
  13863. this._quoteMark = this._determineQuoteMark(options);
  13864. this._syncRawValue();
  13865. }
  13866. /**
  13867. * Intelligently select a quoteMark value based on the value's contents. If
  13868. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  13869. * mark will be picked that minimizes the number of escapes.
  13870. *
  13871. * If there's no clear winner, the quote mark from these options is used,
  13872. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  13873. * true). If the quoteMark is unspecified, a double quote is used.
  13874. *
  13875. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  13876. * from the quoteValue method.
  13877. */;
  13878. _proto.smartQuoteMark = function smartQuoteMark(options) {
  13879. var v = this.value;
  13880. var numSingleQuotes = v.replace(/[^']/g, '').length;
  13881. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  13882. if (numSingleQuotes + numDoubleQuotes === 0) {
  13883. var escaped = (0, _cssesc["default"])(v, {
  13884. isIdentifier: true
  13885. });
  13886. if (escaped === v) {
  13887. return Attribute.NO_QUOTE;
  13888. } else {
  13889. var pref = this.preferredQuoteMark(options);
  13890. if (pref === Attribute.NO_QUOTE) {
  13891. // pick a quote mark that isn't none and see if it's smaller
  13892. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  13893. var opts = CSSESC_QUOTE_OPTIONS[quote];
  13894. var quoteValue = (0, _cssesc["default"])(v, opts);
  13895. if (quoteValue.length < escaped.length) {
  13896. return quote;
  13897. }
  13898. }
  13899. return pref;
  13900. }
  13901. } else if (numDoubleQuotes === numSingleQuotes) {
  13902. return this.preferredQuoteMark(options);
  13903. } else if (numDoubleQuotes < numSingleQuotes) {
  13904. return Attribute.DOUBLE_QUOTE;
  13905. } else {
  13906. return Attribute.SINGLE_QUOTE;
  13907. }
  13908. }
  13909. /**
  13910. * Selects the preferred quote mark based on the options and the current quote mark value.
  13911. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  13912. * instead.
  13913. */;
  13914. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  13915. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  13916. if (quoteMark === undefined) {
  13917. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  13918. }
  13919. if (quoteMark === undefined) {
  13920. quoteMark = Attribute.DOUBLE_QUOTE;
  13921. }
  13922. return quoteMark;
  13923. };
  13924. _proto._syncRawValue = function _syncRawValue() {
  13925. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  13926. if (rawValue === this._value) {
  13927. if (this.raws) {
  13928. delete this.raws.value;
  13929. }
  13930. } else {
  13931. this.raws.value = rawValue;
  13932. }
  13933. };
  13934. _proto._handleEscapes = function _handleEscapes(prop, value) {
  13935. if (this._constructed) {
  13936. var escaped = (0, _cssesc["default"])(value, {
  13937. isIdentifier: true
  13938. });
  13939. if (escaped !== value) {
  13940. this.raws[prop] = escaped;
  13941. } else {
  13942. delete this.raws[prop];
  13943. }
  13944. }
  13945. };
  13946. _proto._spacesFor = function _spacesFor(name) {
  13947. var attrSpaces = {
  13948. before: '',
  13949. after: ''
  13950. };
  13951. var spaces = this.spaces[name] || {};
  13952. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  13953. return Object.assign(attrSpaces, spaces, rawSpaces);
  13954. };
  13955. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  13956. if (spaceName === void 0) {
  13957. spaceName = name;
  13958. }
  13959. if (concat === void 0) {
  13960. concat = defaultAttrConcat;
  13961. }
  13962. var attrSpaces = this._spacesFor(spaceName);
  13963. return concat(this.stringifyProperty(name), attrSpaces);
  13964. }
  13965. /**
  13966. * returns the offset of the attribute part specified relative to the
  13967. * start of the node of the output string.
  13968. *
  13969. * * "ns" - alias for "namespace"
  13970. * * "namespace" - the namespace if it exists.
  13971. * * "attribute" - the attribute name
  13972. * * "attributeNS" - the start of the attribute or its namespace
  13973. * * "operator" - the match operator of the attribute
  13974. * * "value" - The value (string or identifier)
  13975. * * "insensitive" - the case insensitivity flag;
  13976. * @param part One of the possible values inside an attribute.
  13977. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  13978. */;
  13979. _proto.offsetOf = function offsetOf(name) {
  13980. var count = 1;
  13981. var attributeSpaces = this._spacesFor("attribute");
  13982. count += attributeSpaces.before.length;
  13983. if (name === "namespace" || name === "ns") {
  13984. return this.namespace ? count : -1;
  13985. }
  13986. if (name === "attributeNS") {
  13987. return count;
  13988. }
  13989. count += this.namespaceString.length;
  13990. if (this.namespace) {
  13991. count += 1;
  13992. }
  13993. if (name === "attribute") {
  13994. return count;
  13995. }
  13996. count += this.stringifyProperty("attribute").length;
  13997. count += attributeSpaces.after.length;
  13998. var operatorSpaces = this._spacesFor("operator");
  13999. count += operatorSpaces.before.length;
  14000. var operator = this.stringifyProperty("operator");
  14001. if (name === "operator") {
  14002. return operator ? count : -1;
  14003. }
  14004. count += operator.length;
  14005. count += operatorSpaces.after.length;
  14006. var valueSpaces = this._spacesFor("value");
  14007. count += valueSpaces.before.length;
  14008. var value = this.stringifyProperty("value");
  14009. if (name === "value") {
  14010. return value ? count : -1;
  14011. }
  14012. count += value.length;
  14013. count += valueSpaces.after.length;
  14014. var insensitiveSpaces = this._spacesFor("insensitive");
  14015. count += insensitiveSpaces.before.length;
  14016. if (name === "insensitive") {
  14017. return this.insensitive ? count : -1;
  14018. }
  14019. return -1;
  14020. };
  14021. _proto.toString = function toString() {
  14022. var _this2 = this;
  14023. var selector = [this.rawSpaceBefore, '['];
  14024. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14025. if (this.operator && (this.value || this.value === '')) {
  14026. selector.push(this._stringFor('operator'));
  14027. selector.push(this._stringFor('value'));
  14028. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14029. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14030. attrSpaces.before = " ";
  14031. }
  14032. return defaultAttrConcat(attrValue, attrSpaces);
  14033. }));
  14034. }
  14035. selector.push(']');
  14036. selector.push(this.rawSpaceAfter);
  14037. return selector.join('');
  14038. };
  14039. _createClass(Attribute, [{
  14040. key: "quoted",
  14041. get: function get() {
  14042. var qm = this.quoteMark;
  14043. return qm === "'" || qm === '"';
  14044. },
  14045. set: function set(value) {
  14046. warnOfDeprecatedQuotedAssignment();
  14047. }
  14048. /**
  14049. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14050. * returns `null` if the value is not quoted.
  14051. * returns `undefined` if the quotation state is unknown (this can happen when
  14052. * the attribute is constructed without specifying a quote mark.)
  14053. */
  14054. }, {
  14055. key: "quoteMark",
  14056. get: function get() {
  14057. return this._quoteMark;
  14058. }
  14059. /**
  14060. * Set the quote mark to be used by this attribute's value.
  14061. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14062. * value is updated accordingly.
  14063. *
  14064. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14065. */,
  14066. set: function set(quoteMark) {
  14067. if (!this._constructed) {
  14068. this._quoteMark = quoteMark;
  14069. return;
  14070. }
  14071. if (this._quoteMark !== quoteMark) {
  14072. this._quoteMark = quoteMark;
  14073. this._syncRawValue();
  14074. }
  14075. }
  14076. }, {
  14077. key: "qualifiedAttribute",
  14078. get: function get() {
  14079. return this.qualifiedName(this.raws.attribute || this.attribute);
  14080. }
  14081. }, {
  14082. key: "insensitiveFlag",
  14083. get: function get() {
  14084. return this.insensitive ? 'i' : '';
  14085. }
  14086. }, {
  14087. key: "value",
  14088. get: function get() {
  14089. return this._value;
  14090. },
  14091. set:
  14092. /**
  14093. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14094. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14095. * is unescaped during parsing and any quote marks are removed.
  14096. *
  14097. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14098. * a deprecation warning is raised when the new value contains any characters that would
  14099. * require escaping (including if it contains wrapped quotes).
  14100. *
  14101. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14102. * how the new value is quoted.
  14103. */
  14104. function set(v) {
  14105. if (this._constructed) {
  14106. var _unescapeValue2 = unescapeValue(v),
  14107. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14108. unescaped = _unescapeValue2.unescaped,
  14109. quoteMark = _unescapeValue2.quoteMark;
  14110. if (deprecatedUsage) {
  14111. warnOfDeprecatedValueAssignment();
  14112. }
  14113. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14114. return;
  14115. }
  14116. this._value = unescaped;
  14117. this._quoteMark = quoteMark;
  14118. this._syncRawValue();
  14119. } else {
  14120. this._value = v;
  14121. }
  14122. }
  14123. }, {
  14124. key: "insensitive",
  14125. get: function get() {
  14126. return this._insensitive;
  14127. }
  14128. /**
  14129. * Set the case insensitive flag.
  14130. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14131. * of the attribute is updated accordingly.
  14132. *
  14133. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14134. */,
  14135. set: function set(insensitive) {
  14136. if (!insensitive) {
  14137. this._insensitive = false;
  14138. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14139. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14140. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14141. this.raws.insensitiveFlag = undefined;
  14142. }
  14143. }
  14144. this._insensitive = insensitive;
  14145. }
  14146. }, {
  14147. key: "attribute",
  14148. get: function get() {
  14149. return this._attribute;
  14150. },
  14151. set: function set(name) {
  14152. this._handleEscapes("attribute", name);
  14153. this._attribute = name;
  14154. }
  14155. }]);
  14156. return Attribute;
  14157. }(_namespace["default"]);
  14158. exports["default"] = Attribute;
  14159. Attribute.NO_QUOTE = null;
  14160. Attribute.SINGLE_QUOTE = "'";
  14161. Attribute.DOUBLE_QUOTE = '"';
  14162. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14163. "'": {
  14164. quotes: 'single',
  14165. wrap: true
  14166. },
  14167. '"': {
  14168. quotes: 'double',
  14169. wrap: true
  14170. }
  14171. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14172. isIdentifier: true
  14173. }, _CSSESC_QUOTE_OPTIONS);
  14174. function defaultAttrConcat(attrValue, attrSpaces) {
  14175. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14176. }
  14177. } (attribute));
  14178. return attribute;
  14179. }
  14180. var universal = {exports: {}};
  14181. var hasRequiredUniversal;
  14182. function requireUniversal () {
  14183. if (hasRequiredUniversal) return universal.exports;
  14184. hasRequiredUniversal = 1;
  14185. (function (module, exports) {
  14186. exports.__esModule = true;
  14187. exports["default"] = void 0;
  14188. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14189. var _types = /*@__PURE__*/ requireTypes();
  14190. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14191. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14192. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14193. var Universal = /*#__PURE__*/function (_Namespace) {
  14194. _inheritsLoose(Universal, _Namespace);
  14195. function Universal(opts) {
  14196. var _this;
  14197. _this = _Namespace.call(this, opts) || this;
  14198. _this.type = _types.UNIVERSAL;
  14199. _this.value = '*';
  14200. return _this;
  14201. }
  14202. return Universal;
  14203. }(_namespace["default"]);
  14204. exports["default"] = Universal;
  14205. module.exports = exports.default;
  14206. } (universal, universal.exports));
  14207. return universal.exports;
  14208. }
  14209. var combinator = {exports: {}};
  14210. var hasRequiredCombinator;
  14211. function requireCombinator () {
  14212. if (hasRequiredCombinator) return combinator.exports;
  14213. hasRequiredCombinator = 1;
  14214. (function (module, exports) {
  14215. exports.__esModule = true;
  14216. exports["default"] = void 0;
  14217. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14218. var _types = /*@__PURE__*/ requireTypes();
  14219. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14220. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14221. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14222. var Combinator = /*#__PURE__*/function (_Node) {
  14223. _inheritsLoose(Combinator, _Node);
  14224. function Combinator(opts) {
  14225. var _this;
  14226. _this = _Node.call(this, opts) || this;
  14227. _this.type = _types.COMBINATOR;
  14228. return _this;
  14229. }
  14230. return Combinator;
  14231. }(_node["default"]);
  14232. exports["default"] = Combinator;
  14233. module.exports = exports.default;
  14234. } (combinator, combinator.exports));
  14235. return combinator.exports;
  14236. }
  14237. var nesting = {exports: {}};
  14238. var hasRequiredNesting;
  14239. function requireNesting () {
  14240. if (hasRequiredNesting) return nesting.exports;
  14241. hasRequiredNesting = 1;
  14242. (function (module, exports) {
  14243. exports.__esModule = true;
  14244. exports["default"] = void 0;
  14245. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14246. var _types = /*@__PURE__*/ requireTypes();
  14247. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14248. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14249. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14250. var Nesting = /*#__PURE__*/function (_Node) {
  14251. _inheritsLoose(Nesting, _Node);
  14252. function Nesting(opts) {
  14253. var _this;
  14254. _this = _Node.call(this, opts) || this;
  14255. _this.type = _types.NESTING;
  14256. _this.value = '&';
  14257. return _this;
  14258. }
  14259. return Nesting;
  14260. }(_node["default"]);
  14261. exports["default"] = Nesting;
  14262. module.exports = exports.default;
  14263. } (nesting, nesting.exports));
  14264. return nesting.exports;
  14265. }
  14266. var sortAscending = {exports: {}};
  14267. var hasRequiredSortAscending;
  14268. function requireSortAscending () {
  14269. if (hasRequiredSortAscending) return sortAscending.exports;
  14270. hasRequiredSortAscending = 1;
  14271. (function (module, exports) {
  14272. exports.__esModule = true;
  14273. exports["default"] = sortAscending;
  14274. function sortAscending(list) {
  14275. return list.sort(function (a, b) {
  14276. return a - b;
  14277. });
  14278. }
  14279. module.exports = exports.default;
  14280. } (sortAscending, sortAscending.exports));
  14281. return sortAscending.exports;
  14282. }
  14283. var tokenize = {};
  14284. var tokenTypes = {};
  14285. var hasRequiredTokenTypes;
  14286. function requireTokenTypes () {
  14287. if (hasRequiredTokenTypes) return tokenTypes;
  14288. hasRequiredTokenTypes = 1;
  14289. tokenTypes.__esModule = true;
  14290. 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;
  14291. var ampersand = 38; // `&`.charCodeAt(0);
  14292. tokenTypes.ampersand = ampersand;
  14293. var asterisk = 42; // `*`.charCodeAt(0);
  14294. tokenTypes.asterisk = asterisk;
  14295. var at = 64; // `@`.charCodeAt(0);
  14296. tokenTypes.at = at;
  14297. var comma = 44; // `,`.charCodeAt(0);
  14298. tokenTypes.comma = comma;
  14299. var colon = 58; // `:`.charCodeAt(0);
  14300. tokenTypes.colon = colon;
  14301. var semicolon = 59; // `;`.charCodeAt(0);
  14302. tokenTypes.semicolon = semicolon;
  14303. var openParenthesis = 40; // `(`.charCodeAt(0);
  14304. tokenTypes.openParenthesis = openParenthesis;
  14305. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14306. tokenTypes.closeParenthesis = closeParenthesis;
  14307. var openSquare = 91; // `[`.charCodeAt(0);
  14308. tokenTypes.openSquare = openSquare;
  14309. var closeSquare = 93; // `]`.charCodeAt(0);
  14310. tokenTypes.closeSquare = closeSquare;
  14311. var dollar = 36; // `$`.charCodeAt(0);
  14312. tokenTypes.dollar = dollar;
  14313. var tilde = 126; // `~`.charCodeAt(0);
  14314. tokenTypes.tilde = tilde;
  14315. var caret = 94; // `^`.charCodeAt(0);
  14316. tokenTypes.caret = caret;
  14317. var plus = 43; // `+`.charCodeAt(0);
  14318. tokenTypes.plus = plus;
  14319. var equals = 61; // `=`.charCodeAt(0);
  14320. tokenTypes.equals = equals;
  14321. var pipe = 124; // `|`.charCodeAt(0);
  14322. tokenTypes.pipe = pipe;
  14323. var greaterThan = 62; // `>`.charCodeAt(0);
  14324. tokenTypes.greaterThan = greaterThan;
  14325. var space = 32; // ` `.charCodeAt(0);
  14326. tokenTypes.space = space;
  14327. var singleQuote = 39; // `'`.charCodeAt(0);
  14328. tokenTypes.singleQuote = singleQuote;
  14329. var doubleQuote = 34; // `"`.charCodeAt(0);
  14330. tokenTypes.doubleQuote = doubleQuote;
  14331. var slash = 47; // `/`.charCodeAt(0);
  14332. tokenTypes.slash = slash;
  14333. var bang = 33; // `!`.charCodeAt(0);
  14334. tokenTypes.bang = bang;
  14335. var backslash = 92; // '\\'.charCodeAt(0);
  14336. tokenTypes.backslash = backslash;
  14337. var cr = 13; // '\r'.charCodeAt(0);
  14338. tokenTypes.cr = cr;
  14339. var feed = 12; // '\f'.charCodeAt(0);
  14340. tokenTypes.feed = feed;
  14341. var newline = 10; // '\n'.charCodeAt(0);
  14342. tokenTypes.newline = newline;
  14343. var tab = 9; // '\t'.charCodeAt(0);
  14344. // Expose aliases primarily for readability.
  14345. tokenTypes.tab = tab;
  14346. var str = singleQuote;
  14347. // No good single character representation!
  14348. tokenTypes.str = str;
  14349. var comment = -1;
  14350. tokenTypes.comment = comment;
  14351. var word = -2;
  14352. tokenTypes.word = word;
  14353. var combinator = -3;
  14354. tokenTypes.combinator = combinator;
  14355. return tokenTypes;
  14356. }
  14357. var hasRequiredTokenize;
  14358. function requireTokenize () {
  14359. if (hasRequiredTokenize) return tokenize;
  14360. hasRequiredTokenize = 1;
  14361. (function (exports) {
  14362. exports.__esModule = true;
  14363. exports.FIELDS = void 0;
  14364. exports["default"] = tokenize;
  14365. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14366. var _unescapable, _wordDelimiters;
  14367. 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); }
  14368. 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; }
  14369. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14370. 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);
  14371. var hex = {};
  14372. var hexChars = "0123456789abcdefABCDEF";
  14373. for (var i = 0; i < hexChars.length; i++) {
  14374. hex[hexChars.charCodeAt(i)] = true;
  14375. }
  14376. /**
  14377. * Returns the last index of the bar css word
  14378. * @param {string} css The string in which the word begins
  14379. * @param {number} start The index into the string where word's first letter occurs
  14380. */
  14381. function consumeWord(css, start) {
  14382. var next = start;
  14383. var code;
  14384. do {
  14385. code = css.charCodeAt(next);
  14386. if (wordDelimiters[code]) {
  14387. return next - 1;
  14388. } else if (code === t.backslash) {
  14389. next = consumeEscape(css, next) + 1;
  14390. } else {
  14391. // All other characters are part of the word
  14392. next++;
  14393. }
  14394. } while (next < css.length);
  14395. return next - 1;
  14396. }
  14397. /**
  14398. * Returns the last index of the escape sequence
  14399. * @param {string} css The string in which the sequence begins
  14400. * @param {number} start The index into the string where escape character (`\`) occurs.
  14401. */
  14402. function consumeEscape(css, start) {
  14403. var next = start;
  14404. var code = css.charCodeAt(next + 1);
  14405. if (unescapable[code]) ; else if (hex[code]) {
  14406. var hexDigits = 0;
  14407. // consume up to 6 hex chars
  14408. do {
  14409. next++;
  14410. hexDigits++;
  14411. code = css.charCodeAt(next + 1);
  14412. } while (hex[code] && hexDigits < 6);
  14413. // if fewer than 6 hex chars, a trailing space ends the escape
  14414. if (hexDigits < 6 && code === t.space) {
  14415. next++;
  14416. }
  14417. } else {
  14418. // the next char is part of the current word
  14419. next++;
  14420. }
  14421. return next;
  14422. }
  14423. var FIELDS = {
  14424. TYPE: 0,
  14425. START_LINE: 1,
  14426. START_COL: 2,
  14427. END_LINE: 3,
  14428. END_COL: 4,
  14429. START_POS: 5,
  14430. END_POS: 6
  14431. };
  14432. exports.FIELDS = FIELDS;
  14433. function tokenize(input) {
  14434. var tokens = [];
  14435. var css = input.css.valueOf();
  14436. var _css = css,
  14437. length = _css.length;
  14438. var offset = -1;
  14439. var line = 1;
  14440. var start = 0;
  14441. var end = 0;
  14442. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14443. function unclosed(what, fix) {
  14444. if (input.safe) {
  14445. // fyi: this is never set to true.
  14446. css += fix;
  14447. next = css.length - 1;
  14448. } else {
  14449. throw input.error('Unclosed ' + what, line, start - offset, start);
  14450. }
  14451. }
  14452. while (start < length) {
  14453. code = css.charCodeAt(start);
  14454. if (code === t.newline) {
  14455. offset = start;
  14456. line += 1;
  14457. }
  14458. switch (code) {
  14459. case t.space:
  14460. case t.tab:
  14461. case t.newline:
  14462. case t.cr:
  14463. case t.feed:
  14464. next = start;
  14465. do {
  14466. next += 1;
  14467. code = css.charCodeAt(next);
  14468. if (code === t.newline) {
  14469. offset = next;
  14470. line += 1;
  14471. }
  14472. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  14473. tokenType = t.space;
  14474. endLine = line;
  14475. endColumn = next - offset - 1;
  14476. end = next;
  14477. break;
  14478. case t.plus:
  14479. case t.greaterThan:
  14480. case t.tilde:
  14481. case t.pipe:
  14482. next = start;
  14483. do {
  14484. next += 1;
  14485. code = css.charCodeAt(next);
  14486. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  14487. tokenType = t.combinator;
  14488. endLine = line;
  14489. endColumn = start - offset;
  14490. end = next;
  14491. break;
  14492. // Consume these characters as single tokens.
  14493. case t.asterisk:
  14494. case t.ampersand:
  14495. case t.bang:
  14496. case t.comma:
  14497. case t.equals:
  14498. case t.dollar:
  14499. case t.caret:
  14500. case t.openSquare:
  14501. case t.closeSquare:
  14502. case t.colon:
  14503. case t.semicolon:
  14504. case t.openParenthesis:
  14505. case t.closeParenthesis:
  14506. next = start;
  14507. tokenType = code;
  14508. endLine = line;
  14509. endColumn = start - offset;
  14510. end = next + 1;
  14511. break;
  14512. case t.singleQuote:
  14513. case t.doubleQuote:
  14514. quote = code === t.singleQuote ? "'" : '"';
  14515. next = start;
  14516. do {
  14517. escaped = false;
  14518. next = css.indexOf(quote, next + 1);
  14519. if (next === -1) {
  14520. unclosed('quote', quote);
  14521. }
  14522. escapePos = next;
  14523. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  14524. escapePos -= 1;
  14525. escaped = !escaped;
  14526. }
  14527. } while (escaped);
  14528. tokenType = t.str;
  14529. endLine = line;
  14530. endColumn = start - offset;
  14531. end = next + 1;
  14532. break;
  14533. default:
  14534. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  14535. next = css.indexOf('*/', start + 2) + 1;
  14536. if (next === 0) {
  14537. unclosed('comment', '*/');
  14538. }
  14539. content = css.slice(start, next + 1);
  14540. lines = content.split('\n');
  14541. last = lines.length - 1;
  14542. if (last > 0) {
  14543. nextLine = line + last;
  14544. nextOffset = next - lines[last].length;
  14545. } else {
  14546. nextLine = line;
  14547. nextOffset = offset;
  14548. }
  14549. tokenType = t.comment;
  14550. line = nextLine;
  14551. endLine = nextLine;
  14552. endColumn = next - nextOffset;
  14553. } else if (code === t.slash) {
  14554. next = start;
  14555. tokenType = code;
  14556. endLine = line;
  14557. endColumn = start - offset;
  14558. end = next + 1;
  14559. } else {
  14560. next = consumeWord(css, start);
  14561. tokenType = t.word;
  14562. endLine = line;
  14563. endColumn = next - offset;
  14564. }
  14565. end = next + 1;
  14566. break;
  14567. }
  14568. // Ensure that the token structure remains consistent
  14569. tokens.push([tokenType,
  14570. // [0] Token type
  14571. line,
  14572. // [1] Starting line
  14573. start - offset,
  14574. // [2] Starting column
  14575. endLine,
  14576. // [3] Ending line
  14577. endColumn,
  14578. // [4] Ending column
  14579. start,
  14580. // [5] Start position / Source index
  14581. end // [6] End position
  14582. ]);
  14583. // Reset offset for the next token
  14584. if (nextOffset) {
  14585. offset = nextOffset;
  14586. nextOffset = null;
  14587. }
  14588. start = end;
  14589. }
  14590. return tokens;
  14591. }
  14592. } (tokenize));
  14593. return tokenize;
  14594. }
  14595. var hasRequiredParser;
  14596. function requireParser () {
  14597. if (hasRequiredParser) return parser.exports;
  14598. hasRequiredParser = 1;
  14599. (function (module, exports) {
  14600. exports.__esModule = true;
  14601. exports["default"] = void 0;
  14602. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  14603. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  14604. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  14605. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  14606. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  14607. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  14608. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  14609. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  14610. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  14611. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  14612. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  14613. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  14614. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  14615. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  14616. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14617. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  14618. var _util = /*@__PURE__*/ requireUtil();
  14619. var _WHITESPACE_TOKENS, _Object$assign;
  14620. 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); }
  14621. 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; }
  14622. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14623. 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); } }
  14624. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14625. 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);
  14626. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  14627. function tokenStart(token) {
  14628. return {
  14629. line: token[_tokenize.FIELDS.START_LINE],
  14630. column: token[_tokenize.FIELDS.START_COL]
  14631. };
  14632. }
  14633. function tokenEnd(token) {
  14634. return {
  14635. line: token[_tokenize.FIELDS.END_LINE],
  14636. column: token[_tokenize.FIELDS.END_COL]
  14637. };
  14638. }
  14639. function getSource(startLine, startColumn, endLine, endColumn) {
  14640. return {
  14641. start: {
  14642. line: startLine,
  14643. column: startColumn
  14644. },
  14645. end: {
  14646. line: endLine,
  14647. column: endColumn
  14648. }
  14649. };
  14650. }
  14651. function getTokenSource(token) {
  14652. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  14653. }
  14654. function getTokenSourceSpan(startToken, endToken) {
  14655. if (!startToken) {
  14656. return undefined;
  14657. }
  14658. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  14659. }
  14660. function unescapeProp(node, prop) {
  14661. var value = node[prop];
  14662. if (typeof value !== "string") {
  14663. return;
  14664. }
  14665. if (value.indexOf("\\") !== -1) {
  14666. (0, _util.ensureObject)(node, 'raws');
  14667. node[prop] = (0, _util.unesc)(value);
  14668. if (node.raws[prop] === undefined) {
  14669. node.raws[prop] = value;
  14670. }
  14671. }
  14672. return node;
  14673. }
  14674. function indexesOf(array, item) {
  14675. var i = -1;
  14676. var indexes = [];
  14677. while ((i = array.indexOf(item, i + 1)) !== -1) {
  14678. indexes.push(i);
  14679. }
  14680. return indexes;
  14681. }
  14682. function uniqs() {
  14683. var list = Array.prototype.concat.apply([], arguments);
  14684. return list.filter(function (item, i) {
  14685. return i === list.indexOf(item);
  14686. });
  14687. }
  14688. var Parser = /*#__PURE__*/function () {
  14689. function Parser(rule, options) {
  14690. if (options === void 0) {
  14691. options = {};
  14692. }
  14693. this.rule = rule;
  14694. this.options = Object.assign({
  14695. lossy: false,
  14696. safe: false
  14697. }, options);
  14698. this.position = 0;
  14699. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  14700. this.tokens = (0, _tokenize["default"])({
  14701. css: this.css,
  14702. error: this._errorGenerator(),
  14703. safe: this.options.safe
  14704. });
  14705. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  14706. this.root = new _root["default"]({
  14707. source: rootSource
  14708. });
  14709. this.root.errorGenerator = this._errorGenerator();
  14710. var selector = new _selector["default"]({
  14711. source: {
  14712. start: {
  14713. line: 1,
  14714. column: 1
  14715. }
  14716. },
  14717. sourceIndex: 0
  14718. });
  14719. this.root.append(selector);
  14720. this.current = selector;
  14721. this.loop();
  14722. }
  14723. var _proto = Parser.prototype;
  14724. _proto._errorGenerator = function _errorGenerator() {
  14725. var _this = this;
  14726. return function (message, errorOptions) {
  14727. if (typeof _this.rule === 'string') {
  14728. return new Error(message);
  14729. }
  14730. return _this.rule.error(message, errorOptions);
  14731. };
  14732. };
  14733. _proto.attribute = function attribute() {
  14734. var attr = [];
  14735. var startingToken = this.currToken;
  14736. this.position++;
  14737. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14738. attr.push(this.currToken);
  14739. this.position++;
  14740. }
  14741. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14742. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  14743. }
  14744. var len = attr.length;
  14745. var node = {
  14746. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  14747. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  14748. };
  14749. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  14750. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  14751. }
  14752. var pos = 0;
  14753. var spaceBefore = '';
  14754. var commentBefore = '';
  14755. var lastAdded = null;
  14756. var spaceAfterMeaningfulToken = false;
  14757. while (pos < len) {
  14758. var token = attr[pos];
  14759. var content = this.content(token);
  14760. var next = attr[pos + 1];
  14761. switch (token[_tokenize.FIELDS.TYPE]) {
  14762. case tokens.space:
  14763. // if (
  14764. // len === 1 ||
  14765. // pos === 0 && this.content(next) === '|'
  14766. // ) {
  14767. // return this.expected('attribute', token[TOKEN.START_POS], content);
  14768. // }
  14769. spaceAfterMeaningfulToken = true;
  14770. if (this.options.lossy) {
  14771. break;
  14772. }
  14773. if (lastAdded) {
  14774. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  14775. var prevContent = node.spaces[lastAdded].after || '';
  14776. node.spaces[lastAdded].after = prevContent + content;
  14777. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  14778. if (existingComment) {
  14779. node.raws.spaces[lastAdded].after = existingComment + content;
  14780. }
  14781. } else {
  14782. spaceBefore = spaceBefore + content;
  14783. commentBefore = commentBefore + content;
  14784. }
  14785. break;
  14786. case tokens.asterisk:
  14787. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14788. node.operator = content;
  14789. lastAdded = 'operator';
  14790. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  14791. if (spaceBefore) {
  14792. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14793. node.spaces.attribute.before = spaceBefore;
  14794. spaceBefore = '';
  14795. }
  14796. if (commentBefore) {
  14797. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14798. node.raws.spaces.attribute.before = spaceBefore;
  14799. commentBefore = '';
  14800. }
  14801. node.namespace = (node.namespace || "") + content;
  14802. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  14803. if (rawValue) {
  14804. node.raws.namespace += content;
  14805. }
  14806. lastAdded = 'namespace';
  14807. }
  14808. spaceAfterMeaningfulToken = false;
  14809. break;
  14810. case tokens.dollar:
  14811. if (lastAdded === "value") {
  14812. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  14813. node.value += "$";
  14814. if (oldRawValue) {
  14815. node.raws.value = oldRawValue + "$";
  14816. }
  14817. break;
  14818. }
  14819. // Falls through
  14820. case tokens.caret:
  14821. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14822. node.operator = content;
  14823. lastAdded = 'operator';
  14824. }
  14825. spaceAfterMeaningfulToken = false;
  14826. break;
  14827. case tokens.combinator:
  14828. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14829. node.operator = content;
  14830. lastAdded = 'operator';
  14831. }
  14832. if (content !== '|') {
  14833. spaceAfterMeaningfulToken = false;
  14834. break;
  14835. }
  14836. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14837. node.operator = content;
  14838. lastAdded = 'operator';
  14839. } else if (!node.namespace && !node.attribute) {
  14840. node.namespace = true;
  14841. }
  14842. spaceAfterMeaningfulToken = false;
  14843. break;
  14844. case tokens.word:
  14845. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  14846. // this look-ahead probably fails with comment nodes involved.
  14847. !node.operator && !node.namespace) {
  14848. node.namespace = content;
  14849. lastAdded = 'namespace';
  14850. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  14851. if (spaceBefore) {
  14852. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14853. node.spaces.attribute.before = spaceBefore;
  14854. spaceBefore = '';
  14855. }
  14856. if (commentBefore) {
  14857. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14858. node.raws.spaces.attribute.before = commentBefore;
  14859. commentBefore = '';
  14860. }
  14861. node.attribute = (node.attribute || "") + content;
  14862. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  14863. if (_rawValue) {
  14864. node.raws.attribute += content;
  14865. }
  14866. lastAdded = 'attribute';
  14867. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  14868. var _unescaped = (0, _util.unesc)(content);
  14869. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  14870. var oldValue = node.value || '';
  14871. node.value = oldValue + _unescaped;
  14872. node.quoteMark = null;
  14873. if (_unescaped !== content || _oldRawValue) {
  14874. (0, _util.ensureObject)(node, 'raws');
  14875. node.raws.value = (_oldRawValue || oldValue) + content;
  14876. }
  14877. lastAdded = 'value';
  14878. } else {
  14879. var insensitive = content === 'i' || content === "I";
  14880. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  14881. node.insensitive = insensitive;
  14882. if (!insensitive || content === "I") {
  14883. (0, _util.ensureObject)(node, 'raws');
  14884. node.raws.insensitiveFlag = content;
  14885. }
  14886. lastAdded = 'insensitive';
  14887. if (spaceBefore) {
  14888. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  14889. node.spaces.insensitive.before = spaceBefore;
  14890. spaceBefore = '';
  14891. }
  14892. if (commentBefore) {
  14893. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  14894. node.raws.spaces.insensitive.before = commentBefore;
  14895. commentBefore = '';
  14896. }
  14897. } else if (node.value || node.value === '') {
  14898. lastAdded = 'value';
  14899. node.value += content;
  14900. if (node.raws.value) {
  14901. node.raws.value += content;
  14902. }
  14903. }
  14904. }
  14905. spaceAfterMeaningfulToken = false;
  14906. break;
  14907. case tokens.str:
  14908. if (!node.attribute || !node.operator) {
  14909. return this.error("Expected an attribute followed by an operator preceding the string.", {
  14910. index: token[_tokenize.FIELDS.START_POS]
  14911. });
  14912. }
  14913. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  14914. unescaped = _unescapeValue.unescaped,
  14915. quoteMark = _unescapeValue.quoteMark;
  14916. node.value = unescaped;
  14917. node.quoteMark = quoteMark;
  14918. lastAdded = 'value';
  14919. (0, _util.ensureObject)(node, 'raws');
  14920. node.raws.value = content;
  14921. spaceAfterMeaningfulToken = false;
  14922. break;
  14923. case tokens.equals:
  14924. if (!node.attribute) {
  14925. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  14926. }
  14927. if (node.value) {
  14928. return this.error('Unexpected "=" found; an operator was already defined.', {
  14929. index: token[_tokenize.FIELDS.START_POS]
  14930. });
  14931. }
  14932. node.operator = node.operator ? node.operator + content : content;
  14933. lastAdded = 'operator';
  14934. spaceAfterMeaningfulToken = false;
  14935. break;
  14936. case tokens.comment:
  14937. if (lastAdded) {
  14938. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  14939. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  14940. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  14941. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  14942. node.raws.spaces[lastAdded].after = rawLastComment + content;
  14943. } else {
  14944. var lastValue = node[lastAdded] || '';
  14945. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  14946. (0, _util.ensureObject)(node, 'raws');
  14947. node.raws[lastAdded] = rawLastValue + content;
  14948. }
  14949. } else {
  14950. commentBefore = commentBefore + content;
  14951. }
  14952. break;
  14953. default:
  14954. return this.error("Unexpected \"" + content + "\" found.", {
  14955. index: token[_tokenize.FIELDS.START_POS]
  14956. });
  14957. }
  14958. pos++;
  14959. }
  14960. unescapeProp(node, "attribute");
  14961. unescapeProp(node, "namespace");
  14962. this.newNode(new _attribute["default"](node));
  14963. this.position++;
  14964. }
  14965. /**
  14966. * return a node containing meaningless garbage up to (but not including) the specified token position.
  14967. * if the token position is negative, all remaining tokens are consumed.
  14968. *
  14969. * This returns an array containing a single string node if all whitespace,
  14970. * otherwise an array of comment nodes with space before and after.
  14971. *
  14972. * These tokens are not added to the current selector, the caller can add them or use them to amend
  14973. * a previous node's space metadata.
  14974. *
  14975. * In lossy mode, this returns only comments.
  14976. */;
  14977. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  14978. if (stopPosition < 0) {
  14979. stopPosition = this.tokens.length;
  14980. }
  14981. var startPosition = this.position;
  14982. var nodes = [];
  14983. var space = "";
  14984. var lastComment = undefined;
  14985. do {
  14986. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  14987. if (!this.options.lossy) {
  14988. space += this.content();
  14989. }
  14990. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  14991. var spaces = {};
  14992. if (space) {
  14993. spaces.before = space;
  14994. space = "";
  14995. }
  14996. lastComment = new _comment["default"]({
  14997. value: this.content(),
  14998. source: getTokenSource(this.currToken),
  14999. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15000. spaces: spaces
  15001. });
  15002. nodes.push(lastComment);
  15003. }
  15004. } while (++this.position < stopPosition);
  15005. if (space) {
  15006. if (lastComment) {
  15007. lastComment.spaces.after = space;
  15008. } else if (!this.options.lossy) {
  15009. var firstToken = this.tokens[startPosition];
  15010. var lastToken = this.tokens[this.position - 1];
  15011. nodes.push(new _string["default"]({
  15012. value: '',
  15013. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15014. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15015. spaces: {
  15016. before: space,
  15017. after: ''
  15018. }
  15019. }));
  15020. }
  15021. }
  15022. return nodes;
  15023. }
  15024. /**
  15025. *
  15026. * @param {*} nodes
  15027. */;
  15028. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15029. var _this2 = this;
  15030. if (requiredSpace === void 0) {
  15031. requiredSpace = false;
  15032. }
  15033. var space = "";
  15034. var rawSpace = "";
  15035. nodes.forEach(function (n) {
  15036. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15037. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15038. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15039. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15040. });
  15041. if (rawSpace === space) {
  15042. rawSpace = undefined;
  15043. }
  15044. var result = {
  15045. space: space,
  15046. rawSpace: rawSpace
  15047. };
  15048. return result;
  15049. };
  15050. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15051. if (position === void 0) {
  15052. position = this.position;
  15053. }
  15054. 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;
  15055. };
  15056. _proto.namedCombinator = function namedCombinator() {
  15057. if (this.isNamedCombinator()) {
  15058. var nameRaw = this.content(this.tokens[this.position + 1]);
  15059. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15060. var raws = {};
  15061. if (name !== nameRaw) {
  15062. raws.value = "/" + nameRaw + "/";
  15063. }
  15064. var node = new _combinator["default"]({
  15065. value: "/" + name + "/",
  15066. 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]),
  15067. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15068. raws: raws
  15069. });
  15070. this.position = this.position + 3;
  15071. return node;
  15072. } else {
  15073. this.unexpected();
  15074. }
  15075. };
  15076. _proto.combinator = function combinator() {
  15077. var _this3 = this;
  15078. if (this.content() === '|') {
  15079. return this.namespace();
  15080. }
  15081. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15082. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15083. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15084. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15085. if (nodes.length > 0) {
  15086. var last = this.current.last;
  15087. if (last) {
  15088. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15089. space = _this$convertWhitespa.space,
  15090. rawSpace = _this$convertWhitespa.rawSpace;
  15091. if (rawSpace !== undefined) {
  15092. last.rawSpaceAfter += rawSpace;
  15093. }
  15094. last.spaces.after += space;
  15095. } else {
  15096. nodes.forEach(function (n) {
  15097. return _this3.newNode(n);
  15098. });
  15099. }
  15100. }
  15101. return;
  15102. }
  15103. var firstToken = this.currToken;
  15104. var spaceOrDescendantSelectorNodes = undefined;
  15105. if (nextSigTokenPos > this.position) {
  15106. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15107. }
  15108. var node;
  15109. if (this.isNamedCombinator()) {
  15110. node = this.namedCombinator();
  15111. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15112. node = new _combinator["default"]({
  15113. value: this.content(),
  15114. source: getTokenSource(this.currToken),
  15115. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15116. });
  15117. this.position++;
  15118. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15119. this.unexpected();
  15120. }
  15121. if (node) {
  15122. if (spaceOrDescendantSelectorNodes) {
  15123. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15124. _space = _this$convertWhitespa2.space,
  15125. _rawSpace = _this$convertWhitespa2.rawSpace;
  15126. node.spaces.before = _space;
  15127. node.rawSpaceBefore = _rawSpace;
  15128. }
  15129. } else {
  15130. // descendant combinator
  15131. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15132. _space2 = _this$convertWhitespa3.space,
  15133. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15134. if (!_rawSpace2) {
  15135. _rawSpace2 = _space2;
  15136. }
  15137. var spaces = {};
  15138. var raws = {
  15139. spaces: {}
  15140. };
  15141. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15142. spaces.before = _space2.slice(0, _space2.length - 1);
  15143. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15144. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15145. spaces.after = _space2.slice(1);
  15146. raws.spaces.after = _rawSpace2.slice(1);
  15147. } else {
  15148. raws.value = _rawSpace2;
  15149. }
  15150. node = new _combinator["default"]({
  15151. value: ' ',
  15152. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15153. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15154. spaces: spaces,
  15155. raws: raws
  15156. });
  15157. }
  15158. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15159. node.spaces.after = this.optionalSpace(this.content());
  15160. this.position++;
  15161. }
  15162. return this.newNode(node);
  15163. };
  15164. _proto.comma = function comma() {
  15165. if (this.position === this.tokens.length - 1) {
  15166. this.root.trailingComma = true;
  15167. this.position++;
  15168. return;
  15169. }
  15170. this.current._inferEndPosition();
  15171. var selector = new _selector["default"]({
  15172. source: {
  15173. start: tokenStart(this.tokens[this.position + 1])
  15174. },
  15175. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15176. });
  15177. this.current.parent.append(selector);
  15178. this.current = selector;
  15179. this.position++;
  15180. };
  15181. _proto.comment = function comment() {
  15182. var current = this.currToken;
  15183. this.newNode(new _comment["default"]({
  15184. value: this.content(),
  15185. source: getTokenSource(current),
  15186. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15187. }));
  15188. this.position++;
  15189. };
  15190. _proto.error = function error(message, opts) {
  15191. throw this.root.error(message, opts);
  15192. };
  15193. _proto.missingBackslash = function missingBackslash() {
  15194. return this.error('Expected a backslash preceding the semicolon.', {
  15195. index: this.currToken[_tokenize.FIELDS.START_POS]
  15196. });
  15197. };
  15198. _proto.missingParenthesis = function missingParenthesis() {
  15199. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15200. };
  15201. _proto.missingSquareBracket = function missingSquareBracket() {
  15202. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15203. };
  15204. _proto.unexpected = function unexpected() {
  15205. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15206. };
  15207. _proto.unexpectedPipe = function unexpectedPipe() {
  15208. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15209. };
  15210. _proto.namespace = function namespace() {
  15211. var before = this.prevToken && this.content(this.prevToken) || true;
  15212. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15213. this.position++;
  15214. return this.word(before);
  15215. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15216. this.position++;
  15217. return this.universal(before);
  15218. }
  15219. this.unexpectedPipe();
  15220. };
  15221. _proto.nesting = function nesting() {
  15222. if (this.nextToken) {
  15223. var nextContent = this.content(this.nextToken);
  15224. if (nextContent === "|") {
  15225. this.position++;
  15226. return;
  15227. }
  15228. }
  15229. var current = this.currToken;
  15230. this.newNode(new _nesting["default"]({
  15231. value: this.content(),
  15232. source: getTokenSource(current),
  15233. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15234. }));
  15235. this.position++;
  15236. };
  15237. _proto.parentheses = function parentheses() {
  15238. var last = this.current.last;
  15239. var unbalanced = 1;
  15240. this.position++;
  15241. if (last && last.type === types.PSEUDO) {
  15242. var selector = new _selector["default"]({
  15243. source: {
  15244. start: tokenStart(this.tokens[this.position])
  15245. },
  15246. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15247. });
  15248. var cache = this.current;
  15249. last.append(selector);
  15250. this.current = selector;
  15251. while (this.position < this.tokens.length && unbalanced) {
  15252. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15253. unbalanced++;
  15254. }
  15255. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15256. unbalanced--;
  15257. }
  15258. if (unbalanced) {
  15259. this.parse();
  15260. } else {
  15261. this.current.source.end = tokenEnd(this.currToken);
  15262. this.current.parent.source.end = tokenEnd(this.currToken);
  15263. this.position++;
  15264. }
  15265. }
  15266. this.current = cache;
  15267. } else {
  15268. // I think this case should be an error. It's used to implement a basic parse of media queries
  15269. // but I don't think it's a good idea.
  15270. var parenStart = this.currToken;
  15271. var parenValue = "(";
  15272. var parenEnd;
  15273. while (this.position < this.tokens.length && unbalanced) {
  15274. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15275. unbalanced++;
  15276. }
  15277. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15278. unbalanced--;
  15279. }
  15280. parenEnd = this.currToken;
  15281. parenValue += this.parseParenthesisToken(this.currToken);
  15282. this.position++;
  15283. }
  15284. if (last) {
  15285. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15286. } else {
  15287. this.newNode(new _string["default"]({
  15288. value: parenValue,
  15289. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15290. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15291. }));
  15292. }
  15293. }
  15294. if (unbalanced) {
  15295. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15296. }
  15297. };
  15298. _proto.pseudo = function pseudo() {
  15299. var _this4 = this;
  15300. var pseudoStr = '';
  15301. var startingToken = this.currToken;
  15302. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15303. pseudoStr += this.content();
  15304. this.position++;
  15305. }
  15306. if (!this.currToken) {
  15307. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15308. }
  15309. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15310. this.splitWord(false, function (first, length) {
  15311. pseudoStr += first;
  15312. _this4.newNode(new _pseudo["default"]({
  15313. value: pseudoStr,
  15314. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15315. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15316. }));
  15317. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15318. _this4.error('Misplaced parenthesis.', {
  15319. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15320. });
  15321. }
  15322. });
  15323. } else {
  15324. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15325. }
  15326. };
  15327. _proto.space = function space() {
  15328. var content = this.content();
  15329. // Handle space before and after the selector
  15330. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15331. return node.type === 'comment';
  15332. })) {
  15333. this.spaces = this.optionalSpace(content);
  15334. this.position++;
  15335. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15336. this.current.last.spaces.after = this.optionalSpace(content);
  15337. this.position++;
  15338. } else {
  15339. this.combinator();
  15340. }
  15341. };
  15342. _proto.string = function string() {
  15343. var current = this.currToken;
  15344. this.newNode(new _string["default"]({
  15345. value: this.content(),
  15346. source: getTokenSource(current),
  15347. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15348. }));
  15349. this.position++;
  15350. };
  15351. _proto.universal = function universal(namespace) {
  15352. var nextToken = this.nextToken;
  15353. if (nextToken && this.content(nextToken) === '|') {
  15354. this.position++;
  15355. return this.namespace();
  15356. }
  15357. var current = this.currToken;
  15358. this.newNode(new _universal["default"]({
  15359. value: this.content(),
  15360. source: getTokenSource(current),
  15361. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15362. }), namespace);
  15363. this.position++;
  15364. };
  15365. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15366. var _this5 = this;
  15367. var nextToken = this.nextToken;
  15368. var word = this.content();
  15369. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15370. this.position++;
  15371. var current = this.content();
  15372. word += current;
  15373. if (current.lastIndexOf('\\') === current.length - 1) {
  15374. var next = this.nextToken;
  15375. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15376. word += this.requiredSpace(this.content(next));
  15377. this.position++;
  15378. }
  15379. }
  15380. nextToken = this.nextToken;
  15381. }
  15382. var hasClass = indexesOf(word, '.').filter(function (i) {
  15383. // Allow escaped dot within class name
  15384. var escapedDot = word[i - 1] === '\\';
  15385. // Allow decimal numbers percent in @keyframes
  15386. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15387. return !escapedDot && !isKeyframesPercent;
  15388. });
  15389. var hasId = indexesOf(word, '#').filter(function (i) {
  15390. return word[i - 1] !== '\\';
  15391. });
  15392. // Eliminate Sass interpolations from the list of id indexes
  15393. var interpolations = indexesOf(word, '#{');
  15394. if (interpolations.length) {
  15395. hasId = hasId.filter(function (hashIndex) {
  15396. return !~interpolations.indexOf(hashIndex);
  15397. });
  15398. }
  15399. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15400. indices.forEach(function (ind, i) {
  15401. var index = indices[i + 1] || word.length;
  15402. var value = word.slice(ind, index);
  15403. if (i === 0 && firstCallback) {
  15404. return firstCallback.call(_this5, value, indices.length);
  15405. }
  15406. var node;
  15407. var current = _this5.currToken;
  15408. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15409. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15410. if (~hasClass.indexOf(ind)) {
  15411. var classNameOpts = {
  15412. value: value.slice(1),
  15413. source: source,
  15414. sourceIndex: sourceIndex
  15415. };
  15416. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15417. } else if (~hasId.indexOf(ind)) {
  15418. var idOpts = {
  15419. value: value.slice(1),
  15420. source: source,
  15421. sourceIndex: sourceIndex
  15422. };
  15423. node = new _id["default"](unescapeProp(idOpts, "value"));
  15424. } else {
  15425. var tagOpts = {
  15426. value: value,
  15427. source: source,
  15428. sourceIndex: sourceIndex
  15429. };
  15430. unescapeProp(tagOpts, "value");
  15431. node = new _tag["default"](tagOpts);
  15432. }
  15433. _this5.newNode(node, namespace);
  15434. // Ensure that the namespace is used only once
  15435. namespace = null;
  15436. });
  15437. this.position++;
  15438. };
  15439. _proto.word = function word(namespace) {
  15440. var nextToken = this.nextToken;
  15441. if (nextToken && this.content(nextToken) === '|') {
  15442. this.position++;
  15443. return this.namespace();
  15444. }
  15445. return this.splitWord(namespace);
  15446. };
  15447. _proto.loop = function loop() {
  15448. while (this.position < this.tokens.length) {
  15449. this.parse(true);
  15450. }
  15451. this.current._inferEndPosition();
  15452. return this.root;
  15453. };
  15454. _proto.parse = function parse(throwOnParenthesis) {
  15455. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  15456. case tokens.space:
  15457. this.space();
  15458. break;
  15459. case tokens.comment:
  15460. this.comment();
  15461. break;
  15462. case tokens.openParenthesis:
  15463. this.parentheses();
  15464. break;
  15465. case tokens.closeParenthesis:
  15466. if (throwOnParenthesis) {
  15467. this.missingParenthesis();
  15468. }
  15469. break;
  15470. case tokens.openSquare:
  15471. this.attribute();
  15472. break;
  15473. case tokens.dollar:
  15474. case tokens.caret:
  15475. case tokens.equals:
  15476. case tokens.word:
  15477. this.word();
  15478. break;
  15479. case tokens.colon:
  15480. this.pseudo();
  15481. break;
  15482. case tokens.comma:
  15483. this.comma();
  15484. break;
  15485. case tokens.asterisk:
  15486. this.universal();
  15487. break;
  15488. case tokens.ampersand:
  15489. this.nesting();
  15490. break;
  15491. case tokens.slash:
  15492. case tokens.combinator:
  15493. this.combinator();
  15494. break;
  15495. case tokens.str:
  15496. this.string();
  15497. break;
  15498. // These cases throw; no break needed.
  15499. case tokens.closeSquare:
  15500. this.missingSquareBracket();
  15501. case tokens.semicolon:
  15502. this.missingBackslash();
  15503. default:
  15504. this.unexpected();
  15505. }
  15506. }
  15507. /**
  15508. * Helpers
  15509. */;
  15510. _proto.expected = function expected(description, index, found) {
  15511. if (Array.isArray(description)) {
  15512. var last = description.pop();
  15513. description = description.join(', ') + " or " + last;
  15514. }
  15515. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  15516. if (!found) {
  15517. return this.error("Expected " + an + " " + description + ".", {
  15518. index: index
  15519. });
  15520. }
  15521. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  15522. index: index
  15523. });
  15524. };
  15525. _proto.requiredSpace = function requiredSpace(space) {
  15526. return this.options.lossy ? ' ' : space;
  15527. };
  15528. _proto.optionalSpace = function optionalSpace(space) {
  15529. return this.options.lossy ? '' : space;
  15530. };
  15531. _proto.lossySpace = function lossySpace(space, required) {
  15532. if (this.options.lossy) {
  15533. return required ? ' ' : '';
  15534. } else {
  15535. return space;
  15536. }
  15537. };
  15538. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  15539. var content = this.content(token);
  15540. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  15541. return this.requiredSpace(content);
  15542. } else {
  15543. return content;
  15544. }
  15545. };
  15546. _proto.newNode = function newNode(node, namespace) {
  15547. if (namespace) {
  15548. if (/^ +$/.test(namespace)) {
  15549. if (!this.options.lossy) {
  15550. this.spaces = (this.spaces || '') + namespace;
  15551. }
  15552. namespace = true;
  15553. }
  15554. node.namespace = namespace;
  15555. unescapeProp(node, "namespace");
  15556. }
  15557. if (this.spaces) {
  15558. node.spaces.before = this.spaces;
  15559. this.spaces = '';
  15560. }
  15561. return this.current.append(node);
  15562. };
  15563. _proto.content = function content(token) {
  15564. if (token === void 0) {
  15565. token = this.currToken;
  15566. }
  15567. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  15568. };
  15569. /**
  15570. * returns the index of the next non-whitespace, non-comment token.
  15571. * returns -1 if no meaningful token is found.
  15572. */
  15573. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  15574. if (startPosition === void 0) {
  15575. startPosition = this.position + 1;
  15576. }
  15577. var searchPosition = startPosition;
  15578. while (searchPosition < this.tokens.length) {
  15579. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  15580. searchPosition++;
  15581. continue;
  15582. } else {
  15583. return searchPosition;
  15584. }
  15585. }
  15586. return -1;
  15587. };
  15588. _createClass(Parser, [{
  15589. key: "currToken",
  15590. get: function get() {
  15591. return this.tokens[this.position];
  15592. }
  15593. }, {
  15594. key: "nextToken",
  15595. get: function get() {
  15596. return this.tokens[this.position + 1];
  15597. }
  15598. }, {
  15599. key: "prevToken",
  15600. get: function get() {
  15601. return this.tokens[this.position - 1];
  15602. }
  15603. }]);
  15604. return Parser;
  15605. }();
  15606. exports["default"] = Parser;
  15607. module.exports = exports.default;
  15608. } (parser, parser.exports));
  15609. return parser.exports;
  15610. }
  15611. var hasRequiredProcessor;
  15612. function requireProcessor () {
  15613. if (hasRequiredProcessor) return processor.exports;
  15614. hasRequiredProcessor = 1;
  15615. (function (module, exports) {
  15616. exports.__esModule = true;
  15617. exports["default"] = void 0;
  15618. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  15619. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15620. var Processor = /*#__PURE__*/function () {
  15621. function Processor(func, options) {
  15622. this.func = func || function noop() {};
  15623. this.funcRes = null;
  15624. this.options = options;
  15625. }
  15626. var _proto = Processor.prototype;
  15627. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  15628. if (options === void 0) {
  15629. options = {};
  15630. }
  15631. var merged = Object.assign({}, this.options, options);
  15632. if (merged.updateSelector === false) {
  15633. return false;
  15634. } else {
  15635. return typeof rule !== "string";
  15636. }
  15637. };
  15638. _proto._isLossy = function _isLossy(options) {
  15639. if (options === void 0) {
  15640. options = {};
  15641. }
  15642. var merged = Object.assign({}, this.options, options);
  15643. if (merged.lossless === false) {
  15644. return true;
  15645. } else {
  15646. return false;
  15647. }
  15648. };
  15649. _proto._root = function _root(rule, options) {
  15650. if (options === void 0) {
  15651. options = {};
  15652. }
  15653. var parser = new _parser["default"](rule, this._parseOptions(options));
  15654. return parser.root;
  15655. };
  15656. _proto._parseOptions = function _parseOptions(options) {
  15657. return {
  15658. lossy: this._isLossy(options)
  15659. };
  15660. };
  15661. _proto._run = function _run(rule, options) {
  15662. var _this = this;
  15663. if (options === void 0) {
  15664. options = {};
  15665. }
  15666. return new Promise(function (resolve, reject) {
  15667. try {
  15668. var root = _this._root(rule, options);
  15669. Promise.resolve(_this.func(root)).then(function (transform) {
  15670. var string = undefined;
  15671. if (_this._shouldUpdateSelector(rule, options)) {
  15672. string = root.toString();
  15673. rule.selector = string;
  15674. }
  15675. return {
  15676. transform: transform,
  15677. root: root,
  15678. string: string
  15679. };
  15680. }).then(resolve, reject);
  15681. } catch (e) {
  15682. reject(e);
  15683. return;
  15684. }
  15685. });
  15686. };
  15687. _proto._runSync = function _runSync(rule, options) {
  15688. if (options === void 0) {
  15689. options = {};
  15690. }
  15691. var root = this._root(rule, options);
  15692. var transform = this.func(root);
  15693. if (transform && typeof transform.then === "function") {
  15694. throw new Error("Selector processor returned a promise to a synchronous call.");
  15695. }
  15696. var string = undefined;
  15697. if (options.updateSelector && typeof rule !== "string") {
  15698. string = root.toString();
  15699. rule.selector = string;
  15700. }
  15701. return {
  15702. transform: transform,
  15703. root: root,
  15704. string: string
  15705. };
  15706. }
  15707. /**
  15708. * Process rule into a selector AST.
  15709. *
  15710. * @param rule {postcss.Rule | string} The css selector to be processed
  15711. * @param options The options for processing
  15712. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  15713. */;
  15714. _proto.ast = function ast(rule, options) {
  15715. return this._run(rule, options).then(function (result) {
  15716. return result.root;
  15717. });
  15718. }
  15719. /**
  15720. * Process rule into a selector AST synchronously.
  15721. *
  15722. * @param rule {postcss.Rule | string} The css selector to be processed
  15723. * @param options The options for processing
  15724. * @returns {parser.Root} The AST of the selector after processing it.
  15725. */;
  15726. _proto.astSync = function astSync(rule, options) {
  15727. return this._runSync(rule, options).root;
  15728. }
  15729. /**
  15730. * Process a selector into a transformed value asynchronously
  15731. *
  15732. * @param rule {postcss.Rule | string} The css selector to be processed
  15733. * @param options The options for processing
  15734. * @returns {Promise<any>} The value returned by the processor.
  15735. */;
  15736. _proto.transform = function transform(rule, options) {
  15737. return this._run(rule, options).then(function (result) {
  15738. return result.transform;
  15739. });
  15740. }
  15741. /**
  15742. * Process a selector into a transformed value synchronously.
  15743. *
  15744. * @param rule {postcss.Rule | string} The css selector to be processed
  15745. * @param options The options for processing
  15746. * @returns {any} The value returned by the processor.
  15747. */;
  15748. _proto.transformSync = function transformSync(rule, options) {
  15749. return this._runSync(rule, options).transform;
  15750. }
  15751. /**
  15752. * Process a selector into a new selector string asynchronously.
  15753. *
  15754. * @param rule {postcss.Rule | string} The css selector to be processed
  15755. * @param options The options for processing
  15756. * @returns {string} the selector after processing.
  15757. */;
  15758. _proto.process = function process(rule, options) {
  15759. return this._run(rule, options).then(function (result) {
  15760. return result.string || result.root.toString();
  15761. });
  15762. }
  15763. /**
  15764. * Process a selector into a new selector string synchronously.
  15765. *
  15766. * @param rule {postcss.Rule | string} The css selector to be processed
  15767. * @param options The options for processing
  15768. * @returns {string} the selector after processing.
  15769. */;
  15770. _proto.processSync = function processSync(rule, options) {
  15771. var result = this._runSync(rule, options);
  15772. return result.string || result.root.toString();
  15773. };
  15774. return Processor;
  15775. }();
  15776. exports["default"] = Processor;
  15777. module.exports = exports.default;
  15778. } (processor, processor.exports));
  15779. return processor.exports;
  15780. }
  15781. var selectors = {};
  15782. var constructors = {};
  15783. var hasRequiredConstructors;
  15784. function requireConstructors () {
  15785. if (hasRequiredConstructors) return constructors;
  15786. hasRequiredConstructors = 1;
  15787. constructors.__esModule = true;
  15788. 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;
  15789. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  15790. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15791. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15792. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15793. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15794. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15795. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15796. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15797. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15798. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15799. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15800. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15801. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15802. var attribute = function attribute(opts) {
  15803. return new _attribute["default"](opts);
  15804. };
  15805. constructors.attribute = attribute;
  15806. var className = function className(opts) {
  15807. return new _className["default"](opts);
  15808. };
  15809. constructors.className = className;
  15810. var combinator = function combinator(opts) {
  15811. return new _combinator["default"](opts);
  15812. };
  15813. constructors.combinator = combinator;
  15814. var comment = function comment(opts) {
  15815. return new _comment["default"](opts);
  15816. };
  15817. constructors.comment = comment;
  15818. var id = function id(opts) {
  15819. return new _id["default"](opts);
  15820. };
  15821. constructors.id = id;
  15822. var nesting = function nesting(opts) {
  15823. return new _nesting["default"](opts);
  15824. };
  15825. constructors.nesting = nesting;
  15826. var pseudo = function pseudo(opts) {
  15827. return new _pseudo["default"](opts);
  15828. };
  15829. constructors.pseudo = pseudo;
  15830. var root = function root(opts) {
  15831. return new _root["default"](opts);
  15832. };
  15833. constructors.root = root;
  15834. var selector = function selector(opts) {
  15835. return new _selector["default"](opts);
  15836. };
  15837. constructors.selector = selector;
  15838. var string = function string(opts) {
  15839. return new _string["default"](opts);
  15840. };
  15841. constructors.string = string;
  15842. var tag = function tag(opts) {
  15843. return new _tag["default"](opts);
  15844. };
  15845. constructors.tag = tag;
  15846. var universal = function universal(opts) {
  15847. return new _universal["default"](opts);
  15848. };
  15849. constructors.universal = universal;
  15850. return constructors;
  15851. }
  15852. var guards = {};
  15853. var hasRequiredGuards;
  15854. function requireGuards () {
  15855. if (hasRequiredGuards) return guards;
  15856. hasRequiredGuards = 1;
  15857. guards.__esModule = true;
  15858. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  15859. guards.isContainer = isContainer;
  15860. guards.isIdentifier = void 0;
  15861. guards.isNamespace = isNamespace;
  15862. guards.isNesting = void 0;
  15863. guards.isNode = isNode;
  15864. guards.isPseudo = void 0;
  15865. guards.isPseudoClass = isPseudoClass;
  15866. guards.isPseudoElement = isPseudoElement;
  15867. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  15868. var _types = /*@__PURE__*/ requireTypes();
  15869. var _IS_TYPE;
  15870. 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);
  15871. function isNode(node) {
  15872. return typeof node === "object" && IS_TYPE[node.type];
  15873. }
  15874. function isNodeType(type, node) {
  15875. return isNode(node) && node.type === type;
  15876. }
  15877. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  15878. guards.isAttribute = isAttribute;
  15879. var isClassName = isNodeType.bind(null, _types.CLASS);
  15880. guards.isClassName = isClassName;
  15881. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  15882. guards.isCombinator = isCombinator;
  15883. var isComment = isNodeType.bind(null, _types.COMMENT);
  15884. guards.isComment = isComment;
  15885. var isIdentifier = isNodeType.bind(null, _types.ID);
  15886. guards.isIdentifier = isIdentifier;
  15887. var isNesting = isNodeType.bind(null, _types.NESTING);
  15888. guards.isNesting = isNesting;
  15889. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  15890. guards.isPseudo = isPseudo;
  15891. var isRoot = isNodeType.bind(null, _types.ROOT);
  15892. guards.isRoot = isRoot;
  15893. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  15894. guards.isSelector = isSelector;
  15895. var isString = isNodeType.bind(null, _types.STRING);
  15896. guards.isString = isString;
  15897. var isTag = isNodeType.bind(null, _types.TAG);
  15898. guards.isTag = isTag;
  15899. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  15900. guards.isUniversal = isUniversal;
  15901. function isPseudoElement(node) {
  15902. 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");
  15903. }
  15904. function isPseudoClass(node) {
  15905. return isPseudo(node) && !isPseudoElement(node);
  15906. }
  15907. function isContainer(node) {
  15908. return !!(isNode(node) && node.walk);
  15909. }
  15910. function isNamespace(node) {
  15911. return isAttribute(node) || isTag(node);
  15912. }
  15913. return guards;
  15914. }
  15915. var hasRequiredSelectors;
  15916. function requireSelectors () {
  15917. if (hasRequiredSelectors) return selectors;
  15918. hasRequiredSelectors = 1;
  15919. (function (exports) {
  15920. exports.__esModule = true;
  15921. var _types = /*@__PURE__*/ requireTypes();
  15922. Object.keys(_types).forEach(function (key) {
  15923. if (key === "default" || key === "__esModule") return;
  15924. if (key in exports && exports[key] === _types[key]) return;
  15925. exports[key] = _types[key];
  15926. });
  15927. var _constructors = /*@__PURE__*/ requireConstructors();
  15928. Object.keys(_constructors).forEach(function (key) {
  15929. if (key === "default" || key === "__esModule") return;
  15930. if (key in exports && exports[key] === _constructors[key]) return;
  15931. exports[key] = _constructors[key];
  15932. });
  15933. var _guards = /*@__PURE__*/ requireGuards();
  15934. Object.keys(_guards).forEach(function (key) {
  15935. if (key === "default" || key === "__esModule") return;
  15936. if (key in exports && exports[key] === _guards[key]) return;
  15937. exports[key] = _guards[key];
  15938. });
  15939. } (selectors));
  15940. return selectors;
  15941. }
  15942. var hasRequiredDist;
  15943. function requireDist () {
  15944. if (hasRequiredDist) return dist.exports;
  15945. hasRequiredDist = 1;
  15946. (function (module, exports) {
  15947. exports.__esModule = true;
  15948. exports["default"] = void 0;
  15949. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  15950. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  15951. 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); }
  15952. 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; }
  15953. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15954. var parser = function parser(processor) {
  15955. return new _processor["default"](processor);
  15956. };
  15957. Object.assign(parser, selectors);
  15958. delete parser.__esModule;
  15959. var _default = parser;
  15960. exports["default"] = _default;
  15961. module.exports = exports.default;
  15962. } (dist, dist.exports));
  15963. return dist.exports;
  15964. }
  15965. var parse;
  15966. var hasRequiredParse;
  15967. function requireParse () {
  15968. if (hasRequiredParse) return parse;
  15969. hasRequiredParse = 1;
  15970. var openParentheses = "(".charCodeAt(0);
  15971. var closeParentheses = ")".charCodeAt(0);
  15972. var singleQuote = "'".charCodeAt(0);
  15973. var doubleQuote = '"'.charCodeAt(0);
  15974. var backslash = "\\".charCodeAt(0);
  15975. var slash = "/".charCodeAt(0);
  15976. var comma = ",".charCodeAt(0);
  15977. var colon = ":".charCodeAt(0);
  15978. var star = "*".charCodeAt(0);
  15979. var uLower = "u".charCodeAt(0);
  15980. var uUpper = "U".charCodeAt(0);
  15981. var plus = "+".charCodeAt(0);
  15982. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  15983. parse = function(input) {
  15984. var tokens = [];
  15985. var value = input;
  15986. var next,
  15987. quote,
  15988. prev,
  15989. token,
  15990. escape,
  15991. escapePos,
  15992. whitespacePos,
  15993. parenthesesOpenPos;
  15994. var pos = 0;
  15995. var code = value.charCodeAt(pos);
  15996. var max = value.length;
  15997. var stack = [{ nodes: tokens }];
  15998. var balanced = 0;
  15999. var parent;
  16000. var name = "";
  16001. var before = "";
  16002. var after = "";
  16003. while (pos < max) {
  16004. // Whitespaces
  16005. if (code <= 32) {
  16006. next = pos;
  16007. do {
  16008. next += 1;
  16009. code = value.charCodeAt(next);
  16010. } while (code <= 32);
  16011. token = value.slice(pos, next);
  16012. prev = tokens[tokens.length - 1];
  16013. if (code === closeParentheses && balanced) {
  16014. after = token;
  16015. } else if (prev && prev.type === "div") {
  16016. prev.after = token;
  16017. prev.sourceEndIndex += token.length;
  16018. } else if (
  16019. code === comma ||
  16020. code === colon ||
  16021. (code === slash &&
  16022. value.charCodeAt(next + 1) !== star &&
  16023. (!parent ||
  16024. (parent && parent.type === "function" && parent.value !== "calc")))
  16025. ) {
  16026. before = token;
  16027. } else {
  16028. tokens.push({
  16029. type: "space",
  16030. sourceIndex: pos,
  16031. sourceEndIndex: next,
  16032. value: token
  16033. });
  16034. }
  16035. pos = next;
  16036. // Quotes
  16037. } else if (code === singleQuote || code === doubleQuote) {
  16038. next = pos;
  16039. quote = code === singleQuote ? "'" : '"';
  16040. token = {
  16041. type: "string",
  16042. sourceIndex: pos,
  16043. quote: quote
  16044. };
  16045. do {
  16046. escape = false;
  16047. next = value.indexOf(quote, next + 1);
  16048. if (~next) {
  16049. escapePos = next;
  16050. while (value.charCodeAt(escapePos - 1) === backslash) {
  16051. escapePos -= 1;
  16052. escape = !escape;
  16053. }
  16054. } else {
  16055. value += quote;
  16056. next = value.length - 1;
  16057. token.unclosed = true;
  16058. }
  16059. } while (escape);
  16060. token.value = value.slice(pos + 1, next);
  16061. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16062. tokens.push(token);
  16063. pos = next + 1;
  16064. code = value.charCodeAt(pos);
  16065. // Comments
  16066. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16067. next = value.indexOf("*/", pos);
  16068. token = {
  16069. type: "comment",
  16070. sourceIndex: pos,
  16071. sourceEndIndex: next + 2
  16072. };
  16073. if (next === -1) {
  16074. token.unclosed = true;
  16075. next = value.length;
  16076. token.sourceEndIndex = next;
  16077. }
  16078. token.value = value.slice(pos + 2, next);
  16079. tokens.push(token);
  16080. pos = next + 2;
  16081. code = value.charCodeAt(pos);
  16082. // Operation within calc
  16083. } else if (
  16084. (code === slash || code === star) &&
  16085. parent &&
  16086. parent.type === "function" &&
  16087. parent.value === "calc"
  16088. ) {
  16089. token = value[pos];
  16090. tokens.push({
  16091. type: "word",
  16092. sourceIndex: pos - before.length,
  16093. sourceEndIndex: pos + token.length,
  16094. value: token
  16095. });
  16096. pos += 1;
  16097. code = value.charCodeAt(pos);
  16098. // Dividers
  16099. } else if (code === slash || code === comma || code === colon) {
  16100. token = value[pos];
  16101. tokens.push({
  16102. type: "div",
  16103. sourceIndex: pos - before.length,
  16104. sourceEndIndex: pos + token.length,
  16105. value: token,
  16106. before: before,
  16107. after: ""
  16108. });
  16109. before = "";
  16110. pos += 1;
  16111. code = value.charCodeAt(pos);
  16112. // Open parentheses
  16113. } else if (openParentheses === code) {
  16114. // Whitespaces after open parentheses
  16115. next = pos;
  16116. do {
  16117. next += 1;
  16118. code = value.charCodeAt(next);
  16119. } while (code <= 32);
  16120. parenthesesOpenPos = pos;
  16121. token = {
  16122. type: "function",
  16123. sourceIndex: pos - name.length,
  16124. value: name,
  16125. before: value.slice(parenthesesOpenPos + 1, next)
  16126. };
  16127. pos = next;
  16128. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16129. next -= 1;
  16130. do {
  16131. escape = false;
  16132. next = value.indexOf(")", next + 1);
  16133. if (~next) {
  16134. escapePos = next;
  16135. while (value.charCodeAt(escapePos - 1) === backslash) {
  16136. escapePos -= 1;
  16137. escape = !escape;
  16138. }
  16139. } else {
  16140. value += ")";
  16141. next = value.length - 1;
  16142. token.unclosed = true;
  16143. }
  16144. } while (escape);
  16145. // Whitespaces before closed
  16146. whitespacePos = next;
  16147. do {
  16148. whitespacePos -= 1;
  16149. code = value.charCodeAt(whitespacePos);
  16150. } while (code <= 32);
  16151. if (parenthesesOpenPos < whitespacePos) {
  16152. if (pos !== whitespacePos + 1) {
  16153. token.nodes = [
  16154. {
  16155. type: "word",
  16156. sourceIndex: pos,
  16157. sourceEndIndex: whitespacePos + 1,
  16158. value: value.slice(pos, whitespacePos + 1)
  16159. }
  16160. ];
  16161. } else {
  16162. token.nodes = [];
  16163. }
  16164. if (token.unclosed && whitespacePos + 1 !== next) {
  16165. token.after = "";
  16166. token.nodes.push({
  16167. type: "space",
  16168. sourceIndex: whitespacePos + 1,
  16169. sourceEndIndex: next,
  16170. value: value.slice(whitespacePos + 1, next)
  16171. });
  16172. } else {
  16173. token.after = value.slice(whitespacePos + 1, next);
  16174. token.sourceEndIndex = next;
  16175. }
  16176. } else {
  16177. token.after = "";
  16178. token.nodes = [];
  16179. }
  16180. pos = next + 1;
  16181. token.sourceEndIndex = token.unclosed ? next : pos;
  16182. code = value.charCodeAt(pos);
  16183. tokens.push(token);
  16184. } else {
  16185. balanced += 1;
  16186. token.after = "";
  16187. token.sourceEndIndex = pos + 1;
  16188. tokens.push(token);
  16189. stack.push(token);
  16190. tokens = token.nodes = [];
  16191. parent = token;
  16192. }
  16193. name = "";
  16194. // Close parentheses
  16195. } else if (closeParentheses === code && balanced) {
  16196. pos += 1;
  16197. code = value.charCodeAt(pos);
  16198. parent.after = after;
  16199. parent.sourceEndIndex += after.length;
  16200. after = "";
  16201. balanced -= 1;
  16202. stack[stack.length - 1].sourceEndIndex = pos;
  16203. stack.pop();
  16204. parent = stack[balanced];
  16205. tokens = parent.nodes;
  16206. // Words
  16207. } else {
  16208. next = pos;
  16209. do {
  16210. if (code === backslash) {
  16211. next += 1;
  16212. }
  16213. next += 1;
  16214. code = value.charCodeAt(next);
  16215. } while (
  16216. next < max &&
  16217. !(
  16218. code <= 32 ||
  16219. code === singleQuote ||
  16220. code === doubleQuote ||
  16221. code === comma ||
  16222. code === colon ||
  16223. code === slash ||
  16224. code === openParentheses ||
  16225. (code === star &&
  16226. parent &&
  16227. parent.type === "function" &&
  16228. parent.value === "calc") ||
  16229. (code === slash &&
  16230. parent.type === "function" &&
  16231. parent.value === "calc") ||
  16232. (code === closeParentheses && balanced)
  16233. )
  16234. );
  16235. token = value.slice(pos, next);
  16236. if (openParentheses === code) {
  16237. name = token;
  16238. } else if (
  16239. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16240. plus === token.charCodeAt(1) &&
  16241. isUnicodeRange.test(token.slice(2))
  16242. ) {
  16243. tokens.push({
  16244. type: "unicode-range",
  16245. sourceIndex: pos,
  16246. sourceEndIndex: next,
  16247. value: token
  16248. });
  16249. } else {
  16250. tokens.push({
  16251. type: "word",
  16252. sourceIndex: pos,
  16253. sourceEndIndex: next,
  16254. value: token
  16255. });
  16256. }
  16257. pos = next;
  16258. }
  16259. }
  16260. for (pos = stack.length - 1; pos; pos -= 1) {
  16261. stack[pos].unclosed = true;
  16262. stack[pos].sourceEndIndex = value.length;
  16263. }
  16264. return stack[0].nodes;
  16265. };
  16266. return parse;
  16267. }
  16268. var walk$1;
  16269. var hasRequiredWalk;
  16270. function requireWalk () {
  16271. if (hasRequiredWalk) return walk$1;
  16272. hasRequiredWalk = 1;
  16273. walk$1 = function walk(nodes, cb, bubble) {
  16274. var i, max, node, result;
  16275. for (i = 0, max = nodes.length; i < max; i += 1) {
  16276. node = nodes[i];
  16277. if (!bubble) {
  16278. result = cb(node, i, nodes);
  16279. }
  16280. if (
  16281. result !== false &&
  16282. node.type === "function" &&
  16283. Array.isArray(node.nodes)
  16284. ) {
  16285. walk(node.nodes, cb, bubble);
  16286. }
  16287. if (bubble) {
  16288. cb(node, i, nodes);
  16289. }
  16290. }
  16291. };
  16292. return walk$1;
  16293. }
  16294. var stringify_1;
  16295. var hasRequiredStringify;
  16296. function requireStringify () {
  16297. if (hasRequiredStringify) return stringify_1;
  16298. hasRequiredStringify = 1;
  16299. function stringifyNode(node, custom) {
  16300. var type = node.type;
  16301. var value = node.value;
  16302. var buf;
  16303. var customResult;
  16304. if (custom && (customResult = custom(node)) !== undefined) {
  16305. return customResult;
  16306. } else if (type === "word" || type === "space") {
  16307. return value;
  16308. } else if (type === "string") {
  16309. buf = node.quote || "";
  16310. return buf + value + (node.unclosed ? "" : buf);
  16311. } else if (type === "comment") {
  16312. return "/*" + value + (node.unclosed ? "" : "*/");
  16313. } else if (type === "div") {
  16314. return (node.before || "") + value + (node.after || "");
  16315. } else if (Array.isArray(node.nodes)) {
  16316. buf = stringify(node.nodes, custom);
  16317. if (type !== "function") {
  16318. return buf;
  16319. }
  16320. return (
  16321. value +
  16322. "(" +
  16323. (node.before || "") +
  16324. buf +
  16325. (node.after || "") +
  16326. (node.unclosed ? "" : ")")
  16327. );
  16328. }
  16329. return value;
  16330. }
  16331. function stringify(nodes, custom) {
  16332. var result, i;
  16333. if (Array.isArray(nodes)) {
  16334. result = "";
  16335. for (i = nodes.length - 1; ~i; i -= 1) {
  16336. result = stringifyNode(nodes[i], custom) + result;
  16337. }
  16338. return result;
  16339. }
  16340. return stringifyNode(nodes, custom);
  16341. }
  16342. stringify_1 = stringify;
  16343. return stringify_1;
  16344. }
  16345. var unit;
  16346. var hasRequiredUnit;
  16347. function requireUnit () {
  16348. if (hasRequiredUnit) return unit;
  16349. hasRequiredUnit = 1;
  16350. var minus = "-".charCodeAt(0);
  16351. var plus = "+".charCodeAt(0);
  16352. var dot = ".".charCodeAt(0);
  16353. var exp = "e".charCodeAt(0);
  16354. var EXP = "E".charCodeAt(0);
  16355. // Check if three code points would start a number
  16356. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16357. function likeNumber(value) {
  16358. var code = value.charCodeAt(0);
  16359. var nextCode;
  16360. if (code === plus || code === minus) {
  16361. nextCode = value.charCodeAt(1);
  16362. if (nextCode >= 48 && nextCode <= 57) {
  16363. return true;
  16364. }
  16365. var nextNextCode = value.charCodeAt(2);
  16366. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16367. return true;
  16368. }
  16369. return false;
  16370. }
  16371. if (code === dot) {
  16372. nextCode = value.charCodeAt(1);
  16373. if (nextCode >= 48 && nextCode <= 57) {
  16374. return true;
  16375. }
  16376. return false;
  16377. }
  16378. if (code >= 48 && code <= 57) {
  16379. return true;
  16380. }
  16381. return false;
  16382. }
  16383. // Consume a number
  16384. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16385. unit = function(value) {
  16386. var pos = 0;
  16387. var length = value.length;
  16388. var code;
  16389. var nextCode;
  16390. var nextNextCode;
  16391. if (length === 0 || !likeNumber(value)) {
  16392. return false;
  16393. }
  16394. code = value.charCodeAt(pos);
  16395. if (code === plus || code === minus) {
  16396. pos++;
  16397. }
  16398. while (pos < length) {
  16399. code = value.charCodeAt(pos);
  16400. if (code < 48 || code > 57) {
  16401. break;
  16402. }
  16403. pos += 1;
  16404. }
  16405. code = value.charCodeAt(pos);
  16406. nextCode = value.charCodeAt(pos + 1);
  16407. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16408. pos += 2;
  16409. while (pos < length) {
  16410. code = value.charCodeAt(pos);
  16411. if (code < 48 || code > 57) {
  16412. break;
  16413. }
  16414. pos += 1;
  16415. }
  16416. }
  16417. code = value.charCodeAt(pos);
  16418. nextCode = value.charCodeAt(pos + 1);
  16419. nextNextCode = value.charCodeAt(pos + 2);
  16420. if (
  16421. (code === exp || code === EXP) &&
  16422. ((nextCode >= 48 && nextCode <= 57) ||
  16423. ((nextCode === plus || nextCode === minus) &&
  16424. nextNextCode >= 48 &&
  16425. nextNextCode <= 57))
  16426. ) {
  16427. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16428. while (pos < length) {
  16429. code = value.charCodeAt(pos);
  16430. if (code < 48 || code > 57) {
  16431. break;
  16432. }
  16433. pos += 1;
  16434. }
  16435. }
  16436. return {
  16437. number: value.slice(0, pos),
  16438. unit: value.slice(pos)
  16439. };
  16440. };
  16441. return unit;
  16442. }
  16443. var lib;
  16444. var hasRequiredLib;
  16445. function requireLib () {
  16446. if (hasRequiredLib) return lib;
  16447. hasRequiredLib = 1;
  16448. var parse = /*@__PURE__*/ requireParse();
  16449. var walk = /*@__PURE__*/ requireWalk();
  16450. var stringify = /*@__PURE__*/ requireStringify();
  16451. function ValueParser(value) {
  16452. if (this instanceof ValueParser) {
  16453. this.nodes = parse(value);
  16454. return this;
  16455. }
  16456. return new ValueParser(value);
  16457. }
  16458. ValueParser.prototype.toString = function() {
  16459. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  16460. };
  16461. ValueParser.prototype.walk = function(cb, bubble) {
  16462. walk(this.nodes, cb, bubble);
  16463. return this;
  16464. };
  16465. ValueParser.unit = /*@__PURE__*/ requireUnit();
  16466. ValueParser.walk = walk;
  16467. ValueParser.stringify = stringify;
  16468. lib = ValueParser;
  16469. return lib;
  16470. }
  16471. var hasRequiredSrc$2;
  16472. function requireSrc$2 () {
  16473. if (hasRequiredSrc$2) return src$2.exports;
  16474. hasRequiredSrc$2 = 1;
  16475. const selectorParser = /*@__PURE__*/ requireDist();
  16476. const valueParser = /*@__PURE__*/ requireLib();
  16477. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  16478. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  16479. function normalizeNodeArray(nodes) {
  16480. const array = [];
  16481. nodes.forEach((x) => {
  16482. if (Array.isArray(x)) {
  16483. normalizeNodeArray(x).forEach((item) => {
  16484. array.push(item);
  16485. });
  16486. } else if (x) {
  16487. array.push(x);
  16488. }
  16489. });
  16490. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  16491. array.pop();
  16492. }
  16493. return array;
  16494. }
  16495. function localizeNode(rule, mode, localAliasMap) {
  16496. const transform = (node, context) => {
  16497. if (context.ignoreNextSpacing && !isSpacing(node)) {
  16498. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  16499. }
  16500. if (context.enforceNoSpacing && isSpacing(node)) {
  16501. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  16502. }
  16503. let newNodes;
  16504. switch (node.type) {
  16505. case "root": {
  16506. let resultingGlobal;
  16507. context.hasPureGlobals = false;
  16508. newNodes = node.nodes.map((n) => {
  16509. const nContext = {
  16510. global: context.global,
  16511. lastWasSpacing: true,
  16512. hasLocals: false,
  16513. explicit: false,
  16514. };
  16515. n = transform(n, nContext);
  16516. if (typeof resultingGlobal === "undefined") {
  16517. resultingGlobal = nContext.global;
  16518. } else if (resultingGlobal !== nContext.global) {
  16519. throw new Error(
  16520. 'Inconsistent rule global/local result in rule "' +
  16521. node +
  16522. '" (multiple selectors must result in the same mode for the rule)'
  16523. );
  16524. }
  16525. if (!nContext.hasLocals) {
  16526. context.hasPureGlobals = true;
  16527. }
  16528. return n;
  16529. });
  16530. context.global = resultingGlobal;
  16531. node.nodes = normalizeNodeArray(newNodes);
  16532. break;
  16533. }
  16534. case "selector": {
  16535. newNodes = node.map((childNode) => transform(childNode, context));
  16536. node = node.clone();
  16537. node.nodes = normalizeNodeArray(newNodes);
  16538. break;
  16539. }
  16540. case "combinator": {
  16541. if (isSpacing(node)) {
  16542. if (context.ignoreNextSpacing) {
  16543. context.ignoreNextSpacing = false;
  16544. context.lastWasSpacing = false;
  16545. context.enforceNoSpacing = false;
  16546. return null;
  16547. }
  16548. context.lastWasSpacing = true;
  16549. return node;
  16550. }
  16551. break;
  16552. }
  16553. case "pseudo": {
  16554. let childContext;
  16555. const isNested = !!node.length;
  16556. const isScoped = node.value === ":local" || node.value === ":global";
  16557. const isImportExport =
  16558. node.value === ":import" || node.value === ":export";
  16559. if (isImportExport) {
  16560. context.hasLocals = true;
  16561. // :local(.foo)
  16562. } else if (isNested) {
  16563. if (isScoped) {
  16564. if (node.nodes.length === 0) {
  16565. throw new Error(`${node.value}() can't be empty`);
  16566. }
  16567. if (context.inside) {
  16568. throw new Error(
  16569. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16570. );
  16571. }
  16572. childContext = {
  16573. global: node.value === ":global",
  16574. inside: node.value,
  16575. hasLocals: false,
  16576. explicit: true,
  16577. };
  16578. newNodes = node
  16579. .map((childNode) => transform(childNode, childContext))
  16580. .reduce((acc, next) => acc.concat(next.nodes), []);
  16581. if (newNodes.length) {
  16582. const { before, after } = node.spaces;
  16583. const first = newNodes[0];
  16584. const last = newNodes[newNodes.length - 1];
  16585. first.spaces = { before, after: first.spaces.after };
  16586. last.spaces = { before: last.spaces.before, after };
  16587. }
  16588. node = newNodes;
  16589. break;
  16590. } else {
  16591. childContext = {
  16592. global: context.global,
  16593. inside: context.inside,
  16594. lastWasSpacing: true,
  16595. hasLocals: false,
  16596. explicit: context.explicit,
  16597. };
  16598. newNodes = node.map((childNode) => {
  16599. const newContext = {
  16600. ...childContext,
  16601. enforceNoSpacing: false,
  16602. };
  16603. const result = transform(childNode, newContext);
  16604. childContext.global = newContext.global;
  16605. childContext.hasLocals = newContext.hasLocals;
  16606. return result;
  16607. });
  16608. node = node.clone();
  16609. node.nodes = normalizeNodeArray(newNodes);
  16610. if (childContext.hasLocals) {
  16611. context.hasLocals = true;
  16612. }
  16613. }
  16614. break;
  16615. //:local .foo .bar
  16616. } else if (isScoped) {
  16617. if (context.inside) {
  16618. throw new Error(
  16619. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16620. );
  16621. }
  16622. const addBackSpacing = !!node.spaces.before;
  16623. context.ignoreNextSpacing = context.lastWasSpacing
  16624. ? node.value
  16625. : false;
  16626. context.enforceNoSpacing = context.lastWasSpacing
  16627. ? false
  16628. : node.value;
  16629. context.global = node.value === ":global";
  16630. context.explicit = true;
  16631. // because this node has spacing that is lost when we remove it
  16632. // we make up for it by adding an extra combinator in since adding
  16633. // spacing on the parent selector doesn't work
  16634. return addBackSpacing
  16635. ? selectorParser.combinator({ value: " " })
  16636. : null;
  16637. }
  16638. break;
  16639. }
  16640. case "id":
  16641. case "class": {
  16642. if (!node.value) {
  16643. throw new Error("Invalid class or id selector syntax");
  16644. }
  16645. if (context.global) {
  16646. break;
  16647. }
  16648. const isImportedValue = localAliasMap.has(node.value);
  16649. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  16650. if (!isImportedValue || isImportedWithExplicitScope) {
  16651. const innerNode = node.clone();
  16652. innerNode.spaces = { before: "", after: "" };
  16653. node = selectorParser.pseudo({
  16654. value: ":local",
  16655. nodes: [innerNode],
  16656. spaces: node.spaces,
  16657. });
  16658. context.hasLocals = true;
  16659. }
  16660. break;
  16661. }
  16662. case "nesting": {
  16663. if (node.value === "&") {
  16664. context.hasLocals = true;
  16665. }
  16666. }
  16667. }
  16668. context.lastWasSpacing = false;
  16669. context.ignoreNextSpacing = false;
  16670. context.enforceNoSpacing = false;
  16671. return node;
  16672. };
  16673. const rootContext = {
  16674. global: mode === "global",
  16675. hasPureGlobals: false,
  16676. };
  16677. rootContext.selector = selectorParser((root) => {
  16678. transform(root, rootContext);
  16679. }).processSync(rule, { updateSelector: false, lossless: true });
  16680. return rootContext;
  16681. }
  16682. function localizeDeclNode(node, context) {
  16683. switch (node.type) {
  16684. case "word":
  16685. if (context.localizeNextItem) {
  16686. if (!context.localAliasMap.has(node.value)) {
  16687. node.value = ":local(" + node.value + ")";
  16688. context.localizeNextItem = false;
  16689. }
  16690. }
  16691. break;
  16692. case "function":
  16693. if (
  16694. context.options &&
  16695. context.options.rewriteUrl &&
  16696. node.value.toLowerCase() === "url"
  16697. ) {
  16698. node.nodes.map((nestedNode) => {
  16699. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  16700. return;
  16701. }
  16702. let newUrl = context.options.rewriteUrl(
  16703. context.global,
  16704. nestedNode.value
  16705. );
  16706. switch (nestedNode.type) {
  16707. case "string":
  16708. if (nestedNode.quote === "'") {
  16709. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  16710. }
  16711. if (nestedNode.quote === '"') {
  16712. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  16713. }
  16714. break;
  16715. case "word":
  16716. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  16717. break;
  16718. }
  16719. nestedNode.value = newUrl;
  16720. });
  16721. }
  16722. break;
  16723. }
  16724. return node;
  16725. }
  16726. // `none` is special value, other is global values
  16727. const specialKeywords = [
  16728. "none",
  16729. "inherit",
  16730. "initial",
  16731. "revert",
  16732. "revert-layer",
  16733. "unset",
  16734. ];
  16735. function localizeDeclarationValues(localize, declaration, context) {
  16736. const valueNodes = valueParser(declaration.value);
  16737. valueNodes.walk((node, index, nodes) => {
  16738. if (
  16739. node.type === "function" &&
  16740. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  16741. ) {
  16742. return false;
  16743. }
  16744. if (
  16745. node.type === "word" &&
  16746. specialKeywords.includes(node.value.toLowerCase())
  16747. ) {
  16748. return;
  16749. }
  16750. const subContext = {
  16751. options: context.options,
  16752. global: context.global,
  16753. localizeNextItem: localize && !context.global,
  16754. localAliasMap: context.localAliasMap,
  16755. };
  16756. nodes[index] = localizeDeclNode(node, subContext);
  16757. });
  16758. declaration.value = valueNodes.toString();
  16759. }
  16760. function localizeDeclaration(declaration, context) {
  16761. const isAnimation = /animation$/i.test(declaration.prop);
  16762. if (isAnimation) {
  16763. // letter
  16764. // An uppercase letter or a lowercase letter.
  16765. //
  16766. // ident-start code point
  16767. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  16768. //
  16769. // ident code point
  16770. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  16771. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  16772. const validIdent =
  16773. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  16774. /*
  16775. The spec defines some keywords that you can use to describe properties such as the timing
  16776. function. These are still valid animation names, so as long as there is a property that accepts
  16777. a keyword, it is given priority. Only when all the properties that can take a keyword are
  16778. exhausted can the animation name be set to the keyword. I.e.
  16779. animation: infinite infinite;
  16780. The animation will repeat an infinite number of times from the first argument, and will have an
  16781. animation name of infinite from the second.
  16782. */
  16783. const animationKeywords = {
  16784. // animation-direction
  16785. $normal: 1,
  16786. $reverse: 1,
  16787. $alternate: 1,
  16788. "$alternate-reverse": 1,
  16789. // animation-fill-mode
  16790. $forwards: 1,
  16791. $backwards: 1,
  16792. $both: 1,
  16793. // animation-iteration-count
  16794. $infinite: 1,
  16795. // animation-play-state
  16796. $paused: 1,
  16797. $running: 1,
  16798. // animation-timing-function
  16799. $ease: 1,
  16800. "$ease-in": 1,
  16801. "$ease-out": 1,
  16802. "$ease-in-out": 1,
  16803. $linear: 1,
  16804. "$step-end": 1,
  16805. "$step-start": 1,
  16806. // Special
  16807. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  16808. // Global values
  16809. $initial: Infinity,
  16810. $inherit: Infinity,
  16811. $unset: Infinity,
  16812. $revert: Infinity,
  16813. "$revert-layer": Infinity,
  16814. };
  16815. let parsedAnimationKeywords = {};
  16816. const valueNodes = valueParser(declaration.value).walk((node) => {
  16817. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  16818. if (node.type === "div") {
  16819. parsedAnimationKeywords = {};
  16820. return;
  16821. }
  16822. // Do not handle nested functions
  16823. else if (node.type === "function") {
  16824. return false;
  16825. }
  16826. // Ignore all except word
  16827. else if (node.type !== "word") {
  16828. return;
  16829. }
  16830. const value = node.type === "word" ? node.value.toLowerCase() : null;
  16831. let shouldParseAnimationName = false;
  16832. if (value && validIdent.test(value)) {
  16833. if ("$" + value in animationKeywords) {
  16834. parsedAnimationKeywords["$" + value] =
  16835. "$" + value in parsedAnimationKeywords
  16836. ? parsedAnimationKeywords["$" + value] + 1
  16837. : 0;
  16838. shouldParseAnimationName =
  16839. parsedAnimationKeywords["$" + value] >=
  16840. animationKeywords["$" + value];
  16841. } else {
  16842. shouldParseAnimationName = true;
  16843. }
  16844. }
  16845. const subContext = {
  16846. options: context.options,
  16847. global: context.global,
  16848. localizeNextItem: shouldParseAnimationName && !context.global,
  16849. localAliasMap: context.localAliasMap,
  16850. };
  16851. return localizeDeclNode(node, subContext);
  16852. });
  16853. declaration.value = valueNodes.toString();
  16854. return;
  16855. }
  16856. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  16857. if (isAnimationName) {
  16858. return localizeDeclarationValues(true, declaration, context);
  16859. }
  16860. const hasUrl = /url\(/i.test(declaration.value);
  16861. if (hasUrl) {
  16862. return localizeDeclarationValues(false, declaration, context);
  16863. }
  16864. }
  16865. src$2.exports = (options = {}) => {
  16866. if (
  16867. options &&
  16868. options.mode &&
  16869. options.mode !== "global" &&
  16870. options.mode !== "local" &&
  16871. options.mode !== "pure"
  16872. ) {
  16873. throw new Error(
  16874. 'options.mode must be either "global", "local" or "pure" (default "local")'
  16875. );
  16876. }
  16877. const pureMode = options && options.mode === "pure";
  16878. const globalMode = options && options.mode === "global";
  16879. return {
  16880. postcssPlugin: "postcss-modules-local-by-default",
  16881. prepare() {
  16882. const localAliasMap = new Map();
  16883. return {
  16884. Once(root) {
  16885. const { icssImports } = extractICSS(root, false);
  16886. Object.keys(icssImports).forEach((key) => {
  16887. Object.keys(icssImports[key]).forEach((prop) => {
  16888. localAliasMap.set(prop, icssImports[key][prop]);
  16889. });
  16890. });
  16891. root.walkAtRules((atRule) => {
  16892. if (/keyframes$/i.test(atRule.name)) {
  16893. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  16894. atRule.params
  16895. );
  16896. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  16897. atRule.params
  16898. );
  16899. let globalKeyframes = globalMode;
  16900. if (globalMatch) {
  16901. if (pureMode) {
  16902. throw atRule.error(
  16903. "@keyframes :global(...) is not allowed in pure mode"
  16904. );
  16905. }
  16906. atRule.params = globalMatch[1];
  16907. globalKeyframes = true;
  16908. } else if (localMatch) {
  16909. atRule.params = localMatch[0];
  16910. globalKeyframes = false;
  16911. } else if (
  16912. atRule.params &&
  16913. !globalMode &&
  16914. !localAliasMap.has(atRule.params)
  16915. ) {
  16916. atRule.params = ":local(" + atRule.params + ")";
  16917. }
  16918. atRule.walkDecls((declaration) => {
  16919. localizeDeclaration(declaration, {
  16920. localAliasMap,
  16921. options: options,
  16922. global: globalKeyframes,
  16923. });
  16924. });
  16925. } else if (/scope$/i.test(atRule.name)) {
  16926. if (atRule.params) {
  16927. atRule.params = atRule.params
  16928. .split("to")
  16929. .map((item) => {
  16930. const selector = item.trim().slice(1, -1).trim();
  16931. const context = localizeNode(
  16932. selector,
  16933. options.mode,
  16934. localAliasMap
  16935. );
  16936. context.options = options;
  16937. context.localAliasMap = localAliasMap;
  16938. if (pureMode && context.hasPureGlobals) {
  16939. throw atRule.error(
  16940. 'Selector in at-rule"' +
  16941. selector +
  16942. '" is not pure ' +
  16943. "(pure selectors must contain at least one local class or id)"
  16944. );
  16945. }
  16946. return `(${context.selector})`;
  16947. })
  16948. .join(" to ");
  16949. }
  16950. atRule.nodes.forEach((declaration) => {
  16951. if (declaration.type === "decl") {
  16952. localizeDeclaration(declaration, {
  16953. localAliasMap,
  16954. options: options,
  16955. global: globalMode,
  16956. });
  16957. }
  16958. });
  16959. } else if (atRule.nodes) {
  16960. atRule.nodes.forEach((declaration) => {
  16961. if (declaration.type === "decl") {
  16962. localizeDeclaration(declaration, {
  16963. localAliasMap,
  16964. options: options,
  16965. global: globalMode,
  16966. });
  16967. }
  16968. });
  16969. }
  16970. });
  16971. root.walkRules((rule) => {
  16972. if (
  16973. rule.parent &&
  16974. rule.parent.type === "atrule" &&
  16975. /keyframes$/i.test(rule.parent.name)
  16976. ) {
  16977. // ignore keyframe rules
  16978. return;
  16979. }
  16980. const context = localizeNode(rule, options.mode, localAliasMap);
  16981. context.options = options;
  16982. context.localAliasMap = localAliasMap;
  16983. if (pureMode && context.hasPureGlobals) {
  16984. throw rule.error(
  16985. 'Selector "' +
  16986. rule.selector +
  16987. '" is not pure ' +
  16988. "(pure selectors must contain at least one local class or id)"
  16989. );
  16990. }
  16991. rule.selector = context.selector;
  16992. // Less-syntax mixins parse as rules with no nodes
  16993. if (rule.nodes) {
  16994. rule.nodes.forEach((declaration) =>
  16995. localizeDeclaration(declaration, context)
  16996. );
  16997. }
  16998. });
  16999. },
  17000. };
  17001. },
  17002. };
  17003. };
  17004. src$2.exports.postcss = true;
  17005. return src$2.exports;
  17006. }
  17007. var src$1;
  17008. var hasRequiredSrc$1;
  17009. function requireSrc$1 () {
  17010. if (hasRequiredSrc$1) return src$1;
  17011. hasRequiredSrc$1 = 1;
  17012. const selectorParser = /*@__PURE__*/ requireDist();
  17013. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17014. function isNestedRule(rule) {
  17015. if (!rule.parent || rule.parent.type === "root") {
  17016. return false;
  17017. }
  17018. if (rule.parent.type === "rule") {
  17019. return true;
  17020. }
  17021. return isNestedRule(rule.parent);
  17022. }
  17023. function getSingleLocalNamesForComposes(root, rule) {
  17024. if (isNestedRule(rule)) {
  17025. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17026. }
  17027. return root.nodes.map((node) => {
  17028. if (node.type !== "selector" || node.nodes.length !== 1) {
  17029. throw new Error(
  17030. `composition is only allowed when selector is single :local class name not in "${root}"`
  17031. );
  17032. }
  17033. node = node.nodes[0];
  17034. if (
  17035. node.type !== "pseudo" ||
  17036. node.value !== ":local" ||
  17037. node.nodes.length !== 1
  17038. ) {
  17039. throw new Error(
  17040. 'composition is only allowed when selector is single :local class name not in "' +
  17041. root +
  17042. '", "' +
  17043. node +
  17044. '" is weird'
  17045. );
  17046. }
  17047. node = node.first;
  17048. if (node.type !== "selector" || node.length !== 1) {
  17049. throw new Error(
  17050. 'composition is only allowed when selector is single :local class name not in "' +
  17051. root +
  17052. '", "' +
  17053. node +
  17054. '" is weird'
  17055. );
  17056. }
  17057. node = node.first;
  17058. if (node.type !== "class") {
  17059. // 'id' is not possible, because you can't compose ids
  17060. throw new Error(
  17061. 'composition is only allowed when selector is single :local class name not in "' +
  17062. root +
  17063. '", "' +
  17064. node +
  17065. '" is weird'
  17066. );
  17067. }
  17068. return node.value;
  17069. });
  17070. }
  17071. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17072. const unescapeRegExp = new RegExp(
  17073. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17074. "ig"
  17075. );
  17076. function unescape(str) {
  17077. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17078. const high = "0x" + escaped - 0x10000;
  17079. // NaN means non-codepoint
  17080. // Workaround erroneous numeric interpretation of +"0x"
  17081. return high !== high || escapedWhitespace
  17082. ? escaped
  17083. : high < 0
  17084. ? // BMP codepoint
  17085. String.fromCharCode(high + 0x10000)
  17086. : // Supplemental Plane codepoint (surrogate pair)
  17087. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17088. });
  17089. }
  17090. const plugin = (options = {}) => {
  17091. const generateScopedName =
  17092. (options && options.generateScopedName) || plugin.generateScopedName;
  17093. const generateExportEntry =
  17094. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17095. const exportGlobals = options && options.exportGlobals;
  17096. return {
  17097. postcssPlugin: "postcss-modules-scope",
  17098. Once(root, { rule }) {
  17099. const exports = Object.create(null);
  17100. function exportScopedName(name, rawName, node) {
  17101. const scopedName = generateScopedName(
  17102. rawName ? rawName : name,
  17103. root.source.input.from,
  17104. root.source.input.css,
  17105. node
  17106. );
  17107. const exportEntry = generateExportEntry(
  17108. rawName ? rawName : name,
  17109. scopedName,
  17110. root.source.input.from,
  17111. root.source.input.css,
  17112. node
  17113. );
  17114. const { key, value } = exportEntry;
  17115. exports[key] = exports[key] || [];
  17116. if (exports[key].indexOf(value) < 0) {
  17117. exports[key].push(value);
  17118. }
  17119. return scopedName;
  17120. }
  17121. function localizeNode(node) {
  17122. switch (node.type) {
  17123. case "selector":
  17124. node.nodes = node.map((item) => localizeNode(item));
  17125. return node;
  17126. case "class":
  17127. return selectorParser.className({
  17128. value: exportScopedName(
  17129. node.value,
  17130. node.raws && node.raws.value ? node.raws.value : null,
  17131. node
  17132. ),
  17133. });
  17134. case "id": {
  17135. return selectorParser.id({
  17136. value: exportScopedName(
  17137. node.value,
  17138. node.raws && node.raws.value ? node.raws.value : null,
  17139. node
  17140. ),
  17141. });
  17142. }
  17143. case "attribute": {
  17144. if (node.attribute === "class" && node.operator === "=") {
  17145. return selectorParser.attribute({
  17146. attribute: node.attribute,
  17147. operator: node.operator,
  17148. quoteMark: "'",
  17149. value: exportScopedName(node.value, null, null),
  17150. });
  17151. }
  17152. }
  17153. }
  17154. throw new Error(
  17155. `${node.type} ("${node}") is not allowed in a :local block`
  17156. );
  17157. }
  17158. function traverseNode(node) {
  17159. switch (node.type) {
  17160. case "pseudo":
  17161. if (node.value === ":local") {
  17162. if (node.nodes.length !== 1) {
  17163. throw new Error('Unexpected comma (",") in :local block');
  17164. }
  17165. const selector = localizeNode(node.first);
  17166. // move the spaces that were around the pseudo selector to the first
  17167. // non-container node
  17168. selector.first.spaces = node.spaces;
  17169. const nextNode = node.next();
  17170. if (
  17171. nextNode &&
  17172. nextNode.type === "combinator" &&
  17173. nextNode.value === " " &&
  17174. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17175. ) {
  17176. selector.last.spaces.after = " ";
  17177. }
  17178. node.replaceWith(selector);
  17179. return;
  17180. }
  17181. /* falls through */
  17182. case "root":
  17183. case "selector": {
  17184. node.each((item) => traverseNode(item));
  17185. break;
  17186. }
  17187. case "id":
  17188. case "class":
  17189. if (exportGlobals) {
  17190. exports[node.value] = [node.value];
  17191. }
  17192. break;
  17193. }
  17194. return node;
  17195. }
  17196. // Find any :import and remember imported names
  17197. const importedNames = {};
  17198. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17199. rule.walkDecls((decl) => {
  17200. importedNames[decl.prop] = true;
  17201. });
  17202. });
  17203. // Find any :local selectors
  17204. root.walkRules((rule) => {
  17205. let parsedSelector = selectorParser().astSync(rule);
  17206. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17207. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17208. const localNames = getSingleLocalNamesForComposes(
  17209. parsedSelector,
  17210. decl.parent
  17211. );
  17212. const multiple = decl.value.split(",");
  17213. multiple.forEach((value) => {
  17214. const classes = value.trim().split(/\s+/);
  17215. classes.forEach((className) => {
  17216. const global = /^global\(([^)]+)\)$/.exec(className);
  17217. if (global) {
  17218. localNames.forEach((exportedName) => {
  17219. exports[exportedName].push(global[1]);
  17220. });
  17221. } else if (hasOwnProperty.call(importedNames, className)) {
  17222. localNames.forEach((exportedName) => {
  17223. exports[exportedName].push(className);
  17224. });
  17225. } else if (hasOwnProperty.call(exports, className)) {
  17226. localNames.forEach((exportedName) => {
  17227. exports[className].forEach((item) => {
  17228. exports[exportedName].push(item);
  17229. });
  17230. });
  17231. } else {
  17232. throw decl.error(
  17233. `referenced class name "${className}" in ${decl.prop} not found`
  17234. );
  17235. }
  17236. });
  17237. });
  17238. decl.remove();
  17239. });
  17240. // Find any :local values
  17241. rule.walkDecls((decl) => {
  17242. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17243. return;
  17244. }
  17245. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17246. tokens = tokens.map((token, idx) => {
  17247. if (idx === 0 || tokens[idx - 1] === ",") {
  17248. let result = token;
  17249. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17250. if (localMatch) {
  17251. const input = localMatch.input;
  17252. const matchPattern = localMatch[0];
  17253. const matchVal = localMatch[1];
  17254. const newVal = exportScopedName(matchVal);
  17255. result = input.replace(matchPattern, newVal);
  17256. } else {
  17257. return token;
  17258. }
  17259. return result;
  17260. } else {
  17261. return token;
  17262. }
  17263. });
  17264. decl.value = tokens.join("");
  17265. });
  17266. });
  17267. // Find any :local keyframes
  17268. root.walkAtRules(/keyframes$/i, (atRule) => {
  17269. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17270. if (!localMatch) {
  17271. return;
  17272. }
  17273. atRule.params = exportScopedName(localMatch[1]);
  17274. });
  17275. root.walkAtRules(/scope$/i, (atRule) => {
  17276. if (atRule.params) {
  17277. atRule.params = atRule.params
  17278. .split("to")
  17279. .map((item) => {
  17280. const selector = item.trim().slice(1, -1).trim();
  17281. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17282. if (!localMatch) {
  17283. return `(${selector})`;
  17284. }
  17285. let parsedSelector = selectorParser().astSync(selector);
  17286. return `(${traverseNode(parsedSelector).toString()})`;
  17287. })
  17288. .join(" to ");
  17289. }
  17290. });
  17291. // If we found any :locals, insert an :export rule
  17292. const exportedNames = Object.keys(exports);
  17293. if (exportedNames.length > 0) {
  17294. const exportRule = rule({ selector: ":export" });
  17295. exportedNames.forEach((exportedName) =>
  17296. exportRule.append({
  17297. prop: exportedName,
  17298. value: exports[exportedName].join(" "),
  17299. raws: { before: "\n " },
  17300. })
  17301. );
  17302. root.append(exportRule);
  17303. }
  17304. },
  17305. };
  17306. };
  17307. plugin.postcss = true;
  17308. plugin.generateScopedName = function (name, path) {
  17309. const sanitisedPath = path
  17310. .replace(/\.[^./\\]+$/, "")
  17311. .replace(/[\W_]+/g, "_")
  17312. .replace(/^_|_$/g, "");
  17313. return `_${sanitisedPath}__${name}`.trim();
  17314. };
  17315. plugin.generateExportEntry = function (name, scopedName) {
  17316. return {
  17317. key: unescape(name),
  17318. value: unescape(scopedName),
  17319. };
  17320. };
  17321. src$1 = plugin;
  17322. return src$1;
  17323. }
  17324. var stringHash;
  17325. var hasRequiredStringHash;
  17326. function requireStringHash () {
  17327. if (hasRequiredStringHash) return stringHash;
  17328. hasRequiredStringHash = 1;
  17329. function hash(str) {
  17330. var hash = 5381,
  17331. i = str.length;
  17332. while(i) {
  17333. hash = (hash * 33) ^ str.charCodeAt(--i);
  17334. }
  17335. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17336. * integers. Since we want the results to be always positive, convert the
  17337. * signed int to an unsigned by doing an unsigned bitshift. */
  17338. return hash >>> 0;
  17339. }
  17340. stringHash = hash;
  17341. return stringHash;
  17342. }
  17343. var src = {exports: {}};
  17344. var hasRequiredSrc;
  17345. function requireSrc () {
  17346. if (hasRequiredSrc) return src.exports;
  17347. hasRequiredSrc = 1;
  17348. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17349. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17350. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17351. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17352. src.exports = (options) => {
  17353. let importIndex = 0;
  17354. const createImportedName =
  17355. (options && options.createImportedName) ||
  17356. ((importName /*, path*/) =>
  17357. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17358. return {
  17359. postcssPlugin: "postcss-modules-values",
  17360. prepare(result) {
  17361. const importAliases = [];
  17362. const definitions = {};
  17363. return {
  17364. Once(root, postcss) {
  17365. root.walkAtRules(/value/i, (atRule) => {
  17366. const matches = atRule.params.match(matchImports);
  17367. if (matches) {
  17368. let [, /*match*/ aliases, path] = matches;
  17369. // We can use constants for path names
  17370. if (definitions[path]) {
  17371. path = definitions[path];
  17372. }
  17373. const imports = aliases
  17374. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17375. .split(/\s*,\s*/)
  17376. .map((alias) => {
  17377. const tokens = matchImport.exec(alias);
  17378. if (tokens) {
  17379. const [, /*match*/ theirName, myName = theirName] = tokens;
  17380. const importedName = createImportedName(myName);
  17381. definitions[myName] = importedName;
  17382. return { theirName, importedName };
  17383. } else {
  17384. throw new Error(`@import statement "${alias}" is invalid!`);
  17385. }
  17386. });
  17387. importAliases.push({ path, imports });
  17388. atRule.remove();
  17389. return;
  17390. }
  17391. if (atRule.params.indexOf("@value") !== -1) {
  17392. result.warn("Invalid value definition: " + atRule.params);
  17393. }
  17394. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17395. matchValueDefinition
  17396. );
  17397. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17398. if (normalizedValue.length === 0) {
  17399. result.warn("Invalid value definition: " + atRule.params);
  17400. atRule.remove();
  17401. return;
  17402. }
  17403. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17404. if (!isOnlySpace) {
  17405. value = value.trim();
  17406. }
  17407. // Add to the definitions, knowing that values can refer to each other
  17408. definitions[key] = ICSSUtils.replaceValueSymbols(
  17409. value,
  17410. definitions
  17411. );
  17412. atRule.remove();
  17413. });
  17414. /* If we have no definitions, don't continue */
  17415. if (!Object.keys(definitions).length) {
  17416. return;
  17417. }
  17418. /* Perform replacements */
  17419. ICSSUtils.replaceSymbols(root, definitions);
  17420. /* 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 */
  17421. const exportDeclarations = Object.keys(definitions).map((key) =>
  17422. postcss.decl({
  17423. value: definitions[key],
  17424. prop: key,
  17425. raws: { before: "\n " },
  17426. })
  17427. );
  17428. /* Add export rules if any */
  17429. if (exportDeclarations.length > 0) {
  17430. const exportRule = postcss.rule({
  17431. selector: ":export",
  17432. raws: { after: "\n" },
  17433. });
  17434. exportRule.append(exportDeclarations);
  17435. root.prepend(exportRule);
  17436. }
  17437. /* Add import rules */
  17438. importAliases.reverse().forEach(({ path, imports }) => {
  17439. const importRule = postcss.rule({
  17440. selector: `:import(${path})`,
  17441. raws: { after: "\n" },
  17442. });
  17443. imports.forEach(({ theirName, importedName }) => {
  17444. importRule.append({
  17445. value: theirName,
  17446. prop: importedName,
  17447. raws: { before: "\n " },
  17448. });
  17449. });
  17450. root.prepend(importRule);
  17451. });
  17452. },
  17453. };
  17454. },
  17455. };
  17456. };
  17457. src.exports.postcss = true;
  17458. return src.exports;
  17459. }
  17460. var hasRequiredScoping;
  17461. function requireScoping () {
  17462. if (hasRequiredScoping) return scoping;
  17463. hasRequiredScoping = 1;
  17464. Object.defineProperty(scoping, "__esModule", {
  17465. value: true
  17466. });
  17467. scoping.behaviours = void 0;
  17468. scoping.getDefaultPlugins = getDefaultPlugins;
  17469. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  17470. scoping.getScopedNameGenerator = getScopedNameGenerator;
  17471. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  17472. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  17473. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  17474. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  17475. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  17476. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  17477. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17478. const behaviours = {
  17479. LOCAL: "local",
  17480. GLOBAL: "global"
  17481. };
  17482. scoping.behaviours = behaviours;
  17483. function getDefaultPlugins({
  17484. behaviour,
  17485. generateScopedName,
  17486. exportGlobals
  17487. }) {
  17488. const scope = (0, _postcssModulesScope.default)({
  17489. generateScopedName,
  17490. exportGlobals
  17491. });
  17492. const plugins = {
  17493. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17494. mode: "local"
  17495. }), _postcssModulesExtractImports.default, scope],
  17496. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17497. mode: "global"
  17498. }), _postcssModulesExtractImports.default, scope]
  17499. };
  17500. return plugins[behaviour];
  17501. }
  17502. function isValidBehaviour(behaviour) {
  17503. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  17504. }
  17505. function getDefaultScopeBehaviour(scopeBehaviour) {
  17506. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  17507. }
  17508. function generateScopedNameDefault(name, filename, css) {
  17509. const i = css.indexOf(`.${name}`);
  17510. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  17511. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  17512. return `_${name}_${hash}_${lineNumber}`;
  17513. }
  17514. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  17515. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  17516. if (typeof scopedNameGenerator === "function") {
  17517. return scopedNameGenerator;
  17518. }
  17519. return (0, _genericNames.default)(scopedNameGenerator, {
  17520. context: process.cwd(),
  17521. hashPrefix: hashPrefix
  17522. });
  17523. }
  17524. return scoping;
  17525. }
  17526. var hasRequiredPluginFactory;
  17527. function requirePluginFactory () {
  17528. if (hasRequiredPluginFactory) return pluginFactory;
  17529. hasRequiredPluginFactory = 1;
  17530. Object.defineProperty(pluginFactory, "__esModule", {
  17531. value: true
  17532. });
  17533. pluginFactory.makePlugin = makePlugin;
  17534. var _postcss = _interopRequireDefault(require$$0$1);
  17535. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  17536. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  17537. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  17538. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  17539. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  17540. var _scoping = /*@__PURE__*/ requireScoping();
  17541. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17542. const PLUGIN_NAME = "postcss-modules";
  17543. function isGlobalModule(globalModules, inputFile) {
  17544. return globalModules.some(regex => inputFile.match(regex));
  17545. }
  17546. function getDefaultPluginsList(opts, inputFile) {
  17547. const globalModulesList = opts.globalModulePaths || null;
  17548. const exportGlobals = opts.exportGlobals || false;
  17549. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  17550. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  17551. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  17552. return (0, _scoping.getDefaultPlugins)({
  17553. behaviour: _scoping.behaviours.GLOBAL,
  17554. generateScopedName,
  17555. exportGlobals
  17556. });
  17557. }
  17558. return (0, _scoping.getDefaultPlugins)({
  17559. behaviour: defaultBehaviour,
  17560. generateScopedName,
  17561. exportGlobals
  17562. });
  17563. }
  17564. function getLoader(opts, plugins) {
  17565. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  17566. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  17567. }
  17568. function isOurPlugin(plugin) {
  17569. return plugin.postcssPlugin === PLUGIN_NAME;
  17570. }
  17571. function makePlugin(opts) {
  17572. return {
  17573. postcssPlugin: PLUGIN_NAME,
  17574. async OnceExit(css, {
  17575. result
  17576. }) {
  17577. const getJSON = opts.getJSON || _saveJSON.default;
  17578. const inputFile = css.source.input.file;
  17579. const pluginList = getDefaultPluginsList(opts, inputFile);
  17580. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  17581. if (resultPluginIndex === -1) {
  17582. throw new Error("Plugin missing from options.");
  17583. }
  17584. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  17585. const loaderPlugins = [...earlierPlugins, ...pluginList];
  17586. const loader = getLoader(opts, loaderPlugins);
  17587. const fetcher = async (file, relativeTo, depTrace) => {
  17588. const unquoteFile = (0, _unquote.default)(file);
  17589. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  17590. };
  17591. const parser = new _Parser.default(fetcher);
  17592. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  17593. from: inputFile
  17594. });
  17595. const out = loader.finalSource;
  17596. if (out) css.prepend(out);
  17597. if (opts.localsConvention) {
  17598. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  17599. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  17600. }
  17601. result.messages.push({
  17602. type: "export",
  17603. plugin: "postcss-modules",
  17604. exportTokens: parser.exportTokens
  17605. }); // getJSON may return a promise
  17606. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  17607. }
  17608. };
  17609. }
  17610. return pluginFactory;
  17611. }
  17612. var hasRequiredBuild;
  17613. function requireBuild () {
  17614. if (hasRequiredBuild) return build.exports;
  17615. hasRequiredBuild = 1;
  17616. var _fs = require$$0;
  17617. var _fs2 = /*@__PURE__*/ requireFs();
  17618. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  17619. (0, _fs2.setFileSystem)({
  17620. readFile: _fs.readFile,
  17621. writeFile: _fs.writeFile
  17622. });
  17623. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  17624. build.exports.postcss = true;
  17625. return build.exports;
  17626. }
  17627. var buildExports = /*@__PURE__*/ requireBuild();
  17628. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  17629. function compileStyle(options) {
  17630. return doCompileStyle({
  17631. ...options,
  17632. isAsync: false
  17633. });
  17634. }
  17635. function compileStyleAsync(options) {
  17636. return doCompileStyle({
  17637. ...options,
  17638. isAsync: true
  17639. });
  17640. }
  17641. function doCompileStyle(options) {
  17642. const {
  17643. filename,
  17644. id,
  17645. scoped = false,
  17646. trim = true,
  17647. isProd = false,
  17648. modules = false,
  17649. modulesOptions = {},
  17650. preprocessLang,
  17651. postcssOptions,
  17652. postcssPlugins
  17653. } = options;
  17654. const preprocessor = preprocessLang && processors[preprocessLang];
  17655. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  17656. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  17657. const source = preProcessedSource ? preProcessedSource.code : options.source;
  17658. const shortId = id.replace(/^data-v-/, "");
  17659. const longId = `data-v-${shortId}`;
  17660. const plugins = (postcssPlugins || []).slice();
  17661. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  17662. if (trim) {
  17663. plugins.push(trimPlugin());
  17664. }
  17665. if (scoped) {
  17666. plugins.push(scopedPlugin(longId));
  17667. }
  17668. let cssModules;
  17669. if (modules) {
  17670. if (!options.isAsync) {
  17671. throw new Error(
  17672. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  17673. );
  17674. }
  17675. plugins.push(
  17676. postcssModules({
  17677. ...modulesOptions,
  17678. getJSON: (_cssFileName, json) => {
  17679. cssModules = json;
  17680. }
  17681. })
  17682. );
  17683. }
  17684. const postCSSOptions = {
  17685. ...postcssOptions,
  17686. to: filename,
  17687. from: filename
  17688. };
  17689. if (map) {
  17690. postCSSOptions.map = {
  17691. inline: false,
  17692. annotation: false,
  17693. prev: map
  17694. };
  17695. }
  17696. let result;
  17697. let code;
  17698. let outMap;
  17699. const dependencies = new Set(
  17700. preProcessedSource ? preProcessedSource.dependencies : []
  17701. );
  17702. dependencies.delete(filename);
  17703. const errors = [];
  17704. if (preProcessedSource && preProcessedSource.errors.length) {
  17705. errors.push(...preProcessedSource.errors);
  17706. }
  17707. const recordPlainCssDependencies = (messages) => {
  17708. messages.forEach((msg) => {
  17709. if (msg.type === "dependency") {
  17710. dependencies.add(msg.file);
  17711. }
  17712. });
  17713. return dependencies;
  17714. };
  17715. try {
  17716. result = require$$0$1(plugins).process(source, postCSSOptions);
  17717. if (options.isAsync) {
  17718. return result.then((result2) => ({
  17719. code: result2.css || "",
  17720. map: result2.map && result2.map.toJSON(),
  17721. errors,
  17722. modules: cssModules,
  17723. rawResult: result2,
  17724. dependencies: recordPlainCssDependencies(result2.messages)
  17725. })).catch((error) => ({
  17726. code: "",
  17727. map: void 0,
  17728. errors: [...errors, error],
  17729. rawResult: void 0,
  17730. dependencies
  17731. }));
  17732. }
  17733. recordPlainCssDependencies(result.messages);
  17734. code = result.css;
  17735. outMap = result.map;
  17736. } catch (e) {
  17737. errors.push(e);
  17738. }
  17739. return {
  17740. code: code || ``,
  17741. map: outMap && outMap.toJSON(),
  17742. errors,
  17743. rawResult: result,
  17744. dependencies
  17745. };
  17746. }
  17747. function preprocess(options, preprocessor) {
  17748. return preprocessor(
  17749. options.source,
  17750. options.inMap || options.map,
  17751. {
  17752. filename: options.filename,
  17753. ...options.preprocessOptions
  17754. },
  17755. options.preprocessCustomRequire
  17756. );
  17757. }
  17758. const UNKNOWN_TYPE = "Unknown";
  17759. function resolveObjectKey(node, computed) {
  17760. switch (node.type) {
  17761. case "StringLiteral":
  17762. case "NumericLiteral":
  17763. return String(node.value);
  17764. case "Identifier":
  17765. if (!computed) return node.name;
  17766. }
  17767. return void 0;
  17768. }
  17769. function concatStrings(strs) {
  17770. return strs.filter((s) => !!s).join(", ");
  17771. }
  17772. function isLiteralNode(node) {
  17773. return node.type.endsWith("Literal");
  17774. }
  17775. function isCallOf(node, test) {
  17776. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  17777. }
  17778. function toRuntimeTypeString(types) {
  17779. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  17780. }
  17781. function getImportedName(specifier) {
  17782. if (specifier.type === "ImportSpecifier")
  17783. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  17784. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  17785. return "default";
  17786. }
  17787. function getId(node) {
  17788. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  17789. }
  17790. const identity = (str) => str;
  17791. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  17792. const toLowerCase = (str) => str.toLowerCase();
  17793. function toFileNameLowerCase(x) {
  17794. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  17795. }
  17796. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  17797. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  17798. }
  17799. const normalize = (path$1.posix || path$1).normalize;
  17800. const windowsSlashRE = /\\/g;
  17801. function normalizePath(p) {
  17802. return normalize(p.replace(windowsSlashRE, "/"));
  17803. }
  17804. const joinPaths = (path$1.posix || path$1).join;
  17805. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  17806. function getEscapedPropName(key) {
  17807. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  17808. }
  17809. function analyzeScriptBindings(ast) {
  17810. for (const node of ast) {
  17811. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  17812. return analyzeBindingsFromOptions(node.declaration);
  17813. }
  17814. }
  17815. return {};
  17816. }
  17817. function analyzeBindingsFromOptions(node) {
  17818. const bindings = {};
  17819. Object.defineProperty(bindings, "__isScriptSetup", {
  17820. enumerable: false,
  17821. value: false
  17822. });
  17823. for (const property of node.properties) {
  17824. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  17825. if (property.key.name === "props") {
  17826. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17827. bindings[key] = "props";
  17828. }
  17829. } else if (property.key.name === "inject") {
  17830. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17831. bindings[key] = "options";
  17832. }
  17833. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  17834. for (const key of getObjectExpressionKeys(property.value)) {
  17835. bindings[key] = "options";
  17836. }
  17837. }
  17838. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  17839. for (const bodyItem of property.body.body) {
  17840. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  17841. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  17842. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  17843. }
  17844. }
  17845. }
  17846. }
  17847. }
  17848. return bindings;
  17849. }
  17850. function getObjectExpressionKeys(node) {
  17851. const keys = [];
  17852. for (const prop of node.properties) {
  17853. if (prop.type === "SpreadElement") continue;
  17854. const key = resolveObjectKey(prop.key, prop.computed);
  17855. if (key) keys.push(String(key));
  17856. }
  17857. return keys;
  17858. }
  17859. function getArrayExpressionKeys(node) {
  17860. const keys = [];
  17861. for (const element of node.elements) {
  17862. if (element && element.type === "StringLiteral") {
  17863. keys.push(element.value);
  17864. }
  17865. }
  17866. return keys;
  17867. }
  17868. function getObjectOrArrayExpressionKeys(value) {
  17869. if (value.type === "ArrayExpression") {
  17870. return getArrayExpressionKeys(value);
  17871. }
  17872. if (value.type === "ObjectExpression") {
  17873. return getObjectExpressionKeys(value);
  17874. }
  17875. return [];
  17876. }
  17877. var _a, _b;
  17878. class ScriptCompileContext {
  17879. constructor(descriptor, options) {
  17880. this.descriptor = descriptor;
  17881. this.options = options;
  17882. this.isCE = false;
  17883. this.source = this.descriptor.source;
  17884. this.filename = this.descriptor.filename;
  17885. this.s = new MagicString(this.source);
  17886. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  17887. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  17888. this.userImports = /* @__PURE__ */ Object.create(null);
  17889. // macros presence check
  17890. this.hasDefinePropsCall = false;
  17891. this.hasDefineEmitCall = false;
  17892. this.hasDefineExposeCall = false;
  17893. this.hasDefaultExportName = false;
  17894. this.hasDefaultExportRender = false;
  17895. this.hasDefineOptionsCall = false;
  17896. this.hasDefineSlotsCall = false;
  17897. this.hasDefineModelCall = false;
  17898. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  17899. // defineModel
  17900. this.modelDecls = /* @__PURE__ */ Object.create(null);
  17901. // codegen
  17902. this.bindingMetadata = {};
  17903. this.helperImports = /* @__PURE__ */ new Set();
  17904. const { script, scriptSetup } = descriptor;
  17905. const scriptLang = script && script.lang;
  17906. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  17907. this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx";
  17908. this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx";
  17909. const customElement = options.customElement;
  17910. const filename = this.descriptor.filename;
  17911. if (customElement) {
  17912. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  17913. }
  17914. const plugins = resolveParserPlugins(
  17915. scriptLang || scriptSetupLang,
  17916. options.babelParserPlugins
  17917. );
  17918. function parse(input, offset) {
  17919. try {
  17920. return parser$2.parse(input, {
  17921. plugins,
  17922. sourceType: "module"
  17923. }).program;
  17924. } catch (e) {
  17925. e.message = `[vue/compiler-sfc] ${e.message}
  17926. ${descriptor.filename}
  17927. ${shared.generateCodeFrame(
  17928. descriptor.source,
  17929. e.pos + offset,
  17930. e.pos + offset + 1
  17931. )}`;
  17932. throw e;
  17933. }
  17934. }
  17935. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  17936. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  17937. }
  17938. helper(key) {
  17939. this.helperImports.add(key);
  17940. return `_${key}`;
  17941. }
  17942. getString(node, scriptSetup = true) {
  17943. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  17944. return block.content.slice(node.start, node.end);
  17945. }
  17946. warn(msg, node, scope) {
  17947. warn(generateError(msg, node, this, scope));
  17948. }
  17949. error(msg, node, scope) {
  17950. throw new Error(
  17951. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  17952. );
  17953. }
  17954. }
  17955. function generateError(msg, node, ctx, scope) {
  17956. const offset = scope ? scope.offset : ctx.startOffset;
  17957. return `${msg}
  17958. ${(scope || ctx.descriptor).filename}
  17959. ${shared.generateCodeFrame(
  17960. (scope || ctx.descriptor).source,
  17961. node.start + offset,
  17962. node.end + offset
  17963. )}`;
  17964. }
  17965. function resolveParserPlugins(lang, userPlugins, dts = false) {
  17966. const plugins = [];
  17967. if (!userPlugins || !userPlugins.some(
  17968. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  17969. )) {
  17970. plugins.push("importAttributes");
  17971. }
  17972. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  17973. plugins.push("jsx");
  17974. } else if (userPlugins) {
  17975. userPlugins = userPlugins.filter((p) => p !== "jsx");
  17976. }
  17977. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "mtsx") {
  17978. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  17979. if (!userPlugins || !userPlugins.includes("decorators")) {
  17980. plugins.push("decorators-legacy");
  17981. }
  17982. }
  17983. if (userPlugins) {
  17984. plugins.push(...userPlugins);
  17985. }
  17986. return plugins;
  17987. }
  17988. function rewriteDefault(input, as, parserPlugins) {
  17989. const ast = parser$2.parse(input, {
  17990. sourceType: "module",
  17991. plugins: resolveParserPlugins("js", parserPlugins)
  17992. }).program.body;
  17993. const s = new MagicString(input);
  17994. rewriteDefaultAST(ast, s, as);
  17995. return s.toString();
  17996. }
  17997. function rewriteDefaultAST(ast, s, as) {
  17998. if (!hasDefaultExport(ast)) {
  17999. s.append(`
  18000. const ${as} = {}`);
  18001. return;
  18002. }
  18003. ast.forEach((node) => {
  18004. if (node.type === "ExportDefaultDeclaration") {
  18005. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  18006. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  18007. s.overwrite(start, node.declaration.id.start, ` class `);
  18008. s.append(`
  18009. const ${as} = ${node.declaration.id.name}`);
  18010. } else {
  18011. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18012. }
  18013. } else if (node.type === "ExportNamedDeclaration") {
  18014. for (const specifier of node.specifiers) {
  18015. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18016. if (node.source) {
  18017. if (specifier.local.name === "default") {
  18018. s.prepend(
  18019. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18020. `
  18021. );
  18022. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18023. s.remove(specifier.start, end2);
  18024. s.append(`
  18025. const ${as} = __VUE_DEFAULT__`);
  18026. continue;
  18027. } else {
  18028. s.prepend(
  18029. `import { ${s.slice(
  18030. specifier.local.start,
  18031. specifier.local.end
  18032. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18033. `
  18034. );
  18035. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18036. s.remove(specifier.start, end2);
  18037. s.append(`
  18038. const ${as} = __VUE_DEFAULT__`);
  18039. continue;
  18040. }
  18041. }
  18042. const end = specifierEnd(s, specifier.end, node.end);
  18043. s.remove(specifier.start, end);
  18044. s.append(`
  18045. const ${as} = ${specifier.local.name}`);
  18046. }
  18047. }
  18048. }
  18049. });
  18050. }
  18051. function hasDefaultExport(ast) {
  18052. for (const stmt of ast) {
  18053. if (stmt.type === "ExportDefaultDeclaration") {
  18054. return true;
  18055. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18056. (spec) => spec.exported.name === "default"
  18057. )) {
  18058. return true;
  18059. }
  18060. }
  18061. return false;
  18062. }
  18063. function specifierEnd(s, end, nodeEnd) {
  18064. let hasCommas = false;
  18065. let oldEnd = end;
  18066. while (end < nodeEnd) {
  18067. if (/\s/.test(s.slice(end, end + 1))) {
  18068. end++;
  18069. } else if (s.slice(end, end + 1) === ",") {
  18070. end++;
  18071. hasCommas = true;
  18072. break;
  18073. } else if (s.slice(end, end + 1) === "}") {
  18074. break;
  18075. }
  18076. }
  18077. return hasCommas ? end : oldEnd;
  18078. }
  18079. const normalScriptDefaultVar = `__default__`;
  18080. function processNormalScript(ctx, scopeId) {
  18081. var _a;
  18082. const script = ctx.descriptor.script;
  18083. if (script.lang && !ctx.isJS && !ctx.isTS) {
  18084. return script;
  18085. }
  18086. try {
  18087. let content = script.content;
  18088. let map = script.map;
  18089. const scriptAst = ctx.scriptAst;
  18090. const bindings = analyzeScriptBindings(scriptAst.body);
  18091. const { cssVars } = ctx.descriptor;
  18092. const { genDefaultAs, isProd } = ctx.options;
  18093. if (cssVars.length || genDefaultAs) {
  18094. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18095. const s = new MagicString(content);
  18096. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18097. content = s.toString();
  18098. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18099. content += genNormalScriptCssVarsCode(
  18100. cssVars,
  18101. bindings,
  18102. scopeId,
  18103. !!isProd,
  18104. defaultVar
  18105. );
  18106. }
  18107. if (!genDefaultAs) {
  18108. content += `
  18109. export default ${defaultVar}`;
  18110. }
  18111. }
  18112. return {
  18113. ...script,
  18114. content,
  18115. map,
  18116. bindings,
  18117. scriptAst: scriptAst.body
  18118. };
  18119. } catch (e) {
  18120. return script;
  18121. }
  18122. }
  18123. var balancedMatch;
  18124. var hasRequiredBalancedMatch;
  18125. function requireBalancedMatch () {
  18126. if (hasRequiredBalancedMatch) return balancedMatch;
  18127. hasRequiredBalancedMatch = 1;
  18128. balancedMatch = balanced;
  18129. function balanced(a, b, str) {
  18130. if (a instanceof RegExp) a = maybeMatch(a, str);
  18131. if (b instanceof RegExp) b = maybeMatch(b, str);
  18132. var r = range(a, b, str);
  18133. return r && {
  18134. start: r[0],
  18135. end: r[1],
  18136. pre: str.slice(0, r[0]),
  18137. body: str.slice(r[0] + a.length, r[1]),
  18138. post: str.slice(r[1] + b.length)
  18139. };
  18140. }
  18141. function maybeMatch(reg, str) {
  18142. var m = str.match(reg);
  18143. return m ? m[0] : null;
  18144. }
  18145. balanced.range = range;
  18146. function range(a, b, str) {
  18147. var begs, beg, left, right, result;
  18148. var ai = str.indexOf(a);
  18149. var bi = str.indexOf(b, ai + 1);
  18150. var i = ai;
  18151. if (ai >= 0 && bi > 0) {
  18152. if(a===b) {
  18153. return [ai, bi];
  18154. }
  18155. begs = [];
  18156. left = str.length;
  18157. while (i >= 0 && !result) {
  18158. if (i == ai) {
  18159. begs.push(i);
  18160. ai = str.indexOf(a, i + 1);
  18161. } else if (begs.length == 1) {
  18162. result = [ begs.pop(), bi ];
  18163. } else {
  18164. beg = begs.pop();
  18165. if (beg < left) {
  18166. left = beg;
  18167. right = bi;
  18168. }
  18169. bi = str.indexOf(b, i + 1);
  18170. }
  18171. i = ai < bi && ai >= 0 ? ai : bi;
  18172. }
  18173. if (begs.length) {
  18174. result = [ left, right ];
  18175. }
  18176. }
  18177. return result;
  18178. }
  18179. return balancedMatch;
  18180. }
  18181. var braceExpansion;
  18182. var hasRequiredBraceExpansion;
  18183. function requireBraceExpansion () {
  18184. if (hasRequiredBraceExpansion) return braceExpansion;
  18185. hasRequiredBraceExpansion = 1;
  18186. var balanced = /*@__PURE__*/ requireBalancedMatch();
  18187. braceExpansion = expandTop;
  18188. var escSlash = '\0SLASH'+Math.random()+'\0';
  18189. var escOpen = '\0OPEN'+Math.random()+'\0';
  18190. var escClose = '\0CLOSE'+Math.random()+'\0';
  18191. var escComma = '\0COMMA'+Math.random()+'\0';
  18192. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  18193. function numeric(str) {
  18194. return parseInt(str, 10) == str
  18195. ? parseInt(str, 10)
  18196. : str.charCodeAt(0);
  18197. }
  18198. function escapeBraces(str) {
  18199. return str.split('\\\\').join(escSlash)
  18200. .split('\\{').join(escOpen)
  18201. .split('\\}').join(escClose)
  18202. .split('\\,').join(escComma)
  18203. .split('\\.').join(escPeriod);
  18204. }
  18205. function unescapeBraces(str) {
  18206. return str.split(escSlash).join('\\')
  18207. .split(escOpen).join('{')
  18208. .split(escClose).join('}')
  18209. .split(escComma).join(',')
  18210. .split(escPeriod).join('.');
  18211. }
  18212. // Basically just str.split(","), but handling cases
  18213. // where we have nested braced sections, which should be
  18214. // treated as individual members, like {a,{b,c},d}
  18215. function parseCommaParts(str) {
  18216. if (!str)
  18217. return [''];
  18218. var parts = [];
  18219. var m = balanced('{', '}', str);
  18220. if (!m)
  18221. return str.split(',');
  18222. var pre = m.pre;
  18223. var body = m.body;
  18224. var post = m.post;
  18225. var p = pre.split(',');
  18226. p[p.length-1] += '{' + body + '}';
  18227. var postParts = parseCommaParts(post);
  18228. if (post.length) {
  18229. p[p.length-1] += postParts.shift();
  18230. p.push.apply(p, postParts);
  18231. }
  18232. parts.push.apply(parts, p);
  18233. return parts;
  18234. }
  18235. function expandTop(str) {
  18236. if (!str)
  18237. return [];
  18238. // I don't know why Bash 4.3 does this, but it does.
  18239. // Anything starting with {} will have the first two bytes preserved
  18240. // but *only* at the top level, so {},a}b will not expand to anything,
  18241. // but a{},b}c will be expanded to [a}c,abc].
  18242. // One could argue that this is a bug in Bash, but since the goal of
  18243. // this module is to match Bash's rules, we escape a leading {}
  18244. if (str.substr(0, 2) === '{}') {
  18245. str = '\\{\\}' + str.substr(2);
  18246. }
  18247. return expand(escapeBraces(str), true).map(unescapeBraces);
  18248. }
  18249. function embrace(str) {
  18250. return '{' + str + '}';
  18251. }
  18252. function isPadded(el) {
  18253. return /^-?0\d/.test(el);
  18254. }
  18255. function lte(i, y) {
  18256. return i <= y;
  18257. }
  18258. function gte(i, y) {
  18259. return i >= y;
  18260. }
  18261. function expand(str, isTop) {
  18262. var expansions = [];
  18263. var m = balanced('{', '}', str);
  18264. if (!m) return [str];
  18265. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18266. var pre = m.pre;
  18267. var post = m.post.length
  18268. ? expand(m.post, false)
  18269. : [''];
  18270. if (/\$$/.test(m.pre)) {
  18271. for (var k = 0; k < post.length; k++) {
  18272. var expansion = pre+ '{' + m.body + '}' + post[k];
  18273. expansions.push(expansion);
  18274. }
  18275. } else {
  18276. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18277. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18278. var isSequence = isNumericSequence || isAlphaSequence;
  18279. var isOptions = m.body.indexOf(',') >= 0;
  18280. if (!isSequence && !isOptions) {
  18281. // {a},b}
  18282. if (m.post.match(/,.*\}/)) {
  18283. str = m.pre + '{' + m.body + escClose + m.post;
  18284. return expand(str);
  18285. }
  18286. return [str];
  18287. }
  18288. var n;
  18289. if (isSequence) {
  18290. n = m.body.split(/\.\./);
  18291. } else {
  18292. n = parseCommaParts(m.body);
  18293. if (n.length === 1) {
  18294. // x{{a,b}}y ==> x{a}y x{b}y
  18295. n = expand(n[0], false).map(embrace);
  18296. if (n.length === 1) {
  18297. return post.map(function(p) {
  18298. return m.pre + n[0] + p;
  18299. });
  18300. }
  18301. }
  18302. }
  18303. // at this point, n is the parts, and we know it's not a comma set
  18304. // with a single entry.
  18305. var N;
  18306. if (isSequence) {
  18307. var x = numeric(n[0]);
  18308. var y = numeric(n[1]);
  18309. var width = Math.max(n[0].length, n[1].length);
  18310. var incr = n.length == 3
  18311. ? Math.abs(numeric(n[2]))
  18312. : 1;
  18313. var test = lte;
  18314. var reverse = y < x;
  18315. if (reverse) {
  18316. incr *= -1;
  18317. test = gte;
  18318. }
  18319. var pad = n.some(isPadded);
  18320. N = [];
  18321. for (var i = x; test(i, y); i += incr) {
  18322. var c;
  18323. if (isAlphaSequence) {
  18324. c = String.fromCharCode(i);
  18325. if (c === '\\')
  18326. c = '';
  18327. } else {
  18328. c = String(i);
  18329. if (pad) {
  18330. var need = width - c.length;
  18331. if (need > 0) {
  18332. var z = new Array(need + 1).join('0');
  18333. if (i < 0)
  18334. c = '-' + z + c.slice(1);
  18335. else
  18336. c = z + c;
  18337. }
  18338. }
  18339. }
  18340. N.push(c);
  18341. }
  18342. } else {
  18343. N = [];
  18344. for (var j = 0; j < n.length; j++) {
  18345. N.push.apply(N, expand(n[j], false));
  18346. }
  18347. }
  18348. for (var j = 0; j < N.length; j++) {
  18349. for (var k = 0; k < post.length; k++) {
  18350. var expansion = pre + N[j] + post[k];
  18351. if (!isTop || isSequence || expansion)
  18352. expansions.push(expansion);
  18353. }
  18354. }
  18355. }
  18356. return expansions;
  18357. }
  18358. return braceExpansion;
  18359. }
  18360. var braceExpansionExports = /*@__PURE__*/ requireBraceExpansion();
  18361. var expand = /*@__PURE__*/getDefaultExportFromCjs(braceExpansionExports);
  18362. const MAX_PATTERN_LENGTH = 1024 * 64;
  18363. const assertValidPattern = (pattern) => {
  18364. if (typeof pattern !== 'string') {
  18365. throw new TypeError('invalid pattern');
  18366. }
  18367. if (pattern.length > MAX_PATTERN_LENGTH) {
  18368. throw new TypeError('pattern is too long');
  18369. }
  18370. };
  18371. // translate the various posix character classes into unicode properties
  18372. // this works across all unicode locales
  18373. // { <posix class>: [<translation>, /u flag required, negated]
  18374. const posixClasses = {
  18375. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  18376. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  18377. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  18378. '[:blank:]': ['\\p{Zs}\\t', true],
  18379. '[:cntrl:]': ['\\p{Cc}', true],
  18380. '[:digit:]': ['\\p{Nd}', true],
  18381. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  18382. '[:lower:]': ['\\p{Ll}', true],
  18383. '[:print:]': ['\\p{C}', true],
  18384. '[:punct:]': ['\\p{P}', true],
  18385. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  18386. '[:upper:]': ['\\p{Lu}', true],
  18387. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  18388. '[:xdigit:]': ['A-Fa-f0-9', false],
  18389. };
  18390. // only need to escape a few things inside of brace expressions
  18391. // escapes: [ \ ] -
  18392. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  18393. // escape all regexp magic characters
  18394. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18395. // everything has already been escaped, we just have to join
  18396. const rangesToString = (ranges) => ranges.join('');
  18397. // takes a glob string at a posix brace expression, and returns
  18398. // an equivalent regular expression source, and boolean indicating
  18399. // whether the /u flag needs to be applied, and the number of chars
  18400. // consumed to parse the character class.
  18401. // This also removes out of order ranges, and returns ($.) if the
  18402. // entire class just no good.
  18403. const parseClass = (glob, position) => {
  18404. const pos = position;
  18405. /* c8 ignore start */
  18406. if (glob.charAt(pos) !== '[') {
  18407. throw new Error('not in a brace expression');
  18408. }
  18409. /* c8 ignore stop */
  18410. const ranges = [];
  18411. const negs = [];
  18412. let i = pos + 1;
  18413. let sawStart = false;
  18414. let uflag = false;
  18415. let escaping = false;
  18416. let negate = false;
  18417. let endPos = pos;
  18418. let rangeStart = '';
  18419. WHILE: while (i < glob.length) {
  18420. const c = glob.charAt(i);
  18421. if ((c === '!' || c === '^') && i === pos + 1) {
  18422. negate = true;
  18423. i++;
  18424. continue;
  18425. }
  18426. if (c === ']' && sawStart && !escaping) {
  18427. endPos = i + 1;
  18428. break;
  18429. }
  18430. sawStart = true;
  18431. if (c === '\\') {
  18432. if (!escaping) {
  18433. escaping = true;
  18434. i++;
  18435. continue;
  18436. }
  18437. // escaped \ char, fall through and treat like normal char
  18438. }
  18439. if (c === '[' && !escaping) {
  18440. // either a posix class, a collation equivalent, or just a [
  18441. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  18442. if (glob.startsWith(cls, i)) {
  18443. // invalid, [a-[] is fine, but not [a-[:alpha]]
  18444. if (rangeStart) {
  18445. return ['$.', false, glob.length - pos, true];
  18446. }
  18447. i += cls.length;
  18448. if (neg)
  18449. negs.push(unip);
  18450. else
  18451. ranges.push(unip);
  18452. uflag = uflag || u;
  18453. continue WHILE;
  18454. }
  18455. }
  18456. }
  18457. // now it's just a normal character, effectively
  18458. escaping = false;
  18459. if (rangeStart) {
  18460. // throw this range away if it's not valid, but others
  18461. // can still match.
  18462. if (c > rangeStart) {
  18463. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  18464. }
  18465. else if (c === rangeStart) {
  18466. ranges.push(braceEscape(c));
  18467. }
  18468. rangeStart = '';
  18469. i++;
  18470. continue;
  18471. }
  18472. // now might be the start of a range.
  18473. // can be either c-d or c-] or c<more...>] or c] at this point
  18474. if (glob.startsWith('-]', i + 1)) {
  18475. ranges.push(braceEscape(c + '-'));
  18476. i += 2;
  18477. continue;
  18478. }
  18479. if (glob.startsWith('-', i + 1)) {
  18480. rangeStart = c;
  18481. i += 2;
  18482. continue;
  18483. }
  18484. // not the start of a range, just a single character
  18485. ranges.push(braceEscape(c));
  18486. i++;
  18487. }
  18488. if (endPos < i) {
  18489. // didn't see the end of the class, not a valid class,
  18490. // but might still be valid as a literal match.
  18491. return ['', false, 0, false];
  18492. }
  18493. // if we got no ranges and no negates, then we have a range that
  18494. // cannot possibly match anything, and that poisons the whole glob
  18495. if (!ranges.length && !negs.length) {
  18496. return ['$.', false, glob.length - pos, true];
  18497. }
  18498. // if we got one positive range, and it's a single character, then that's
  18499. // not actually a magic pattern, it's just that one literal character.
  18500. // we should not treat that as "magic", we should just return the literal
  18501. // character. [_] is a perfectly valid way to escape glob magic chars.
  18502. if (negs.length === 0 &&
  18503. ranges.length === 1 &&
  18504. /^\\?.$/.test(ranges[0]) &&
  18505. !negate) {
  18506. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  18507. return [regexpEscape(r), false, endPos - pos, false];
  18508. }
  18509. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  18510. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  18511. const comb = ranges.length && negs.length
  18512. ? '(' + sranges + '|' + snegs + ')'
  18513. : ranges.length
  18514. ? sranges
  18515. : snegs;
  18516. return [comb, uflag, endPos - pos, true];
  18517. };
  18518. /**
  18519. * Un-escape a string that has been escaped with {@link escape}.
  18520. *
  18521. * If the {@link windowsPathsNoEscape} option is used, then square-brace
  18522. * escapes are removed, but not backslash escapes. For example, it will turn
  18523. * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
  18524. * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
  18525. *
  18526. * When `windowsPathsNoEscape` is not set, then both brace escapes and
  18527. * backslash escapes are removed.
  18528. *
  18529. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  18530. * or unescaped.
  18531. */
  18532. const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
  18533. return windowsPathsNoEscape
  18534. ? s.replace(/\[([^\/\\])\]/g, '$1')
  18535. : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
  18536. };
  18537. // parse a single path portion
  18538. const types = new Set(['!', '?', '+', '*', '@']);
  18539. const isExtglobType = (c) => types.has(c);
  18540. // Patterns that get prepended to bind to the start of either the
  18541. // entire string, or just a single path portion, to prevent dots
  18542. // and/or traversal patterns, when needed.
  18543. // Exts don't need the ^ or / bit, because the root binds that already.
  18544. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  18545. const startNoDot = '(?!\\.)';
  18546. // characters that indicate a start of pattern needs the "no dots" bit,
  18547. // because a dot *might* be matched. ( is not in the list, because in
  18548. // the case of a child extglob, it will handle the prevention itself.
  18549. const addPatternStart = new Set(['[', '.']);
  18550. // cases where traversal is A-OK, no dot prevention needed
  18551. const justDots = new Set(['..', '.']);
  18552. const reSpecials = new Set('().*{}+?[]^$\\!');
  18553. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18554. // any single thing other than /
  18555. const qmark$1 = '[^/]';
  18556. // * => any number of characters
  18557. const star$1 = qmark$1 + '*?';
  18558. // use + when we need to ensure that *something* matches, because the * is
  18559. // the only thing in the path portion.
  18560. const starNoEmpty = qmark$1 + '+?';
  18561. // remove the \ chars that we added if we end up doing a nonmagic compare
  18562. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  18563. class AST {
  18564. type;
  18565. #root;
  18566. #hasMagic;
  18567. #uflag = false;
  18568. #parts = [];
  18569. #parent;
  18570. #parentIndex;
  18571. #negs;
  18572. #filledNegs = false;
  18573. #options;
  18574. #toString;
  18575. // set to true if it's an extglob with no children
  18576. // (which really means one child of '')
  18577. #emptyExt = false;
  18578. constructor(type, parent, options = {}) {
  18579. this.type = type;
  18580. // extglobs are inherently magical
  18581. if (type)
  18582. this.#hasMagic = true;
  18583. this.#parent = parent;
  18584. this.#root = this.#parent ? this.#parent.#root : this;
  18585. this.#options = this.#root === this ? options : this.#root.#options;
  18586. this.#negs = this.#root === this ? [] : this.#root.#negs;
  18587. if (type === '!' && !this.#root.#filledNegs)
  18588. this.#negs.push(this);
  18589. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  18590. }
  18591. get hasMagic() {
  18592. /* c8 ignore start */
  18593. if (this.#hasMagic !== undefined)
  18594. return this.#hasMagic;
  18595. /* c8 ignore stop */
  18596. for (const p of this.#parts) {
  18597. if (typeof p === 'string')
  18598. continue;
  18599. if (p.type || p.hasMagic)
  18600. return (this.#hasMagic = true);
  18601. }
  18602. // note: will be undefined until we generate the regexp src and find out
  18603. return this.#hasMagic;
  18604. }
  18605. // reconstructs the pattern
  18606. toString() {
  18607. if (this.#toString !== undefined)
  18608. return this.#toString;
  18609. if (!this.type) {
  18610. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  18611. }
  18612. else {
  18613. return (this.#toString =
  18614. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  18615. }
  18616. }
  18617. #fillNegs() {
  18618. /* c8 ignore start */
  18619. if (this !== this.#root)
  18620. throw new Error('should only call on root');
  18621. if (this.#filledNegs)
  18622. return this;
  18623. /* c8 ignore stop */
  18624. // call toString() once to fill this out
  18625. this.toString();
  18626. this.#filledNegs = true;
  18627. let n;
  18628. while ((n = this.#negs.pop())) {
  18629. if (n.type !== '!')
  18630. continue;
  18631. // walk up the tree, appending everthing that comes AFTER parentIndex
  18632. let p = n;
  18633. let pp = p.#parent;
  18634. while (pp) {
  18635. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  18636. for (const part of n.#parts) {
  18637. /* c8 ignore start */
  18638. if (typeof part === 'string') {
  18639. throw new Error('string part in extglob AST??');
  18640. }
  18641. /* c8 ignore stop */
  18642. part.copyIn(pp.#parts[i]);
  18643. }
  18644. }
  18645. p = pp;
  18646. pp = p.#parent;
  18647. }
  18648. }
  18649. return this;
  18650. }
  18651. push(...parts) {
  18652. for (const p of parts) {
  18653. if (p === '')
  18654. continue;
  18655. /* c8 ignore start */
  18656. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  18657. throw new Error('invalid part: ' + p);
  18658. }
  18659. /* c8 ignore stop */
  18660. this.#parts.push(p);
  18661. }
  18662. }
  18663. toJSON() {
  18664. const ret = this.type === null
  18665. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  18666. : [this.type, ...this.#parts.map(p => p.toJSON())];
  18667. if (this.isStart() && !this.type)
  18668. ret.unshift([]);
  18669. if (this.isEnd() &&
  18670. (this === this.#root ||
  18671. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  18672. ret.push({});
  18673. }
  18674. return ret;
  18675. }
  18676. isStart() {
  18677. if (this.#root === this)
  18678. return true;
  18679. // if (this.type) return !!this.#parent?.isStart()
  18680. if (!this.#parent?.isStart())
  18681. return false;
  18682. if (this.#parentIndex === 0)
  18683. return true;
  18684. // if everything AHEAD of this is a negation, then it's still the "start"
  18685. const p = this.#parent;
  18686. for (let i = 0; i < this.#parentIndex; i++) {
  18687. const pp = p.#parts[i];
  18688. if (!(pp instanceof AST && pp.type === '!')) {
  18689. return false;
  18690. }
  18691. }
  18692. return true;
  18693. }
  18694. isEnd() {
  18695. if (this.#root === this)
  18696. return true;
  18697. if (this.#parent?.type === '!')
  18698. return true;
  18699. if (!this.#parent?.isEnd())
  18700. return false;
  18701. if (!this.type)
  18702. return this.#parent?.isEnd();
  18703. // if not root, it'll always have a parent
  18704. /* c8 ignore start */
  18705. const pl = this.#parent ? this.#parent.#parts.length : 0;
  18706. /* c8 ignore stop */
  18707. return this.#parentIndex === pl - 1;
  18708. }
  18709. copyIn(part) {
  18710. if (typeof part === 'string')
  18711. this.push(part);
  18712. else
  18713. this.push(part.clone(this));
  18714. }
  18715. clone(parent) {
  18716. const c = new AST(this.type, parent);
  18717. for (const p of this.#parts) {
  18718. c.copyIn(p);
  18719. }
  18720. return c;
  18721. }
  18722. static #parseAST(str, ast, pos, opt) {
  18723. let escaping = false;
  18724. let inBrace = false;
  18725. let braceStart = -1;
  18726. let braceNeg = false;
  18727. if (ast.type === null) {
  18728. // outside of a extglob, append until we find a start
  18729. let i = pos;
  18730. let acc = '';
  18731. while (i < str.length) {
  18732. const c = str.charAt(i++);
  18733. // still accumulate escapes at this point, but we do ignore
  18734. // starts that are escaped
  18735. if (escaping || c === '\\') {
  18736. escaping = !escaping;
  18737. acc += c;
  18738. continue;
  18739. }
  18740. if (inBrace) {
  18741. if (i === braceStart + 1) {
  18742. if (c === '^' || c === '!') {
  18743. braceNeg = true;
  18744. }
  18745. }
  18746. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18747. inBrace = false;
  18748. }
  18749. acc += c;
  18750. continue;
  18751. }
  18752. else if (c === '[') {
  18753. inBrace = true;
  18754. braceStart = i;
  18755. braceNeg = false;
  18756. acc += c;
  18757. continue;
  18758. }
  18759. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  18760. ast.push(acc);
  18761. acc = '';
  18762. const ext = new AST(c, ast);
  18763. i = AST.#parseAST(str, ext, i, opt);
  18764. ast.push(ext);
  18765. continue;
  18766. }
  18767. acc += c;
  18768. }
  18769. ast.push(acc);
  18770. return i;
  18771. }
  18772. // some kind of extglob, pos is at the (
  18773. // find the next | or )
  18774. let i = pos + 1;
  18775. let part = new AST(null, ast);
  18776. const parts = [];
  18777. let acc = '';
  18778. while (i < str.length) {
  18779. const c = str.charAt(i++);
  18780. // still accumulate escapes at this point, but we do ignore
  18781. // starts that are escaped
  18782. if (escaping || c === '\\') {
  18783. escaping = !escaping;
  18784. acc += c;
  18785. continue;
  18786. }
  18787. if (inBrace) {
  18788. if (i === braceStart + 1) {
  18789. if (c === '^' || c === '!') {
  18790. braceNeg = true;
  18791. }
  18792. }
  18793. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18794. inBrace = false;
  18795. }
  18796. acc += c;
  18797. continue;
  18798. }
  18799. else if (c === '[') {
  18800. inBrace = true;
  18801. braceStart = i;
  18802. braceNeg = false;
  18803. acc += c;
  18804. continue;
  18805. }
  18806. if (isExtglobType(c) && str.charAt(i) === '(') {
  18807. part.push(acc);
  18808. acc = '';
  18809. const ext = new AST(c, part);
  18810. part.push(ext);
  18811. i = AST.#parseAST(str, ext, i, opt);
  18812. continue;
  18813. }
  18814. if (c === '|') {
  18815. part.push(acc);
  18816. acc = '';
  18817. parts.push(part);
  18818. part = new AST(null, ast);
  18819. continue;
  18820. }
  18821. if (c === ')') {
  18822. if (acc === '' && ast.#parts.length === 0) {
  18823. ast.#emptyExt = true;
  18824. }
  18825. part.push(acc);
  18826. acc = '';
  18827. ast.push(...parts, part);
  18828. return i;
  18829. }
  18830. acc += c;
  18831. }
  18832. // unfinished extglob
  18833. // if we got here, it was a malformed extglob! not an extglob, but
  18834. // maybe something else in there.
  18835. ast.type = null;
  18836. ast.#hasMagic = undefined;
  18837. ast.#parts = [str.substring(pos - 1)];
  18838. return i;
  18839. }
  18840. static fromGlob(pattern, options = {}) {
  18841. const ast = new AST(null, undefined, options);
  18842. AST.#parseAST(pattern, ast, 0, options);
  18843. return ast;
  18844. }
  18845. // returns the regular expression if there's magic, or the unescaped
  18846. // string if not.
  18847. toMMPattern() {
  18848. // should only be called on root
  18849. /* c8 ignore start */
  18850. if (this !== this.#root)
  18851. return this.#root.toMMPattern();
  18852. /* c8 ignore stop */
  18853. const glob = this.toString();
  18854. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  18855. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  18856. // still need a regular expression if we have to case-insensitively
  18857. // match capital/lowercase characters.
  18858. const anyMagic = hasMagic ||
  18859. this.#hasMagic ||
  18860. (this.#options.nocase &&
  18861. !this.#options.nocaseMagicOnly &&
  18862. glob.toUpperCase() !== glob.toLowerCase());
  18863. if (!anyMagic) {
  18864. return body;
  18865. }
  18866. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  18867. return Object.assign(new RegExp(`^${re}$`, flags), {
  18868. _src: re,
  18869. _glob: glob,
  18870. });
  18871. }
  18872. get options() {
  18873. return this.#options;
  18874. }
  18875. // returns the string match, the regexp source, whether there's magic
  18876. // in the regexp (so a regular expression is required) and whether or
  18877. // not the uflag is needed for the regular expression (for posix classes)
  18878. // TODO: instead of injecting the start/end at this point, just return
  18879. // the BODY of the regexp, along with the start/end portions suitable
  18880. // for binding the start/end in either a joined full-path makeRe context
  18881. // (where we bind to (^|/), or a standalone matchPart context (where
  18882. // we bind to ^, and not /). Otherwise slashes get duped!
  18883. //
  18884. // In part-matching mode, the start is:
  18885. // - if not isStart: nothing
  18886. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  18887. // - if dots allowed or not possible: ^
  18888. // - if dots possible and not allowed: ^(?!\.)
  18889. // end is:
  18890. // - if not isEnd(): nothing
  18891. // - else: $
  18892. //
  18893. // In full-path matching mode, we put the slash at the START of the
  18894. // pattern, so start is:
  18895. // - if first pattern: same as part-matching mode
  18896. // - if not isStart(): nothing
  18897. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  18898. // - if dots allowed or not possible: /
  18899. // - if dots possible and not allowed: /(?!\.)
  18900. // end is:
  18901. // - if last pattern, same as part-matching mode
  18902. // - else nothing
  18903. //
  18904. // Always put the (?:$|/) on negated tails, though, because that has to be
  18905. // there to bind the end of the negated pattern portion, and it's easier to
  18906. // just stick it in now rather than try to inject it later in the middle of
  18907. // the pattern.
  18908. //
  18909. // We can just always return the same end, and leave it up to the caller
  18910. // to know whether it's going to be used joined or in parts.
  18911. // And, if the start is adjusted slightly, can do the same there:
  18912. // - if not isStart: nothing
  18913. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  18914. // - if dots allowed or not possible: (?:/|^)
  18915. // - if dots possible and not allowed: (?:/|^)(?!\.)
  18916. //
  18917. // But it's better to have a simpler binding without a conditional, for
  18918. // performance, so probably better to return both start options.
  18919. //
  18920. // Then the caller just ignores the end if it's not the first pattern,
  18921. // and the start always gets applied.
  18922. //
  18923. // But that's always going to be $ if it's the ending pattern, or nothing,
  18924. // so the caller can just attach $ at the end of the pattern when building.
  18925. //
  18926. // So the todo is:
  18927. // - better detect what kind of start is needed
  18928. // - return both flavors of starting pattern
  18929. // - attach $ at the end of the pattern when creating the actual RegExp
  18930. //
  18931. // Ah, but wait, no, that all only applies to the root when the first pattern
  18932. // is not an extglob. If the first pattern IS an extglob, then we need all
  18933. // that dot prevention biz to live in the extglob portions, because eg
  18934. // +(*|.x*) can match .xy but not .yx.
  18935. //
  18936. // So, return the two flavors if it's #root and the first child is not an
  18937. // AST, otherwise leave it to the child AST to handle it, and there,
  18938. // use the (?:^|/) style of start binding.
  18939. //
  18940. // Even simplified further:
  18941. // - Since the start for a join is eg /(?!\.) and the start for a part
  18942. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  18943. // or start or whatever) and prepend ^ or / at the Regexp construction.
  18944. toRegExpSource(allowDot) {
  18945. const dot = allowDot ?? !!this.#options.dot;
  18946. if (this.#root === this)
  18947. this.#fillNegs();
  18948. if (!this.type) {
  18949. const noEmpty = this.isStart() && this.isEnd();
  18950. const src = this.#parts
  18951. .map(p => {
  18952. const [re, _, hasMagic, uflag] = typeof p === 'string'
  18953. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  18954. : p.toRegExpSource(allowDot);
  18955. this.#hasMagic = this.#hasMagic || hasMagic;
  18956. this.#uflag = this.#uflag || uflag;
  18957. return re;
  18958. })
  18959. .join('');
  18960. let start = '';
  18961. if (this.isStart()) {
  18962. if (typeof this.#parts[0] === 'string') {
  18963. // this is the string that will match the start of the pattern,
  18964. // so we need to protect against dots and such.
  18965. // '.' and '..' cannot match unless the pattern is that exactly,
  18966. // even if it starts with . or dot:true is set.
  18967. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  18968. if (!dotTravAllowed) {
  18969. const aps = addPatternStart;
  18970. // check if we have a possibility of matching . or ..,
  18971. // and prevent that.
  18972. const needNoTrav =
  18973. // dots are allowed, and the pattern starts with [ or .
  18974. (dot && aps.has(src.charAt(0))) ||
  18975. // the pattern starts with \., and then [ or .
  18976. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  18977. // the pattern starts with \.\., and then [ or .
  18978. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  18979. // no need to prevent dots if it can't match a dot, or if a
  18980. // sub-pattern will be preventing it anyway.
  18981. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  18982. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  18983. }
  18984. }
  18985. }
  18986. // append the "end of path portion" pattern to negation tails
  18987. let end = '';
  18988. if (this.isEnd() &&
  18989. this.#root.#filledNegs &&
  18990. this.#parent?.type === '!') {
  18991. end = '(?:$|\\/)';
  18992. }
  18993. const final = start + src + end;
  18994. return [
  18995. final,
  18996. unescape(src),
  18997. (this.#hasMagic = !!this.#hasMagic),
  18998. this.#uflag,
  18999. ];
  19000. }
  19001. // We need to calculate the body *twice* if it's a repeat pattern
  19002. // at the start, once in nodot mode, then again in dot mode, so a
  19003. // pattern like *(?) can match 'x.y'
  19004. const repeated = this.type === '*' || this.type === '+';
  19005. // some kind of extglob
  19006. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  19007. let body = this.#partsToRegExp(dot);
  19008. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19009. // invalid extglob, has to at least be *something* present, if it's
  19010. // the entire path portion.
  19011. const s = this.toString();
  19012. this.#parts = [s];
  19013. this.type = null;
  19014. this.#hasMagic = undefined;
  19015. return [s, unescape(this.toString()), false, false];
  19016. }
  19017. // XXX abstract out this map method
  19018. let bodyDotAllowed = !repeated || allowDot || dot || false
  19019. ? ''
  19020. : this.#partsToRegExp(true);
  19021. if (bodyDotAllowed === body) {
  19022. bodyDotAllowed = '';
  19023. }
  19024. if (bodyDotAllowed) {
  19025. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19026. }
  19027. // an empty !() is exactly equivalent to a starNoEmpty
  19028. let final = '';
  19029. if (this.type === '!' && this.#emptyExt) {
  19030. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19031. }
  19032. else {
  19033. const close = this.type === '!'
  19034. ? // !() must match something,but !(x) can match ''
  19035. '))' +
  19036. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19037. star$1 +
  19038. ')'
  19039. : this.type === '@'
  19040. ? ')'
  19041. : this.type === '?'
  19042. ? ')?'
  19043. : this.type === '+' && bodyDotAllowed
  19044. ? ')'
  19045. : this.type === '*' && bodyDotAllowed
  19046. ? `)?`
  19047. : `)${this.type}`;
  19048. final = start + body + close;
  19049. }
  19050. return [
  19051. final,
  19052. unescape(body),
  19053. (this.#hasMagic = !!this.#hasMagic),
  19054. this.#uflag,
  19055. ];
  19056. }
  19057. #partsToRegExp(dot) {
  19058. return this.#parts
  19059. .map(p => {
  19060. // extglob ASTs should only contain parent ASTs
  19061. /* c8 ignore start */
  19062. if (typeof p === 'string') {
  19063. throw new Error('string type in extglob ast??');
  19064. }
  19065. /* c8 ignore stop */
  19066. // can ignore hasMagic, because extglobs are already always magic
  19067. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19068. this.#uflag = this.#uflag || uflag;
  19069. return re;
  19070. })
  19071. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19072. .join('|');
  19073. }
  19074. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19075. let escaping = false;
  19076. let re = '';
  19077. let uflag = false;
  19078. for (let i = 0; i < glob.length; i++) {
  19079. const c = glob.charAt(i);
  19080. if (escaping) {
  19081. escaping = false;
  19082. re += (reSpecials.has(c) ? '\\' : '') + c;
  19083. continue;
  19084. }
  19085. if (c === '\\') {
  19086. if (i === glob.length - 1) {
  19087. re += '\\\\';
  19088. }
  19089. else {
  19090. escaping = true;
  19091. }
  19092. continue;
  19093. }
  19094. if (c === '[') {
  19095. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  19096. if (consumed) {
  19097. re += src;
  19098. uflag = uflag || needUflag;
  19099. i += consumed - 1;
  19100. hasMagic = hasMagic || magic;
  19101. continue;
  19102. }
  19103. }
  19104. if (c === '*') {
  19105. if (noEmpty && glob === '*')
  19106. re += starNoEmpty;
  19107. else
  19108. re += star$1;
  19109. hasMagic = true;
  19110. continue;
  19111. }
  19112. if (c === '?') {
  19113. re += qmark$1;
  19114. hasMagic = true;
  19115. continue;
  19116. }
  19117. re += regExpEscape$1(c);
  19118. }
  19119. return [re, unescape(glob), !!hasMagic, uflag];
  19120. }
  19121. }
  19122. /**
  19123. * Escape all magic characters in a glob pattern.
  19124. *
  19125. * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
  19126. * option is used, then characters are escaped by wrapping in `[]`, because
  19127. * a magic character wrapped in a character class can only be satisfied by
  19128. * that exact character. In this mode, `\` is _not_ escaped, because it is
  19129. * not interpreted as a magic character, but instead as a path separator.
  19130. */
  19131. const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
  19132. // don't need to escape +@! because we escape the parens
  19133. // that make those magic, and escaping ! as [!] isn't valid,
  19134. // because [!]] is a valid glob class meaning not ']'.
  19135. return windowsPathsNoEscape
  19136. ? s.replace(/[?*()[\]]/g, '[$&]')
  19137. : s.replace(/[?*()[\]\\]/g, '\\$&');
  19138. };
  19139. const minimatch = (p, pattern, options = {}) => {
  19140. assertValidPattern(pattern);
  19141. // shortcut: comments match nothing.
  19142. if (!options.nocomment && pattern.charAt(0) === '#') {
  19143. return false;
  19144. }
  19145. return new Minimatch(pattern, options).match(p);
  19146. };
  19147. // Optimized checking for the most common glob patterns.
  19148. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  19149. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  19150. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  19151. const starDotExtTestNocase = (ext) => {
  19152. ext = ext.toLowerCase();
  19153. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  19154. };
  19155. const starDotExtTestNocaseDot = (ext) => {
  19156. ext = ext.toLowerCase();
  19157. return (f) => f.toLowerCase().endsWith(ext);
  19158. };
  19159. const starDotStarRE = /^\*+\.\*+$/;
  19160. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  19161. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  19162. const dotStarRE = /^\.\*+$/;
  19163. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  19164. const starRE = /^\*+$/;
  19165. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  19166. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  19167. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  19168. const qmarksTestNocase = ([$0, ext = '']) => {
  19169. const noext = qmarksTestNoExt([$0]);
  19170. if (!ext)
  19171. return noext;
  19172. ext = ext.toLowerCase();
  19173. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19174. };
  19175. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  19176. const noext = qmarksTestNoExtDot([$0]);
  19177. if (!ext)
  19178. return noext;
  19179. ext = ext.toLowerCase();
  19180. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19181. };
  19182. const qmarksTestDot = ([$0, ext = '']) => {
  19183. const noext = qmarksTestNoExtDot([$0]);
  19184. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19185. };
  19186. const qmarksTest = ([$0, ext = '']) => {
  19187. const noext = qmarksTestNoExt([$0]);
  19188. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19189. };
  19190. const qmarksTestNoExt = ([$0]) => {
  19191. const len = $0.length;
  19192. return (f) => f.length === len && !f.startsWith('.');
  19193. };
  19194. const qmarksTestNoExtDot = ([$0]) => {
  19195. const len = $0.length;
  19196. return (f) => f.length === len && f !== '.' && f !== '..';
  19197. };
  19198. /* c8 ignore start */
  19199. const defaultPlatform = (typeof process === 'object' && process
  19200. ? (typeof process.env === 'object' &&
  19201. process.env &&
  19202. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  19203. process.platform
  19204. : 'posix');
  19205. const path = {
  19206. win32: { sep: '\\' },
  19207. posix: { sep: '/' },
  19208. };
  19209. /* c8 ignore stop */
  19210. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  19211. minimatch.sep = sep;
  19212. const GLOBSTAR = Symbol('globstar **');
  19213. minimatch.GLOBSTAR = GLOBSTAR;
  19214. // any single thing other than /
  19215. // don't need to escape / when using new RegExp()
  19216. const qmark = '[^/]';
  19217. // * => any number of characters
  19218. const star = qmark + '*?';
  19219. // ** when dots are allowed. Anything goes, except .. and .
  19220. // not (^ or / followed by one or two dots followed by $ or /),
  19221. // followed by anything, any number of times.
  19222. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  19223. // not a ^ or / followed by a dot,
  19224. // followed by anything, any number of times.
  19225. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  19226. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  19227. minimatch.filter = filter;
  19228. const ext = (a, b = {}) => Object.assign({}, a, b);
  19229. const defaults = (def) => {
  19230. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  19231. return minimatch;
  19232. }
  19233. const orig = minimatch;
  19234. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  19235. return Object.assign(m, {
  19236. Minimatch: class Minimatch extends orig.Minimatch {
  19237. constructor(pattern, options = {}) {
  19238. super(pattern, ext(def, options));
  19239. }
  19240. static defaults(options) {
  19241. return orig.defaults(ext(def, options)).Minimatch;
  19242. }
  19243. },
  19244. AST: class AST extends orig.AST {
  19245. /* c8 ignore start */
  19246. constructor(type, parent, options = {}) {
  19247. super(type, parent, ext(def, options));
  19248. }
  19249. /* c8 ignore stop */
  19250. static fromGlob(pattern, options = {}) {
  19251. return orig.AST.fromGlob(pattern, ext(def, options));
  19252. }
  19253. },
  19254. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  19255. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  19256. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  19257. defaults: (options) => orig.defaults(ext(def, options)),
  19258. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  19259. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  19260. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  19261. sep: orig.sep,
  19262. GLOBSTAR: GLOBSTAR,
  19263. });
  19264. };
  19265. minimatch.defaults = defaults;
  19266. // Brace expansion:
  19267. // a{b,c}d -> abd acd
  19268. // a{b,}c -> abc ac
  19269. // a{0..3}d -> a0d a1d a2d a3d
  19270. // a{b,c{d,e}f}g -> abg acdfg acefg
  19271. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19272. //
  19273. // Invalid sets are not expanded.
  19274. // a{2..}b -> a{2..}b
  19275. // a{b}c -> a{b}c
  19276. const braceExpand = (pattern, options = {}) => {
  19277. assertValidPattern(pattern);
  19278. // Thanks to Yeting Li <https://github.com/yetingli> for
  19279. // improving this regexp to avoid a ReDOS vulnerability.
  19280. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  19281. // shortcut. no need to expand.
  19282. return [pattern];
  19283. }
  19284. return expand(pattern);
  19285. };
  19286. minimatch.braceExpand = braceExpand;
  19287. // parse a component of the expanded set.
  19288. // At this point, no pattern may contain "/" in it
  19289. // so we're going to return a 2d array, where each entry is the full
  19290. // pattern, split on '/', and then turned into a regular expression.
  19291. // A regexp is made at the end which joins each array with an
  19292. // escaped /, and another full one which joins each regexp with |.
  19293. //
  19294. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19295. // when it is the *only* thing in a path portion. Otherwise, any series
  19296. // of * is equivalent to a single *. Globstar behavior is enabled by
  19297. // default, and can be disabled by setting options.noglobstar.
  19298. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  19299. minimatch.makeRe = makeRe;
  19300. const match = (list, pattern, options = {}) => {
  19301. const mm = new Minimatch(pattern, options);
  19302. list = list.filter(f => mm.match(f));
  19303. if (mm.options.nonull && !list.length) {
  19304. list.push(pattern);
  19305. }
  19306. return list;
  19307. };
  19308. minimatch.match = match;
  19309. // replace stuff like \* with *
  19310. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  19311. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19312. class Minimatch {
  19313. options;
  19314. set;
  19315. pattern;
  19316. windowsPathsNoEscape;
  19317. nonegate;
  19318. negate;
  19319. comment;
  19320. empty;
  19321. preserveMultipleSlashes;
  19322. partial;
  19323. globSet;
  19324. globParts;
  19325. nocase;
  19326. isWindows;
  19327. platform;
  19328. windowsNoMagicRoot;
  19329. regexp;
  19330. constructor(pattern, options = {}) {
  19331. assertValidPattern(pattern);
  19332. options = options || {};
  19333. this.options = options;
  19334. this.pattern = pattern;
  19335. this.platform = options.platform || defaultPlatform;
  19336. this.isWindows = this.platform === 'win32';
  19337. this.windowsPathsNoEscape =
  19338. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  19339. if (this.windowsPathsNoEscape) {
  19340. this.pattern = this.pattern.replace(/\\/g, '/');
  19341. }
  19342. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  19343. this.regexp = null;
  19344. this.negate = false;
  19345. this.nonegate = !!options.nonegate;
  19346. this.comment = false;
  19347. this.empty = false;
  19348. this.partial = !!options.partial;
  19349. this.nocase = !!this.options.nocase;
  19350. this.windowsNoMagicRoot =
  19351. options.windowsNoMagicRoot !== undefined
  19352. ? options.windowsNoMagicRoot
  19353. : !!(this.isWindows && this.nocase);
  19354. this.globSet = [];
  19355. this.globParts = [];
  19356. this.set = [];
  19357. // make the set of regexps etc.
  19358. this.make();
  19359. }
  19360. hasMagic() {
  19361. if (this.options.magicalBraces && this.set.length > 1) {
  19362. return true;
  19363. }
  19364. for (const pattern of this.set) {
  19365. for (const part of pattern) {
  19366. if (typeof part !== 'string')
  19367. return true;
  19368. }
  19369. }
  19370. return false;
  19371. }
  19372. debug(..._) { }
  19373. make() {
  19374. const pattern = this.pattern;
  19375. const options = this.options;
  19376. // empty patterns and comments match nothing.
  19377. if (!options.nocomment && pattern.charAt(0) === '#') {
  19378. this.comment = true;
  19379. return;
  19380. }
  19381. if (!pattern) {
  19382. this.empty = true;
  19383. return;
  19384. }
  19385. // step 1: figure out negation, etc.
  19386. this.parseNegate();
  19387. // step 2: expand braces
  19388. this.globSet = [...new Set(this.braceExpand())];
  19389. if (options.debug) {
  19390. this.debug = (...args) => console.error(...args);
  19391. }
  19392. this.debug(this.pattern, this.globSet);
  19393. // step 3: now we have a set, so turn each one into a series of
  19394. // path-portion matching patterns.
  19395. // These will be regexps, except in the case of "**", which is
  19396. // set to the GLOBSTAR object for globstar behavior,
  19397. // and will not contain any / characters
  19398. //
  19399. // First, we preprocess to make the glob pattern sets a bit simpler
  19400. // and deduped. There are some perf-killing patterns that can cause
  19401. // problems with a glob walk, but we can simplify them down a bit.
  19402. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  19403. this.globParts = this.preprocess(rawGlobParts);
  19404. this.debug(this.pattern, this.globParts);
  19405. // glob --> regexps
  19406. let set = this.globParts.map((s, _, __) => {
  19407. if (this.isWindows && this.windowsNoMagicRoot) {
  19408. // check if it's a drive or unc path.
  19409. const isUNC = s[0] === '' &&
  19410. s[1] === '' &&
  19411. (s[2] === '?' || !globMagic.test(s[2])) &&
  19412. !globMagic.test(s[3]);
  19413. const isDrive = /^[a-z]:/i.test(s[0]);
  19414. if (isUNC) {
  19415. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  19416. }
  19417. else if (isDrive) {
  19418. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  19419. }
  19420. }
  19421. return s.map(ss => this.parse(ss));
  19422. });
  19423. this.debug(this.pattern, set);
  19424. // filter out everything that didn't compile properly.
  19425. this.set = set.filter(s => s.indexOf(false) === -1);
  19426. // do not treat the ? in UNC paths as magic
  19427. if (this.isWindows) {
  19428. for (let i = 0; i < this.set.length; i++) {
  19429. const p = this.set[i];
  19430. if (p[0] === '' &&
  19431. p[1] === '' &&
  19432. this.globParts[i][2] === '?' &&
  19433. typeof p[3] === 'string' &&
  19434. /^[a-z]:$/i.test(p[3])) {
  19435. p[2] = '?';
  19436. }
  19437. }
  19438. }
  19439. this.debug(this.pattern, this.set);
  19440. }
  19441. // various transforms to equivalent pattern sets that are
  19442. // faster to process in a filesystem walk. The goal is to
  19443. // eliminate what we can, and push all ** patterns as far
  19444. // to the right as possible, even if it increases the number
  19445. // of patterns that we have to process.
  19446. preprocess(globParts) {
  19447. // if we're not in globstar mode, then turn all ** into *
  19448. if (this.options.noglobstar) {
  19449. for (let i = 0; i < globParts.length; i++) {
  19450. for (let j = 0; j < globParts[i].length; j++) {
  19451. if (globParts[i][j] === '**') {
  19452. globParts[i][j] = '*';
  19453. }
  19454. }
  19455. }
  19456. }
  19457. const { optimizationLevel = 1 } = this.options;
  19458. if (optimizationLevel >= 2) {
  19459. // aggressive optimization for the purpose of fs walking
  19460. globParts = this.firstPhasePreProcess(globParts);
  19461. globParts = this.secondPhasePreProcess(globParts);
  19462. }
  19463. else if (optimizationLevel >= 1) {
  19464. // just basic optimizations to remove some .. parts
  19465. globParts = this.levelOneOptimize(globParts);
  19466. }
  19467. else {
  19468. // just collapse multiple ** portions into one
  19469. globParts = this.adjascentGlobstarOptimize(globParts);
  19470. }
  19471. return globParts;
  19472. }
  19473. // just get rid of adjascent ** portions
  19474. adjascentGlobstarOptimize(globParts) {
  19475. return globParts.map(parts => {
  19476. let gs = -1;
  19477. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19478. let i = gs;
  19479. while (parts[i + 1] === '**') {
  19480. i++;
  19481. }
  19482. if (i !== gs) {
  19483. parts.splice(gs, i - gs);
  19484. }
  19485. }
  19486. return parts;
  19487. });
  19488. }
  19489. // get rid of adjascent ** and resolve .. portions
  19490. levelOneOptimize(globParts) {
  19491. return globParts.map(parts => {
  19492. parts = parts.reduce((set, part) => {
  19493. const prev = set[set.length - 1];
  19494. if (part === '**' && prev === '**') {
  19495. return set;
  19496. }
  19497. if (part === '..') {
  19498. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  19499. set.pop();
  19500. return set;
  19501. }
  19502. }
  19503. set.push(part);
  19504. return set;
  19505. }, []);
  19506. return parts.length === 0 ? [''] : parts;
  19507. });
  19508. }
  19509. levelTwoFileOptimize(parts) {
  19510. if (!Array.isArray(parts)) {
  19511. parts = this.slashSplit(parts);
  19512. }
  19513. let didSomething = false;
  19514. do {
  19515. didSomething = false;
  19516. // <pre>/<e>/<rest> -> <pre>/<rest>
  19517. if (!this.preserveMultipleSlashes) {
  19518. for (let i = 1; i < parts.length - 1; i++) {
  19519. const p = parts[i];
  19520. // don't squeeze out UNC patterns
  19521. if (i === 1 && p === '' && parts[0] === '')
  19522. continue;
  19523. if (p === '.' || p === '') {
  19524. didSomething = true;
  19525. parts.splice(i, 1);
  19526. i--;
  19527. }
  19528. }
  19529. if (parts[0] === '.' &&
  19530. parts.length === 2 &&
  19531. (parts[1] === '.' || parts[1] === '')) {
  19532. didSomething = true;
  19533. parts.pop();
  19534. }
  19535. }
  19536. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19537. let dd = 0;
  19538. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19539. const p = parts[dd - 1];
  19540. if (p && p !== '.' && p !== '..' && p !== '**') {
  19541. didSomething = true;
  19542. parts.splice(dd - 1, 2);
  19543. dd -= 2;
  19544. }
  19545. }
  19546. } while (didSomething);
  19547. return parts.length === 0 ? [''] : parts;
  19548. }
  19549. // First phase: single-pattern processing
  19550. // <pre> is 1 or more portions
  19551. // <rest> is 1 or more portions
  19552. // <p> is any portion other than ., .., '', or **
  19553. // <e> is . or ''
  19554. //
  19555. // **/.. is *brutal* for filesystem walking performance, because
  19556. // it effectively resets the recursive walk each time it occurs,
  19557. // and ** cannot be reduced out by a .. pattern part like a regexp
  19558. // or most strings (other than .., ., and '') can be.
  19559. //
  19560. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19561. // <pre>/<e>/<rest> -> <pre>/<rest>
  19562. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19563. // **/**/<rest> -> **/<rest>
  19564. //
  19565. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  19566. // this WOULD be allowed if ** did follow symlinks, or * didn't
  19567. firstPhasePreProcess(globParts) {
  19568. let didSomething = false;
  19569. do {
  19570. didSomething = false;
  19571. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19572. for (let parts of globParts) {
  19573. let gs = -1;
  19574. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19575. let gss = gs;
  19576. while (parts[gss + 1] === '**') {
  19577. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  19578. gss++;
  19579. }
  19580. // eg, if gs is 2 and gss is 4, that means we have 3 **
  19581. // parts, and can remove 2 of them.
  19582. if (gss > gs) {
  19583. parts.splice(gs + 1, gss - gs);
  19584. }
  19585. let next = parts[gs + 1];
  19586. const p = parts[gs + 2];
  19587. const p2 = parts[gs + 3];
  19588. if (next !== '..')
  19589. continue;
  19590. if (!p ||
  19591. p === '.' ||
  19592. p === '..' ||
  19593. !p2 ||
  19594. p2 === '.' ||
  19595. p2 === '..') {
  19596. continue;
  19597. }
  19598. didSomething = true;
  19599. // edit parts in place, and push the new one
  19600. parts.splice(gs, 1);
  19601. const other = parts.slice(0);
  19602. other[gs] = '**';
  19603. globParts.push(other);
  19604. gs--;
  19605. }
  19606. // <pre>/<e>/<rest> -> <pre>/<rest>
  19607. if (!this.preserveMultipleSlashes) {
  19608. for (let i = 1; i < parts.length - 1; i++) {
  19609. const p = parts[i];
  19610. // don't squeeze out UNC patterns
  19611. if (i === 1 && p === '' && parts[0] === '')
  19612. continue;
  19613. if (p === '.' || p === '') {
  19614. didSomething = true;
  19615. parts.splice(i, 1);
  19616. i--;
  19617. }
  19618. }
  19619. if (parts[0] === '.' &&
  19620. parts.length === 2 &&
  19621. (parts[1] === '.' || parts[1] === '')) {
  19622. didSomething = true;
  19623. parts.pop();
  19624. }
  19625. }
  19626. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19627. let dd = 0;
  19628. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19629. const p = parts[dd - 1];
  19630. if (p && p !== '.' && p !== '..' && p !== '**') {
  19631. didSomething = true;
  19632. const needDot = dd === 1 && parts[dd + 1] === '**';
  19633. const splin = needDot ? ['.'] : [];
  19634. parts.splice(dd - 1, 2, ...splin);
  19635. if (parts.length === 0)
  19636. parts.push('');
  19637. dd -= 2;
  19638. }
  19639. }
  19640. }
  19641. } while (didSomething);
  19642. return globParts;
  19643. }
  19644. // second phase: multi-pattern dedupes
  19645. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  19646. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  19647. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  19648. //
  19649. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  19650. // ^-- not valid because ** doens't follow symlinks
  19651. secondPhasePreProcess(globParts) {
  19652. for (let i = 0; i < globParts.length - 1; i++) {
  19653. for (let j = i + 1; j < globParts.length; j++) {
  19654. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  19655. if (matched) {
  19656. globParts[i] = [];
  19657. globParts[j] = matched;
  19658. break;
  19659. }
  19660. }
  19661. }
  19662. return globParts.filter(gs => gs.length);
  19663. }
  19664. partsMatch(a, b, emptyGSMatch = false) {
  19665. let ai = 0;
  19666. let bi = 0;
  19667. let result = [];
  19668. let which = '';
  19669. while (ai < a.length && bi < b.length) {
  19670. if (a[ai] === b[bi]) {
  19671. result.push(which === 'b' ? b[bi] : a[ai]);
  19672. ai++;
  19673. bi++;
  19674. }
  19675. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  19676. result.push(a[ai]);
  19677. ai++;
  19678. }
  19679. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  19680. result.push(b[bi]);
  19681. bi++;
  19682. }
  19683. else if (a[ai] === '*' &&
  19684. b[bi] &&
  19685. (this.options.dot || !b[bi].startsWith('.')) &&
  19686. b[bi] !== '**') {
  19687. if (which === 'b')
  19688. return false;
  19689. which = 'a';
  19690. result.push(a[ai]);
  19691. ai++;
  19692. bi++;
  19693. }
  19694. else if (b[bi] === '*' &&
  19695. a[ai] &&
  19696. (this.options.dot || !a[ai].startsWith('.')) &&
  19697. a[ai] !== '**') {
  19698. if (which === 'a')
  19699. return false;
  19700. which = 'b';
  19701. result.push(b[bi]);
  19702. ai++;
  19703. bi++;
  19704. }
  19705. else {
  19706. return false;
  19707. }
  19708. }
  19709. // if we fall out of the loop, it means they two are identical
  19710. // as long as their lengths match
  19711. return a.length === b.length && result;
  19712. }
  19713. parseNegate() {
  19714. if (this.nonegate)
  19715. return;
  19716. const pattern = this.pattern;
  19717. let negate = false;
  19718. let negateOffset = 0;
  19719. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  19720. negate = !negate;
  19721. negateOffset++;
  19722. }
  19723. if (negateOffset)
  19724. this.pattern = pattern.slice(negateOffset);
  19725. this.negate = negate;
  19726. }
  19727. // set partial to true to test if, for example,
  19728. // "/a/b" matches the start of "/*/b/*/d"
  19729. // Partial means, if you run out of file before you run
  19730. // out of pattern, then that's fine, as long as all
  19731. // the parts match.
  19732. matchOne(file, pattern, partial = false) {
  19733. const options = this.options;
  19734. // UNC paths like //?/X:/... can match X:/... and vice versa
  19735. // Drive letters in absolute drive or unc paths are always compared
  19736. // case-insensitively.
  19737. if (this.isWindows) {
  19738. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  19739. const fileUNC = !fileDrive &&
  19740. file[0] === '' &&
  19741. file[1] === '' &&
  19742. file[2] === '?' &&
  19743. /^[a-z]:$/i.test(file[3]);
  19744. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  19745. const patternUNC = !patternDrive &&
  19746. pattern[0] === '' &&
  19747. pattern[1] === '' &&
  19748. pattern[2] === '?' &&
  19749. typeof pattern[3] === 'string' &&
  19750. /^[a-z]:$/i.test(pattern[3]);
  19751. const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
  19752. const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
  19753. if (typeof fdi === 'number' && typeof pdi === 'number') {
  19754. const [fd, pd] = [file[fdi], pattern[pdi]];
  19755. if (fd.toLowerCase() === pd.toLowerCase()) {
  19756. pattern[pdi] = fd;
  19757. if (pdi > fdi) {
  19758. pattern = pattern.slice(pdi);
  19759. }
  19760. else if (fdi > pdi) {
  19761. file = file.slice(fdi);
  19762. }
  19763. }
  19764. }
  19765. }
  19766. // resolve and reduce . and .. portions in the file as well.
  19767. // dont' need to do the second phase, because it's only one string[]
  19768. const { optimizationLevel = 1 } = this.options;
  19769. if (optimizationLevel >= 2) {
  19770. file = this.levelTwoFileOptimize(file);
  19771. }
  19772. this.debug('matchOne', this, { file, pattern });
  19773. this.debug('matchOne', file.length, pattern.length);
  19774. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  19775. this.debug('matchOne loop');
  19776. var p = pattern[pi];
  19777. var f = file[fi];
  19778. this.debug(pattern, p, f);
  19779. // should be impossible.
  19780. // some invalid regexp stuff in the set.
  19781. /* c8 ignore start */
  19782. if (p === false) {
  19783. return false;
  19784. }
  19785. /* c8 ignore stop */
  19786. if (p === GLOBSTAR) {
  19787. this.debug('GLOBSTAR', [pattern, p, f]);
  19788. // "**"
  19789. // a/**/b/**/c would match the following:
  19790. // a/b/x/y/z/c
  19791. // a/x/y/z/b/c
  19792. // a/b/x/b/x/c
  19793. // a/b/c
  19794. // To do this, take the rest of the pattern after
  19795. // the **, and see if it would match the file remainder.
  19796. // If so, return success.
  19797. // If not, the ** "swallows" a segment, and try again.
  19798. // This is recursively awful.
  19799. //
  19800. // a/**/b/**/c matching a/b/x/y/z/c
  19801. // - a matches a
  19802. // - doublestar
  19803. // - matchOne(b/x/y/z/c, b/**/c)
  19804. // - b matches b
  19805. // - doublestar
  19806. // - matchOne(x/y/z/c, c) -> no
  19807. // - matchOne(y/z/c, c) -> no
  19808. // - matchOne(z/c, c) -> no
  19809. // - matchOne(c, c) yes, hit
  19810. var fr = fi;
  19811. var pr = pi + 1;
  19812. if (pr === pl) {
  19813. this.debug('** at the end');
  19814. // a ** at the end will just swallow the rest.
  19815. // We have found a match.
  19816. // however, it will not swallow /.x, unless
  19817. // options.dot is set.
  19818. // . and .. are *never* matched by **, for explosively
  19819. // exponential reasons.
  19820. for (; fi < fl; fi++) {
  19821. if (file[fi] === '.' ||
  19822. file[fi] === '..' ||
  19823. (!options.dot && file[fi].charAt(0) === '.'))
  19824. return false;
  19825. }
  19826. return true;
  19827. }
  19828. // ok, let's see if we can swallow whatever we can.
  19829. while (fr < fl) {
  19830. var swallowee = file[fr];
  19831. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  19832. // XXX remove this slice. Just pass the start index.
  19833. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  19834. this.debug('globstar found match!', fr, fl, swallowee);
  19835. // found a match.
  19836. return true;
  19837. }
  19838. else {
  19839. // can't swallow "." or ".." ever.
  19840. // can only swallow ".foo" when explicitly asked.
  19841. if (swallowee === '.' ||
  19842. swallowee === '..' ||
  19843. (!options.dot && swallowee.charAt(0) === '.')) {
  19844. this.debug('dot detected!', file, fr, pattern, pr);
  19845. break;
  19846. }
  19847. // ** swallows a segment, and continue.
  19848. this.debug('globstar swallow a segment, and continue');
  19849. fr++;
  19850. }
  19851. }
  19852. // no match was found.
  19853. // However, in partial mode, we can't say this is necessarily over.
  19854. /* c8 ignore start */
  19855. if (partial) {
  19856. // ran out of file
  19857. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  19858. if (fr === fl) {
  19859. return true;
  19860. }
  19861. }
  19862. /* c8 ignore stop */
  19863. return false;
  19864. }
  19865. // something other than **
  19866. // non-magic patterns just have to match exactly
  19867. // patterns with magic have been turned into regexps.
  19868. let hit;
  19869. if (typeof p === 'string') {
  19870. hit = f === p;
  19871. this.debug('string match', p, f, hit);
  19872. }
  19873. else {
  19874. hit = p.test(f);
  19875. this.debug('pattern match', p, f, hit);
  19876. }
  19877. if (!hit)
  19878. return false;
  19879. }
  19880. // Note: ending in / means that we'll get a final ""
  19881. // at the end of the pattern. This can only match a
  19882. // corresponding "" at the end of the file.
  19883. // If the file ends in /, then it can only match a
  19884. // a pattern that ends in /, unless the pattern just
  19885. // doesn't have any more for it. But, a/b/ should *not*
  19886. // match "a/b/*", even though "" matches against the
  19887. // [^/]*? pattern, except in partial mode, where it might
  19888. // simply not be reached yet.
  19889. // However, a/b/ should still satisfy a/*
  19890. // now either we fell off the end of the pattern, or we're done.
  19891. if (fi === fl && pi === pl) {
  19892. // ran out of pattern and filename at the same time.
  19893. // an exact hit!
  19894. return true;
  19895. }
  19896. else if (fi === fl) {
  19897. // ran out of file, but still had pattern left.
  19898. // this is ok if we're doing the match as part of
  19899. // a glob fs traversal.
  19900. return partial;
  19901. }
  19902. else if (pi === pl) {
  19903. // ran out of pattern, still have file left.
  19904. // this is only acceptable if we're on the very last
  19905. // empty segment of a file with a trailing slash.
  19906. // a/* should match a/b/
  19907. return fi === fl - 1 && file[fi] === '';
  19908. /* c8 ignore start */
  19909. }
  19910. else {
  19911. // should be unreachable.
  19912. throw new Error('wtf?');
  19913. }
  19914. /* c8 ignore stop */
  19915. }
  19916. braceExpand() {
  19917. return braceExpand(this.pattern, this.options);
  19918. }
  19919. parse(pattern) {
  19920. assertValidPattern(pattern);
  19921. const options = this.options;
  19922. // shortcuts
  19923. if (pattern === '**')
  19924. return GLOBSTAR;
  19925. if (pattern === '')
  19926. return '';
  19927. // far and away, the most common glob pattern parts are
  19928. // *, *.*, and *.<ext> Add a fast check method for those.
  19929. let m;
  19930. let fastTest = null;
  19931. if ((m = pattern.match(starRE))) {
  19932. fastTest = options.dot ? starTestDot : starTest;
  19933. }
  19934. else if ((m = pattern.match(starDotExtRE))) {
  19935. fastTest = (options.nocase
  19936. ? options.dot
  19937. ? starDotExtTestNocaseDot
  19938. : starDotExtTestNocase
  19939. : options.dot
  19940. ? starDotExtTestDot
  19941. : starDotExtTest)(m[1]);
  19942. }
  19943. else if ((m = pattern.match(qmarksRE))) {
  19944. fastTest = (options.nocase
  19945. ? options.dot
  19946. ? qmarksTestNocaseDot
  19947. : qmarksTestNocase
  19948. : options.dot
  19949. ? qmarksTestDot
  19950. : qmarksTest)(m);
  19951. }
  19952. else if ((m = pattern.match(starDotStarRE))) {
  19953. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  19954. }
  19955. else if ((m = pattern.match(dotStarRE))) {
  19956. fastTest = dotStarTest;
  19957. }
  19958. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  19959. if (fastTest && typeof re === 'object') {
  19960. // Avoids overriding in frozen environments
  19961. Reflect.defineProperty(re, 'test', { value: fastTest });
  19962. }
  19963. return re;
  19964. }
  19965. makeRe() {
  19966. if (this.regexp || this.regexp === false)
  19967. return this.regexp;
  19968. // at this point, this.set is a 2d array of partial
  19969. // pattern strings, or "**".
  19970. //
  19971. // It's better to use .match(). This function shouldn't
  19972. // be used, really, but it's pretty convenient sometimes,
  19973. // when you just want to work with a regex.
  19974. const set = this.set;
  19975. if (!set.length) {
  19976. this.regexp = false;
  19977. return this.regexp;
  19978. }
  19979. const options = this.options;
  19980. const twoStar = options.noglobstar
  19981. ? star
  19982. : options.dot
  19983. ? twoStarDot
  19984. : twoStarNoDot;
  19985. const flags = new Set(options.nocase ? ['i'] : []);
  19986. // regexpify non-globstar patterns
  19987. // if ** is only item, then we just do one twoStar
  19988. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  19989. // if ** is last, append (\/twoStar|) to previous
  19990. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  19991. // then filter out GLOBSTAR symbols
  19992. let re = set
  19993. .map(pattern => {
  19994. const pp = pattern.map(p => {
  19995. if (p instanceof RegExp) {
  19996. for (const f of p.flags.split(''))
  19997. flags.add(f);
  19998. }
  19999. return typeof p === 'string'
  20000. ? regExpEscape(p)
  20001. : p === GLOBSTAR
  20002. ? GLOBSTAR
  20003. : p._src;
  20004. });
  20005. pp.forEach((p, i) => {
  20006. const next = pp[i + 1];
  20007. const prev = pp[i - 1];
  20008. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  20009. return;
  20010. }
  20011. if (prev === undefined) {
  20012. if (next !== undefined && next !== GLOBSTAR) {
  20013. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  20014. }
  20015. else {
  20016. pp[i] = twoStar;
  20017. }
  20018. }
  20019. else if (next === undefined) {
  20020. pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
  20021. }
  20022. else if (next !== GLOBSTAR) {
  20023. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  20024. pp[i + 1] = GLOBSTAR;
  20025. }
  20026. });
  20027. return pp.filter(p => p !== GLOBSTAR).join('/');
  20028. })
  20029. .join('|');
  20030. // need to wrap in parens if we had more than one thing with |,
  20031. // otherwise only the first will be anchored to ^ and the last to $
  20032. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  20033. // must match entire pattern
  20034. // ending in a * or ** will make it less strict.
  20035. re = '^' + open + re + close + '$';
  20036. // can match anything, as long as it's not this.
  20037. if (this.negate)
  20038. re = '^(?!' + re + ').+$';
  20039. try {
  20040. this.regexp = new RegExp(re, [...flags].join(''));
  20041. /* c8 ignore start */
  20042. }
  20043. catch (ex) {
  20044. // should be impossible
  20045. this.regexp = false;
  20046. }
  20047. /* c8 ignore stop */
  20048. return this.regexp;
  20049. }
  20050. slashSplit(p) {
  20051. // if p starts with // on windows, we preserve that
  20052. // so that UNC paths aren't broken. Otherwise, any number of
  20053. // / characters are coalesced into one, unless
  20054. // preserveMultipleSlashes is set to true.
  20055. if (this.preserveMultipleSlashes) {
  20056. return p.split('/');
  20057. }
  20058. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  20059. // add an extra '' for the one we lose
  20060. return ['', ...p.split(/\/+/)];
  20061. }
  20062. else {
  20063. return p.split(/\/+/);
  20064. }
  20065. }
  20066. match(f, partial = this.partial) {
  20067. this.debug('match', f, this.pattern);
  20068. // short-circuit in the case of busted things.
  20069. // comments, etc.
  20070. if (this.comment) {
  20071. return false;
  20072. }
  20073. if (this.empty) {
  20074. return f === '';
  20075. }
  20076. if (f === '/' && partial) {
  20077. return true;
  20078. }
  20079. const options = this.options;
  20080. // windows: need to use /, not \
  20081. if (this.isWindows) {
  20082. f = f.split('\\').join('/');
  20083. }
  20084. // treat the test path as a set of pathparts.
  20085. const ff = this.slashSplit(f);
  20086. this.debug(this.pattern, 'split', ff);
  20087. // just ONE of the pattern sets in this.set needs to match
  20088. // in order for it to be valid. If negating, then just one
  20089. // match means that we have failed.
  20090. // Either way, return on the first hit.
  20091. const set = this.set;
  20092. this.debug(this.pattern, 'set', set);
  20093. // Find the basename of the path by looking for the last non-empty segment
  20094. let filename = ff[ff.length - 1];
  20095. if (!filename) {
  20096. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  20097. filename = ff[i];
  20098. }
  20099. }
  20100. for (let i = 0; i < set.length; i++) {
  20101. const pattern = set[i];
  20102. let file = ff;
  20103. if (options.matchBase && pattern.length === 1) {
  20104. file = [filename];
  20105. }
  20106. const hit = this.matchOne(file, pattern, partial);
  20107. if (hit) {
  20108. if (options.flipNegate) {
  20109. return true;
  20110. }
  20111. return !this.negate;
  20112. }
  20113. }
  20114. // didn't get any hits. this is success if it's a negative
  20115. // pattern, failure otherwise.
  20116. if (options.flipNegate) {
  20117. return false;
  20118. }
  20119. return this.negate;
  20120. }
  20121. static defaults(def) {
  20122. return minimatch.defaults(def).Minimatch;
  20123. }
  20124. }
  20125. /* c8 ignore stop */
  20126. minimatch.AST = AST;
  20127. minimatch.Minimatch = Minimatch;
  20128. minimatch.escape = escape;
  20129. minimatch.unescape = unescape;
  20130. class TypeScope {
  20131. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  20132. this.filename = filename;
  20133. this.source = source;
  20134. this.offset = offset;
  20135. this.imports = imports;
  20136. this.types = types;
  20137. this.declares = declares;
  20138. this.isGenericScope = false;
  20139. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  20140. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  20141. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  20142. }
  20143. }
  20144. function resolveTypeElements(ctx, node, scope, typeParameters) {
  20145. const canCache = !typeParameters;
  20146. if (canCache && node._resolvedElements) {
  20147. return node._resolvedElements;
  20148. }
  20149. const resolved = innerResolveTypeElements(
  20150. ctx,
  20151. node,
  20152. node._ownerScope || scope || ctxToScope(ctx),
  20153. typeParameters
  20154. );
  20155. return canCache ? node._resolvedElements = resolved : resolved;
  20156. }
  20157. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  20158. var _a, _b;
  20159. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  20160. return { props: {} };
  20161. }
  20162. switch (node.type) {
  20163. case "TSTypeLiteral":
  20164. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  20165. case "TSInterfaceDeclaration":
  20166. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  20167. case "TSTypeAliasDeclaration":
  20168. case "TSTypeAnnotation":
  20169. case "TSParenthesizedType":
  20170. return resolveTypeElements(
  20171. ctx,
  20172. node.typeAnnotation,
  20173. scope,
  20174. typeParameters
  20175. );
  20176. case "TSFunctionType": {
  20177. return { props: {}, calls: [node] };
  20178. }
  20179. case "TSUnionType":
  20180. case "TSIntersectionType":
  20181. return mergeElements(
  20182. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  20183. node.type
  20184. );
  20185. case "TSMappedType":
  20186. return resolveMappedType(ctx, node, scope, typeParameters);
  20187. case "TSIndexedAccessType": {
  20188. const types = resolveIndexType(ctx, node, scope);
  20189. return mergeElements(
  20190. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  20191. "TSUnionType"
  20192. );
  20193. }
  20194. case "TSExpressionWithTypeArguments":
  20195. // referenced by interface extends
  20196. case "TSTypeReference": {
  20197. const typeName = getReferenceName(node);
  20198. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  20199. return resolveExtractPropTypes(
  20200. resolveTypeElements(
  20201. ctx,
  20202. node.typeParameters.params[0],
  20203. scope,
  20204. typeParameters
  20205. ),
  20206. scope
  20207. );
  20208. }
  20209. const resolved = resolveTypeReference(ctx, node, scope);
  20210. if (resolved) {
  20211. let typeParams;
  20212. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  20213. typeParams = /* @__PURE__ */ Object.create(null);
  20214. resolved.typeParameters.params.forEach((p, i) => {
  20215. let param = typeParameters && typeParameters[p.name];
  20216. if (!param) param = node.typeParameters.params[i];
  20217. typeParams[p.name] = param;
  20218. });
  20219. }
  20220. return resolveTypeElements(
  20221. ctx,
  20222. resolved,
  20223. resolved._ownerScope,
  20224. typeParams
  20225. );
  20226. } else {
  20227. if (typeof typeName === "string") {
  20228. if (typeParameters && typeParameters[typeName]) {
  20229. return resolveTypeElements(
  20230. ctx,
  20231. typeParameters[typeName],
  20232. scope,
  20233. typeParameters
  20234. );
  20235. }
  20236. if (
  20237. // @ts-expect-error
  20238. SupportedBuiltinsSet.has(typeName)
  20239. ) {
  20240. return resolveBuiltin(
  20241. ctx,
  20242. node,
  20243. typeName,
  20244. scope,
  20245. typeParameters
  20246. );
  20247. } else if (typeName === "ReturnType" && node.typeParameters) {
  20248. const ret = resolveReturnType(
  20249. ctx,
  20250. node.typeParameters.params[0],
  20251. scope
  20252. );
  20253. if (ret) {
  20254. return resolveTypeElements(ctx, ret, scope);
  20255. }
  20256. }
  20257. }
  20258. return ctx.error(
  20259. `Unresolvable type reference or unsupported built-in utility type`,
  20260. node,
  20261. scope
  20262. );
  20263. }
  20264. }
  20265. case "TSImportType": {
  20266. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  20267. return resolveExtractPropTypes(
  20268. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  20269. scope
  20270. );
  20271. }
  20272. const sourceScope = importSourceToScope(
  20273. ctx,
  20274. node.argument,
  20275. scope,
  20276. node.argument.value
  20277. );
  20278. const resolved = resolveTypeReference(ctx, node, sourceScope);
  20279. if (resolved) {
  20280. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20281. }
  20282. break;
  20283. }
  20284. case "TSTypeQuery":
  20285. {
  20286. const resolved = resolveTypeReference(ctx, node, scope);
  20287. if (resolved) {
  20288. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20289. }
  20290. }
  20291. break;
  20292. }
  20293. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  20294. }
  20295. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  20296. const res = { props: {} };
  20297. for (const e of elements) {
  20298. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  20299. if (typeParameters) {
  20300. scope = createChildScope(scope);
  20301. scope.isGenericScope = true;
  20302. Object.assign(scope.types, typeParameters);
  20303. }
  20304. e._ownerScope = scope;
  20305. const name = getId(e.key);
  20306. if (name && !e.computed) {
  20307. res.props[name] = e;
  20308. } else if (e.key.type === "TemplateLiteral") {
  20309. for (const key of resolveTemplateKeys(ctx, e.key, scope)) {
  20310. res.props[key] = e;
  20311. }
  20312. } else {
  20313. ctx.error(
  20314. `Unsupported computed key in type referenced by a macro`,
  20315. e.key,
  20316. scope
  20317. );
  20318. }
  20319. } else if (e.type === "TSCallSignatureDeclaration") {
  20320. (res.calls || (res.calls = [])).push(e);
  20321. }
  20322. }
  20323. return res;
  20324. }
  20325. function mergeElements(maps, type) {
  20326. if (maps.length === 1) return maps[0];
  20327. const res = { props: {} };
  20328. const { props: baseProps } = res;
  20329. for (const { props, calls } of maps) {
  20330. for (const key in props) {
  20331. if (!shared.hasOwn(baseProps, key)) {
  20332. baseProps[key] = props[key];
  20333. } else {
  20334. baseProps[key] = createProperty(
  20335. baseProps[key].key,
  20336. {
  20337. type,
  20338. // @ts-expect-error
  20339. types: [baseProps[key], props[key]]
  20340. },
  20341. baseProps[key]._ownerScope,
  20342. baseProps[key].optional || props[key].optional
  20343. );
  20344. }
  20345. }
  20346. if (calls) {
  20347. (res.calls || (res.calls = [])).push(...calls);
  20348. }
  20349. }
  20350. return res;
  20351. }
  20352. function createProperty(key, typeAnnotation, scope, optional) {
  20353. return {
  20354. type: "TSPropertySignature",
  20355. key,
  20356. kind: "get",
  20357. optional,
  20358. typeAnnotation: {
  20359. type: "TSTypeAnnotation",
  20360. typeAnnotation
  20361. },
  20362. _ownerScope: scope
  20363. };
  20364. }
  20365. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  20366. const base = typeElementsToMap(
  20367. ctx,
  20368. node.body.body,
  20369. node._ownerScope,
  20370. typeParameters
  20371. );
  20372. if (node.extends) {
  20373. for (const ext of node.extends) {
  20374. try {
  20375. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  20376. for (const key in props) {
  20377. if (!shared.hasOwn(base.props, key)) {
  20378. base.props[key] = props[key];
  20379. }
  20380. }
  20381. if (calls) {
  20382. ;
  20383. (base.calls || (base.calls = [])).push(...calls);
  20384. }
  20385. } catch (e) {
  20386. ctx.error(
  20387. `Failed to resolve extends base type.
  20388. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  20389. interface Props extends /* @vue-ignore */ Base {}
  20390. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  20391. ext,
  20392. scope
  20393. );
  20394. }
  20395. }
  20396. }
  20397. return base;
  20398. }
  20399. function resolveMappedType(ctx, node, scope, typeParameters) {
  20400. const res = { props: {} };
  20401. let keys;
  20402. if (node.nameType) {
  20403. const { name, constraint } = node.typeParameter;
  20404. scope = createChildScope(scope);
  20405. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  20406. keys = resolveStringType(ctx, node.nameType, scope);
  20407. } else {
  20408. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  20409. }
  20410. for (const key of keys) {
  20411. res.props[key] = createProperty(
  20412. {
  20413. type: "Identifier",
  20414. name: key
  20415. },
  20416. node.typeAnnotation,
  20417. scope,
  20418. !!node.optional
  20419. );
  20420. }
  20421. return res;
  20422. }
  20423. function resolveIndexType(ctx, node, scope) {
  20424. var _a, _b;
  20425. if (node.indexType.type === "TSNumberKeyword") {
  20426. return resolveArrayElementType(ctx, node.objectType, scope);
  20427. }
  20428. const { indexType, objectType } = node;
  20429. const types = [];
  20430. let keys;
  20431. let resolved;
  20432. if (indexType.type === "TSStringKeyword") {
  20433. resolved = resolveTypeElements(ctx, objectType, scope);
  20434. keys = Object.keys(resolved.props);
  20435. } else {
  20436. keys = resolveStringType(ctx, indexType, scope);
  20437. resolved = resolveTypeElements(ctx, objectType, scope);
  20438. }
  20439. for (const key of keys) {
  20440. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  20441. if (targetType) {
  20442. targetType._ownerScope = resolved.props[key]._ownerScope;
  20443. types.push(targetType);
  20444. }
  20445. }
  20446. return types;
  20447. }
  20448. function resolveArrayElementType(ctx, node, scope) {
  20449. if (node.type === "TSArrayType") {
  20450. return [node.elementType];
  20451. }
  20452. if (node.type === "TSTupleType") {
  20453. return node.elementTypes.map(
  20454. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  20455. );
  20456. }
  20457. if (node.type === "TSTypeReference") {
  20458. if (getReferenceName(node) === "Array" && node.typeParameters) {
  20459. return node.typeParameters.params;
  20460. } else {
  20461. const resolved = resolveTypeReference(ctx, node, scope);
  20462. if (resolved) {
  20463. return resolveArrayElementType(ctx, resolved, scope);
  20464. }
  20465. }
  20466. }
  20467. return ctx.error(
  20468. "Failed to resolve element type from target type",
  20469. node,
  20470. scope
  20471. );
  20472. }
  20473. function resolveStringType(ctx, node, scope) {
  20474. switch (node.type) {
  20475. case "StringLiteral":
  20476. return [node.value];
  20477. case "TSLiteralType":
  20478. return resolveStringType(ctx, node.literal, scope);
  20479. case "TSUnionType":
  20480. return node.types.map((t) => resolveStringType(ctx, t, scope)).flat();
  20481. case "TemplateLiteral": {
  20482. return resolveTemplateKeys(ctx, node, scope);
  20483. }
  20484. case "TSTypeReference": {
  20485. const resolved = resolveTypeReference(ctx, node, scope);
  20486. if (resolved) {
  20487. return resolveStringType(ctx, resolved, scope);
  20488. }
  20489. if (node.typeName.type === "Identifier") {
  20490. const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope);
  20491. switch (node.typeName.name) {
  20492. case "Extract":
  20493. return getParam(1);
  20494. case "Exclude": {
  20495. const excluded = getParam(1);
  20496. return getParam().filter((s) => !excluded.includes(s));
  20497. }
  20498. case "Uppercase":
  20499. return getParam().map((s) => s.toUpperCase());
  20500. case "Lowercase":
  20501. return getParam().map((s) => s.toLowerCase());
  20502. case "Capitalize":
  20503. return getParam().map(shared.capitalize);
  20504. case "Uncapitalize":
  20505. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  20506. default:
  20507. ctx.error(
  20508. "Unsupported type when resolving index type",
  20509. node.typeName,
  20510. scope
  20511. );
  20512. }
  20513. }
  20514. }
  20515. }
  20516. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  20517. }
  20518. function resolveTemplateKeys(ctx, node, scope) {
  20519. if (!node.expressions.length) {
  20520. return [node.quasis[0].value.raw];
  20521. }
  20522. const res = [];
  20523. const e = node.expressions[0];
  20524. const q = node.quasis[0];
  20525. const leading = q ? q.value.raw : ``;
  20526. const resolved = resolveStringType(ctx, e, scope);
  20527. const restResolved = resolveTemplateKeys(
  20528. ctx,
  20529. {
  20530. ...node,
  20531. expressions: node.expressions.slice(1),
  20532. quasis: q ? node.quasis.slice(1) : node.quasis
  20533. },
  20534. scope
  20535. );
  20536. for (const r of resolved) {
  20537. for (const rr of restResolved) {
  20538. res.push(leading + r + rr);
  20539. }
  20540. }
  20541. return res;
  20542. }
  20543. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  20544. "Partial",
  20545. "Required",
  20546. "Readonly",
  20547. "Pick",
  20548. "Omit"
  20549. ]);
  20550. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  20551. const t = resolveTypeElements(
  20552. ctx,
  20553. node.typeParameters.params[0],
  20554. scope,
  20555. typeParameters
  20556. );
  20557. switch (name) {
  20558. case "Partial": {
  20559. const res2 = { props: {}, calls: t.calls };
  20560. Object.keys(t.props).forEach((key) => {
  20561. res2.props[key] = { ...t.props[key], optional: true };
  20562. });
  20563. return res2;
  20564. }
  20565. case "Required": {
  20566. const res2 = { props: {}, calls: t.calls };
  20567. Object.keys(t.props).forEach((key) => {
  20568. res2.props[key] = { ...t.props[key], optional: false };
  20569. });
  20570. return res2;
  20571. }
  20572. case "Readonly":
  20573. return t;
  20574. case "Pick": {
  20575. const picked = resolveStringType(
  20576. ctx,
  20577. node.typeParameters.params[1],
  20578. scope
  20579. );
  20580. const res2 = { props: {}, calls: t.calls };
  20581. for (const key of picked) {
  20582. res2.props[key] = t.props[key];
  20583. }
  20584. return res2;
  20585. }
  20586. case "Omit":
  20587. const omitted = resolveStringType(
  20588. ctx,
  20589. node.typeParameters.params[1],
  20590. scope
  20591. );
  20592. const res = { props: {}, calls: t.calls };
  20593. for (const key in t.props) {
  20594. if (!omitted.includes(key)) {
  20595. res.props[key] = t.props[key];
  20596. }
  20597. }
  20598. return res;
  20599. }
  20600. }
  20601. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  20602. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  20603. if (canCache && node._resolvedReference) {
  20604. return node._resolvedReference;
  20605. }
  20606. const resolved = innerResolveTypeReference(
  20607. ctx,
  20608. scope || ctxToScope(ctx),
  20609. name || getReferenceName(node),
  20610. node,
  20611. onlyExported
  20612. );
  20613. return canCache ? node._resolvedReference = resolved : resolved;
  20614. }
  20615. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  20616. if (typeof name === "string") {
  20617. if (scope.imports[name]) {
  20618. return resolveTypeFromImport(ctx, node, name, scope);
  20619. } else {
  20620. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  20621. if (lookupSource[name]) {
  20622. return lookupSource[name];
  20623. } else {
  20624. const globalScopes = resolveGlobalScope(ctx);
  20625. if (globalScopes) {
  20626. for (const s of globalScopes) {
  20627. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  20628. if (src[name]) {
  20629. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  20630. return src[name];
  20631. }
  20632. }
  20633. }
  20634. }
  20635. }
  20636. } else {
  20637. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  20638. if (ns) {
  20639. if (ns.type !== "TSModuleDeclaration") {
  20640. ns = ns._ns;
  20641. }
  20642. if (ns) {
  20643. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  20644. return innerResolveTypeReference(
  20645. ctx,
  20646. childScope,
  20647. name.length > 2 ? name.slice(1) : name[name.length - 1],
  20648. node,
  20649. !ns.declare
  20650. );
  20651. }
  20652. }
  20653. }
  20654. }
  20655. function getReferenceName(node) {
  20656. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  20657. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  20658. return ref.name;
  20659. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  20660. return qualifiedNameToPath(ref);
  20661. } else {
  20662. return "default";
  20663. }
  20664. }
  20665. function qualifiedNameToPath(node) {
  20666. if (node.type === "Identifier") {
  20667. return [node.name];
  20668. } else {
  20669. return [...qualifiedNameToPath(node.left), node.right.name];
  20670. }
  20671. }
  20672. function resolveGlobalScope(ctx) {
  20673. if (ctx.options.globalTypeFiles) {
  20674. const fs = resolveFS(ctx);
  20675. if (!fs) {
  20676. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  20677. }
  20678. return ctx.options.globalTypeFiles.map(
  20679. (file) => fileToScope(ctx, normalizePath(file), true)
  20680. );
  20681. }
  20682. }
  20683. let ts;
  20684. let loadTS;
  20685. function registerTS(_loadTS) {
  20686. loadTS = () => {
  20687. try {
  20688. return _loadTS();
  20689. } catch (err) {
  20690. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  20691. throw new Error(
  20692. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.'
  20693. );
  20694. } else {
  20695. throw new Error(
  20696. "Failed to load TypeScript for resolving imported types."
  20697. );
  20698. }
  20699. }
  20700. };
  20701. }
  20702. function resolveFS(ctx) {
  20703. if (ctx.fs) {
  20704. return ctx.fs;
  20705. }
  20706. if (!ts && loadTS) {
  20707. ts = loadTS();
  20708. }
  20709. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  20710. if (!fs) {
  20711. return;
  20712. }
  20713. return ctx.fs = {
  20714. fileExists(file) {
  20715. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  20716. file = file.replace(/\.ts$/, "");
  20717. }
  20718. return fs.fileExists(file);
  20719. },
  20720. readFile(file) {
  20721. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  20722. file = file.replace(/\.ts$/, "");
  20723. }
  20724. return fs.readFile(file);
  20725. },
  20726. realpath: fs.realpath
  20727. };
  20728. }
  20729. function resolveTypeFromImport(ctx, node, name, scope) {
  20730. const { source, imported } = scope.imports[name];
  20731. const sourceScope = importSourceToScope(ctx, node, scope, source);
  20732. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  20733. }
  20734. function importSourceToScope(ctx, node, scope, source) {
  20735. let fs;
  20736. try {
  20737. fs = resolveFS(ctx);
  20738. } catch (err) {
  20739. return ctx.error(err.message, node, scope);
  20740. }
  20741. if (!fs) {
  20742. return ctx.error(
  20743. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  20744. node,
  20745. scope
  20746. );
  20747. }
  20748. let resolved = scope.resolvedImportSources[source];
  20749. if (!resolved) {
  20750. if (source.startsWith("..")) {
  20751. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  20752. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  20753. resolved = resolveExt(filename, fs);
  20754. } else if (source[0] === ".") {
  20755. const filename = joinPaths(path$1.dirname(scope.filename), source);
  20756. resolved = resolveExt(filename, fs);
  20757. } else {
  20758. if (!ts) {
  20759. if (loadTS) ts = loadTS();
  20760. if (!ts) {
  20761. return ctx.error(
  20762. `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.`,
  20763. node,
  20764. scope
  20765. );
  20766. }
  20767. }
  20768. resolved = resolveWithTS(scope.filename, source, ts, fs);
  20769. }
  20770. if (resolved) {
  20771. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  20772. }
  20773. }
  20774. if (resolved) {
  20775. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  20776. return fileToScope(ctx, resolved);
  20777. } else {
  20778. return ctx.error(
  20779. `Failed to resolve import source ${JSON.stringify(source)}.`,
  20780. node,
  20781. scope
  20782. );
  20783. }
  20784. }
  20785. function resolveExt(filename, fs) {
  20786. filename = filename.replace(/\.js$/, "");
  20787. const tryResolve = (filename2) => {
  20788. if (fs.fileExists(filename2)) return filename2;
  20789. };
  20790. 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`));
  20791. }
  20792. const tsConfigCache = createCache();
  20793. const tsConfigRefMap = /* @__PURE__ */ new Map();
  20794. function resolveWithTS(containingFile, source, ts2, fs) {
  20795. var _a, _b;
  20796. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  20797. let tsCompilerOptions;
  20798. let tsResolveCache;
  20799. if (configPath) {
  20800. let configs;
  20801. const normalizedConfigPath = normalizePath(configPath);
  20802. const cached = tsConfigCache.get(normalizedConfigPath);
  20803. if (!cached) {
  20804. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  20805. tsConfigCache.set(normalizedConfigPath, configs);
  20806. } else {
  20807. configs = cached;
  20808. }
  20809. let matchedConfig;
  20810. if (configs.length === 1) {
  20811. matchedConfig = configs[0];
  20812. } else {
  20813. for (const c of configs) {
  20814. const base = normalizePath(
  20815. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  20816. );
  20817. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  20818. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  20819. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, joinPaths(base, p))))) {
  20820. if (excluded && excluded.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  20821. continue;
  20822. }
  20823. matchedConfig = c;
  20824. break;
  20825. }
  20826. }
  20827. if (!matchedConfig) {
  20828. matchedConfig = configs[configs.length - 1];
  20829. }
  20830. }
  20831. tsCompilerOptions = matchedConfig.config.options;
  20832. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  20833. process__namespace.cwd(),
  20834. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  20835. tsCompilerOptions
  20836. ));
  20837. } else {
  20838. tsCompilerOptions = {};
  20839. }
  20840. const res = ts2.resolveModuleName(
  20841. source,
  20842. containingFile,
  20843. tsCompilerOptions,
  20844. fs,
  20845. tsResolveCache
  20846. );
  20847. if (res.resolvedModule) {
  20848. let filename = res.resolvedModule.resolvedFileName;
  20849. if (filename.endsWith(".vue.ts") && !filename.endsWith(".d.vue.ts")) {
  20850. filename = filename.replace(/\.ts$/, "");
  20851. }
  20852. return fs.realpath ? fs.realpath(filename) : filename;
  20853. }
  20854. }
  20855. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  20856. const parseConfigHost = ts2.sys;
  20857. const config = ts2.parseJsonConfigFileContent(
  20858. ts2.readConfigFile(configPath, fs.readFile).config,
  20859. parseConfigHost,
  20860. path$1.dirname(configPath),
  20861. void 0,
  20862. configPath
  20863. );
  20864. const res = [config];
  20865. visited.add(configPath);
  20866. if (config.projectReferences) {
  20867. for (const ref of config.projectReferences) {
  20868. const refPath = ts2.resolveProjectReferencePath(ref);
  20869. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  20870. continue;
  20871. }
  20872. tsConfigRefMap.set(refPath, configPath);
  20873. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  20874. }
  20875. }
  20876. return res;
  20877. }
  20878. const fileToScopeCache = createCache();
  20879. function invalidateTypeCache(filename) {
  20880. filename = normalizePath(filename);
  20881. fileToScopeCache.delete(filename);
  20882. tsConfigCache.delete(filename);
  20883. const affectedConfig = tsConfigRefMap.get(filename);
  20884. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  20885. }
  20886. function fileToScope(ctx, filename, asGlobal = false) {
  20887. const cached = fileToScopeCache.get(filename);
  20888. if (cached) {
  20889. return cached;
  20890. }
  20891. const fs = resolveFS(ctx);
  20892. const source = fs.readFile(filename) || "";
  20893. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  20894. const scope = new TypeScope(filename, source, 0, recordImports(body));
  20895. recordTypes(ctx, body, scope, asGlobal);
  20896. fileToScopeCache.set(filename, scope);
  20897. return scope;
  20898. }
  20899. function parseFile(filename, content, fs, parserPlugins) {
  20900. const ext = path$1.extname(filename);
  20901. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".mtsx") {
  20902. return parser$2.parse(content, {
  20903. plugins: resolveParserPlugins(
  20904. ext.slice(1),
  20905. parserPlugins,
  20906. /\.d\.m?ts$/.test(filename)
  20907. ),
  20908. sourceType: "module"
  20909. }).program.body;
  20910. }
  20911. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  20912. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  20913. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  20914. if (hasArbitraryTypeDeclaration) {
  20915. return parser$2.parse(fs.readFile(arbitraryTypeSource), {
  20916. plugins: resolveParserPlugins("ts", parserPlugins, true),
  20917. sourceType: "module"
  20918. }).program.body;
  20919. }
  20920. if (ext === ".vue") {
  20921. const {
  20922. descriptor: { script, scriptSetup }
  20923. } = parse$1(content);
  20924. if (!script && !scriptSetup) {
  20925. return [];
  20926. }
  20927. const scriptOffset = script ? script.loc.start.offset : Infinity;
  20928. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  20929. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  20930. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  20931. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  20932. if (secondBlock) {
  20933. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  20934. }
  20935. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  20936. return parser$2.parse(scriptContent, {
  20937. plugins: resolveParserPlugins(lang, parserPlugins),
  20938. sourceType: "module"
  20939. }).program.body;
  20940. }
  20941. return [];
  20942. }
  20943. function ctxToScope(ctx) {
  20944. if (ctx.scope) {
  20945. return ctx.scope;
  20946. }
  20947. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  20948. const scope = new TypeScope(
  20949. ctx.filename,
  20950. ctx.source,
  20951. "startOffset" in ctx ? ctx.startOffset : 0,
  20952. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  20953. );
  20954. recordTypes(ctx, body, scope);
  20955. return ctx.scope = scope;
  20956. }
  20957. function moduleDeclToScope(ctx, node, parentScope) {
  20958. if (node._resolvedChildScope) {
  20959. return node._resolvedChildScope;
  20960. }
  20961. const scope = createChildScope(parentScope);
  20962. if (node.body.type === "TSModuleDeclaration") {
  20963. const decl = node.body;
  20964. decl._ownerScope = scope;
  20965. const id = getId(decl.id);
  20966. scope.types[id] = scope.exportedTypes[id] = decl;
  20967. } else {
  20968. recordTypes(ctx, node.body.body, scope);
  20969. }
  20970. return node._resolvedChildScope = scope;
  20971. }
  20972. function createChildScope(parentScope) {
  20973. return new TypeScope(
  20974. parentScope.filename,
  20975. parentScope.source,
  20976. parentScope.offset,
  20977. Object.create(parentScope.imports),
  20978. Object.create(parentScope.types),
  20979. Object.create(parentScope.declares)
  20980. );
  20981. }
  20982. const importExportRE = /^Import|^Export/;
  20983. function recordTypes(ctx, body, scope, asGlobal = false) {
  20984. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  20985. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  20986. for (const stmt of body) {
  20987. if (asGlobal) {
  20988. if (isAmbient) {
  20989. if (stmt.declare) {
  20990. recordType(stmt, types, declares);
  20991. }
  20992. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  20993. for (const s of stmt.body.body) {
  20994. recordType(s, types, declares);
  20995. }
  20996. }
  20997. } else {
  20998. recordType(stmt, types, declares);
  20999. }
  21000. }
  21001. if (!asGlobal) {
  21002. for (const stmt of body) {
  21003. if (stmt.type === "ExportNamedDeclaration") {
  21004. if (stmt.declaration) {
  21005. recordType(stmt.declaration, types, declares);
  21006. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  21007. } else {
  21008. for (const spec of stmt.specifiers) {
  21009. if (spec.type === "ExportSpecifier") {
  21010. const local = spec.local.name;
  21011. const exported = getId(spec.exported);
  21012. if (stmt.source) {
  21013. imports[exported] = {
  21014. source: stmt.source.value,
  21015. imported: local
  21016. };
  21017. exportedTypes[exported] = {
  21018. type: "TSTypeReference",
  21019. typeName: {
  21020. type: "Identifier",
  21021. name: local
  21022. },
  21023. _ownerScope: scope
  21024. };
  21025. } else if (types[local]) {
  21026. exportedTypes[exported] = types[local];
  21027. }
  21028. }
  21029. }
  21030. }
  21031. } else if (stmt.type === "ExportAllDeclaration") {
  21032. const sourceScope = importSourceToScope(
  21033. ctx,
  21034. stmt.source,
  21035. scope,
  21036. stmt.source.value
  21037. );
  21038. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  21039. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  21040. if (stmt.declaration.type !== "Identifier") {
  21041. recordType(stmt.declaration, types, declares, "default");
  21042. recordType(
  21043. stmt.declaration,
  21044. exportedTypes,
  21045. exportedDeclares,
  21046. "default"
  21047. );
  21048. } else if (types[stmt.declaration.name]) {
  21049. exportedTypes["default"] = types[stmt.declaration.name];
  21050. }
  21051. }
  21052. }
  21053. }
  21054. for (const key of Object.keys(types)) {
  21055. const node = types[key];
  21056. node._ownerScope = scope;
  21057. if (node._ns) node._ns._ownerScope = scope;
  21058. }
  21059. for (const key of Object.keys(declares)) {
  21060. declares[key]._ownerScope = scope;
  21061. }
  21062. }
  21063. function recordType(node, types, declares, overwriteId) {
  21064. switch (node.type) {
  21065. case "TSInterfaceDeclaration":
  21066. case "TSEnumDeclaration":
  21067. case "TSModuleDeclaration": {
  21068. const id = overwriteId || getId(node.id);
  21069. let existing = types[id];
  21070. if (existing) {
  21071. if (node.type === "TSModuleDeclaration") {
  21072. if (existing.type === "TSModuleDeclaration") {
  21073. mergeNamespaces(existing, node);
  21074. } else {
  21075. attachNamespace(existing, node);
  21076. }
  21077. break;
  21078. }
  21079. if (existing.type === "TSModuleDeclaration") {
  21080. types[id] = node;
  21081. attachNamespace(node, existing);
  21082. break;
  21083. }
  21084. if (existing.type !== node.type) {
  21085. break;
  21086. }
  21087. if (node.type === "TSInterfaceDeclaration") {
  21088. existing.body.body.push(...node.body.body);
  21089. } else {
  21090. existing.members.push(...node.members);
  21091. }
  21092. } else {
  21093. types[id] = node;
  21094. }
  21095. break;
  21096. }
  21097. case "ClassDeclaration":
  21098. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  21099. break;
  21100. case "TSTypeAliasDeclaration":
  21101. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  21102. break;
  21103. case "TSDeclareFunction":
  21104. if (node.id) declares[node.id.name] = node;
  21105. break;
  21106. case "VariableDeclaration": {
  21107. if (node.declare) {
  21108. for (const decl of node.declarations) {
  21109. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  21110. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  21111. }
  21112. }
  21113. }
  21114. break;
  21115. }
  21116. }
  21117. }
  21118. function mergeNamespaces(to, from) {
  21119. const toBody = to.body;
  21120. const fromBody = from.body;
  21121. if (toBody.type === "TSModuleDeclaration") {
  21122. if (fromBody.type === "TSModuleDeclaration") {
  21123. mergeNamespaces(toBody, fromBody);
  21124. } else {
  21125. fromBody.body.push({
  21126. type: "ExportNamedDeclaration",
  21127. declaration: toBody,
  21128. exportKind: "type",
  21129. specifiers: []
  21130. });
  21131. }
  21132. } else if (fromBody.type === "TSModuleDeclaration") {
  21133. toBody.body.push({
  21134. type: "ExportNamedDeclaration",
  21135. declaration: fromBody,
  21136. exportKind: "type",
  21137. specifiers: []
  21138. });
  21139. } else {
  21140. toBody.body.push(...fromBody.body);
  21141. }
  21142. }
  21143. function attachNamespace(to, ns) {
  21144. if (!to._ns) {
  21145. to._ns = ns;
  21146. } else {
  21147. mergeNamespaces(to._ns, ns);
  21148. }
  21149. }
  21150. function recordImports(body) {
  21151. const imports = /* @__PURE__ */ Object.create(null);
  21152. for (const s of body) {
  21153. recordImport(s, imports);
  21154. }
  21155. return imports;
  21156. }
  21157. function recordImport(node, imports) {
  21158. if (node.type !== "ImportDeclaration") {
  21159. return;
  21160. }
  21161. for (const s of node.specifiers) {
  21162. imports[s.local.name] = {
  21163. imported: getImportedName(s),
  21164. source: node.source.value
  21165. };
  21166. }
  21167. }
  21168. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false) {
  21169. try {
  21170. switch (node.type) {
  21171. case "TSStringKeyword":
  21172. return ["String"];
  21173. case "TSNumberKeyword":
  21174. return ["Number"];
  21175. case "TSBooleanKeyword":
  21176. return ["Boolean"];
  21177. case "TSObjectKeyword":
  21178. return ["Object"];
  21179. case "TSNullKeyword":
  21180. return ["null"];
  21181. case "TSTypeLiteral":
  21182. case "TSInterfaceDeclaration": {
  21183. const types = /* @__PURE__ */ new Set();
  21184. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  21185. for (const m of members) {
  21186. if (isKeyOf) {
  21187. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  21188. types.add("Number");
  21189. } else if (m.type === "TSIndexSignature") {
  21190. const annotation = m.parameters[0].typeAnnotation;
  21191. if (annotation && annotation.type !== "Noop") {
  21192. const type = inferRuntimeType(
  21193. ctx,
  21194. annotation.typeAnnotation,
  21195. scope
  21196. )[0];
  21197. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  21198. types.add(type);
  21199. }
  21200. } else {
  21201. types.add("String");
  21202. }
  21203. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  21204. types.add("Function");
  21205. } else {
  21206. types.add("Object");
  21207. }
  21208. }
  21209. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  21210. }
  21211. case "TSPropertySignature":
  21212. if (node.typeAnnotation) {
  21213. return inferRuntimeType(
  21214. ctx,
  21215. node.typeAnnotation.typeAnnotation,
  21216. scope
  21217. );
  21218. }
  21219. break;
  21220. case "TSMethodSignature":
  21221. case "TSFunctionType":
  21222. return ["Function"];
  21223. case "TSArrayType":
  21224. case "TSTupleType":
  21225. return ["Array"];
  21226. case "TSLiteralType":
  21227. switch (node.literal.type) {
  21228. case "StringLiteral":
  21229. return ["String"];
  21230. case "BooleanLiteral":
  21231. return ["Boolean"];
  21232. case "NumericLiteral":
  21233. case "BigIntLiteral":
  21234. return ["Number"];
  21235. default:
  21236. return [UNKNOWN_TYPE];
  21237. }
  21238. case "TSTypeReference": {
  21239. const resolved = resolveTypeReference(ctx, node, scope);
  21240. if (resolved) {
  21241. if (resolved.type === "TSTypeAliasDeclaration") {
  21242. return inferRuntimeType(
  21243. ctx,
  21244. resolved.typeAnnotation,
  21245. resolved._ownerScope,
  21246. isKeyOf
  21247. );
  21248. }
  21249. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  21250. }
  21251. if (node.typeName.type === "Identifier") {
  21252. if (isKeyOf) {
  21253. switch (node.typeName.name) {
  21254. case "String":
  21255. case "Array":
  21256. case "ArrayLike":
  21257. case "Parameters":
  21258. case "ConstructorParameters":
  21259. case "ReadonlyArray":
  21260. return ["String", "Number"];
  21261. // TS built-in utility types
  21262. case "Record":
  21263. case "Partial":
  21264. case "Required":
  21265. case "Readonly":
  21266. if (node.typeParameters && node.typeParameters.params[0]) {
  21267. return inferRuntimeType(
  21268. ctx,
  21269. node.typeParameters.params[0],
  21270. scope,
  21271. true
  21272. );
  21273. }
  21274. break;
  21275. case "Pick":
  21276. case "Extract":
  21277. if (node.typeParameters && node.typeParameters.params[1]) {
  21278. return inferRuntimeType(
  21279. ctx,
  21280. node.typeParameters.params[1],
  21281. scope
  21282. );
  21283. }
  21284. break;
  21285. case "Function":
  21286. case "Object":
  21287. case "Set":
  21288. case "Map":
  21289. case "WeakSet":
  21290. case "WeakMap":
  21291. case "Date":
  21292. case "Promise":
  21293. case "Error":
  21294. case "Uppercase":
  21295. case "Lowercase":
  21296. case "Capitalize":
  21297. case "Uncapitalize":
  21298. case "ReadonlyMap":
  21299. case "ReadonlySet":
  21300. return ["String"];
  21301. }
  21302. } else {
  21303. switch (node.typeName.name) {
  21304. case "Array":
  21305. case "Function":
  21306. case "Object":
  21307. case "Set":
  21308. case "Map":
  21309. case "WeakSet":
  21310. case "WeakMap":
  21311. case "Date":
  21312. case "Promise":
  21313. case "Error":
  21314. return [node.typeName.name];
  21315. // TS built-in utility types
  21316. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  21317. case "Partial":
  21318. case "Required":
  21319. case "Readonly":
  21320. case "Record":
  21321. case "Pick":
  21322. case "Omit":
  21323. case "InstanceType":
  21324. return ["Object"];
  21325. case "Uppercase":
  21326. case "Lowercase":
  21327. case "Capitalize":
  21328. case "Uncapitalize":
  21329. return ["String"];
  21330. case "Parameters":
  21331. case "ConstructorParameters":
  21332. case "ReadonlyArray":
  21333. return ["Array"];
  21334. case "ReadonlyMap":
  21335. return ["Map"];
  21336. case "ReadonlySet":
  21337. return ["Set"];
  21338. case "NonNullable":
  21339. if (node.typeParameters && node.typeParameters.params[0]) {
  21340. return inferRuntimeType(
  21341. ctx,
  21342. node.typeParameters.params[0],
  21343. scope
  21344. ).filter((t) => t !== "null");
  21345. }
  21346. break;
  21347. case "Extract":
  21348. if (node.typeParameters && node.typeParameters.params[1]) {
  21349. return inferRuntimeType(
  21350. ctx,
  21351. node.typeParameters.params[1],
  21352. scope
  21353. );
  21354. }
  21355. break;
  21356. case "Exclude":
  21357. case "OmitThisParameter":
  21358. if (node.typeParameters && node.typeParameters.params[0]) {
  21359. return inferRuntimeType(
  21360. ctx,
  21361. node.typeParameters.params[0],
  21362. scope
  21363. );
  21364. }
  21365. break;
  21366. }
  21367. }
  21368. }
  21369. break;
  21370. }
  21371. case "TSParenthesizedType":
  21372. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  21373. case "TSUnionType":
  21374. return flattenTypes(ctx, node.types, scope, isKeyOf);
  21375. case "TSIntersectionType": {
  21376. return flattenTypes(ctx, node.types, scope, isKeyOf).filter(
  21377. (t) => t !== UNKNOWN_TYPE
  21378. );
  21379. }
  21380. case "TSEnumDeclaration":
  21381. return inferEnumType(node);
  21382. case "TSSymbolKeyword":
  21383. return ["Symbol"];
  21384. case "TSIndexedAccessType": {
  21385. const types = resolveIndexType(ctx, node, scope);
  21386. return flattenTypes(ctx, types, scope, isKeyOf);
  21387. }
  21388. case "ClassDeclaration":
  21389. return ["Object"];
  21390. case "TSImportType": {
  21391. const sourceScope = importSourceToScope(
  21392. ctx,
  21393. node.argument,
  21394. scope,
  21395. node.argument.value
  21396. );
  21397. const resolved = resolveTypeReference(ctx, node, sourceScope);
  21398. if (resolved) {
  21399. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  21400. }
  21401. break;
  21402. }
  21403. case "TSTypeQuery": {
  21404. const id = node.exprName;
  21405. if (id.type === "Identifier") {
  21406. const matched = scope.declares[id.name];
  21407. if (matched) {
  21408. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  21409. }
  21410. }
  21411. break;
  21412. }
  21413. // e.g. readonly
  21414. case "TSTypeOperator": {
  21415. return inferRuntimeType(
  21416. ctx,
  21417. node.typeAnnotation,
  21418. scope,
  21419. node.operator === "keyof"
  21420. );
  21421. }
  21422. case "TSAnyKeyword": {
  21423. if (isKeyOf) {
  21424. return ["String", "Number", "Symbol"];
  21425. }
  21426. break;
  21427. }
  21428. }
  21429. } catch (e) {
  21430. }
  21431. return [UNKNOWN_TYPE];
  21432. }
  21433. function flattenTypes(ctx, types, scope, isKeyOf = false) {
  21434. if (types.length === 1) {
  21435. return inferRuntimeType(ctx, types[0], scope, isKeyOf);
  21436. }
  21437. return [
  21438. ...new Set(
  21439. [].concat(
  21440. ...types.map((t) => inferRuntimeType(ctx, t, scope, isKeyOf))
  21441. )
  21442. )
  21443. ];
  21444. }
  21445. function inferEnumType(node) {
  21446. const types = /* @__PURE__ */ new Set();
  21447. for (const m of node.members) {
  21448. if (m.initializer) {
  21449. switch (m.initializer.type) {
  21450. case "StringLiteral":
  21451. types.add("String");
  21452. break;
  21453. case "NumericLiteral":
  21454. types.add("Number");
  21455. break;
  21456. }
  21457. }
  21458. }
  21459. return types.size ? [...types] : ["Number"];
  21460. }
  21461. function resolveExtractPropTypes({ props }, scope) {
  21462. const res = { props: {} };
  21463. for (const key in props) {
  21464. const raw = props[key];
  21465. res.props[key] = reverseInferType(
  21466. raw.key,
  21467. raw.typeAnnotation.typeAnnotation,
  21468. scope
  21469. );
  21470. }
  21471. return res;
  21472. }
  21473. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  21474. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  21475. const typeType = findStaticPropertyType(node, "type");
  21476. if (typeType) {
  21477. const requiredType = findStaticPropertyType(node, "required");
  21478. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  21479. return reverseInferType(key, typeType, scope, optional2, false);
  21480. }
  21481. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  21482. if (node.typeName.name.endsWith("Constructor")) {
  21483. return createProperty(
  21484. key,
  21485. ctorToType(node.typeName.name),
  21486. scope,
  21487. optional
  21488. );
  21489. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  21490. return createProperty(key, node.typeParameters.params[0], scope, optional);
  21491. }
  21492. }
  21493. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  21494. for (const t of node.typeParameters.params) {
  21495. const inferred = reverseInferType(key, t, scope, optional);
  21496. if (inferred) return inferred;
  21497. }
  21498. }
  21499. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  21500. }
  21501. function ctorToType(ctorType) {
  21502. const ctor = ctorType.slice(0, -11);
  21503. switch (ctor) {
  21504. case "String":
  21505. case "Number":
  21506. case "Boolean":
  21507. return { type: `TS${ctor}Keyword` };
  21508. case "Array":
  21509. case "Function":
  21510. case "Object":
  21511. case "Set":
  21512. case "Map":
  21513. case "WeakSet":
  21514. case "WeakMap":
  21515. case "Date":
  21516. case "Promise":
  21517. return {
  21518. type: "TSTypeReference",
  21519. typeName: { type: "Identifier", name: ctor }
  21520. };
  21521. }
  21522. return { type: `TSNullKeyword` };
  21523. }
  21524. function findStaticPropertyType(node, key) {
  21525. const prop = node.members.find(
  21526. (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation
  21527. );
  21528. return prop && prop.typeAnnotation.typeAnnotation;
  21529. }
  21530. function resolveReturnType(ctx, arg, scope) {
  21531. var _a;
  21532. let resolved = arg;
  21533. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  21534. resolved = resolveTypeReference(ctx, arg, scope);
  21535. }
  21536. if (!resolved) return;
  21537. if (resolved.type === "TSFunctionType") {
  21538. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  21539. }
  21540. if (resolved.type === "TSDeclareFunction") {
  21541. return resolved.returnType;
  21542. }
  21543. }
  21544. function resolveUnionType(ctx, node, scope) {
  21545. if (node.type === "TSTypeReference") {
  21546. const resolved = resolveTypeReference(ctx, node, scope);
  21547. if (resolved) node = resolved;
  21548. }
  21549. let types;
  21550. if (node.type === "TSUnionType") {
  21551. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  21552. } else {
  21553. types = [node];
  21554. }
  21555. return types;
  21556. }
  21557. const DEFINE_MODEL = "defineModel";
  21558. function processDefineModel(ctx, node, declId) {
  21559. if (!isCallOf(node, DEFINE_MODEL)) {
  21560. return false;
  21561. }
  21562. ctx.hasDefineModelCall = true;
  21563. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  21564. let modelName;
  21565. let options;
  21566. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  21567. const hasName = arg0 && arg0.type === "StringLiteral";
  21568. if (hasName) {
  21569. modelName = arg0.value;
  21570. options = node.arguments[1];
  21571. } else {
  21572. modelName = "modelValue";
  21573. options = arg0;
  21574. }
  21575. if (ctx.modelDecls[modelName]) {
  21576. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  21577. }
  21578. let optionsString = options && ctx.getString(options);
  21579. let optionsRemoved = !options;
  21580. const runtimeOptionNodes = [];
  21581. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  21582. let removed = 0;
  21583. for (let i = options.properties.length - 1; i >= 0; i--) {
  21584. const p = options.properties[i];
  21585. const next = options.properties[i + 1];
  21586. const start = p.start;
  21587. const end = next ? next.start : options.end - 1;
  21588. 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"))) {
  21589. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  21590. } else {
  21591. removed++;
  21592. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  21593. runtimeOptionNodes.push(p);
  21594. }
  21595. }
  21596. if (removed === options.properties.length) {
  21597. optionsRemoved = true;
  21598. ctx.s.remove(
  21599. ctx.startOffset + (hasName ? arg0.end : options.start),
  21600. ctx.startOffset + options.end
  21601. );
  21602. }
  21603. }
  21604. ctx.modelDecls[modelName] = {
  21605. type,
  21606. options: optionsString,
  21607. runtimeOptionNodes,
  21608. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  21609. };
  21610. ctx.bindingMetadata[modelName] = "props";
  21611. ctx.s.overwrite(
  21612. ctx.startOffset + node.callee.start,
  21613. ctx.startOffset + node.callee.end,
  21614. ctx.helper("useModel")
  21615. );
  21616. ctx.s.appendLeft(
  21617. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  21618. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  21619. );
  21620. return true;
  21621. }
  21622. function genModelProps(ctx) {
  21623. if (!ctx.hasDefineModelCall) return;
  21624. const isProd = !!ctx.options.isProd;
  21625. let modelPropsDecl = "";
  21626. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  21627. ctx.modelDecls
  21628. )) {
  21629. let skipCheck = false;
  21630. let codegenOptions = ``;
  21631. let runtimeTypes = type && inferRuntimeType(ctx, type);
  21632. if (runtimeTypes) {
  21633. const hasBoolean = runtimeTypes.includes("Boolean");
  21634. const hasFunction = runtimeTypes.includes("Function");
  21635. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  21636. if (hasUnknownType) {
  21637. if (hasBoolean || hasFunction) {
  21638. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  21639. skipCheck = true;
  21640. } else {
  21641. runtimeTypes = ["null"];
  21642. }
  21643. }
  21644. if (!isProd) {
  21645. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  21646. } else if (hasBoolean || runtimeOptions && hasFunction) {
  21647. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  21648. } else ;
  21649. }
  21650. let decl;
  21651. if (codegenOptions && runtimeOptions) {
  21652. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  21653. } else if (codegenOptions) {
  21654. decl = `{ ${codegenOptions} }`;
  21655. } else if (runtimeOptions) {
  21656. decl = runtimeOptions;
  21657. } else {
  21658. decl = `{}`;
  21659. }
  21660. modelPropsDecl += `
  21661. ${JSON.stringify(name)}: ${decl},`;
  21662. const modifierPropName = JSON.stringify(
  21663. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  21664. );
  21665. modelPropsDecl += `
  21666. ${modifierPropName}: {},`;
  21667. }
  21668. return `{${modelPropsDecl}
  21669. }`;
  21670. }
  21671. const DEFINE_PROPS = "defineProps";
  21672. const WITH_DEFAULTS = "withDefaults";
  21673. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  21674. if (!isCallOf(node, DEFINE_PROPS)) {
  21675. return processWithDefaults(ctx, node, declId);
  21676. }
  21677. if (ctx.hasDefinePropsCall) {
  21678. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  21679. }
  21680. ctx.hasDefinePropsCall = true;
  21681. ctx.propsRuntimeDecl = node.arguments[0];
  21682. if (ctx.propsRuntimeDecl) {
  21683. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  21684. if (!(key in ctx.bindingMetadata)) {
  21685. ctx.bindingMetadata[key] = "props";
  21686. }
  21687. }
  21688. }
  21689. if (node.typeParameters) {
  21690. if (ctx.propsRuntimeDecl) {
  21691. ctx.error(
  21692. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  21693. node
  21694. );
  21695. }
  21696. ctx.propsTypeDecl = node.typeParameters.params[0];
  21697. }
  21698. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  21699. processPropsDestructure(ctx, declId);
  21700. }
  21701. ctx.propsCall = node;
  21702. ctx.propsDecl = declId;
  21703. return true;
  21704. }
  21705. function processWithDefaults(ctx, node, declId) {
  21706. if (!isCallOf(node, WITH_DEFAULTS)) {
  21707. return false;
  21708. }
  21709. if (!processDefineProps(
  21710. ctx,
  21711. node.arguments[0],
  21712. declId,
  21713. true
  21714. )) {
  21715. ctx.error(
  21716. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  21717. node.arguments[0] || node
  21718. );
  21719. }
  21720. if (ctx.propsRuntimeDecl) {
  21721. ctx.error(
  21722. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  21723. node
  21724. );
  21725. }
  21726. if (declId && declId.type === "ObjectPattern") {
  21727. ctx.warn(
  21728. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  21729. Reactive destructure will be disabled when using withDefaults().
  21730. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  21731. node.callee
  21732. );
  21733. }
  21734. ctx.propsRuntimeDefaults = node.arguments[1];
  21735. if (!ctx.propsRuntimeDefaults) {
  21736. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  21737. }
  21738. ctx.propsCall = node;
  21739. return true;
  21740. }
  21741. function genRuntimeProps(ctx) {
  21742. let propsDecls;
  21743. if (ctx.propsRuntimeDecl) {
  21744. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  21745. if (ctx.propsDestructureDecl) {
  21746. const defaults = [];
  21747. for (const key in ctx.propsDestructuredBindings) {
  21748. const d = genDestructuredDefaultValue(ctx, key);
  21749. const finalKey = getEscapedPropName(key);
  21750. if (d)
  21751. defaults.push(
  21752. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  21753. );
  21754. }
  21755. if (defaults.length) {
  21756. propsDecls = `/*@__PURE__*/${ctx.helper(
  21757. `mergeDefaults`
  21758. )}(${propsDecls}, {
  21759. ${defaults.join(",\n ")}
  21760. })`;
  21761. }
  21762. }
  21763. } else if (ctx.propsTypeDecl) {
  21764. propsDecls = extractRuntimeProps(ctx);
  21765. }
  21766. const modelsDecls = genModelProps(ctx);
  21767. if (propsDecls && modelsDecls) {
  21768. return `/*@__PURE__*/${ctx.helper(
  21769. "mergeModels"
  21770. )}(${propsDecls}, ${modelsDecls})`;
  21771. } else {
  21772. return modelsDecls || propsDecls;
  21773. }
  21774. }
  21775. function extractRuntimeProps(ctx) {
  21776. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  21777. if (!props.length) {
  21778. return;
  21779. }
  21780. const propStrings = [];
  21781. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  21782. for (const prop of props) {
  21783. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  21784. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  21785. ctx.bindingMetadata[prop.key] = "props";
  21786. }
  21787. }
  21788. let propsDecls = `{
  21789. ${propStrings.join(",\n ")}
  21790. }`;
  21791. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  21792. propsDecls = `/*@__PURE__*/${ctx.helper(
  21793. "mergeDefaults"
  21794. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  21795. }
  21796. return propsDecls;
  21797. }
  21798. function resolveRuntimePropsFromType(ctx, node) {
  21799. const props = [];
  21800. const elements = resolveTypeElements(ctx, node);
  21801. for (const key in elements.props) {
  21802. const e = elements.props[key];
  21803. let type = inferRuntimeType(ctx, e);
  21804. let skipCheck = false;
  21805. if (type.includes(UNKNOWN_TYPE)) {
  21806. if (type.includes("Boolean") || type.includes("Function")) {
  21807. type = type.filter((t) => t !== UNKNOWN_TYPE);
  21808. skipCheck = true;
  21809. } else {
  21810. type = ["null"];
  21811. }
  21812. }
  21813. props.push({
  21814. key,
  21815. required: !e.optional,
  21816. type: type || [`null`],
  21817. skipCheck
  21818. });
  21819. }
  21820. return props;
  21821. }
  21822. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  21823. let defaultString;
  21824. const destructured = genDestructuredDefaultValue(ctx, key, type);
  21825. if (destructured) {
  21826. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  21827. } else if (hasStaticDefaults) {
  21828. const prop = ctx.propsRuntimeDefaults.properties.find(
  21829. (node) => {
  21830. if (node.type === "SpreadElement") return false;
  21831. return resolveObjectKey(node.key, node.computed) === key;
  21832. }
  21833. );
  21834. if (prop) {
  21835. if (prop.type === "ObjectProperty") {
  21836. defaultString = `default: ${ctx.getString(prop.value)}`;
  21837. } else {
  21838. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  21839. }
  21840. }
  21841. }
  21842. const finalKey = getEscapedPropName(key);
  21843. if (!ctx.options.isProd) {
  21844. return `${finalKey}: { ${concatStrings([
  21845. `type: ${toRuntimeTypeString(type)}`,
  21846. `required: ${required}`,
  21847. skipCheck && "skipCheck: true",
  21848. defaultString
  21849. ])} }`;
  21850. } else if (type.some(
  21851. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  21852. )) {
  21853. return `${finalKey}: { ${concatStrings([
  21854. `type: ${toRuntimeTypeString(type)}`,
  21855. defaultString
  21856. ])} }`;
  21857. } else {
  21858. if (ctx.isCE) {
  21859. if (defaultString) {
  21860. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  21861. type
  21862. )} }`}`;
  21863. } else {
  21864. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  21865. }
  21866. }
  21867. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  21868. }
  21869. }
  21870. function hasStaticWithDefaults(ctx) {
  21871. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  21872. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  21873. ));
  21874. }
  21875. function genDestructuredDefaultValue(ctx, key, inferredType) {
  21876. const destructured = ctx.propsDestructuredBindings[key];
  21877. const defaultVal = destructured && destructured.default;
  21878. if (defaultVal) {
  21879. const value = ctx.getString(defaultVal);
  21880. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  21881. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  21882. const valueType = inferValueType(unwrapped);
  21883. if (valueType && !inferredType.includes(valueType)) {
  21884. ctx.error(
  21885. `Default value of prop "${key}" does not match declared type.`,
  21886. unwrapped
  21887. );
  21888. }
  21889. }
  21890. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  21891. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  21892. return {
  21893. valueString: needFactoryWrap ? `() => (${value})` : value,
  21894. needSkipFactory
  21895. };
  21896. }
  21897. }
  21898. function inferValueType(node) {
  21899. switch (node.type) {
  21900. case "StringLiteral":
  21901. return "String";
  21902. case "NumericLiteral":
  21903. return "Number";
  21904. case "BooleanLiteral":
  21905. return "Boolean";
  21906. case "ObjectExpression":
  21907. return "Object";
  21908. case "ArrayExpression":
  21909. return "Array";
  21910. case "FunctionExpression":
  21911. case "ArrowFunctionExpression":
  21912. return "Function";
  21913. }
  21914. }
  21915. function processPropsDestructure(ctx, declId) {
  21916. if (ctx.options.propsDestructure === "error") {
  21917. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  21918. } else if (ctx.options.propsDestructure === false) {
  21919. return;
  21920. }
  21921. ctx.propsDestructureDecl = declId;
  21922. const registerBinding = (key, local, defaultValue) => {
  21923. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  21924. if (local !== key) {
  21925. ctx.bindingMetadata[local] = "props-aliased";
  21926. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  21927. }
  21928. };
  21929. for (const prop of declId.properties) {
  21930. if (prop.type === "ObjectProperty") {
  21931. const propKey = resolveObjectKey(prop.key, prop.computed);
  21932. if (!propKey) {
  21933. ctx.error(
  21934. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  21935. prop.key
  21936. );
  21937. }
  21938. if (prop.value.type === "AssignmentPattern") {
  21939. const { left, right } = prop.value;
  21940. if (left.type !== "Identifier") {
  21941. ctx.error(
  21942. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  21943. left
  21944. );
  21945. }
  21946. registerBinding(propKey, left.name, right);
  21947. } else if (prop.value.type === "Identifier") {
  21948. registerBinding(propKey, prop.value.name);
  21949. } else {
  21950. ctx.error(
  21951. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  21952. prop.value
  21953. );
  21954. }
  21955. } else {
  21956. ctx.propsDestructureRestId = prop.argument.name;
  21957. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  21958. }
  21959. }
  21960. }
  21961. function transformDestructuredProps(ctx, vueImportAliases) {
  21962. if (ctx.options.propsDestructure === false) {
  21963. return;
  21964. }
  21965. const rootScope = /* @__PURE__ */ Object.create(null);
  21966. const scopeStack = [rootScope];
  21967. let currentScope = rootScope;
  21968. const excludedIds = /* @__PURE__ */ new WeakSet();
  21969. const parentStack = [];
  21970. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  21971. for (const key in ctx.propsDestructuredBindings) {
  21972. const { local } = ctx.propsDestructuredBindings[key];
  21973. rootScope[local] = true;
  21974. propsLocalToPublicMap[local] = key;
  21975. }
  21976. function pushScope() {
  21977. scopeStack.push(currentScope = Object.create(currentScope));
  21978. }
  21979. function popScope() {
  21980. scopeStack.pop();
  21981. currentScope = scopeStack[scopeStack.length - 1] || null;
  21982. }
  21983. function registerLocalBinding(id) {
  21984. excludedIds.add(id);
  21985. if (currentScope) {
  21986. currentScope[id.name] = false;
  21987. } else {
  21988. ctx.error(
  21989. "registerBinding called without active scope, something is wrong.",
  21990. id
  21991. );
  21992. }
  21993. }
  21994. function walkScope(node, isRoot = false) {
  21995. for (const stmt of node.body) {
  21996. if (stmt.type === "VariableDeclaration") {
  21997. walkVariableDeclaration(stmt, isRoot);
  21998. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  21999. if (stmt.declare || !stmt.id) continue;
  22000. registerLocalBinding(stmt.id);
  22001. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  22002. walkVariableDeclaration(stmt.left);
  22003. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  22004. walkVariableDeclaration(stmt.declaration, isRoot);
  22005. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  22006. walkVariableDeclaration(stmt.body, isRoot);
  22007. }
  22008. }
  22009. }
  22010. function walkVariableDeclaration(stmt, isRoot = false) {
  22011. if (stmt.declare) {
  22012. return;
  22013. }
  22014. for (const decl of stmt.declarations) {
  22015. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  22016. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  22017. if (isDefineProps) {
  22018. excludedIds.add(id);
  22019. } else {
  22020. registerLocalBinding(id);
  22021. }
  22022. }
  22023. }
  22024. }
  22025. function rewriteId(id, parent, parentStack2) {
  22026. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  22027. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  22028. }
  22029. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  22030. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  22031. ctx.s.appendLeft(
  22032. id.end + ctx.startOffset,
  22033. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  22034. );
  22035. }
  22036. } else {
  22037. ctx.s.overwrite(
  22038. id.start + ctx.startOffset,
  22039. id.end + ctx.startOffset,
  22040. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  22041. );
  22042. }
  22043. }
  22044. function checkUsage(node, method, alias = method) {
  22045. if (isCallOf(node, alias)) {
  22046. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22047. if (arg.type === "Identifier" && currentScope[arg.name]) {
  22048. ctx.error(
  22049. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  22050. arg
  22051. );
  22052. }
  22053. }
  22054. }
  22055. const ast = ctx.scriptSetupAst;
  22056. walkScope(ast, true);
  22057. estreeWalker.walk(ast, {
  22058. enter(node, parent) {
  22059. parent && parentStack.push(parent);
  22060. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22061. return this.skip();
  22062. }
  22063. checkUsage(node, "watch", vueImportAliases.watch);
  22064. checkUsage(node, "toRef", vueImportAliases.toRef);
  22065. if (CompilerDOM.isFunctionType(node)) {
  22066. pushScope();
  22067. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  22068. if (node.body.type === "BlockStatement") {
  22069. walkScope(node.body);
  22070. }
  22071. return;
  22072. }
  22073. if (node.type === "CatchClause") {
  22074. pushScope();
  22075. if (node.param && node.param.type === "Identifier") {
  22076. registerLocalBinding(node.param);
  22077. }
  22078. walkScope(node.body);
  22079. return;
  22080. }
  22081. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22082. pushScope();
  22083. walkScope(node);
  22084. return;
  22085. }
  22086. if (node.type === "Identifier") {
  22087. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  22088. if (currentScope[node.name]) {
  22089. rewriteId(node, parent, parentStack);
  22090. }
  22091. }
  22092. }
  22093. },
  22094. leave(node, parent) {
  22095. parent && parentStack.pop();
  22096. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node) || node.type === "CatchClause") {
  22097. popScope();
  22098. }
  22099. }
  22100. });
  22101. }
  22102. const DEFINE_EMITS = "defineEmits";
  22103. function processDefineEmits(ctx, node, declId) {
  22104. if (!isCallOf(node, DEFINE_EMITS)) {
  22105. return false;
  22106. }
  22107. if (ctx.hasDefineEmitCall) {
  22108. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  22109. }
  22110. ctx.hasDefineEmitCall = true;
  22111. ctx.emitsRuntimeDecl = node.arguments[0];
  22112. if (node.typeParameters) {
  22113. if (ctx.emitsRuntimeDecl) {
  22114. ctx.error(
  22115. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22116. node
  22117. );
  22118. }
  22119. ctx.emitsTypeDecl = node.typeParameters.params[0];
  22120. }
  22121. ctx.emitDecl = declId;
  22122. return true;
  22123. }
  22124. function genRuntimeEmits(ctx) {
  22125. let emitsDecl = "";
  22126. if (ctx.emitsRuntimeDecl) {
  22127. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  22128. } else if (ctx.emitsTypeDecl) {
  22129. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  22130. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  22131. }
  22132. if (ctx.hasDefineModelCall) {
  22133. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  22134. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  22135. "mergeModels"
  22136. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  22137. }
  22138. return emitsDecl;
  22139. }
  22140. function extractRuntimeEmits(ctx) {
  22141. const emits = /* @__PURE__ */ new Set();
  22142. const node = ctx.emitsTypeDecl;
  22143. if (node.type === "TSFunctionType") {
  22144. extractEventNames(ctx, node.parameters[0], emits);
  22145. return emits;
  22146. }
  22147. const { props, calls } = resolveTypeElements(ctx, node);
  22148. let hasProperty = false;
  22149. for (const key in props) {
  22150. emits.add(key);
  22151. hasProperty = true;
  22152. }
  22153. if (calls) {
  22154. if (hasProperty) {
  22155. ctx.error(
  22156. `defineEmits() type cannot mixed call signature and property syntax.`,
  22157. node
  22158. );
  22159. }
  22160. for (const call of calls) {
  22161. extractEventNames(ctx, call.parameters[0], emits);
  22162. }
  22163. }
  22164. return emits;
  22165. }
  22166. function extractEventNames(ctx, eventName, emits) {
  22167. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  22168. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  22169. for (const type of types) {
  22170. if (type.type === "TSLiteralType") {
  22171. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  22172. emits.add(String(type.literal.value));
  22173. }
  22174. }
  22175. }
  22176. }
  22177. }
  22178. const DEFINE_EXPOSE = "defineExpose";
  22179. function processDefineExpose(ctx, node) {
  22180. if (isCallOf(node, DEFINE_EXPOSE)) {
  22181. if (ctx.hasDefineExposeCall) {
  22182. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  22183. }
  22184. ctx.hasDefineExposeCall = true;
  22185. return true;
  22186. }
  22187. return false;
  22188. }
  22189. const DEFINE_SLOTS = "defineSlots";
  22190. function processDefineSlots(ctx, node, declId) {
  22191. if (!isCallOf(node, DEFINE_SLOTS)) {
  22192. return false;
  22193. }
  22194. if (ctx.hasDefineSlotsCall) {
  22195. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  22196. }
  22197. ctx.hasDefineSlotsCall = true;
  22198. if (node.arguments.length > 0) {
  22199. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  22200. }
  22201. if (declId) {
  22202. ctx.s.overwrite(
  22203. ctx.startOffset + node.start,
  22204. ctx.startOffset + node.end,
  22205. `${ctx.helper("useSlots")}()`
  22206. );
  22207. }
  22208. return true;
  22209. }
  22210. const DEFINE_OPTIONS = "defineOptions";
  22211. function processDefineOptions(ctx, node) {
  22212. if (!isCallOf(node, DEFINE_OPTIONS)) {
  22213. return false;
  22214. }
  22215. if (ctx.hasDefineOptionsCall) {
  22216. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  22217. }
  22218. if (node.typeParameters) {
  22219. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  22220. }
  22221. if (!node.arguments[0]) return true;
  22222. ctx.hasDefineOptionsCall = true;
  22223. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22224. let propsOption = void 0;
  22225. let emitsOption = void 0;
  22226. let exposeOption = void 0;
  22227. let slotsOption = void 0;
  22228. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  22229. for (const prop of ctx.optionsRuntimeDecl.properties) {
  22230. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  22231. switch (prop.key.name) {
  22232. case "props":
  22233. propsOption = prop;
  22234. break;
  22235. case "emits":
  22236. emitsOption = prop;
  22237. break;
  22238. case "expose":
  22239. exposeOption = prop;
  22240. break;
  22241. case "slots":
  22242. slotsOption = prop;
  22243. break;
  22244. }
  22245. }
  22246. }
  22247. }
  22248. if (propsOption) {
  22249. ctx.error(
  22250. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  22251. propsOption
  22252. );
  22253. }
  22254. if (emitsOption) {
  22255. ctx.error(
  22256. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  22257. emitsOption
  22258. );
  22259. }
  22260. if (exposeOption) {
  22261. ctx.error(
  22262. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  22263. exposeOption
  22264. );
  22265. }
  22266. if (slotsOption) {
  22267. ctx.error(
  22268. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  22269. slotsOption
  22270. );
  22271. }
  22272. return true;
  22273. }
  22274. function processAwait(ctx, node, needSemi, isStatement) {
  22275. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  22276. const startOffset = ctx.startOffset;
  22277. const argumentStr = ctx.descriptor.source.slice(
  22278. argumentStart + startOffset,
  22279. node.argument.end + startOffset
  22280. );
  22281. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  22282. ctx.s.overwrite(
  22283. node.start + startOffset,
  22284. argumentStart + startOffset,
  22285. `${needSemi ? `;` : ``}(
  22286. ([__temp,__restore] = ${ctx.helper(
  22287. `withAsyncContext`
  22288. )}(${containsNestedAwait ? `async ` : ``}() => `
  22289. );
  22290. ctx.s.appendLeft(
  22291. node.end + startOffset,
  22292. `)),
  22293. ${isStatement ? `` : `__temp = `}await __temp,
  22294. __restore()${isStatement ? `` : `,
  22295. __temp`}
  22296. )`
  22297. );
  22298. }
  22299. const MACROS = [
  22300. DEFINE_PROPS,
  22301. DEFINE_EMITS,
  22302. DEFINE_EXPOSE,
  22303. DEFINE_OPTIONS,
  22304. DEFINE_SLOTS,
  22305. DEFINE_MODEL,
  22306. WITH_DEFAULTS
  22307. ];
  22308. function compileScript(sfc, options) {
  22309. var _a, _b, _c;
  22310. if (!options.id) {
  22311. warnOnce(
  22312. `compileScript now requires passing the \`id\` option.
  22313. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  22314. );
  22315. }
  22316. const ctx = new ScriptCompileContext(sfc, options);
  22317. const { script, scriptSetup, source, filename } = sfc;
  22318. const hoistStatic = options.hoistStatic !== false && !script;
  22319. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  22320. const scriptLang = script && script.lang;
  22321. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  22322. if (!scriptSetup) {
  22323. if (!script) {
  22324. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  22325. }
  22326. return processNormalScript(ctx, scopeId);
  22327. }
  22328. if (script && scriptLang !== scriptSetupLang) {
  22329. throw new Error(
  22330. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  22331. );
  22332. }
  22333. if (scriptSetupLang && !ctx.isJS && !ctx.isTS) {
  22334. return scriptSetup;
  22335. }
  22336. const scriptBindings = /* @__PURE__ */ Object.create(null);
  22337. const setupBindings = /* @__PURE__ */ Object.create(null);
  22338. let defaultExport;
  22339. let hasAwait = false;
  22340. let hasInlinedSsrRenderFn = false;
  22341. const startOffset = ctx.startOffset;
  22342. const endOffset = ctx.endOffset;
  22343. const scriptStartOffset = script && script.loc.start.offset;
  22344. const scriptEndOffset = script && script.loc.end.offset;
  22345. function hoistNode(node) {
  22346. const start = node.start + startOffset;
  22347. let end = node.end + startOffset;
  22348. if (node.trailingComments && node.trailingComments.length > 0) {
  22349. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  22350. end = lastCommentNode.end + startOffset;
  22351. }
  22352. while (end <= source.length) {
  22353. if (!/\s/.test(source.charAt(end))) {
  22354. break;
  22355. }
  22356. end++;
  22357. }
  22358. ctx.s.move(start, end, 0);
  22359. }
  22360. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  22361. let isUsedInTemplate = needTemplateUsageCheck;
  22362. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  22363. isUsedInTemplate = isImportUsed(local, sfc);
  22364. }
  22365. ctx.userImports[local] = {
  22366. isType,
  22367. imported,
  22368. local,
  22369. source: source2,
  22370. isFromSetup,
  22371. isUsedInTemplate
  22372. };
  22373. }
  22374. function checkInvalidScopeReference(node, method) {
  22375. if (!node) return;
  22376. CompilerDOM.walkIdentifiers(node, (id) => {
  22377. const binding = setupBindings[id.name];
  22378. if (binding && binding !== "literal-const") {
  22379. ctx.error(
  22380. `\`${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.`,
  22381. id
  22382. );
  22383. }
  22384. });
  22385. }
  22386. const scriptAst = ctx.scriptAst;
  22387. const scriptSetupAst = ctx.scriptSetupAst;
  22388. if (scriptAst) {
  22389. for (const node of scriptAst.body) {
  22390. if (node.type === "ImportDeclaration") {
  22391. for (const specifier of node.specifiers) {
  22392. const imported = getImportedName(specifier);
  22393. registerUserImport(
  22394. node.source.value,
  22395. specifier.local.name,
  22396. imported,
  22397. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22398. false,
  22399. !options.inlineTemplate
  22400. );
  22401. }
  22402. }
  22403. }
  22404. }
  22405. for (const node of scriptSetupAst.body) {
  22406. if (node.type === "ImportDeclaration") {
  22407. hoistNode(node);
  22408. let removed = 0;
  22409. const removeSpecifier = (i) => {
  22410. const removeLeft = i > removed;
  22411. removed++;
  22412. const current = node.specifiers[i];
  22413. const next = node.specifiers[i + 1];
  22414. ctx.s.remove(
  22415. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  22416. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  22417. );
  22418. };
  22419. for (let i = 0; i < node.specifiers.length; i++) {
  22420. const specifier = node.specifiers[i];
  22421. const local = specifier.local.name;
  22422. const imported = getImportedName(specifier);
  22423. const source2 = node.source.value;
  22424. const existing = ctx.userImports[local];
  22425. if (source2 === "vue" && MACROS.includes(imported)) {
  22426. if (local === imported) {
  22427. warnOnce(
  22428. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  22429. );
  22430. } else {
  22431. ctx.error(
  22432. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  22433. specifier
  22434. );
  22435. }
  22436. removeSpecifier(i);
  22437. } else if (existing) {
  22438. if (existing.source === source2 && existing.imported === imported) {
  22439. removeSpecifier(i);
  22440. } else {
  22441. ctx.error(
  22442. `different imports aliased to same local name.`,
  22443. specifier
  22444. );
  22445. }
  22446. } else {
  22447. registerUserImport(
  22448. source2,
  22449. local,
  22450. imported,
  22451. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22452. true,
  22453. !options.inlineTemplate
  22454. );
  22455. }
  22456. }
  22457. if (node.specifiers.length && removed === node.specifiers.length) {
  22458. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22459. }
  22460. }
  22461. }
  22462. const vueImportAliases = {};
  22463. for (const key in ctx.userImports) {
  22464. const { source: source2, imported, local } = ctx.userImports[key];
  22465. if (source2 === "vue") vueImportAliases[imported] = local;
  22466. }
  22467. if (script && scriptAst) {
  22468. for (const node of scriptAst.body) {
  22469. if (node.type === "ExportDefaultDeclaration") {
  22470. defaultExport = node;
  22471. let optionProperties;
  22472. if (defaultExport.declaration.type === "ObjectExpression") {
  22473. optionProperties = defaultExport.declaration.properties;
  22474. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  22475. optionProperties = defaultExport.declaration.arguments[0].properties;
  22476. }
  22477. if (optionProperties) {
  22478. for (const p of optionProperties) {
  22479. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  22480. ctx.hasDefaultExportName = true;
  22481. }
  22482. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  22483. ctx.hasDefaultExportRender = true;
  22484. }
  22485. }
  22486. }
  22487. const start = node.start + scriptStartOffset;
  22488. const end = node.declaration.start + scriptStartOffset;
  22489. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  22490. } else if (node.type === "ExportNamedDeclaration") {
  22491. const defaultSpecifier = node.specifiers.find(
  22492. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  22493. );
  22494. if (defaultSpecifier) {
  22495. defaultExport = node;
  22496. if (node.specifiers.length > 1) {
  22497. ctx.s.remove(
  22498. defaultSpecifier.start + scriptStartOffset,
  22499. defaultSpecifier.end + scriptStartOffset
  22500. );
  22501. } else {
  22502. ctx.s.remove(
  22503. node.start + scriptStartOffset,
  22504. node.end + scriptStartOffset
  22505. );
  22506. }
  22507. if (node.source) {
  22508. ctx.s.prepend(
  22509. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  22510. `
  22511. );
  22512. } else {
  22513. ctx.s.appendLeft(
  22514. scriptEndOffset,
  22515. `
  22516. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  22517. `
  22518. );
  22519. }
  22520. }
  22521. if (node.declaration) {
  22522. walkDeclaration(
  22523. "script",
  22524. node.declaration,
  22525. scriptBindings,
  22526. vueImportAliases,
  22527. hoistStatic
  22528. );
  22529. }
  22530. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  22531. walkDeclaration(
  22532. "script",
  22533. node,
  22534. scriptBindings,
  22535. vueImportAliases,
  22536. hoistStatic
  22537. );
  22538. }
  22539. }
  22540. if (scriptStartOffset > startOffset) {
  22541. if (!/\n$/.test(script.content.trim())) {
  22542. ctx.s.appendLeft(scriptEndOffset, `
  22543. `);
  22544. }
  22545. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  22546. }
  22547. }
  22548. for (const node of scriptSetupAst.body) {
  22549. if (node.type === "ExpressionStatement") {
  22550. const expr = CompilerDOM.unwrapTSNode(node.expression);
  22551. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  22552. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22553. } else if (processDefineExpose(ctx, expr)) {
  22554. const callee = expr.callee;
  22555. ctx.s.overwrite(
  22556. callee.start + startOffset,
  22557. callee.end + startOffset,
  22558. "__expose"
  22559. );
  22560. } else {
  22561. processDefineModel(ctx, expr);
  22562. }
  22563. }
  22564. if (node.type === "VariableDeclaration" && !node.declare) {
  22565. const total = node.declarations.length;
  22566. let left = total;
  22567. let lastNonRemoved;
  22568. for (let i = 0; i < total; i++) {
  22569. const decl = node.declarations[i];
  22570. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  22571. if (init) {
  22572. if (processDefineOptions(ctx, init)) {
  22573. ctx.error(
  22574. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  22575. node
  22576. );
  22577. }
  22578. const isDefineProps = processDefineProps(ctx, init, decl.id);
  22579. if (ctx.propsDestructureRestId) {
  22580. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  22581. }
  22582. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  22583. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  22584. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  22585. if (left === 1) {
  22586. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22587. } else {
  22588. let start = decl.start + startOffset;
  22589. let end = decl.end + startOffset;
  22590. if (i === total - 1) {
  22591. start = node.declarations[lastNonRemoved].end + startOffset;
  22592. } else {
  22593. end = node.declarations[i + 1].start + startOffset;
  22594. }
  22595. ctx.s.remove(start, end);
  22596. left--;
  22597. }
  22598. } else if (isDefineEmits) {
  22599. ctx.s.overwrite(
  22600. startOffset + init.start,
  22601. startOffset + init.end,
  22602. "__emit"
  22603. );
  22604. } else {
  22605. lastNonRemoved = i;
  22606. }
  22607. }
  22608. }
  22609. }
  22610. let isAllLiteral = false;
  22611. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  22612. isAllLiteral = walkDeclaration(
  22613. "scriptSetup",
  22614. node,
  22615. setupBindings,
  22616. vueImportAliases,
  22617. hoistStatic,
  22618. !!ctx.propsDestructureDecl
  22619. );
  22620. }
  22621. if (hoistStatic && isAllLiteral) {
  22622. hoistNode(node);
  22623. }
  22624. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  22625. const scope = [scriptSetupAst.body];
  22626. estreeWalker.walk(node, {
  22627. enter(child, parent) {
  22628. if (CompilerDOM.isFunctionType(child)) {
  22629. this.skip();
  22630. }
  22631. if (child.type === "BlockStatement") {
  22632. scope.push(child.body);
  22633. }
  22634. if (child.type === "AwaitExpression") {
  22635. hasAwait = true;
  22636. const currentScope = scope[scope.length - 1];
  22637. const needsSemi = currentScope.some((n, i) => {
  22638. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  22639. });
  22640. processAwait(
  22641. ctx,
  22642. child,
  22643. needsSemi,
  22644. parent.type === "ExpressionStatement"
  22645. );
  22646. }
  22647. },
  22648. exit(node2) {
  22649. if (node2.type === "BlockStatement") scope.pop();
  22650. }
  22651. });
  22652. }
  22653. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  22654. ctx.error(
  22655. `<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.`,
  22656. node
  22657. );
  22658. }
  22659. if (ctx.isTS) {
  22660. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  22661. if (node.type !== "TSEnumDeclaration") {
  22662. hoistNode(node);
  22663. }
  22664. }
  22665. }
  22666. }
  22667. if (ctx.propsDestructureDecl) {
  22668. transformDestructuredProps(ctx, vueImportAliases);
  22669. }
  22670. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  22671. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  22672. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  22673. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  22674. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  22675. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  22676. for (const node of runtimeOptionNodes) {
  22677. checkInvalidScopeReference(node, DEFINE_MODEL);
  22678. }
  22679. }
  22680. if (script) {
  22681. if (startOffset < scriptStartOffset) {
  22682. ctx.s.remove(0, startOffset);
  22683. ctx.s.remove(endOffset, scriptStartOffset);
  22684. ctx.s.remove(scriptEndOffset, source.length);
  22685. } else {
  22686. ctx.s.remove(0, scriptStartOffset);
  22687. ctx.s.remove(scriptEndOffset, startOffset);
  22688. ctx.s.remove(endOffset, source.length);
  22689. }
  22690. } else {
  22691. ctx.s.remove(0, startOffset);
  22692. ctx.s.remove(endOffset, source.length);
  22693. }
  22694. if (scriptAst) {
  22695. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  22696. }
  22697. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  22698. ctx.userImports
  22699. )) {
  22700. if (isType) continue;
  22701. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  22702. }
  22703. for (const key in scriptBindings) {
  22704. ctx.bindingMetadata[key] = scriptBindings[key];
  22705. }
  22706. for (const key in setupBindings) {
  22707. ctx.bindingMetadata[key] = setupBindings[key];
  22708. }
  22709. if (sfc.cssVars.length && // no need to do this when targeting SSR
  22710. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  22711. ctx.helperImports.add(CSS_VARS_HELPER);
  22712. ctx.helperImports.add("unref");
  22713. ctx.s.prependLeft(
  22714. startOffset,
  22715. `
  22716. ${genCssVarsCode(
  22717. sfc.cssVars,
  22718. ctx.bindingMetadata,
  22719. scopeId,
  22720. !!options.isProd
  22721. )}
  22722. `
  22723. );
  22724. }
  22725. let args = `__props`;
  22726. if (ctx.propsTypeDecl) {
  22727. args += `: any`;
  22728. }
  22729. if (ctx.propsDecl) {
  22730. if (ctx.propsDestructureRestId) {
  22731. ctx.s.overwrite(
  22732. startOffset + ctx.propsCall.start,
  22733. startOffset + ctx.propsCall.end,
  22734. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  22735. Object.keys(ctx.propsDestructuredBindings)
  22736. )})`
  22737. );
  22738. ctx.s.overwrite(
  22739. startOffset + ctx.propsDestructureDecl.start,
  22740. startOffset + ctx.propsDestructureDecl.end,
  22741. ctx.propsDestructureRestId
  22742. );
  22743. } else if (!ctx.propsDestructureDecl) {
  22744. ctx.s.overwrite(
  22745. startOffset + ctx.propsCall.start,
  22746. startOffset + ctx.propsCall.end,
  22747. "__props"
  22748. );
  22749. }
  22750. }
  22751. if (hasAwait) {
  22752. const any = ctx.isTS ? `: any` : ``;
  22753. ctx.s.prependLeft(startOffset, `
  22754. let __temp${any}, __restore${any}
  22755. `);
  22756. }
  22757. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  22758. if (ctx.emitDecl) {
  22759. destructureElements.push(`emit: __emit`);
  22760. }
  22761. if (destructureElements.length) {
  22762. args += `, { ${destructureElements.join(", ")} }`;
  22763. }
  22764. let templateMap;
  22765. let returned;
  22766. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  22767. const allBindings = {
  22768. ...scriptBindings,
  22769. ...setupBindings
  22770. };
  22771. for (const key in ctx.userImports) {
  22772. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  22773. allBindings[key] = true;
  22774. }
  22775. }
  22776. returned = `{ `;
  22777. for (const key in allBindings) {
  22778. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  22779. returned += `get ${key}() { return ${key} }, `;
  22780. } else if (ctx.bindingMetadata[key] === "setup-let") {
  22781. const setArg = key === "v" ? `_v` : `v`;
  22782. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  22783. } else {
  22784. returned += `${key}, `;
  22785. }
  22786. }
  22787. returned = returned.replace(/, $/, "") + ` }`;
  22788. } else {
  22789. if (sfc.template && !sfc.template.src) {
  22790. if (options.templateOptions && options.templateOptions.ssr) {
  22791. hasInlinedSsrRenderFn = true;
  22792. }
  22793. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate({
  22794. filename,
  22795. ast: sfc.template.ast,
  22796. source: sfc.template.content,
  22797. inMap: sfc.template.map,
  22798. ...options.templateOptions,
  22799. id: scopeId,
  22800. scoped: sfc.styles.some((s) => s.scoped),
  22801. isProd: options.isProd,
  22802. ssrCssVars: sfc.cssVars,
  22803. compilerOptions: {
  22804. ...options.templateOptions && options.templateOptions.compilerOptions,
  22805. inline: true,
  22806. isTS: ctx.isTS,
  22807. bindingMetadata: ctx.bindingMetadata
  22808. }
  22809. });
  22810. templateMap = map2;
  22811. if (tips.length) {
  22812. tips.forEach(warnOnce);
  22813. }
  22814. const err = errors[0];
  22815. if (typeof err === "string") {
  22816. throw new Error(err);
  22817. } else if (err) {
  22818. if (err.loc) {
  22819. err.message += `
  22820. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  22821. source,
  22822. err.loc.start.offset,
  22823. err.loc.end.offset
  22824. ) + `
  22825. `;
  22826. }
  22827. throw err;
  22828. }
  22829. if (preamble) {
  22830. ctx.s.prepend(preamble);
  22831. }
  22832. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  22833. ctx.helperImports.delete("unref");
  22834. }
  22835. returned = code;
  22836. } else {
  22837. returned = `() => {}`;
  22838. }
  22839. }
  22840. if (!options.inlineTemplate && true) {
  22841. ctx.s.appendRight(
  22842. endOffset,
  22843. `
  22844. const __returned__ = ${returned}
  22845. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  22846. return __returned__
  22847. }
  22848. `
  22849. );
  22850. } else {
  22851. ctx.s.appendRight(endOffset, `
  22852. return ${returned}
  22853. }
  22854. `);
  22855. }
  22856. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  22857. let runtimeOptions = ``;
  22858. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  22859. const match = filename.match(/([^/\\]+)\.\w+$/);
  22860. if (match) {
  22861. runtimeOptions += `
  22862. __name: '${match[1]}',`;
  22863. }
  22864. }
  22865. if (hasInlinedSsrRenderFn) {
  22866. runtimeOptions += `
  22867. __ssrInlineRender: true,`;
  22868. }
  22869. const propsDecl = genRuntimeProps(ctx);
  22870. if (propsDecl) runtimeOptions += `
  22871. props: ${propsDecl},`;
  22872. const emitsDecl = genRuntimeEmits(ctx);
  22873. if (emitsDecl) runtimeOptions += `
  22874. emits: ${emitsDecl},`;
  22875. let definedOptions = "";
  22876. if (ctx.optionsRuntimeDecl) {
  22877. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  22878. }
  22879. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  22880. `;
  22881. if (ctx.isTS) {
  22882. const def = (defaultExport ? `
  22883. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  22884. ...${definedOptions},` : "");
  22885. ctx.s.prependLeft(
  22886. startOffset,
  22887. `
  22888. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  22889. `defineComponent`
  22890. )}({${def}${runtimeOptions}
  22891. ${hasAwait ? `async ` : ``}setup(${args}) {
  22892. ${exposeCall}`
  22893. );
  22894. ctx.s.appendRight(endOffset, `})`);
  22895. } else {
  22896. if (defaultExport || definedOptions) {
  22897. ctx.s.prependLeft(
  22898. startOffset,
  22899. `
  22900. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  22901. ${hasAwait ? `async ` : ``}setup(${args}) {
  22902. ${exposeCall}`
  22903. );
  22904. ctx.s.appendRight(endOffset, `})`);
  22905. } else {
  22906. ctx.s.prependLeft(
  22907. startOffset,
  22908. `
  22909. ${genDefaultAs} {${runtimeOptions}
  22910. ${hasAwait ? `async ` : ``}setup(${args}) {
  22911. ${exposeCall}`
  22912. );
  22913. ctx.s.appendRight(endOffset, `}`);
  22914. }
  22915. }
  22916. if (ctx.helperImports.size > 0) {
  22917. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  22918. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  22919. ctx.s.prepend(
  22920. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  22921. `
  22922. );
  22923. }
  22924. const content = ctx.s.toString();
  22925. let map = options.sourceMap !== false ? ctx.s.generateMap({
  22926. source: filename,
  22927. hires: true,
  22928. includeContent: true
  22929. }) : void 0;
  22930. if (templateMap && map) {
  22931. const offset = content.indexOf(returned);
  22932. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  22933. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  22934. }
  22935. return {
  22936. ...scriptSetup,
  22937. bindings: ctx.bindingMetadata,
  22938. imports: ctx.userImports,
  22939. content,
  22940. map,
  22941. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  22942. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  22943. deps: ctx.deps ? [...ctx.deps] : void 0
  22944. };
  22945. }
  22946. function registerBinding(bindings, node, type) {
  22947. bindings[node.name] = type;
  22948. }
  22949. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  22950. let isAllLiteral = false;
  22951. if (node.type === "VariableDeclaration") {
  22952. const isConst = node.kind === "const";
  22953. isAllLiteral = isConst && node.declarations.every(
  22954. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  22955. );
  22956. for (const { id, init: _init } of node.declarations) {
  22957. const init = _init && CompilerDOM.unwrapTSNode(_init);
  22958. const isConstMacroCall = isConst && isCallOf(
  22959. init,
  22960. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  22961. );
  22962. if (id.type === "Identifier") {
  22963. let bindingType;
  22964. const userReactiveBinding = userImportAliases["reactive"];
  22965. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  22966. bindingType = "literal-const";
  22967. } else if (isCallOf(init, userReactiveBinding)) {
  22968. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  22969. } else if (
  22970. // if a declaration is a const literal, we can mark it so that
  22971. // the generated render fn code doesn't need to unref() it
  22972. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  22973. ) {
  22974. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  22975. } else if (isConst) {
  22976. if (isCallOf(
  22977. init,
  22978. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  22979. )) {
  22980. bindingType = "setup-ref";
  22981. } else {
  22982. bindingType = "setup-maybe-ref";
  22983. }
  22984. } else {
  22985. bindingType = "setup-let";
  22986. }
  22987. registerBinding(bindings, id, bindingType);
  22988. } else {
  22989. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  22990. continue;
  22991. }
  22992. if (id.type === "ObjectPattern") {
  22993. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  22994. } else if (id.type === "ArrayPattern") {
  22995. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  22996. }
  22997. }
  22998. }
  22999. } else if (node.type === "TSEnumDeclaration") {
  23000. isAllLiteral = node.members.every(
  23001. (member) => !member.initializer || isStaticNode(member.initializer)
  23002. );
  23003. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  23004. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  23005. bindings[node.id.name] = "setup-const";
  23006. }
  23007. return isAllLiteral;
  23008. }
  23009. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  23010. for (const p of node.properties) {
  23011. if (p.type === "ObjectProperty") {
  23012. if (p.key.type === "Identifier" && p.key === p.value) {
  23013. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23014. registerBinding(bindings, p.key, type);
  23015. } else {
  23016. walkPattern(p.value, bindings, isConst, isDefineCall);
  23017. }
  23018. } else {
  23019. const type = isConst ? "setup-const" : "setup-let";
  23020. registerBinding(bindings, p.argument, type);
  23021. }
  23022. }
  23023. }
  23024. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  23025. for (const e of node.elements) {
  23026. e && walkPattern(e, bindings, isConst, isDefineCall);
  23027. }
  23028. }
  23029. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  23030. if (node.type === "Identifier") {
  23031. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23032. registerBinding(bindings, node, type);
  23033. } else if (node.type === "RestElement") {
  23034. const type = isConst ? "setup-const" : "setup-let";
  23035. registerBinding(bindings, node.argument, type);
  23036. } else if (node.type === "ObjectPattern") {
  23037. walkObjectPattern(node, bindings, isConst);
  23038. } else if (node.type === "ArrayPattern") {
  23039. walkArrayPattern(node, bindings, isConst);
  23040. } else if (node.type === "AssignmentPattern") {
  23041. if (node.left.type === "Identifier") {
  23042. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23043. registerBinding(bindings, node.left, type);
  23044. } else {
  23045. walkPattern(node.left, bindings, isConst);
  23046. }
  23047. }
  23048. }
  23049. function canNeverBeRef(node, userReactiveImport) {
  23050. if (isCallOf(node, userReactiveImport)) {
  23051. return true;
  23052. }
  23053. switch (node.type) {
  23054. case "UnaryExpression":
  23055. case "BinaryExpression":
  23056. case "ArrayExpression":
  23057. case "ObjectExpression":
  23058. case "FunctionExpression":
  23059. case "ArrowFunctionExpression":
  23060. case "UpdateExpression":
  23061. case "ClassExpression":
  23062. case "TaggedTemplateExpression":
  23063. return true;
  23064. case "SequenceExpression":
  23065. return canNeverBeRef(
  23066. node.expressions[node.expressions.length - 1],
  23067. userReactiveImport
  23068. );
  23069. default:
  23070. if (isLiteralNode(node)) {
  23071. return true;
  23072. }
  23073. return false;
  23074. }
  23075. }
  23076. function isStaticNode(node) {
  23077. node = CompilerDOM.unwrapTSNode(node);
  23078. switch (node.type) {
  23079. case "UnaryExpression":
  23080. return isStaticNode(node.argument);
  23081. case "LogicalExpression":
  23082. // 1 > 2
  23083. case "BinaryExpression":
  23084. return isStaticNode(node.left) && isStaticNode(node.right);
  23085. case "ConditionalExpression": {
  23086. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  23087. }
  23088. case "SequenceExpression":
  23089. // (1, 2)
  23090. case "TemplateLiteral":
  23091. return node.expressions.every((expr) => isStaticNode(expr));
  23092. case "ParenthesizedExpression":
  23093. return isStaticNode(node.expression);
  23094. case "StringLiteral":
  23095. case "NumericLiteral":
  23096. case "BooleanLiteral":
  23097. case "NullLiteral":
  23098. case "BigIntLiteral":
  23099. return true;
  23100. }
  23101. return false;
  23102. }
  23103. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  23104. const generator = new sourceMapJs.SourceMapGenerator();
  23105. const addMapping = (map, lineOffset = 0) => {
  23106. const consumer = new sourceMapJs.SourceMapConsumer(map);
  23107. consumer.sources.forEach((sourceFile) => {
  23108. generator._sources.add(sourceFile);
  23109. const sourceContent = consumer.sourceContentFor(sourceFile);
  23110. if (sourceContent != null) {
  23111. generator.setSourceContent(sourceFile, sourceContent);
  23112. }
  23113. });
  23114. consumer.eachMapping((m) => {
  23115. if (m.originalLine == null) return;
  23116. generator.addMapping({
  23117. generated: {
  23118. line: m.generatedLine + lineOffset,
  23119. column: m.generatedColumn
  23120. },
  23121. original: {
  23122. line: m.originalLine,
  23123. column: m.originalColumn
  23124. },
  23125. source: m.source,
  23126. name: m.name
  23127. });
  23128. });
  23129. };
  23130. addMapping(scriptMap);
  23131. addMapping(templateMap, templateLineOffset);
  23132. generator._sourceRoot = scriptMap.sourceRoot;
  23133. generator._file = scriptMap.file;
  23134. return generator.toJSON();
  23135. }
  23136. const version = "3.5.16";
  23137. const parseCache = parseCache$1;
  23138. const errorMessages = {
  23139. ...CompilerDOM.errorMessages,
  23140. ...CompilerDOM.DOMErrorMessages
  23141. };
  23142. const walk = estreeWalker.walk;
  23143. const shouldTransformRef = () => false;
  23144. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  23145. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  23146. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  23147. exports.isStaticProperty = compilerCore.isStaticProperty;
  23148. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  23149. exports.MagicString = MagicString;
  23150. exports.babelParse = parser$2.parse;
  23151. exports.compileScript = compileScript;
  23152. exports.compileStyle = compileStyle;
  23153. exports.compileStyleAsync = compileStyleAsync;
  23154. exports.compileTemplate = compileTemplate;
  23155. exports.errorMessages = errorMessages;
  23156. exports.extractRuntimeEmits = extractRuntimeEmits;
  23157. exports.extractRuntimeProps = extractRuntimeProps;
  23158. exports.inferRuntimeType = inferRuntimeType;
  23159. exports.invalidateTypeCache = invalidateTypeCache;
  23160. exports.parse = parse$1;
  23161. exports.parseCache = parseCache;
  23162. exports.registerTS = registerTS;
  23163. exports.resolveTypeElements = resolveTypeElements;
  23164. exports.rewriteDefault = rewriteDefault;
  23165. exports.rewriteDefaultAST = rewriteDefaultAST;
  23166. exports.shouldTransformRef = shouldTransformRef;
  23167. exports.version = version;
  23168. exports.walk = walk;